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
modulo-dm/modulo
Modules/ELCodable/ELCodable/Decimal.swift
1
293
// // Decimal.swift // Decimal // // Created by Brandon Sneed on 11/7/15. // Copyright © 2015 WalmartLabs. All rights reserved. // import Foundation extension Decimal { public var value: NSDecimalNumber { get { return (self as NSDecimalNumber) } } }
mit
pablogsIO/MadridShops
MadridShops/View/CityDataInformationMapPin.swift
1
626
// // MapPinCityDataInformation.swift // MadridShops // // Created by Pablo García on 25/09/2017. // Copyright © 2017 KC. All rights reserved. // import MapKit class CityDataInformationMapPin: NSObject, MKAnnotation{ var title: String? var subtitle: String? var coordinate: CLLocationCoordinate2D var logo: String var entity: CityDataInformationModel init(title: String,latitude: Double, longitude: Double,logo: String,entity: CityDataInformationModel){ self.title = title self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) self.logo = logo self.entity = entity } }
mit
thoughtbot/Perform
Sources/Perform/Perform.swift
1
3166
import UIKit extension UIViewController { /// Perform the storyboard segue identified by `segue`, invoking `prepare` /// with the destination view controller when `prepareForSegue(_:sender:)` /// is received. /// /// **Example** /// /// // prepare for segue inside the closure /// perform(.showTaskDetails) { taskVC in /// taskVC.task = self.selectedTask /// } /// /// // just perform a segue /// perform(.signOut) /// /// If the destination view controller itself doesn't match the destination /// type specified by `segue`, its view controller hierarchy is searched /// until the matching view controller is found. For example, if the desired /// view controller is embedded inside a `UINavigationController`, it will /// still be found and passed along to `prepare`. /// /// - parameter segue: /// An instance of `Segue<Destination>` which specifies the identifier /// and destination view controller type. /// /// - parameter prepare: /// A function that will be invoked with the matching destination view /// view controller when `prepareForSegue(_:sender:)` is received. The /// default value for this parameter does nothing. /// /// - note: /// If no matching view controller is found in the destination /// view controller hierarchy, this method will raise a fatal error /// and crash. This usually means that the view controller hasn't /// been configured with the correct type in the storyboard. public func perform<Destination>(_ segue: Segue<Destination>, prepare: @escaping (Destination) -> Void = { _ in }) { performSegue(withIdentifier: segue.identifier) { [segueDescription = { String(reflecting: segue) }] segue, _ in guard let destination = segue.destinationViewController(ofType: Destination.self) else { #if DEBUG let printHierarchy = "_printHierarchy" let hierarchy = segue.destination.perform(Selector(printHierarchy)).takeUnretainedValue() fatalError("\(segueDescription()): expected destination view controller hierarchy to include \(Destination.self), got:\n\(hierarchy)") #else fatalError("\(segueDescription()): expected destination view controller hierarchy to include \(Destination.self)") #endif } prepare(destination) } } internal func performSegue(withIdentifier identifier: String, sender: Any? = nil, prepare: @escaping (UIStoryboardSegue, Any?) -> Void) { _ = try! aspect_hook( #selector(UIViewController.prepare(for:sender:)), options: .optionAutomaticRemoval, body: { info in let arguments = info.arguments()! prepare(arguments.first as! UIStoryboardSegue, arguments.second) } ) performSegue(withIdentifier: identifier, sender: sender) } } // MARK: - Type checker ambiguity hack extension UIViewController { @available(*, unavailable) public func perform() { fatalError( "This method will never be called, and exists only to remove an " + "apparent ambiguity resolving the generic method 'perform(_:prepare:)'" ) } }
mit
fabiomassimo/eidolon
Kiosk/UITextField+RAC.swift
1
215
import UIKit import ReactiveCocoa extension UITextField { public func returnKeySignal () -> RACSignal { return rac_signalForControlEvents(.EditingDidEndOnExit).takeUntil(rac_willDeallocSignal()) } }
mit
Shvier/QuickPlayer-Swift
QuickPlayer-Example/QuickPlayer-Example/ViewController.swift
1
1160
// // ViewController.swift // QuickPlayer-Example // // Created by Shvier on 31/03/2017. // Copyright © 2017 Shvier. All rights reserved. // import UIKit import QuickPlayer import AVFoundation class ViewController: UIViewController { var player: QuickPlayer! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. player = QuickPlayer(frame: view.frame) view.addSubview(player.playerView) player.startPlay(videoUrl: URL(string: "https://www.videvo.net/videvo_files/converted/2013_06/videos/OldFashionedFilmLeaderCountdownVidevo.mov22394.mp4")!) DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in self.player.replaceCurrentItem(coverUrl: nil, videoUrl: URL(string: "https://www.videvo.net/videvo_files/converted/2014_08/videos/Earth_Zoom_In.mov35908.mp4")!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: QuickPlayerDelegate { }
mit
Verchen/Swift-Project
JinRong/JinRong/Classes/Authentication(认证)/Model/ContactsModel.swift
1
639
// // ContactsModel.swift // JinRong // // Created by 乔伟成 on 2017/7/25. // Copyright © 2017年 乔伟成. All rights reserved. // import UIKit import ObjectMapper class ContactsModel: Mappable { var addTime : String? var id : Int? var name : String? var relationId : Int? var tel : String? var userId : Int? required init?(map: Map) { } func mapping(map: Map) { addTime <- map["add_time"] id <- map["id"] name <- map["name"] relationId <- map["relation_id"] tel <- map["tel"] userId <- map["user_id"] } }
mit
mklbtz/finch
Sources/TaskManagement/Storage.swift
1
1644
import Foundation public struct Storage<Stored> { public let path: String public let defaultValue: Stored? let transcoder: Transcoder<Stored, Data> public init(atPath path: String, default: Stored? = nil, transcoder: Transcoder<Stored, Data>) { self.path = path self.transcoder = transcoder self.defaultValue = `default` } } extension Storage { public func load() throws -> Stored { return try withNiceErrors { do { let input = try file.load() return try transcoder.decode(input) } catch File.Error.couldNotRead(let file) { if let defaultValue = defaultValue { return defaultValue } else { throw File.Error.couldNotRead(file) } } } } public func save(_ stored: Stored) throws { return try withNiceErrors { let output = try transcoder.encode(stored) try file.save(output) } } var file: File { return File(atPath: path) } private func withNiceErrors<A>(_ run: () throws -> A) rethrows -> A { do { return try run() } catch let error as NSError { print("caught NSError") throw error.localizedDescription } } } extension Storage where Stored == [Task] { public static var defaultPath: String { return ".todo" } } public func TaskStorage(atPath path: String = Storage<[Task]>.defaultPath) -> Storage<[Task]> { return .init(atPath: path, default: [], transcoder: JSONTranscoder()) } public func StringStorage(atPath path: String = Storage<[Task]>.defaultPath) -> Storage<String> { return .init(atPath: path, transcoder: StringTranscoder()) }
mit
jhong70/JKHImageZoomTransition
Example/TransitionPlayer/TransitionPlayer/AppDelegate.swift
1
2183
// // AppDelegate.swift // TransitionPlayer // // Created by Joon Hong on 8/4/16. // Copyright © 2016 JoonKiHong. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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
neonichu/Roark
Sources/test/main.swift
1
240
import Roark InitializeXcode() let project = Project(file: Process.arguments.last!) print(project.name) print((project.targets.map { $0.description }).joinWithSeparator("\n")) print(project.targetNamed("BlogTests")) print(project.write())
mit
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/Connect View Controllers/GKHostViewController/SwiftUI/ActivityIndicatorView.swift
2
569
// // ActivityIndicatorView.swift // WikiRaces // // Created by Andrew Finke on 6/25/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import SwiftUI struct ActivityIndicatorView: UIViewRepresentable { func makeUIView(context: UIViewRepresentableContext<ActivityIndicatorView>) -> UIActivityIndicatorView { let view = UIActivityIndicatorView(style: .medium) view.startAnimating() return view } func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicatorView>) {} }
mit
J3D1-WARR10R/WikiRaces
WKRUIKit/WKRUIKit/Elements/WKRUIStyle.swift
2
606
// // WKRUIStyle.swift // WKRUIKit // // Created by Andrew Finke on 9/22/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import UIKit import SwiftUI final public class WKRUIStyle { public static func isDark(_ traitCollection: UITraitCollection) -> Bool { if traitCollection.userInterfaceStyle == .dark { return true } else { return false } } public static func isDark(_ colorScheme: ColorScheme) -> Bool { if colorScheme == .dark { return true } else { return false } } }
mit
wikimedia/wikipedia-ios
Widgets/Widgets/TopReadWidget.swift
1
15581
import SwiftUI import WidgetKit import WMF // MARK: - Widget struct TopReadWidget: Widget { private let kind: String = WidgetController.SupportedWidget.topRead.identifier public var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: TopReadProvider(), content: { entry in TopReadView(entry: entry) }) .configurationDisplayName(LocalizedStrings.widgetTitle) .description(LocalizedStrings.widgetDescription) .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) } } // MARK: - Data final class TopReadData { // MARK: Properties static let shared = TopReadData() let maximumRankedArticles = 4 var placeholder: TopReadEntry { return TopReadEntry(date: Date()) } func fetchLatestAvailableTopRead(usingCache: Bool = false, completion userCompletion: @escaping (TopReadEntry) -> Void) { let widgetController = WidgetController.shared widgetController.startWidgetUpdateTask(userCompletion) { (dataStore, widgetUpdateTaskCompletion) in widgetController.fetchNewestWidgetContentGroup(with: .topRead, in: dataStore, isNetworkFetchAllowed: !usingCache) { (contentGroup) in guard let contentGroup = contentGroup else { widgetUpdateTaskCompletion(self.placeholder) return } self.assembleTopReadFromContentGroup(contentGroup, with: dataStore, usingImageCache: usingCache, completion: widgetUpdateTaskCompletion) } } } // MARK: Private private func assembleTopReadFromContentGroup(_ topRead: WMFContentGroup, with dataStore: MWKDataStore, usingImageCache: Bool = false, completion: @escaping (TopReadEntry) -> Void) { guard let articlePreviews = topRead.contentPreview as? [WMFFeedTopReadArticlePreview] else { completion(placeholder) return } // The WMFContentGroup can only be accessed synchronously // re-accessing it from the main queue or another queue might lead to unexpected behavior let layoutDirection: LayoutDirection = topRead.isRTL ? .rightToLeft : .leftToRight let groupURL = topRead.url let isCurrent = topRead.isForToday // even though the top read data is from yesterday, the content group is for today var rankedElements: [TopReadEntry.RankedElement] = [] for articlePreview in articlePreviews { if let fetchedArticle = dataStore.fetchArticle(with: articlePreview.articleURL), let viewCounts = fetchedArticle.pageViewsSortedByDate { let title = fetchedArticle.displayTitle ?? articlePreview.displayTitle let description = fetchedArticle.wikidataDescription ?? articlePreview.wikidataDescription ?? fetchedArticle.snippet ?? articlePreview.snippet ?? "" let rankedElement = TopReadEntry.RankedElement(title: title, description: description, articleURL: articlePreview.articleURL, thumbnailURL: articlePreview.thumbnailURL, viewCounts: viewCounts) rankedElements.append(rankedElement) } } rankedElements = Array(rankedElements.prefix(maximumRankedArticles)) let group = DispatchGroup() for (index, element) in rankedElements.enumerated() { group.enter() guard let thumbnailURL = element.thumbnailURL else { group.leave() continue } let fetcher = dataStore.cacheController.imageCache if usingImageCache { if let cachedImage = fetcher.cachedImage(withURL: thumbnailURL) { rankedElements[index].image = cachedImage.staticImage } group.leave() continue } fetcher.fetchImage(withURL: thumbnailURL, failure: { _ in group.leave() }, success: { fetchedImage in rankedElements[index].image = fetchedImage.image.staticImage group.leave() }) } group.notify(queue: .main) { completion(TopReadEntry(date: Date(), rankedElements: rankedElements, groupURL: groupURL, isCurrent: isCurrent, contentLayoutDirection: layoutDirection)) } } } // MARK: - Model struct TopReadEntry: TimelineEntry { struct RankedElement: Identifiable { var id: String = UUID().uuidString let title: String let description: String var articleURL: URL? = nil var image: UIImage? = nil var thumbnailURL: URL? = nil let viewCounts: [NSNumber] } let date: Date // for Timeline Entry var rankedElements: [RankedElement] = Array(repeating: RankedElement.init(title: "–", description: "–", image: nil, viewCounts: [.init(floatLiteral: 0)]), count: 4) var groupURL: URL? = nil var isCurrent: Bool = false var contentLayoutDirection: LayoutDirection = .leftToRight } // MARK: - TimelineProvider struct TopReadProvider: TimelineProvider { // MARK: Nested Types public typealias Entry = TopReadEntry // MARK: Properties private let dataStore = TopReadData.shared // MARK: TimelineProvider func placeholder(in: Context) -> TopReadEntry { return dataStore.placeholder } func getTimeline(in context: Context, completion: @escaping (Timeline<TopReadEntry>) -> Void) { dataStore.fetchLatestAvailableTopRead { entry in let isError = entry.groupURL == nil || !entry.isCurrent let nextUpdate: Date let currentDate = Date() if !isError { nextUpdate = currentDate.randomDateShortlyAfterMidnight() ?? currentDate } else { let components = DateComponents(hour: 2) nextUpdate = Calendar.current.date(byAdding: components, to: currentDate) ?? currentDate } completion(Timeline(entries: [entry], policy: .after(nextUpdate))) } } func getSnapshot(in context: Context, completion: @escaping (TopReadEntry) -> Void) { dataStore.fetchLatestAvailableTopRead(usingCache: context.isPreview) { (entry) in completion(entry) } } } // MARK: - Views struct TopReadView: View { @Environment(\.widgetFamily) private var family @Environment(\.colorScheme) private var colorScheme var entry: TopReadProvider.Entry? var readersTextColor: Color { colorScheme == .light ? Theme.light.colors.rankGradientEnd.asColor : Theme.dark.colors.rankGradientEnd.asColor } @ViewBuilder var body: some View { GeometryReader { proxy in switch family { case .systemMedium: rowBasedWidget(.systemMedium) .widgetURL(entry?.groupURL) case .systemLarge: rowBasedWidget(.systemLarge) .widgetURL(entry?.groupURL) default: smallWidget .frame(width: proxy.size.width, height: proxy.size.height, alignment: .center) .overlay(TopReadOverlayView(rankedElement: entry?.rankedElements.first)) .widgetURL(entry?.rankedElements.first?.articleURL) } } .environment(\.layoutDirection, entry?.contentLayoutDirection ?? .leftToRight) .flipsForRightToLeftLayoutDirection(true) } // MARK: View Components @ViewBuilder var smallWidget: some View { if let image = entry?.rankedElements.first?.image { Image(uiImage: image).resizable().scaledToFill() } else { Rectangle() .foregroundColor(colorScheme == .dark ? Color.black : Color.white) } } @ViewBuilder func rowBasedWidget(_ family: WidgetFamily) -> some View { let showSparkline = family == .systemLarge ? true : false let rowCount = family == .systemLarge ? 4 : 2 VStack(alignment: .leading, spacing: 8) { Text(TopReadWidget.LocalizedStrings.widgetTitle) .font(.subheadline) .fontWeight(.bold) ForEach(entry?.rankedElements.indices.prefix(rowCount) ?? 0..<0, id: \.self) { elementIndex in if let articleURL = entry?.rankedElements[elementIndex].articleURL { Link(destination: articleURL, label: { elementRow(elementIndex, rowCount: rowCount, showSparkline: showSparkline) }) } else { elementRow(elementIndex, rowCount: rowCount, showSparkline: showSparkline) } } } .padding(16) } @ViewBuilder func elementRow(_ index: Int, rowCount: Int, showSparkline: Bool = false) -> some View { let rankColor = colorScheme == .light ? Theme.light.colors.rankGradient.color(at: CGFloat(index)/CGFloat(rowCount)).asColor : Theme.dark.colors.rankGradient.color(at: CGFloat(index)/CGFloat(rowCount)).asColor GeometryReader { proxy in HStack(alignment: .center) { Circle() .strokeBorder(rankColor, lineWidth: 1) .frame(width: 22, height: 22, alignment: .leading) .overlay( Text("\(NumberFormatter.localizedThousandsStringFromNumber(NSNumber(value: index + 1)))") .font(.footnote) .fontWeight(.light) .foregroundColor(rankColor) ) .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 7)) VStack(alignment: .leading, spacing: 5) { Text("\(entry?.rankedElements[index].title ?? "–")") .font(.subheadline) .fontWeight(.semibold) .foregroundColor(Color(.label)) if showSparkline { Text("\(entry?.rankedElements[index].description ?? "–")") .lineLimit(2) .font(.caption) .foregroundColor(Color(.secondaryLabel)) Sparkline(style: .compactWithViewCount, timeSeries: entry?.rankedElements[index].viewCounts) .cornerRadius(4) .frame(height: proxy.size.height / 3.0, alignment: .leading) } else { Text("\(numberOfReadersTextOrEmptyForViewCount(entry?.rankedElements[index].viewCounts.last))") .font(.caption) .fontWeight(.medium) .lineLimit(2) .foregroundColor(readersTextColor) } } Spacer() elementImageOrEmptyView(index) .frame(width: proxy.size.height / 1.1, height: proxy.size.height / 1.1, alignment: .trailing) .mask( RoundedRectangle(cornerRadius: 5, style: .continuous) ) } } } @ViewBuilder func elementImageOrEmptyView(_ elementIndex: Int) -> some View { if let image = entry?.rankedElements[elementIndex].image { Image(uiImage: image) .resizable() .aspectRatio(contentMode: .fill) } else { EmptyView() } } // MARK: Private private func numberOfReadersTextOrEmptyForViewCount(_ viewCount: NSNumber?) -> String { guard let viewCount = viewCount else { return "–" } let formattedCount = NumberFormatter.localizedThousandsStringFromNumber(viewCount) return String.localizedStringWithFormat(TopReadWidget.LocalizedStrings.readersCountFormat, formattedCount) } } struct TopReadOverlayView: View { @Environment(\.colorScheme) var colorScheme var rankedElement: TopReadEntry.RankedElement? var isExpandedStyle: Bool { return rankedElement?.image == nil } var readersForegroundColor: Color { colorScheme == .light ? Theme.light.colors.rankGradientEnd.asColor : Theme.dark.colors.rankGradientEnd.asColor } var primaryTextColor: Color { isExpandedStyle ? colorScheme == .dark ? Color.white : Color.black : .white } private var currentNumberOfReadersTextOrEmpty: String { guard let currentViewCount = rankedElement?.viewCounts.last else { return "–" } let formattedCount = NumberFormatter.localizedThousandsStringFromNumber(currentViewCount) return String.localizedStringWithFormat(TopReadWidget.LocalizedStrings.readersCountFormat, formattedCount) } var body: some View { if isExpandedStyle { content } else { content .background( Rectangle() .foregroundColor(.black) .mask(LinearGradient(gradient: Gradient(colors: [.clear, .black]), startPoint: .center, endPoint: .bottom)) .opacity(0.35) ) } } // MARK: View Components var content: some View { VStack(alignment: .leading) { if isExpandedStyle { Text(currentNumberOfReadersTextOrEmpty) .fontWeight(.medium) .lineLimit(nil) .font(.subheadline) .foregroundColor(readersForegroundColor) .padding(EdgeInsets(top: 16, leading: 16, bottom: 0, trailing: 0)) } sparkline(expanded: isExpandedStyle) Spacer() description() } .foregroundColor(.white) } func sparkline(expanded: Bool) -> some View { HStack(alignment: .top) { Spacer() if expanded { Sparkline(style: .expanded, timeSeries: rankedElement?.viewCounts) .padding(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 16)) } else { Sparkline(style: .compact, timeSeries: rankedElement?.viewCounts) .cornerRadius(4) .frame(height: 20, alignment: .trailing) .padding(EdgeInsets(top: 16, leading: 0, bottom: 0, trailing: 16)) // TODO: Apply shadow just to final content – not children views as well // .clipped() // .readableShadow(intensity: 0.60) } } } func description() -> some View { VStack(alignment: .leading, spacing: 5) { Text(TopReadWidget.LocalizedStrings.widgetTitle) .font(.caption2) .fontWeight(.bold) .aspectRatio(contentMode: .fit) .foregroundColor(primaryTextColor) .readableShadow(intensity: isExpandedStyle ? 0 : 0.8) Text("\(rankedElement?.title ?? "–")") .lineLimit(nil) .font(.headline) .foregroundColor(primaryTextColor) .readableShadow(intensity: isExpandedStyle ? 0 : 0.8) } .padding(EdgeInsets(top: 0, leading: 16, bottom: 16, trailing: 16)) } }
mit
mabidakun/StringSearchKit
StringSearchKit/Classes/Sequence+Additions.swift
1
1386
// // Created by Mike O. Abidakun 2017. // Copyright (c) 2017-Present Mike O. Abidakun. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension Sequence where Iterator.Element == String { func addEntries(to trie: Trie) { forEach { trie.add(string: $0) } } }
mit
TheTekton/Malibu
MalibuTests/Specs/Validation/StatusCodeVadatorSpec.swift
1
1300
@testable import Malibu import Quick import Nimble class StatusCodeValidatorSpec: QuickSpec { override func spec() { describe("StatusCodeValidator") { let URL = NSURL(string: "http://hyper.no")! let request = NSURLRequest(URL: URL) let data = NSData() var validator: StatusCodeValidator<[Int]>! describe("#validate") { beforeEach { validator = StatusCodeValidator(statusCodes: [200]) } context("when response has expected status code") { it("does not throw an error") { let HTTPResponse = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/2.0", headerFields: nil)! let result = Wave(data: data, request: request, response: HTTPResponse) expect{ try validator.validate(result) }.toNot(throwError()) } } context("when response has not expected status code") { it("throws an error") { let HTTPResponse = NSHTTPURLResponse(URL: URL, statusCode: 404, HTTPVersion: "HTTP/2.0", headerFields: nil)! let result = Wave(data: data, request: request, response: HTTPResponse) expect{ try validator.validate(result) }.to(throwError()) } } } } } }
mit
applivery/applivery-ios-sdk
AppliveryBehaviorTests/Mocks/FeedbackCoordinatorMock.swift
1
469
// // FeedbackCoordinatorMock.swift // AppliverySDK // // Created by Alejandro Jiménez on 28/2/16. // Copyright © 2016 Applivery S.L. All rights reserved. // import Foundation @testable import Applivery class FeedbackCoordinatorMock: PFeedbackCoordinator { var outShowFeedbackCalled = false var outCloseFeedbackCalled = false func showFeedack() { self.outShowFeedbackCalled = true } func closeFeedback() { self.outCloseFeedbackCalled = true } }
mit
huangboju/Eyepetizer
Eyepetizer/Eyepetizer/Main/MainNavigation.swift
1
2614
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // class MainNavigation: UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() if respondsToSelector(Selector("interactivePopGestureRecognizer")) { interactivePopGestureRecognizer?.delegate = self navigationBar.titleTextAttributes = ["Font" : UIFont.customFont_Lobster(fontSize: LABEL_FONT_SIZE)] delegate = self } navigationBar.tintColor = UIColor.blackColor() navigationBar.barStyle = .Default navigationBar.backIndicatorImage = R.image.ic_action_back() navigationBar.backIndicatorTransitionMaskImage = R.image.ic_action_back() } override func pushViewController(viewController: UIViewController, animated: Bool) { if respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated { interactivePopGestureRecognizer?.enabled = false } super.pushViewController(viewController, animated: animated) } override func popToRootViewControllerAnimated(animated: Bool) -> [UIViewController]? { if respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated { interactivePopGestureRecognizer?.enabled = false } return super.popToRootViewControllerAnimated(animated) } override func popToViewController(viewController: UIViewController, animated: Bool) -> [UIViewController]? { if respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated { interactivePopGestureRecognizer?.enabled = false } return super.popToViewController(viewController, animated: false) } // MARK: - UINavigationControllerDelegate func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) { if respondsToSelector(Selector("interactivePopGestureRecognizer")) { interactivePopGestureRecognizer?.enabled = true } } //MARK: - UIGestureRecognizerDelegate func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == interactivePopGestureRecognizer { if viewControllers.count < 2 || visibleViewController == viewControllers[0] { return false } } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
cubixlabs/SocialGIST
Pods/GISTFramework/GISTFramework/Classes/Extentions/UIView+Utility.swift
1
4775
// // UIView+Utility.swift // GISTFramework // // Created by Shoaib Abdul on 14/06/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit // MARK: - UIView Utility Extension public extension UIView { /// Rotate a view by specified degrees in CGFloat public var rotation:CGFloat { get { let radians:CGFloat = atan2(self.transform.b, self.transform.a) let degrees:CGFloat = radians * (180.0 / CGFloat(M_PI)) return degrees; } set { let radians = newValue / 180.0 * CGFloat(M_PI) let rotation = self.transform.rotated(by: radians); self.transform = rotation } } //P.E. /// Loads nib from Bundle /// /// - Parameters: /// - nibName: Nib Name /// - viewIndex: View Index /// - owner: Nib Owner AnyObject /// - Returns: UIView public class func loadWithNib(_ nibName:String, viewIndex:Int, owner: AnyObject) -> Any { return Bundle.main.loadNibNamed(nibName, owner: owner, options: nil)![viewIndex]; } //F.E. /// Loads dynamic nib from Bundle /// /// - Parameters: /// - nibName: Nib Name /// - viewIndex: View Index /// - owner: Nib Owner AnyObject /// - Returns: UIView public class func loadDynamicViewWithNib(_ nibName:String, viewIndex:Int, owner: AnyObject) -> Any { let bundle = Bundle(for: type(of: owner)); let nib = UINib(nibName: nibName, bundle: bundle); let rView: Any = nib.instantiate(withOwner: owner, options: nil)[viewIndex]; return rView; } //F.E. /// Adds Boarder for the View /// /// - Parameters: /// - color: Border Color /// - width: Border Width public func addBorder(_ color:UIColor?, width:Int){ let layer:CALayer = self.layer; layer.borderColor = color?.cgColor layer.borderWidth = (CGFloat(width)/CGFloat(2)) as CGFloat } //F.E. /// Makes Rounded corners of View. it trims the view in circle public func addRoundedCorners() { self.addRoundedCorners(self.frame.size.width/2.0); } //F.E. /// Adds rounded corner with defined radius /// /// - Parameter radius: Radius Value public func addRoundedCorners(_ radius:CGFloat) { let layer:CALayer = self.layer; layer.cornerRadius = radius layer.masksToBounds = true } //F.E. /// Adds Drop shadow on the view public func addDropShadow() { let shadowPath:UIBezierPath=UIBezierPath(rect: self.bounds) let layer:CALayer = self.layer; layer.shadowColor = UIColor.black.cgColor; layer.shadowOffset = CGSize(width: 1, height: 1); layer.shadowOpacity = 0.21 layer.shadowRadius = 2.0 layer.shadowPath = shadowPath.cgPath layer.masksToBounds = false; } //F.E. /// Shows view with fadeIn animation /// /// - Parameters: /// - duration: Fade duration - Default Value is 0.25 /// - completion: Completion block public func fadeIn(withDuration duration:Double = 0.25, _ completion:((_ finished:Bool)->())? = nil) { self.alpha = 0.0; self.isHidden = false; UIView.animate(withDuration: duration, animations: { () -> Void in self.alpha = 1.0; }, completion: { (finish:Bool) -> Void in completion?(finish) }) } //F.E. // Hides view with fadeOut animation /// /// - Parameters: /// - duration: Fade duration - Default Value is 0.25 /// - completion: Completion block public func fadeOut(withDuration duration:Double = 0.25, _ completion:((_ finished:Bool)->())? = nil) { self.alpha = 1.0 UIView.animate(withDuration: duration, animations: { () -> Void in self.alpha=0.0; }, completion: { (finish:Bool) -> Void in self.isHidden = true; completion?(finish) }) } //F.E. /// Shakes view in a static animation public func shake() { let shake:CABasicAnimation = CABasicAnimation(keyPath: "position"); shake.duration = 0.1; shake.repeatCount = 2; shake.autoreverses = true; shake.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 5, y: self.center.y)); shake.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 5, y: self.center.y)); self.layer.add(shake, forKey: "position"); } //F.E. /// Rempves all views from the view public func removeAllSubviews() { for view in self.subviews { view.removeFromSuperview(); } } //F.E. } //E.E.
gpl-3.0
BanyaKrylov/Learn-Swift
Skill/Homework 12/Homework 12/ThreeWeather.swift
1
2275
// // ThreeWeather.swift // Homework 12 // // Created by Ivan Krylov on 18.02.2020. // Copyright © 2020 Ivan Krylov. All rights reserved. // import Foundation class ThreeWeather { var weatherCondition: String = "" var temp: Int = 0 var date: String = "" init?(weatherJson: NSDictionary) { if let listJson = weatherJson["list"] as? NSArray { for item in listJson { if let main = item as? NSDictionary { if let date = main["dt_txt"] as? String { self.date = date print(date) } if let temp = main["main"] as? NSDictionary { if let temperature = temp["temp"] as? Double { self.temp = Int(round(temperature - 273.15)) print(temp) } } if let nestedJson = main["weather"] as? NSArray { if let desc = nestedJson[0] as? NSDictionary { if let weathCond = desc["description"] as? String { self.weatherCondition = weathCond print(weatherCondition) } } } } } } // guard let listJson = weatherJson["list"] as? NSArray else { return nil } // guard let zeroMain = listJson[0] as? NSDictionary else { return nil } // guard let date = zeroMain["dt_txt"] as? String else { return nil } // self.date = date // guard let temp = zeroMain["main"] as? NSDictionary else { return nil } // guard let temperature = temp["temp"] as? Double else { return nil } // self.temp = Int(round(temperature - 273.15)) // guard let weather = zeroMain["weather"] as? NSArray else { return nil } // guard let desc = weather[0] as? NSDictionary else { return nil } // guard let weatherCondition = desc["description"] as? String else { return nil } // self.weatherCondition = weatherCondition.capitalized } }
apache-2.0
KennethTsang/GrowingTextView
Example/GrowingTextView/Example2.swift
1
2172
// // Example2.swift // GrowingTextView // // Created by Tsang Kenneth on 16/3/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import GrowingTextView class Example2: UIViewController { @IBOutlet weak var inputToolbar: UIView! @IBOutlet weak var textView: GrowingTextView! @IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // *** Customize GrowingTextView *** textView.layer.cornerRadius = 4.0 // *** Listen to keyboard show / hide *** NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) // *** Hide keyboard when tapping outside *** let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler)) view.addGestureRecognizer(tapGesture) } deinit { NotificationCenter.default.removeObserver(self) } @objc private func keyboardWillChangeFrame(_ notification: Notification) { if let endFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { var keyboardHeight = UIScreen.main.bounds.height - endFrame.origin.y if #available(iOS 11, *) { if keyboardHeight > 0 { keyboardHeight = keyboardHeight - view.safeAreaInsets.bottom } } textViewBottomConstraint.constant = keyboardHeight + 8 view.layoutIfNeeded() } } @objc func tapGestureHandler() { view.endEditing(true) } } extension Example2: GrowingTextViewDelegate { // *** Call layoutIfNeeded on superview for animation when changing height *** func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) { UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) } }
mit
rzrasel/iOS-Swift-2016-01
SwiftCameraGalleryOne/RzLibs/UIImage+Utils.swift
2
1787
// // UIImage+Utils.swift // SwiftCameraGallery // // Created by NextDot on 2/4/16. // Copyright © 2016 RzRasel. All rights reserved. // import Foundation import UIKit extension UIImage{ //|------------------------------------| //|------------------------------------| //|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| func imageResize(image: UIImage, scaledToSize newSize: CGSize) -> UIImage { var width: CGFloat! var height: CGFloat! //IMAGE SIZE if image.size.width/newSize.width >= image.size.height / newSize.height{ width = newSize.width height = image.size.height / (image.size.width/newSize.width) }else{ height = newSize.height width = image.size.width / (image.size.height/newSize.height) } let sizeImageSmall = CGSizeMake(width, height) //end print(sizeImageSmall) UIGraphicsBeginImageContext(sizeImageSmall); image.drawInRect(CGRectMake(0,0,sizeImageSmall.width,sizeImageSmall.height)) let newImage:UIImage=UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } //|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| class func imageWithColor(color: UIColor) -> UIImage { let rect = CGRectMake(0.0, 0.0, 1.0, 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } //|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| }
apache-2.0
MountainHill/Swift-at-Artsy
Beginners/Lesson Three/Lesson Three.playground/Sources/Source.swift
2
95
public enum ArtworkAvailablility { case NotForSale case ForSale case OnHold case Sold }
cc0-1.0
kortnee1021/Kortnee
03-Single View App/Swift 1/BMI-Step7/BMI/ViewController.swift
4
1707
// // ViewController.swift // BMI // // Created by Nicholas Outram on 30/12/2014. // Copyright (c) 2014 Plymouth University. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { var weight : Double? var height : Double? var bmi : Double? { get { if (weight != nil) && (height != nil) { return weight! / (height! * height!) } else { return nil } } } @IBOutlet weak var bmiLabel: UILabel! @IBOutlet weak var heightTextField: UITextField! @IBOutlet weak var weightTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() updateUI() return true } func updateUI() { if let b = self.bmi { self.bmiLabel.text = String(format: "%4.1f", b) } } func textFieldDidEndEditing(textField: UITextField) { let conv = { NSNumberFormatter().numberFromString($0)?.doubleValue } switch (textField) { case self.weightTextField: self.weight = conv(textField.text) case self.heightTextField: self.height = conv(textField.text) default: println("Something has gone very wrong!") } updateUI() } }
mit
exponent/exponent
packages/expo-dev-menu/ios/UITests/DevMenuUIMatchers.swift
2
2760
import XCTest import UIKit class DevMenuViews { static let mainScreen = "DevMenuMainScreen" static let footer = "DevMenuFooter" static let settingsScreen = "DevMenuSettingsScreen" static let profileScreen = "DevMenuProfileScreen" } class DevMenuUIMatchers { static func currentRootView() -> UIView? { return UIApplication.shared.keyWindow?.rootViewController?.view } static func findView(rootView: UIView, _ matcher: (UIView) -> Bool) -> UIView? { if matcher(rootView) { return rootView } for subView in rootView.subviews { let found = findView(rootView: subView, matcher) if found != nil { return found } } return nil } static func findView(_ matcher: (UIView) -> Bool) -> UIView? { guard let view = DevMenuUIMatchers.currentRootView() else { return nil } return findView(rootView: view, matcher) } static func findView(rootView: UIView, tag: String) -> UIView? { return DevMenuUIMatchers.findView(rootView: rootView) { return $0.accessibilityIdentifier == tag && $0.isVisible() } } static func findView(tag: String) -> UIView? { guard let view = DevMenuUIMatchers.currentRootView() else { return nil } return findView(rootView: view, tag: tag) } static func waitForView(_ matcher: (UIView) -> Bool) -> UIView { let timer = Date(timeIntervalSinceNow: DevMenuTestOptions.defaultTimeout) while timer.timeIntervalSinceNow > 0 { DevMenuLooper.runMainLoop(for: DevMenuTestOptions.loopTime) guard let view = DevMenuUIMatchers.currentRootView() else { continue } let found = findView(rootView: view, matcher) if found != nil { return found! } } XCTFail("Can not find view.") return UIView() // just for compiler } static func waitForView(tag: String) -> UIView { return waitForView { return $0.accessibilityIdentifier == tag && $0.isVisible() } } static func waitForView(text: String) -> UIView { return waitForView { if type(of: $0) == NSClassFromString("RCTTextView")! { return $0.isVisible() && ($0.value(forKey: "_textStorage") as! NSTextStorage).string == text } return false } } static func findView(rootView: UIView, text: String) -> UIView? { findView(rootView: rootView) { if type(of: $0) == NSClassFromString("RCTTextView")! { return $0.isVisible() && ($0.value(forKey: "_textStorage") as! NSTextStorage).string == text } return false } } static func findView(text: String) -> UIView? { guard let view = DevMenuUIMatchers.currentRootView() else { return nil } return findView(rootView: view, text: text) } }
bsd-3-clause
suominentoni/nearest-departures
HSL Nearest Departures WatchKit Extension/NearestStopsInterfaceController.swift
1
5044
import WatchKit import Foundation import NearestDeparturesDigitransit open class NearestStopsInterfaceController: WKInterfaceController, CLLocationManagerDelegate { @IBOutlet var nearestStopsTable: WKInterfaceTable! @IBOutlet var loadingIndicatorLabel: WKInterfaceLabel! var nearestStops: [Stop] = [] var locationManager: CLLocationManager! var lat: Double = 0 var lon: Double = 0 override open func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { nearestStopsTable.performSegue(forRow: rowIndex) } open override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? { if let row = table.rowController(at: rowIndex) as? NearestStopsRow { return ["stopCode": row.code] } return nil } override open func awake(withContext context: Any?) { super.awake(withContext: context) self.setTitle(NSLocalizedString("NEAREST", comment: "")) self.initTimer() locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = 5 if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined) { locationManager.requestWhenInUseAuthorization() } else { requestLocation() } } open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { requestLocation() } func requestLocation() { showLoadingIndicator() if(CLLocationManager.authorizationStatus() != CLAuthorizationStatus.restricted || CLLocationManager.authorizationStatus() != CLAuthorizationStatus.denied) { NSLog("Requesting location") locationManager.requestLocation() } } open func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { NSLog("Location Manager error: " + error.localizedDescription) if(error._code == CLError.Code.denied.rawValue) { self.presentAlert( NSLocalizedString("LOCATION_REQUEST_FAILED_TITLE", comment: ""), message: NSLocalizedString("LOCATION_REQUEST_FAILED_MSG", comment: ""), action: requestLocation) } else { requestLocation() } } open func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { NSLog("New location data received") let lat = locations.last!.coordinate.latitude let lon = locations.last!.coordinate.longitude TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: updateInterface) } fileprivate func updateInterface(_ nearestStops: [Stop]) -> Void { NSLog("Updating Nearest Stops interface") let nearestStopsWithDepartures = nearestStops.filter({ $0.departures.count > 0 }) loadingIndicatorLabel.setHidden(true) hideLoadingIndicator() self.nearestStops = nearestStopsWithDepartures nearestStopsTable.setNumberOfRows(nearestStopsWithDepartures.count, withRowType: "nearestStopsRow") if(nearestStopsWithDepartures.count == 0) { self.presentAlert(NSLocalizedString("NO_STOPS_TITLE", comment: ""), message: NSLocalizedString("NO_STOPS_MSG", comment: "")) } else { var i: Int = 0 for stop in nearestStopsWithDepartures { let nearestStopRow = nearestStopsTable.rowController(at: i) as! NearestStopsRow nearestStopRow.code = stop.codeLong nearestStopRow.stopName.setText(stop.name) nearestStopRow.stopCode.setText(stop.codeShort) nearestStopRow.distance.setText(String(stop.distance) + " m") i += 1 } } } override open func willDisappear() { invalidateTimer() } override open func willActivate() { requestLocation() } fileprivate func showLoadingIndicator() { initTimer() self.loadingIndicatorLabel.setHidden(false) } fileprivate func hideLoadingIndicator() { self.loadingIndicatorLabel.setHidden(true) } @IBAction func refreshClick() { requestLocation() } var counter = 1 var timer: Timer = Timer() func initTimer() { invalidateTimer() self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(NearestStopsInterfaceController.updateLoadingIndicatorText), userInfo: nil, repeats: true) self.timer.fire() } func invalidateTimer() { self.timer.invalidate() } @objc fileprivate func updateLoadingIndicatorText() { self.counter == 4 ? (self.counter = 1) : (self.counter = self.counter + 1) let dots = (1...counter).map({_ in "."}).joined() self.loadingIndicatorLabel.setText(dots) } }
mit
react-native-kit/react-native-track-player
example/ios/example/dummy.swift
1
150
// // dummy.swift // example // // Created by David Chavez on 03.04.18. // Copyright © 2018 Facebook. All rights reserved. // import Foundation
apache-2.0
thombles/Flyweight
Flyweight/ViewControllers/SecondViewController.swift
1
1003
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // 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 class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
OscarSwanros/swift
test/Interpreter/SDK/weak_objc_interop.swift
16
794
// RUN: %empty-directory(%t) // // RUN: cp %s %t/main.swift // RUN: %target-clang -fobjc-arc %S/Inputs/ObjCWeak/ObjCWeak.m -c -o %t/ObjCWeak.o // RUN: %target-build-swift %t/main.swift -I %S/Inputs/ObjCWeak/ -Xlinker %t/ObjCWeak.o -o %t/weak_objc_interop -Xfrontend -disable-access-control // RUN: %target-run %t/weak_objc_interop 2>&1 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import ObjCWeak // Test that instances of pure Swift classes can be referenced using ObjC // weak references. class C { @objc var description: String { return "Swift Object" } } tryWeakReferencing { C() } // CHECK: before giving up strong reference: // CHECK-NEXT: Swift Object // CHECK-NEXT: after giving up strong reference: // CHECK-NEXT: Gone
apache-2.0
cdzombak/finder-atom
finder-atom/ViewController.swift
1
479
// // ViewController.swift // finder-atom // // Created by Chris Dzombak on 12/23/16. // Copyright © 2016 Chris Dzombak. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBAction func openSystemPreferences(_ sender: AnyObject?) { if !NSWorkspace.shared().open(URL(fileURLWithPath: "/System/Library/PreferencePanes/Extensions.prefPane")) { NSLog("[Error] Failed to open Extensions preference pane") } } }
mpl-2.0
LonelyHusky/SCWeibo
SCWeibo/Classes/Tools/SCNetworkTools.swift
1
1582
// // SCNetworkTools.swift // SCWeibo // // Created by 云卷云舒丶 on 16/7/23. // // import UIKit import AFNetworking enum SCRequestMethod:String { case Post = "post" case Get = "get" } class SCNetworkTools: AFHTTPSessionManager { // 单例:全局访问点 static let sharedTools: SCNetworkTools = { let tools = SCNetworkTools() tools.responseSerializer.acceptableContentTypes?.insert("text/html") tools.responseSerializer.acceptableContentTypes?.insert("text/plain") return tools }() // 定义请求 typealias SCRequestCallBack = (responseObject:AnyObject?,error:NSError?)->() func request(method:SCRequestMethod = .Get,urlString:String ,parameters:AnyObject?,finished:SCRequestCallBack) { // 定义一个请求成功之后要执行的闭包 let success = {(dataTasks:NSURLSessionTask,responseObject:AnyObject?)-> Void in // 请求成功的回调 finished(responseObject:responseObject,error: nil) } // 定义一个请求失败之后要执行的闭包 let failure = { (dataTasks:NSURLSessionDataTask?,error:NSError) ->Void in finished(responseObject:nil,error: error) } if method == .Get { GET(urlString,parameters: parameters,progress: nil,success: success,failure: failure) }else{ POST(urlString, parameters: parameters, progress: nil,success: success, failure: failure) } } }
mit
DeKoServidoni/Hackaton2016
Ágora/SearchProductsViewController.swift
1
3585
// // SearchProductsViewController.swift // Ágora // // Created by Clerton Leal on 20/08/16. // Copyright © 2016 Avenue Code. All rights reserved. // import UIKit protocol SearchDelegate { func itemsSelected(products: [Product]) } class SearchProductViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet var myTableView: UITableView! var initialList = ProductStore.getAllProducts() var list = ProductStore.getAllProducts() var delegate: SearchDelegate? override func prefersStatusBarHidden() -> Bool { return true } @IBAction func cancelAction(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func addAction(sender: UIBarButtonItem) { if delegate != nil { let coisas = initialList.filter({ (p) -> Bool in return p.checked }) delegate?.itemsSelected(coisas) self.dismissViewControllerAnimated(true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() myTableView.allowsMultipleSelection = true } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return list.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("myCell")! as UITableViewCell let product = list[indexPath.row] if (product.checked) { cell.accessoryType = UITableViewCellAccessoryType.Checkmark } else { cell.accessoryType = UITableViewCellAccessoryType.None } cell.selectionStyle = .None cell.textLabel?.text = product.name return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark var product = list[indexPath.row] product.checked = true initialList = initialList.map { (Product) -> Product in if (product.name == Product.name) { return product; } return Product } searchBar.resignFirstResponder() } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None var product = list[indexPath.row] product.checked = false initialList = initialList.map { (Product) -> Product in if (product.name == Product.name) { return product; } return Product } searchBar.resignFirstResponder() } func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { let searchText = self.searchBar.text! + text if (searchText.isEmpty || (text.isEmpty) && searchText.characters.count == 1) { list = initialList } else { list = initialList.filter { (Product) -> Bool in return Product.name.containsString(searchText) } } self.myTableView.reloadData() return true } }
apache-2.0
bravelocation/yeltzland-ios
yeltzland/MainSplitViewController.swift
1
5320
// // MainSplitViewController.swift // Yeltzland // // Created by John Pollard on 01/11/2020. // Copyright © 2020 John Pollard. All rights reserved. // import UIKit #if canImport(SwiftUI) import Combine #endif class MainSplitViewController: UISplitViewController { private lazy var navigationCommandSubscriber: Any? = nil private lazy var reloadCommandSubscriber: Any? = nil private lazy var historyCommandSubscriber: Any? = nil var sidebarViewController: UIViewController! init?(tabController: MainTabBarController) { if #available(iOS 14.0, *) { super.init(style: .doubleColumn) self.sidebarViewController = SidebarViewController() self.primaryBackgroundStyle = .sidebar self.preferredDisplayMode = .oneOverSecondary self.setViewController(self.sidebarViewController, for: .primary) let initalView = self.initialSecondaryView() self.setViewController(initalView, for: .secondary) self.setViewController(tabController, for: .compact) // Set color of expand button and expanders self.view.tintColor = UIColor.white self.setupMenuCommandHandler() } else { super.init(coder: NSCoder()) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initialSecondaryView() -> UIViewController { let webViewController = WebPageViewController() webViewController.navigationElement = NavigationManager.shared.mainSection.elements.first return UINavigationController(rootViewController: webViewController) } } // MARK: - Menu options extension MainSplitViewController { func setupMenuCommandHandler() { if #available(iOS 14.0, *) { self.navigationCommandSubscriber = NotificationCenter.default.publisher(for: .navigationCommand) .receive(on: RunLoop.main) .sink(receiveValue: { notification in if let sender = notification.object as? UIKeyCommand { if let keyInput = sender.input, let sidebarVC = self.sidebarViewController as? SidebarViewController { if let inputValue = Int(keyInput) { sidebarVC.handleMainKeyboardCommand(inputValue) } else { sidebarVC.handleOtherKeyboardCommand(keyInput) } } } }) self.reloadCommandSubscriber = NotificationCenter.default.publisher(for: .reloadCommand) .receive(on: RunLoop.main) .sink(receiveValue: { _ in print("Handle reload command ...") if let sidebarVC = self.sidebarViewController as? SidebarViewController { sidebarVC.handleReloadKeyboardCommand() } }) self.historyCommandSubscriber = NotificationCenter.default.publisher(for: .historyCommand) .receive(on: RunLoop.main) .sink(receiveValue: { notification in if let command = notification.object as? UIKeyCommand, let sidebarVC = self.sidebarViewController as? SidebarViewController { sidebarVC.handleHistoryKeyboardCommand(sender: command) } }) } } func isBackMenuEnabled() -> Bool { if #available(iOS 14.0, *) { if let sidebarVC = self.sidebarViewController as? SidebarViewController, let webViewController = sidebarVC.currentWebController() { return webViewController.webView?.canGoBack ?? false } } return false } func isForwardMenuEnabled() -> Bool { if #available(iOS 14.0, *) { if let sidebarVC = self.sidebarViewController as? SidebarViewController, let webViewController = sidebarVC.currentWebController() { return webViewController.webView?.canGoForward ?? false } } return false } func isHomeMenuEnabled() -> Bool { if #available(iOS 14.0, *) { if let sidebarVC = self.sidebarViewController as? SidebarViewController { return sidebarVC.currentWebController() != nil } } return false } } // MARK: - UIResponder function extension MainSplitViewController { /// Description Restores the tab state based on the juser activity /// - Parameter activity: Activity state to restore override func restoreUserActivityState(_ activity: NSUserActivity) { print("Restoring user activity in split controller [\(activity.activityType)] ...") // Pass through directly to sidebar controller if #available(iOS 14.0, *) { if let sidebarVC = self.sidebarViewController as? SidebarViewController { sidebarVC.restoreUserActivity(activity) } } } }
mit
VBVMI/VerseByVerse-iOS
Pods/VimeoNetworking/VimeoNetworking/Sources/Scope.swift
1
2388
// // Scope.swift // VimeoNetworkingExample-iOS // // Created by Huebner, Rob on 3/23/16. // Copyright © 2016 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `Scope` describes a permission that your application requests from the API public enum Scope: String { /// View public videos case Public = "public" /// View private videos case Private = "private" /// View Vimeo On Demand purchase history case Purchased = "purchased" /// Create new videos, groups, albums, etc. case Create = "create" /// Edit videos, groups, albums, etc. case Edit = "edit" /// Delete videos, groups, albums, etc. case Delete = "delete" /// Interact with a video on behalf of a user, such as liking a video or adding it to your watch later queue case Interact = "interact" /// Upload a video case Upload = "upload" /** Combines an array of scopes into a scope string as expected by the api - parameter scopes: an array of `Scope` values - returns: a string of space-separated scope strings */ public static func combine(_ scopes: [Scope]) -> String { return scopes.map({ $0.rawValue }).joined(separator: " ") } }
mit
CraigZheng/KomicaViewer
KomicaViewer/KomicaViewer/ViewController/SettingsTableViewController.swift
1
11206
// // SettingsTableViewController.swift // KomicaViewer // // Created by Craig Zheng on 15/12/16. // Copyright © 2016 Craig. All rights reserved. // import UIKit import StoreKit import SwiftMessages import MBProgressHUD class SettingsTableViewController: UITableViewController { fileprivate let cellIdentifier = "cellIdentifier" fileprivate let remoteActionCellIdentifier = "remoteActionCellIdentifier" fileprivate let selectedIndexPathKey = "selectedIndexPathKey" fileprivate let iapRemoveAd = "com.craig.KomicaViewer.removeAdvertisement" fileprivate var lastSectionIndex: Int { return numberOfSections(in: tableView) - 1 } fileprivate var iapProducts: [SKProduct] = [] fileprivate var isDownloading = false fileprivate var overrideLoadingIndicator = true fileprivate enum Section: Int { case settings, remoteActions } override func viewDidLoad() { super.viewDidLoad() let productIdentifiers: Set<ProductIdentifier> = [iapRemoveAd] overrideLoadingIndicator = false showLoading() IAPHelper.sharedInstance.requestProducts(productIdentifiers) { [weak self] (response, error) in DispatchQueue.main.async { self?.hideLoading() self?.overrideLoadingIndicator = true if let response = response, !response.products.isEmpty { // Reload tableView with the newly downloaded product. self?.iapProducts.append(contentsOf: response.products) if let product = self?.iapProducts.first { self?.removeAdCell.textLabel?.text = product.localizedTitle self?.removeAdCell.detailTextLabel?.text = product.localizedPrice() } self?.tableView.reloadData() } } } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: Configuration.updatedNotification), object: nil, queue: OperationQueue.main) { [weak self] _ in self?.tableView.reloadData() } } override func showLoading() { isDownloading = true if overrideLoadingIndicator { // Show on the highest level, block all user interactions. MBProgressHUD.showAdded(to: self.navigationController?.view ?? self.view, animated: true) } else { super.showLoading() } } override func hideLoading() { isDownloading = false MBProgressHUD.hideAllHUDs(for: self.navigationController?.view ?? self.view, animated: true) super.hideLoading() } // MARK: - UI elements. @IBOutlet weak var showImageSwitch: UISwitch! { didSet { showImageSwitch.setOn(Configuration.singleton.showImage, animated: false) } } @IBOutlet weak var removeAdCell: UITableViewCell! @IBOutlet weak var restorePurchaseCell: UITableViewCell! @IBOutlet weak var noAdvertisementCell: UITableViewCell! // MARK: - UI actions. @IBAction func showImageSwitchAction(_ sender: AnyObject) { Configuration.singleton.showImage = showImageSwitch.isOn } // MARK: - Table view data source override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch Section(rawValue: indexPath.section)! { case .settings: // When IAP product is empty or the product is already purchased, don't show the removeAdCell and restorePurchaseCell. let cell = super.tableView(tableView, cellForRowAt: indexPath) switch cell { case restorePurchaseCell, removeAdCell: return iapProducts.isEmpty || AdConfiguration.singleton.isAdRemovePurchased ? 0 : UITableViewAutomaticDimension case noAdvertisementCell: return AdConfiguration.singleton.isAdRemovePurchased ? UITableViewAutomaticDimension : 0 default: return UITableViewAutomaticDimension } case .remoteActions: return CGFloat(Configuration.singleton.remoteActions.count * 44) + 20 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .settings: // TODO: settings. return super.tableView(tableView, cellForRowAt: indexPath) case .remoteActions: let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.textLabel?.text = "App Version: " + Configuration.bundleVersion return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // When the app is performing network task, don't interrupt. if isDownloading { return } // Remote action section. if indexPath.section == lastSectionIndex, let urlString = Configuration.singleton.remoteActions[indexPath.row].values.first, let url = URL(string: urlString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } else { if let cell = tableView.cellForRow(at: indexPath) { switch cell { case removeAdCell: // Initiate purchasing. if let product = self.iapProducts.first { showLoading() IAPHelper.sharedInstance.purchaseProduct(product.productIdentifier) { [weak self] (purchasedIdentifier, error) in if let purchasedIdentifier = purchasedIdentifier, !purchasedIdentifier.isEmpty { // Inform success. AdConfiguration.singleton.isAdRemovePurchased = true self?.tableView.reloadData() MessagePopup.showMessage(title: "Payment Made", message: "You've acquired this item: \(product.localizedTitle)", layout: .cardView, theme: .success, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } else { self?.handle(error) } self?.hideLoading() } } break case restorePurchaseCell: // Restore purchase. if let product = self.iapProducts.first { showLoading() IAPHelper.sharedInstance.restorePurchases({ [weak self] (productIdentifiers, error) in self?.hideLoading() if productIdentifiers.contains(product.productIdentifier) { // Restoration successful. AdConfiguration.singleton.isAdRemovePurchased = true self?.tableView.reloadData() MessagePopup.showMessage(title: "Restoration Successful", message: "You've acquired this item: \(product.localizedTitle)", layout: .cardView, theme: .success, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } else if let error = error { self?.handle(error) } else { // Network transaction was successful, but no purchase is recorded. MessagePopup.showMessage(title: "Failed To Restore", message: "There is no previous payment made by this account, please verify your account and try again.", layout: .cardView, theme: .error, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } }) } break default: break } } } } private func handle(_ error: Error?) { if let error = error as? NSError, let errorCode = SKError.Code(rawValue: error.code) { // If user cancels the transaction, no need to display any error. var message: String? switch errorCode { case .paymentCancelled: message = nil default: message = error.localizedFailureReason ?? error.localizedDescription } if let message = message, !message.isEmpty { MessagePopup.showMessage(title: "Failed To Purchase", message: "Cannot make a payment due to the following reason: \n\(message)", layout: .cardView, theme: .error, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } } else { // Generic error. MessagePopup.showMessage(title: "Failed To Connect", message: "The connection to the server seems to be broken, please try again later.", layout: .cardView, theme: .error, position: .bottom, buttonTitle: "OK", buttonActionHandler: { _ in SwiftMessages.hide() }) } } }
mit
erprashantrastogi/iPadCustomKeyboard
Keyboard/Helper/CircularArray.swift
2
1275
// // CircularArray.swift // ELDeveloperKeyboard // // Created by Eric Lin on 2014-07-02. // Copyright (c) 2016 Kari Kraam. All rights reserved. // /** A circular array that can be cycled through. */ class CircularArray<T> { // MARK: Properties private let items: [T] private lazy var index = 0 var currentItem: T? { if items.count == 0 { return nil } return items[index] } var nextItem: T? { if items.count == 0 { return nil } return index + 1 == items.count ? items[0] : items[index + 1] } var previousItem: T? { if items.count == 0 { return nil } return index == 0 ? items[items.count - 1] : items[index - 1] } // MARK: Constructors init(items: [T]) { self.items = items } // MARK: Methods func increment() { if items.count > 0 { index += 1 if index == items.count { index = 0 } } } func decrement() { if items.count > 0 { index -= 1 if index < 0 { index = items.count - 1 } } } }
apache-2.0
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01556-resolvetypedecl.swift
1
226
// 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 < { { } class a<T where T : A class A<T where H : b
mit
Fenrikur/ef-app_ios
Domain Model/EurofurenceModel/Private/RemoteNotificationRegistrationController.swift
1
1240
import EventBus import Foundation class RemoteNotificationRegistrationController { private let remoteNotificationsTokenRegistration: RemoteNotificationsTokenRegistration? private var deviceToken: Data? private var authenticationToken: String? init(eventBus: EventBus, remoteNotificationsTokenRegistration: RemoteNotificationsTokenRegistration?) { self.remoteNotificationsTokenRegistration = remoteNotificationsTokenRegistration eventBus.subscribe(consumer: BlockEventConsumer(block: remoteNotificationRegistrationSucceeded)) eventBus.subscribe(consumer: BlockEventConsumer(block: userDidLogin)) } private func reregisterNotificationToken() { remoteNotificationsTokenRegistration?.registerRemoteNotificationsDeviceToken(deviceToken, userAuthenticationToken: authenticationToken) { (_) in } } private func remoteNotificationRegistrationSucceeded(_ event: DomainEvent.RemoteNotificationTokenAvailable) { deviceToken = event.deviceToken reregisterNotificationToken() } private func userDidLogin(_ event: DomainEvent.LoggedIn) { authenticationToken = event.authenticationToken reregisterNotificationToken() } }
mit
qmathe/Confetti
Style/ButtonStyle.swift
1
261
/** Copyright (C) 2016 Quentin Mathe Date: August 2016 License: MIT */ import Foundation open class ButtonStyle: Style, RenderableAspect { func render(_ item: Item, with renderer: Renderer) -> RenderedNode { return renderer.renderButton(item) } }
mit
Fenrikur/ef-app_ios
EurofurenceTests/Director/Module Interactions/ApplicationDirectorTests.swift
1
1742
@testable import Eurofurence import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class ApplicationDirectorTests: XCTestCase { var context: ApplicationDirectorTestBuilder.Context! override func setUp() { super.setUp() context = ApplicationDirectorTestBuilder().build() } func testWhenKnowledgeEntrySelectsWebLinkTheWebModuleIsPresentedOntoTheTabInterface() { context.navigateToTabController() let entry = FakeKnowledgeEntry.random context.knowledgeListModule.simulateKnowledgeGroupSelected(.random) context.knowledgeGroupEntriesModule.simulateKnowledgeEntrySelected(.random) let link = entry.links.randomElement().element let url = URL.random context.linkRouter.stubContent(.web(url), for: link) context.knowledgeDetailModule.simulateLinkSelected(link) let webModuleForURL = context.webModuleProviding.producedWebModules[url] XCTAssertNotNil(webModuleForURL) XCTAssertEqual(webModuleForURL, context.tabModule.stubInterface.capturedPresentedViewController) } func testWhenKnowledgeEntrySelectsExternalAppLinkTheURLLauncherIsToldToHandleTheURL() { context.navigateToTabController() let entry = FakeKnowledgeEntry.random context.knowledgeListModule.simulateKnowledgeGroupSelected(.random) context.knowledgeGroupEntriesModule.simulateKnowledgeEntrySelected(.random) let link = entry.links.randomElement().element let url = URL.random context.linkRouter.stubContent(.externalURL(url), for: link) context.knowledgeDetailModule.simulateLinkSelected(link) XCTAssertEqual(url, context.urlOpener.capturedURLToOpen) } }
mit
TurfDb/Turf
Turf/Migrations/CollectionMigration.swift
1
265
public protocol CollectionMigration { var collectionName: String { get } var fromSchemaVersion: UInt64 { get } var toSchemaVersion: UInt64 { get } func migrate(serializedValue: Data, key: String, operations: CollectionMigrationOperations) throws }
mit
KevinYangGit/DYTV
DYZB/DYZB/Classes/Main/Controller/CustomNavigationController.swift
1
1134
// // CustomNavigationController.swift // DYZB // // Created by boxfishedu on 2016/10/22. // Copyright © 2016年 杨琦. All rights reserved. // import UIKit class CustomNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() guard let systemGes = interactivePopGestureRecognizer else { return } guard let v = systemGes.view else { return } let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targetObjc = targets?.first else { return } guard let target = targetObjc.value(forKey: "target") else { return } let action = Selector(("handleNavigationTransition:")) let panGes = UIPanGestureRecognizer() v.addGestureRecognizer(panGes) panGes.addTarget(target, action: action) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.hidesBottomBarWhenPushed = true super.pushViewController(viewController, animated: animated) } }
mit
ALiOSDev/ALTableView
ALTableViewSwift/ALTableView/ALTableView/ALTableViewClasses/Elements/Row/ALRowElement.swift
1
4028
// // RowElement.swift // ALTableView // // Created by lorenzo villarroel perez on 7/3/18. // Copyright © 2018 lorenzo villarroel perez. All rights reserved. // import UIKit public typealias ALCellPressedHandler = (UIViewController?, UITableViewCell) -> Void public typealias ALCellCreatedHandler = (Any?, UITableViewCell) -> Void public typealias ALCellDeselectedHandler = (UITableViewCell) -> Void //Implemented by ALRowElement public protocol ALRowElementProtocol { func rowElementPressed(viewController: UIViewController?, cell: UITableViewCell) func rowElementDeselected(cell: UITableViewCell) } //Implemented by UITableViewCell public protocol ALCellProtocol { func cellPressed (viewController: UIViewController?) -> Void func cellDeselected () -> Void func cellCreated(dataObject: Any?) -> Void } extension ALCellProtocol { public func cellPressed (viewController: UIViewController?) -> Void { } public func cellDeselected () -> Void { } public func cellCreated(dataObject: Any?) -> Void { print("ALCellProtocol") } } public class ALRowElement: ALElement, ALRowElementProtocol { //MARK: - Properties private var className: AnyClass //TODO es posible que el className no sea necesario private let cellStyle: UITableViewCell.CellStyle internal var editingAllowed: Bool private var pressedHandler: ALCellPressedHandler? private var createdHandler: ALCellCreatedHandler? private var deselectedHandler: ALCellDeselectedHandler? //MARK: - Initializers public init(className: AnyClass, identifier: String, dataObject: Any?, cellStyle: UITableViewCell.CellStyle = .default, estimateHeightMode: Bool = false, height: CGFloat = 44.0, editingAllowed: Bool = false, pressedHandler: ALCellPressedHandler? = nil, createdHandler: ALCellCreatedHandler? = nil, deselectedHandler: ALCellDeselectedHandler? = nil) { self.className = className self.cellStyle = cellStyle self.editingAllowed = editingAllowed self.pressedHandler = pressedHandler self.createdHandler = createdHandler self.deselectedHandler = deselectedHandler super.init(identifier: identifier, dataObject: dataObject, estimateHeightMode: estimateHeightMode, height: height) } //MARK: - Getters internal func getViewFrom(tableView: UITableView) -> UITableViewCell { guard let dequeuedElement: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: self.identifier) else { return UITableViewCell() } if let alCell = dequeuedElement as? ALCellProtocol { object_setClass(alCell, self.className) alCell.cellCreated(dataObject: self.dataObject) } if let handler:ALCellCreatedHandler = self.createdHandler { handler(self.dataObject, dequeuedElement) } return dequeuedElement } //MARK: - Setters internal func setCellHeight(height: CGFloat) -> Void { self.height = height } //MARK: - ALRowElementProtocol public func rowElementPressed(viewController: UIViewController?, cell: UITableViewCell) { if let cell: ALCellProtocol = cell as? ALCellProtocol { cell.cellPressed(viewController: viewController) } if let handler:ALCellPressedHandler = self.pressedHandler { handler(viewController, cell) } } public func rowElementDeselected(cell: UITableViewCell) { if let cell: ALCellProtocol = cell as? ALCellProtocol { cell.cellDeselected() } if let handler: ALCellDeselectedHandler = self.deselectedHandler { handler(cell) } } }
mit
SheffieldKevin/SwiftGraphics
SwiftGraphics_UnitTests/SwiftUtilities_Tests.swift
1
3445
// // SwiftUtilities_Tests.swift // SwiftUtilities Tests // // Created by Jonathan Wight on 8/12/14. // Copyright (c) 2014 schwa.io. All rights reserved. // import Cocoa import XCTest import SwiftUtilities class SwiftUtilities_Tests: XCTestCase { // override func setUp() { // super.setUp() // // Put setup code here. This method is called before the invocation of each test method in the class. // } // // override func tearDown() { // // Put teardown code here. This method is called after the invocation of each test method in the class. // super.tearDown() // } func testCGPointExtensions() { let value1 = CGPoint(x: 10) XCTAssertNotEqual(value1, CGPoint.zero) XCTAssertEqual(value1, CGPoint(x: 10, y: 0)) let value2 = value1 + CGPoint(y: 20) XCTAssertEqual(value2, CGPoint(x: 10, y: 20)) let value3 = value2 * 2 XCTAssertEqual(value3, CGPoint(x: 20, y: 40)) let value4 = value3 - CGPoint(x: 1, y: 1) XCTAssertEqual(value4, CGPoint(x: 19, y: 39)) } func testCGSizeExtensions() { let value1 = CGSize(width: 10) XCTAssertNotEqual(value1, CGSize.zero) XCTAssertEqual(value1, CGSize(width: 10, height: 0)) let value2 = value1 + CGSize(height: 20) XCTAssertEqual(value2, CGSize(width: 10, height: 20)) let value3 = value2 * 2 XCTAssertEqual(value3, CGSize(width: 20, height: 40)) } func testCGRectExtensions() { let value1 = CGRect(width: 100, height: 200) XCTAssertEqual(value1, CGRect(x: 0, y: 0, width: 100, height: 200)) let value2 = CGRect(size: CGSize(width: 100, height: 200)) XCTAssertEqual(value2, CGRect(x: 0, y: 0, width: 100, height: 200)) } func testQuadrants() { XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 10, y: 10)), Quadrant.TopRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: -10, y: 10)), Quadrant.TopLeft) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 10, y: -10)), Quadrant.BottomRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: -10, y: -10)), Quadrant.BottomLeft) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 0, y: 0)), Quadrant.TopRight) let origin = CGPoint(x: 10, y: 10) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 15, y: 15), origin: origin), Quadrant.TopRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 5, y: 15), origin: origin), Quadrant.TopLeft) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 15, y: 5), origin: origin), Quadrant.BottomRight) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 5, y: 5), origin: origin), Quadrant.BottomLeft) let rect = CGRect(width: 100, height: 50) XCTAssertEqual(Quadrant.fromPoint(CGPoint(x: 15, y: 15), rect: rect), Quadrant.BottomLeft) XCTAssertEqual(Quadrant.TopRight.quadrantRectOfRect(rect), CGRect(x: 50, y: 25, width: 50, height: 25)) XCTAssertEqual(Quadrant.BottomLeft.quadrantRectOfRect(rect), CGRect(x: 0, y: 0, width: 50, height: 25)) } func testBoolEnum() { let b = BoolEnum(false) XCTAssertEqual(b, false) XCTAssertEqual(b, BoolEnum.False) } // func testPerformanceExample() { // // This is an example of a performance test case. // self.measureBlock() { // // Put the code you want to measure the time of here. // } // } }
bsd-2-clause
abbeycode/Carthage
Source/carthage/Build.swift
1
8740
// // Build.swift // Carthage // // Created by Justin Spahr-Summers on 2014-10-11. // Copyright (c) 2014 Carthage. All rights reserved. // import Box import CarthageKit import Commandant import Foundation import Result import ReactiveCocoa import ReactiveTask public struct BuildCommand: CommandType { public let verb = "build" public let function = "Build the project's dependencies" public func run(mode: CommandMode) -> Result<(), CommandantError<CarthageError>> { return producerWithOptions(BuildOptions.evaluate(mode)) |> flatMap(.Merge) { options in return self.buildWithOptions(options) |> promoteErrors } |> waitOnCommand } /// Builds a project with the given options. public func buildWithOptions(options: BuildOptions) -> SignalProducer<(), CarthageError> { return self.openLoggingHandle(options) |> flatMap(.Merge) { (stdoutHandle, temporaryURL) -> SignalProducer<(), CarthageError> in let directoryURL = NSURL.fileURLWithPath(options.directoryPath, isDirectory: true)! var buildProgress = self.buildProjectInDirectoryURL(directoryURL, options: options) |> flatten(.Concat) let stderrHandle = NSFileHandle.fileHandleWithStandardError() // Redirect any error-looking messages from stdout, because // Xcode doesn't always forward them. if !options.verbose { let (stdoutProducer, stdoutSink) = SignalProducer<NSData, NoError>.buffer(0) let grepTask: BuildSchemeProducer = launchTask(TaskDescription(launchPath: "/usr/bin/grep", arguments: [ "--extended-regexp", "(warning|error|failed):" ], standardInput: stdoutProducer)) |> on(next: { taskEvent in switch taskEvent { case let .StandardOutput(data): stderrHandle.writeData(data) default: break } }) |> catch { _ in .empty } |> then(.empty) |> promoteErrors(CarthageError.self) buildProgress = buildProgress |> on(next: { taskEvent in switch taskEvent { case let .StandardOutput(data): sendNext(stdoutSink, data) default: break } }, terminated: { sendCompleted(stdoutSink) }, interrupted: { sendInterrupted(stdoutSink) }) buildProgress = SignalProducer(values: [ grepTask, buildProgress ]) |> flatten(.Merge) } let formatting = options.colorOptions.formatting return buildProgress |> on(started: { if let temporaryURL = temporaryURL { carthage.println(formatting.bullets + "xcodebuild output can be found in " + formatting.path(string: temporaryURL.path!)) } }, next: { taskEvent in switch taskEvent { case let .StandardOutput(data): stdoutHandle.writeData(data) case let .StandardError(data): stderrHandle.writeData(data) case let .Success(box): let (project, scheme) = box.value carthage.println(formatting.bullets + "Building scheme " + formatting.quote(scheme) + " in " + formatting.projectName(string: project.description)) } }) |> then(.empty) } } /// Builds the project in the given directory, using the given options. /// /// Returns a producer of producers, representing each scheme being built. private func buildProjectInDirectoryURL(directoryURL: NSURL, options: BuildOptions) -> SignalProducer<BuildSchemeProducer, CarthageError> { let project = Project(directoryURL: directoryURL) let buildProducer = project.loadCombinedCartfile() |> map { _ in project } |> catch { error in if options.skipCurrent { return SignalProducer(error: error) } else { // Ignore Cartfile loading failures. Assume the user just // wants to build the enclosing project. return .empty } } |> flatMap(.Merge) { project in return project.migrateIfNecessary(options.colorOptions) |> on(next: carthage.println) |> then(SignalProducer(value: project)) } |> flatMap(.Merge) { project in return project.buildCheckedOutDependenciesWithConfiguration(options.configuration, forPlatform: options.buildPlatform.platform) } if options.skipCurrent { return buildProducer } else { let currentProducers = buildInDirectory(directoryURL, withConfiguration: options.configuration, platform: options.buildPlatform.platform) return buildProducer |> concat(currentProducers) } } /// Opens a temporary file on disk, returning a handle and the URL to the /// file. private func openTemporaryFile() -> SignalProducer<(NSFileHandle, NSURL), NSError> { return SignalProducer.try { var temporaryDirectoryTemplate: ContiguousArray<CChar> = NSTemporaryDirectory().stringByAppendingPathComponent("carthage-xcodebuild.XXXXXX.log").nulTerminatedUTF8.map { CChar($0) } let logFD = temporaryDirectoryTemplate.withUnsafeMutableBufferPointer { (inout template: UnsafeMutableBufferPointer<CChar>) -> Int32 in return mkstemps(template.baseAddress, 4) } if logFD < 0 { return .failure(NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil)) } let temporaryPath = temporaryDirectoryTemplate.withUnsafeBufferPointer { (ptr: UnsafeBufferPointer<CChar>) -> String in return String.fromCString(ptr.baseAddress)! } let handle = NSFileHandle(fileDescriptor: logFD, closeOnDealloc: true) let fileURL = NSURL.fileURLWithPath(temporaryPath, isDirectory: false)! return .success((handle, fileURL)) } } /// Opens a file handle for logging, returning the handle and the URL to any /// temporary file on disk. private func openLoggingHandle(options: BuildOptions) -> SignalProducer<(NSFileHandle, NSURL?), CarthageError> { if options.verbose { let out: (NSFileHandle, NSURL?) = (NSFileHandle.fileHandleWithStandardOutput(), nil) return SignalProducer(value: out) } else { return openTemporaryFile() |> map { handle, URL in (handle, .Some(URL)) } |> mapError { error in let temporaryDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)! return .WriteFailed(temporaryDirectoryURL, error) } } } } public struct BuildOptions: OptionsType { public let configuration: String public let buildPlatform: BuildPlatform public let skipCurrent: Bool public let colorOptions: ColorOptions public let verbose: Bool public let directoryPath: String public static func create(configuration: String)(buildPlatform: BuildPlatform)(skipCurrent: Bool)(colorOptions: ColorOptions)(verbose: Bool)(directoryPath: String) -> BuildOptions { return self(configuration: configuration, buildPlatform: buildPlatform, skipCurrent: skipCurrent, colorOptions: colorOptions, verbose: verbose, directoryPath: directoryPath) } public static func evaluate(m: CommandMode) -> Result<BuildOptions, CommandantError<CarthageError>> { return create <*> m <| Option(key: "configuration", defaultValue: "Release", usage: "the Xcode configuration to build") <*> m <| Option(key: "platform", defaultValue: .All, usage: "the platform to build for (one of ‘all’, ‘Mac’, or ‘iOS’)") <*> m <| Option(key: "skip-current", defaultValue: true, usage: "don't skip building the Carthage project (in addition to its dependencies)") <*> ColorOptions.evaluate(m) <*> m <| Option(key: "verbose", defaultValue: false, usage: "print xcodebuild output inline") <*> m <| Option(defaultValue: NSFileManager.defaultManager().currentDirectoryPath, usage: "the directory containing the Carthage project") } } /// Represents the user’s chosen platform to build for. public enum BuildPlatform { /// Build for all available platforms. case All /// Build only for iOS. case iOS /// Build only for OS X. case Mac /// Build only for watchOS. case watchOS /// The `Platform` corresponding to this setting. public var platform: Platform? { switch self { case .All: return nil case .iOS: return .iOS case .Mac: return .Mac case .watchOS: return .watchOS } } } extension BuildPlatform: Printable { public var description: String { switch self { case .All: return "all" case .iOS: return "iOS" case .Mac: return "Mac" case .watchOS: return "watchOS" } } } extension BuildPlatform: ArgumentType { public static let name = "platform" private static let acceptedStrings: [String: BuildPlatform] = [ "Mac": .Mac, "macosx": .Mac, "iOS": .iOS, "iphoneos": .iOS, "iphonesimulator": .iOS, "watchOS": .watchOS, "watchsimulator": .watchOS, "all": .All ] public static func fromString(string: String) -> BuildPlatform? { for (key, platform) in acceptedStrings { if string.caseInsensitiveCompare(key) == NSComparisonResult.OrderedSame { return platform } } return nil } }
mit
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/SQLite.swift/Sources/SQLite/Typed/Query.swift
25
36369
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // public protocol QueryType : Expressible { var clauses: QueryClauses { get set } init(_ name: String, database: String?) } public protocol SchemaType : QueryType { static var identifier: String { get } } extension SchemaType { /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select(id, email) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ column1: Expressible, _ more: Expressible...) -> Self { return select(false, [column1] + more) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct column1: Expressible, _ more: Expressible...) -> Self { return select(true, [column1] + more) } /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select([id, email]) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ all: [Expressible]) -> Self { return select(false, all) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: [email]) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct columns: [Expressible]) -> Self { return select(true, columns) } /// Builds a copy of the query with the `SELECT *` clause applied. /// /// let users = Table("users") /// /// users.select(*) /// // SELECT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT *` clause applied. public func select(_ star: Star) -> Self { return select([star(nil, nil)]) } /// Builds a copy of the query with the `SELECT DISTINCT *` clause applied. /// /// let users = Table("users") /// /// users.select(distinct: *) /// // SELECT DISTINCT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT DISTINCT *` clause applied. public func select(distinct star: Star) -> Self { return select(distinct: [star(nil, nil)]) } /// Builds a scalar copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.select(id) /// // SELECT "id" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select<V : Value>(_ column: Expression<V>) -> ScalarQuery<V> { return select(false, [column]) } public func select<V : Value>(_ column: Expression<V?>) -> ScalarQuery<V?> { return select(false, [column]) } /// Builds a scalar copy of the query with the `SELECT DISTINCT` clause /// applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter column: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select<V : Value>(distinct column: Expression<V>) -> ScalarQuery<V> { return select(true, [column]) } public func select<V : Value>(distinct column: Expression<V?>) -> ScalarQuery<V?> { return select(true, [column]) } public var count: ScalarQuery<Int> { return select(Expression.count(*)) } } extension QueryType { fileprivate func select<Q : QueryType>(_ distinct: Bool, _ columns: [Expressible]) -> Q { var query = Q.init(clauses.from.name, database: clauses.from.database) query.clauses = clauses query.clauses.select = (distinct, columns) return query } // MARK: JOIN /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression<Bool>) -> Self { return join(table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression<Bool?>) -> Self { return join(.inner, table, on: condition) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool>) -> Self { return join(type, table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool?>) -> Self { var query = self query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible)) return query } // MARK: WHERE /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.filter(id == 1) /// // SELECT * FROM "users" WHERE ("id" = 1) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(_ predicate: Expression<Bool>) -> Self { return filter(Expression<Bool?>(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let age = Expression<Int?>("age") /// /// users.filter(age >= 35) /// // SELECT * FROM "users" WHERE ("age" >= 35) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(_ predicate: Expression<Bool?>) -> Self { var query = self query.clauses.filters = query.clauses.filters.map { $0 && predicate } ?? predicate return query } /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression<Bool>) -> Self { return `where`(Expression<Bool?>(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression<Bool?>) -> Self { return filter(predicate) } // MARK: GROUP BY /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: Expressible...) -> Self { return group(by) } /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: [Expressible]) -> Self { return group(by, nil) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression<Bool>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression<Bool?>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression<Bool>) -> Self { return group(by, Expression<Bool?>(having)) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression<Bool?>) -> Self { return group(by, having) } fileprivate func group(_ by: [Expressible], _ having: Expression<Bool?>?) -> Self { var query = self query.clauses.group = (by, having) return query } // MARK: ORDER BY /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order(email.desc, name.asc) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(_ by: Expressible...) -> Self { return order(by) } /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order([email.desc, name.asc]) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(_ by: [Expressible]) -> Self { var query = self query.clauses.order = by return query } // MARK: LIMIT/OFFSET /// Sets the LIMIT clause (and resets any OFFSET clause) on the query. /// /// let users = Table("users") /// /// users.limit(20) /// // SELECT * FROM "users" LIMIT 20 /// /// - Parameter length: The maximum number of rows to return (or `nil` to /// return unlimited rows). /// /// - Returns: A query with the given LIMIT clause applied. public func limit(_ length: Int?) -> Self { return limit(length, nil) } /// Sets LIMIT and OFFSET clauses on the query. /// /// let users = Table("users") /// /// users.limit(20, offset: 20) /// // SELECT * FROM "users" LIMIT 20 OFFSET 20 /// /// - Parameters: /// /// - length: The maximum number of rows to return. /// /// - offset: The number of rows to skip. /// /// - Returns: A query with the given LIMIT and OFFSET clauses applied. public func limit(_ length: Int, offset: Int) -> Self { return limit(length, offset) } // prevents limit(nil, offset: 5) fileprivate func limit(_ length: Int?, _ offset: Int?) -> Self { var query = self query.clauses.limit = length.map { ($0, offset) } return query } // MARK: - Clauses // // MARK: SELECT // MARK: - fileprivate var selectClause: Expressible { return " ".join([ Expression<Void>(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"), ", ".join(clauses.select.columns), Expression<Void>(literal: "FROM"), tableName(alias: true) ]) } fileprivate var joinClause: Expressible? { guard !clauses.join.isEmpty else { return nil } return " ".join(clauses.join.map { type, query, condition in " ".join([ Expression<Void>(literal: "\(type.rawValue) JOIN"), query.tableName(alias: true), Expression<Void>(literal: "ON"), condition ]) }) } fileprivate var whereClause: Expressible? { guard let filters = clauses.filters else { return nil } return " ".join([ Expression<Void>(literal: "WHERE"), filters ]) } fileprivate var groupByClause: Expressible? { guard let group = clauses.group else { return nil } let groupByClause = " ".join([ Expression<Void>(literal: "GROUP BY"), ", ".join(group.by) ]) guard let having = group.having else { return groupByClause } return " ".join([ groupByClause, " ".join([ Expression<Void>(literal: "HAVING"), having ]) ]) } fileprivate var orderClause: Expressible? { guard !clauses.order.isEmpty else { return nil } return " ".join([ Expression<Void>(literal: "ORDER BY"), ", ".join(clauses.order) ]) } fileprivate var limitOffsetClause: Expressible? { guard let limit = clauses.limit else { return nil } let limitClause = Expression<Void>(literal: "LIMIT \(limit.length)") guard let offset = limit.offset else { return limitClause } return " ".join([ limitClause, Expression<Void>(literal: "OFFSET \(offset)") ]) } // MARK: - public func alias(_ aliasName: String) -> Self { var query = self query.clauses.from = (clauses.from.name, aliasName, clauses.from.database) return query } // MARK: - Operations // // MARK: INSERT public func insert(_ value: Setter, _ more: Setter...) -> Insert { return insert([value] + more) } public func insert(_ values: [Setter]) -> Insert { return insert(nil, values) } public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert { return insert(or: onConflict, values) } public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert { return insert(onConflict, values) } fileprivate func insert(_ or: OnConflict?, _ values: [Setter]) -> Insert { let insert = values.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in (insert.columns + [setter.column], insert.values + [setter.value]) } let clauses: [Expressible?] = [ Expression<Void>(literal: "INSERT"), or.map { Expression<Void>(literal: "OR \($0.rawValue)") }, Expression<Void>(literal: "INTO"), tableName(), "".wrap(insert.columns) as Expression<Void>, Expression<Void>(literal: "VALUES"), "".wrap(insert.values) as Expression<Void>, whereClause ] return Insert(" ".join(clauses.flatMap { $0 }).expression) } /// Runs an `INSERT` statement against the query with `DEFAULT VALUES`. public func insert() -> Insert { return Insert(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), Expression<Void>(literal: "DEFAULT VALUES") ]).expression) } /// Runs an `INSERT` statement against the query with the results of another /// query. /// /// - Parameter query: A query to `SELECT` results from. /// /// - Returns: The number of updated rows and statement. public func insert(_ query: QueryType) -> Update { return Update(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), query.expression ]).expression) } // MARK: UPDATE public func update(_ values: Setter...) -> Update { return update(values) } public func update(_ values: [Setter]) -> Update { let clauses: [Expressible?] = [ Expression<Void>(literal: "UPDATE"), tableName(), Expression<Void>(literal: "SET"), ", ".join(values.map { " = ".join([$0.column, $0.value]) }), whereClause ] return Update(" ".join(clauses.flatMap { $0 }).expression) } // MARK: DELETE public func delete() -> Delete { let clauses: [Expressible?] = [ Expression<Void>(literal: "DELETE FROM"), tableName(), whereClause ] return Delete(" ".join(clauses.flatMap { $0 }).expression) } // MARK: EXISTS public var exists: Select<Bool> { return Select(" ".join([ Expression<Void>(literal: "SELECT EXISTS"), "".wrap(expression) as Expression<Void> ]).expression) } // MARK: - /// Prefixes a column expression with the query’s table name or alias. /// /// - Parameter column: A column expression. /// /// - Returns: A column expression namespaced with the query’s table name or /// alias. public func namespace<V>(_ column: Expression<V>) -> Expression<V> { return Expression(".".join([tableName(), column]).expression) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Expression<Blob> { return namespace(column) } public subscript(column: Expression<Blob?>) -> Expression<Blob?> { return namespace(column) } public subscript(column: Expression<Bool>) -> Expression<Bool> { return namespace(column) } public subscript(column: Expression<Bool?>) -> Expression<Bool?> { return namespace(column) } public subscript(column: Expression<Double>) -> Expression<Double> { return namespace(column) } public subscript(column: Expression<Double?>) -> Expression<Double?> { return namespace(column) } public subscript(column: Expression<Int>) -> Expression<Int> { return namespace(column) } public subscript(column: Expression<Int?>) -> Expression<Int?> { return namespace(column) } public subscript(column: Expression<Int64>) -> Expression<Int64> { return namespace(column) } public subscript(column: Expression<Int64?>) -> Expression<Int64?> { return namespace(column) } public subscript(column: Expression<String>) -> Expression<String> { return namespace(column) } public subscript(column: Expression<String?>) -> Expression<String?> { return namespace(column) } /// Prefixes a star with the query’s table name or alias. /// /// - Parameter star: A literal `*`. /// /// - Returns: A `*` expression namespaced with the query’s table name or /// alias. public subscript(star: Star) -> Expression<Void> { return namespace(star(nil, nil)) } // MARK: - // TODO: alias support func tableName(alias aliased: Bool = false) -> Expressible { guard let alias = clauses.from.alias , aliased else { return database(namespace: clauses.from.alias ?? clauses.from.name) } return " ".join([ database(namespace: clauses.from.name), Expression<Void>(literal: "AS"), Expression<Void>(alias) ]) } func tableName(qualified: Bool) -> Expressible { if qualified { return tableName() } return Expression<Void>(clauses.from.alias ?? clauses.from.name) } func database(namespace name: String) -> Expressible { let name = Expression<Void>(name) guard let database = clauses.from.database else { return name } return ".".join([Expression<Void>(database), name]) } public var expression: Expression<Void> { let clauses: [Expressible?] = [ selectClause, joinClause, whereClause, groupByClause, orderClause, limitOffsetClause ] return " ".join(clauses.flatMap { $0 }).expression } } // TODO: decide: simplify the below with a boxed type instead /// Queries a collection of chainable helper functions and expressions to build /// executable SQL statements. public struct Table : SchemaType { public static let identifier = "TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct View : SchemaType { public static let identifier = "VIEW" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct VirtualTable : SchemaType { public static let identifier = "VIRTUAL TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc. public struct ScalarQuery<V> : QueryType { public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: decide: simplify the below with a boxed type instead public struct Select<T> : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Insert : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Update : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Delete : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } extension Connection { public func prepare(_ query: QueryType) throws -> AnySequence<Row> { let expression = query.expression let statement = try prepare(expression.template, expression.bindings) let columnNames: [String: Int] = try { var (columnNames, idx) = ([String: Int](), 0) column: for each in query.clauses.select.columns { var names = each.expression.template.characters.split { $0 == "." }.map(String.init) let column = names.removeLast() let namespace = names.joined(separator: ".") func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) { return { (query: QueryType) throws -> (Void) in var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database) q.clauses.select = query.clauses.select let e = q.expression var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() } if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } } for name in names { columnNames[name] = idx; idx += 1 } } } if column == "*" { var select = query select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible]) let queries = [select] + query.clauses.join.map { $0.query } if !namespace.isEmpty { for q in queries { if q.tableName().expression.template == namespace { try expandGlob(true)(q) continue column } } fatalError("no such table: \(namespace)") } for q in queries { try expandGlob(query.clauses.join.count > 0)(q) } continue } columnNames[each.expression.template] = idx idx += 1 } return columnNames }() return AnySequence { AnyIterator { statement.next().map { Row(columnNames, $0) } } } } public func scalar<V : Value>(_ query: ScalarQuery<V>) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(_ query: ScalarQuery<V?>) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func scalar<V : Value>(_ query: Select<V>) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(_ query: Select<V?>) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func pluck(_ query: QueryType) throws -> Row? { return try prepare(query.limit(1, query.clauses.limit?.offset)).makeIterator().next() } /// Runs an `Insert` query. /// /// - SeeAlso: `QueryType.insert(value:_:)` /// - SeeAlso: `QueryType.insert(values:)` /// - SeeAlso: `QueryType.insert(or:_:)` /// - SeeAlso: `QueryType.insert()` /// /// - Parameter query: An insert query. /// /// - Returns: The insert’s rowid. @discardableResult public func run(_ query: Insert) throws -> Int64 { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.lastInsertRowid } } /// Runs an `Update` query. /// /// - SeeAlso: `QueryType.insert(query:)` /// - SeeAlso: `QueryType.update(values:)` /// /// - Parameter query: An update query. /// /// - Returns: The number of updated rows. @discardableResult public func run(_ query: Update) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } /// Runs a `Delete` query. /// /// - SeeAlso: `QueryType.delete()` /// /// - Parameter query: A delete query. /// /// - Returns: The number of deleted rows. @discardableResult public func run(_ query: Delete) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } } public struct Row { fileprivate let columnNames: [String: Int] fileprivate let values: [Binding?] fileprivate init(_ columnNames: [String: Int], _ values: [Binding?]) { self.columnNames = columnNames self.values = values } /// Returns a row’s value for the given column. /// /// - Parameter column: An expression representing a column selected in a Query. /// /// - Returns: The value for the given column. public func get<V: Value>(_ column: Expression<V>) -> V { return get(Expression<V?>(column))! } public func get<V: Value>(_ column: Expression<V?>) -> V? { func valueAtIndex(_ idx: Int) -> V? { guard let value = values[idx] as? V.Datatype else { return nil } return (V.fromDatatypeValue(value) as? V)! } guard let idx = columnNames[column.template] else { let similar = Array(columnNames.keys).filter { $0.hasSuffix(".\(column.template)") } switch similar.count { case 0: fatalError("no such column '\(column.template)' in columns: \(columnNames.keys.sorted())") case 1: return valueAtIndex(columnNames[similar[0]]!) default: fatalError("ambiguous column '\(column.template)' (please disambiguate: \(similar))") } } return valueAtIndex(idx) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Blob { return get(column) } public subscript(column: Expression<Blob?>) -> Blob? { return get(column) } public subscript(column: Expression<Bool>) -> Bool { return get(column) } public subscript(column: Expression<Bool?>) -> Bool? { return get(column) } public subscript(column: Expression<Double>) -> Double { return get(column) } public subscript(column: Expression<Double?>) -> Double? { return get(column) } public subscript(column: Expression<Int>) -> Int { return get(column) } public subscript(column: Expression<Int?>) -> Int? { return get(column) } public subscript(column: Expression<Int64>) -> Int64 { return get(column) } public subscript(column: Expression<Int64?>) -> Int64? { return get(column) } public subscript(column: Expression<String>) -> String { return get(column) } public subscript(column: Expression<String?>) -> String? { return get(column) } } /// Determines the join operator for a query’s `JOIN` clause. public enum JoinType : String { /// A `CROSS` join. case cross = "CROSS" /// An `INNER` join. case inner = "INNER" /// A `LEFT OUTER` join. case leftOuter = "LEFT OUTER" } /// ON CONFLICT resolutions. public enum OnConflict: String { case replace = "REPLACE" case rollback = "ROLLBACK" case abort = "ABORT" case fail = "FAIL" case ignore = "IGNORE" } // MARK: - Private public struct QueryClauses { var select = (distinct: false, columns: [Expression<Void>(literal: "*") as Expressible]) var from: (name: String, alias: String?, database: String?) var join = [(type: JoinType, query: QueryType, condition: Expressible)]() var filters: Expression<Bool?>? var group: (by: [Expressible], having: Expression<Bool?>?)? var order = [Expressible]() var limit: (length: Int, offset: Int?)? fileprivate init(_ name: String, alias: String?, database: String?) { self.from = (name, alias, database) } }
mit
krzyzanowskim/Natalie
Sources/natalie/Natalie.swift
1
14239
// // Natalie.swift // Natalie // // Created by Marcin Krzyzanowski on 07/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // import Foundation struct Natalie { struct Header: CustomStringConvertible { var description: String { var output = String() output += "//\n" output += "// Autogenerated by Natalie - Storyboard Generator\n" output += "// by Marcin Krzyzanowski http://krzyzanowskim.com\n" output += "//\n" return output } } let storyboards: [StoryboardFile] let header = Header() var storyboardCustomModules: Set<String> { return Set(storyboards.lazy.flatMap { $0.storyboard.customModules }) } init(storyboards: [StoryboardFile]) { self.storyboards = storyboards assert(Set(storyboards.map { $0.storyboard.os }).count < 2) } static func process(storyboards: [StoryboardFile]) -> String { var output = String() for os in OS.allValues { let storyboardsForOS = storyboards.filter { $0.storyboard.os == os } if !storyboardsForOS.isEmpty { if storyboardsForOS.count != storyboards.count { output += "#if os(\(os.rawValue))\n" } output += Natalie(storyboards: storyboardsForOS).process(os: os) if storyboardsForOS.count != storyboards.count { output += "#endif\n" } } } return output } func process(os: OS) -> String { var output = "" output += header.description output += "import \(os.framework)\n" for module in storyboardCustomModules { output += "import \(module)\n" } output += "\n" output += "// MARK: - Storyboards\n" output += "\n" output += "extension \(os.storyboardType) {\n" for (signatureType, returnType) in os.storyboardInstantiationInfo { output += " func instantiateViewController<T: \(returnType)>(ofType type: T.Type) -> T? where T: IdentifiableProtocol {\n" output += " let instance = type.init()\n" output += " if let identifier = instance.storyboardIdentifier {\n" output += " return self.instantiate\(signatureType)(withIdentifier: identifier) as? T\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" } output += "}\n" output += "\n" output += "protocol Storyboard {\n" output += " static var storyboard: \(os.storyboardType) { get }\n" output += " static var identifier: \(os.storyboardIdentifierType) { get }\n" output += "}\n" output += "\n" output += "struct Storyboards {\n" for file in storyboards { output += file.storyboard.processStoryboard(storyboardName: file.storyboardName, os: os) } output += "}\n" output += "\n" let colors = storyboards .flatMap { $0.storyboard.colors } .filter { $0.catalog != .system } .compactMap { $0.assetName } if !colors.isEmpty { output += "// MARK: - Colors\n" output += "@available(\(os.colorOS), *)\n" output += "extension \(os.colorType) {\n" for colorName in Set(colors) { output += " static let \(swiftRepresentation(for: colorName, firstLetter: .none)) = \(os.colorType)(named: \(initIdentifier(for: os.colorNameType, value: colorName)))\n" } output += "}\n" output += "\n" } output += "// MARK: - ReusableKind\n" output += "enum ReusableKind: String, CustomStringConvertible {\n" output += " case tableViewCell = \"tableViewCell\"\n" output += " case collectionViewCell = \"collectionViewCell\"\n" output += "\n" output += " var description: String { return self.rawValue }\n" output += "}\n" output += "\n" output += "// MARK: - SegueKind\n" output += "enum SegueKind: String, CustomStringConvertible {\n" output += " case relationship = \"relationship\"\n" output += " case show = \"show\"\n" output += " case presentation = \"presentation\"\n" output += " case embed = \"embed\"\n" output += " case unwind = \"unwind\"\n" output += " case push = \"push\"\n" output += " case modal = \"modal\"\n" output += " case popover = \"popover\"\n" output += " case replace = \"replace\"\n" output += " case custom = \"custom\"\n" output += "\n" output += " var description: String { return self.rawValue }\n" output += "}\n" output += "\n" output += "// MARK: - IdentifiableProtocol\n" output += "\n" output += "public protocol IdentifiableProtocol: Equatable {\n" output += " var storyboardIdentifier: \(os.storyboardSceneIdentifierType)? { get }\n" output += "}\n" output += "\n" output += "// MARK: - SegueProtocol\n" output += "\n" output += "public protocol SegueProtocol {\n" output += " var identifier: \(os.storyboardSegueIdentifierType)? { get }\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {\n" output += " return lhs.identifier == rhs.identifier\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {\n" output += " return lhs.identifier == rhs.identifier\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: T, rhs: \(os.storyboardSegueIdentifierType)) -> Bool {\n" output += " return lhs.identifier == rhs\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: T, rhs: \(os.storyboardSegueIdentifierType)) -> Bool {\n" output += " return lhs.identifier == rhs\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: \(os.storyboardSegueIdentifierType), rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: \(os.storyboardSegueIdentifierType), rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier\n" output += "}\n" output += "\n" if os.storyboardSegueIdentifierType != "String" { output += "extension \(os.storyboardSegueIdentifierType): ExpressibleByStringLiteral {\n" output += " public typealias StringLiteralType = String\n" output += " public init(stringLiteral value: StringLiteralType) {\n" output += " self.init(rawValue: value)\n" output += " }\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {\n" output += " return lhs.identifier?.rawValue == rhs\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {\n" output += " return lhs.identifier?.rawValue == rhs\n" output += "}\n" output += "\n" output += "public func ==<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier?.rawValue\n" output += "}\n" output += "\n" output += "public func ~=<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {\n" output += " return lhs == rhs.identifier?.rawValue\n" output += "}\n" output += "\n" } output += "// MARK: - ReusableViewProtocol\n" output += "public protocol ReusableViewProtocol: IdentifiableProtocol {\n" output += " var viewType: \(os.viewType).Type? { get }\n" output += "}\n" output += "\n" output += "public func ==<T: ReusableViewProtocol, U: ReusableViewProtocol>(lhs: T, rhs: U) -> Bool {\n" output += " return lhs.storyboardIdentifier == rhs.storyboardIdentifier\n" output += "}\n" output += "\n" output += "// MARK: - Protocol Implementation\n" output += "extension \(os.storyboardSegueType): SegueProtocol {\n" output += "}\n" output += "\n" if let reusableViews = os.resuableViews { for reusableView in reusableViews { output += "extension \(reusableView): ReusableViewProtocol {\n" output += " public var viewType: UIView.Type? { return type(of: self) }\n" output += " public var storyboardIdentifier: String? { return self.reuseIdentifier }\n" output += "}\n" output += "\n" } } for controllerType in os.storyboardControllerTypes { output += "// MARK: - \(controllerType) extension\n" output += "extension \(controllerType) {\n" output += " func perform<T: SegueProtocol>(segue: T, sender: Any?) {\n" output += " if let identifier = segue.identifier {\n" output += " performSegue(withIdentifier: identifier, sender: sender)\n" output += " }\n" output += " }\n" output += "\n" output += " func perform<T: SegueProtocol>(segue: T) {\n" output += " perform(segue: segue, sender: nil)\n" output += " }\n" output += "}\n" } if os == OS.iOS { output += "// MARK: - UICollectionView\n" output += "\n" output += "extension UICollectionView {\n" output += "\n" output += " func dequeue<T: ReusableViewProtocol>(reusable: T, for: IndexPath) -> UICollectionViewCell? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableCell(withReuseIdentifier: identifier, for: `for`)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func register<T: ReusableViewProtocol>(reusable: T) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forCellWithReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "\n" output += " func dequeueReusableSupplementaryViewOfKind<T: ReusableViewProtocol>(elementKind: String, withReusable reusable: T, for: IndexPath) -> UICollectionReusableView? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableSupplementaryView(ofKind: elementKind, withReuseIdentifier: identifier, for: `for`)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func register<T: ReusableViewProtocol>(reusable: T, forSupplementaryViewOfKind elementKind: String) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "}\n" output += "// MARK: - UITableView\n" output += "\n" output += "extension UITableView {\n" output += "\n" output += " func dequeue<T: ReusableViewProtocol>(reusable: T, for: IndexPath) -> UITableViewCell? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableCell(withIdentifier: identifier, for: `for`)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func register<T: ReusableViewProtocol>(reusable: T) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forCellReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "\n" output += " func dequeueReusableHeaderFooter<T: ReusableViewProtocol>(_ reusable: T) -> UITableViewHeaderFooterView? {\n" output += " if let identifier = reusable.storyboardIdentifier {\n" output += " return dequeueReusableHeaderFooterView(withIdentifier: identifier)\n" output += " }\n" output += " return nil\n" output += " }\n" output += "\n" output += " func registerReusableHeaderFooter<T: ReusableViewProtocol>(_ reusable: T) {\n" output += " if let type = reusable.viewType, let identifier = reusable.storyboardIdentifier {\n" output += " register(type, forHeaderFooterViewReuseIdentifier: identifier)\n" output += " }\n" output += " }\n" output += "}\n" } let storyboardModules = storyboardCustomModules for file in storyboards { output += file.storyboard.processViewControllers(storyboardCustomModules: storyboardModules) } return output } }
mit
BenEmdon/swift-algorithm-club
Ternary Search Tree/TST.playground/Sources/TernarySearchTree.swift
1
2719
// // TernarySearchTree.swift // // // Created by Siddharth Atre on 3/15/16. // // import Foundation public class TernarySearchTree<Element> { var root: TSTNode<Element>? public init() {} //MARK: - Insertion public func insert(data: Element, withKey key: String) -> Bool { return insertNode(&root, withData: data, andKey: key, atIndex: 0) } private func insertNode(inout aNode: TSTNode<Element>?, withData data: Element, andKey key: String, atIndex charIndex: Int) -> Bool { //sanity check. if key.characters.count == 0 { return false } //create a new node if necessary. if aNode == nil { let index = key.startIndex.advancedBy(charIndex) aNode = TSTNode<Element>(key: key[index]) } //if current char is less than the current node's char, go left let index = key.startIndex.advancedBy(charIndex) if key[index] < aNode!.key { return insertNode(&aNode!.left, withData: data, andKey: key, atIndex: charIndex) } //if it's greater, go right. else if key[index] > aNode!.key { return insertNode(&aNode!.right, withData: data, andKey: key, atIndex: charIndex) } //current char is equal to the current nodes, go middle else { //continue down the middle. if charIndex + 1 < key.characters.count { return insertNode(&aNode!.middle, withData: data, andKey: key, atIndex: charIndex + 1) } //otherwise, all done. else { aNode!.data = data aNode?.hasData = true return true } } } //MARK: - Finding public func find(key: String) -> Element? { return findNode(root, withKey: key, atIndex: 0) } private func findNode(aNode: TSTNode<Element>?, withKey key: String, atIndex charIndex: Int) -> Element? { //Given key does not exist in tree. if aNode == nil { return nil } let index = key.startIndex.advancedBy(charIndex) //go left if key[index] < aNode!.key { return findNode(aNode!.left, withKey: key, atIndex: charIndex) } //go right else if key[index] > aNode!.key { return findNode(aNode!.right, withKey: key, atIndex: charIndex) } //go middle else { if charIndex + 1 < key.characters.count { return findNode(aNode!.middle, withKey: key, atIndex: charIndex + 1) } else { return aNode!.data } } } }
mit
AnirudhDas/AniruddhaDas.github.io
RedBus/RedBus/Model/BusesList.swift
1
3607
// // BusesList.swift // RedBus // // Created by Anirudh Das on 8/22/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation enum SortBusesBy { case ratingAscending case ratingDescending case departureTimeAscending case departureTimeDescending case fareAscending case fareDescending case none } struct BusesList { var sortBy: SortBusesBy = .none var busType: BusType? var allBuses: [BusDetail]? = [] var filteredBuses: [BusDetail] { if let allBuses = allBuses { guard let busType = busType else { return sortBusList(busList: Array(allBuses)) } //No filter added if busType.isAc == false && busType.isNonAc == false && busType.isSeater == false && busType.isSleeper == false { return sortBusList(busList: Array(allBuses)) } //Set Filters let acBuses = allBuses.filter({ busType.isAc && (busType.isAc == $0.busType.isAc) }) let nonAcBuses = allBuses.filter({ busType.isNonAc && (busType.isNonAc == $0.busType.isNonAc) }) let seaterBuses = allBuses.filter({ busType.isSeater && (busType.isSeater == $0.busType.isSeater) }) let sleeperBuses = allBuses.filter({ busType.isSleeper && (busType.isSleeper == $0.busType.isSleeper) }) let setAcBuses: Set<BusDetail> = Set(acBuses) let setNonAcBuses: Set<BusDetail> = Set(nonAcBuses) let setSeaterBuses: Set<BusDetail> = Set(seaterBuses) let setSleeperBuses: Set<BusDetail> = Set(sleeperBuses) var filteredSet = setAcBuses.union(setNonAcBuses).union(setSeaterBuses).union(setSleeperBuses) if busType.isAc { filteredSet = filteredSet.intersection(setAcBuses) } if busType.isNonAc { filteredSet = filteredSet.intersection(setNonAcBuses) } if busType.isSeater { filteredSet = filteredSet.intersection(setSeaterBuses) } if busType.isSleeper { filteredSet = filteredSet.intersection(setSleeperBuses) } return sortBusList(busList: Array(filteredSet)) } return [] } func sortBusList(busList: [BusDetail]) -> [BusDetail] { var sortedList: [BusDetail] = [] switch sortBy { case .ratingAscending: sortedList = busList.sorted(by: { return ($0.rating != -1 && $1.rating != -1) ? $0.rating < $1.rating : true }) case .ratingDescending: sortedList = busList.sorted(by: { return ($0.rating != -1 && $1.rating != -1) ? $0.rating > $1.rating : true }) case .departureTimeAscending: sortedList = busList.sorted(by: { return $0.departureTime < $1.departureTime }) case .departureTimeDescending: sortedList = busList.sorted(by: { return $0.departureTime > $1.departureTime }) case .fareAscending: sortedList = busList.sorted(by: { return $0.fare < $1.fare }) case .fareDescending: sortedList = busList.sorted(by: { return $0.fare > $1.fare }) case .none: sortedList = busList } return sortedList } }
apache-2.0
dreamsxin/swift
validation-test/stdlib/CoreAudio.swift
3
10091
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import StdlibCollectionUnittest import CoreAudio // Used in tests below. extension AudioBuffer : Equatable {} public func == (lhs: AudioBuffer, rhs: AudioBuffer) -> Bool { return lhs.mNumberChannels == rhs.mNumberChannels && lhs.mDataByteSize == rhs.mDataByteSize && lhs.mData == rhs.mData } var CoreAudioTestSuite = TestSuite("CoreAudio") // The size of the non-flexible part of an AudioBufferList. #if arch(i386) || arch(arm) let ablHeaderSize = 4 #elseif arch(x86_64) || arch(arm64) let ablHeaderSize = 8 #endif CoreAudioTestSuite.test("UnsafeBufferPointer.init(_: AudioBuffer)") { do { let audioBuffer = AudioBuffer( mNumberChannels: 0, mDataByteSize: 0, mData: nil) let result: UnsafeBufferPointer<Float> = UnsafeBufferPointer(audioBuffer) expectEqual(nil, result.baseAddress) expectEqual(0, result.count) } do { let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) let result: UnsafeBufferPointer<Float> = UnsafeBufferPointer(audioBuffer) expectEqual( UnsafePointer<Float>(audioBuffer.mData!), result.baseAddress) expectEqual(256, result.count) } } CoreAudioTestSuite.test("UnsafeMutableBufferPointer.init(_: AudioBuffer)") { do { let audioBuffer = AudioBuffer( mNumberChannels: 0, mDataByteSize: 0, mData: nil) let result: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(audioBuffer) expectEqual(nil, result.baseAddress) expectEqual(0, result.count) } do { let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) let result: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(audioBuffer) expectEqual( UnsafeMutablePointer<Float>(audioBuffer.mData!), result.baseAddress) expectEqual(256, result.count) } } CoreAudioTestSuite.test( "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)") { do { // NULL pointer. let buffer = UnsafeMutableBufferPointer<Float>(start: nil, count: 0) let result = AudioBuffer(buffer, numberOfChannels: 2) expectEqual(2, result.mNumberChannels) expectEqual(0, result.mDataByteSize) expectEqual(nil, result.mData) } do { // Non-NULL pointer. let buffer = UnsafeMutableBufferPointer<Float>( start: UnsafeMutablePointer<Float>(bitPattern: 0x1234_5678), count: 0) let result = AudioBuffer(buffer, numberOfChannels: 2) expectEqual(2, result.mNumberChannels) expectEqual(0, result.mDataByteSize) expectEqual(buffer.baseAddress, result.mData) } } CoreAudioTestSuite.test( "AudioBuffer.init(_: UnsafeMutableBufferPointer, numberOfChannels: Int)/trap") { #if arch(i386) || arch(arm) let overflowingCount = Int.max #elseif arch(x86_64) || arch(arm64) let overflowingCount = Int(UInt32.max) #endif let buffer = UnsafeMutableBufferPointer<Float>( start: UnsafeMutablePointer<Float>(bitPattern: 0x1234_5678), count: overflowingCount) expectCrashLater() // An overflow happens when we try to compute the value for mDataByteSize. _ = AudioBuffer(buffer, numberOfChannels: 2) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)") { expectEqual(ablHeaderSize + strideof(AudioBuffer), AudioBufferList.sizeInBytes(maximumBuffers: 1)) expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer), AudioBufferList.sizeInBytes(maximumBuffers: 16)) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count<0") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count==0") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/overflow") { expectCrashLater() AudioBufferList.sizeInBytes(maximumBuffers: Int.max) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { do { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 1) expectEqual(1, ablPtrWrapper.count) free(ablPtrWrapper.unsafeMutablePointer) } do { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) expectEqual(16, ablPtrWrapper.count) free(ablPtrWrapper.unsafeMutablePointer) } } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count==0") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: 0) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count<0") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/overflow") { expectCrashLater() AudioBufferList.allocate(maximumBuffers: Int.max) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/AssociatedTypes") { typealias Subject = UnsafeMutableAudioBufferListPointer expectRandomAccessCollectionAssociatedTypes( collectionType: Subject.self, iteratorType: IndexingIterator<Subject>.self, subSequenceType: MutableRandomAccessSlice<Subject>.self, indexType: Int.self, indexDistanceType: Int.self, indicesType: CountableRange<Int>.self) } CoreAudioTestSuite.test( "UnsafeMutableAudioBufferListPointer.init(_: UnsafeMutablePointer<AudioBufferList>)," + "UnsafeMutableAudioBufferListPointer.unsafePointer," + "UnsafeMutableAudioBufferListPointer.unsafeMutablePointer") { do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(nil) expectEmpty(ablPtrWrapper) } do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( UnsafeMutablePointer<AudioBufferList>(bitPattern: 0x1234_5678)!) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper.unsafePointer) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper.unsafeMutablePointer) } do { let ablPtrWrapper = UnsafeMutableAudioBufferListPointer( UnsafeMutablePointer<AudioBufferList>(bitPattern: 0x1234_5678)) expectNotEmpty(ablPtrWrapper) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper!.unsafePointer) expectEqual( UnsafePointer<AudioBufferList>(bitPattern: 0x1234_5678), ablPtrWrapper!.unsafeMutablePointer) } } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.count") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) let ablPtr = UnsafeMutablePointer<AudioBufferList>( UnsafeMutablePointer<UInt8>(allocatingCapacity: sizeInBytes)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the 'count' property has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) // Test getter. UnsafeMutablePointer<UInt32>(ablPtr).pointee = 0x1234_5678 expectEqual(0x1234_5678, ablPtrWrapper.count) // Test setter. ablPtrWrapper.count = 0x7765_4321 expectEqual(0x7765_4321, UnsafeMutablePointer<UInt32>(ablPtr).pointee) ablPtr.deallocateCapacity(sizeInBytes) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) let ablPtr = UnsafeMutablePointer<AudioBufferList>( UnsafeMutablePointer<UInt8>(allocatingCapacity: sizeInBytes)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the subscript has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) do { // Test getter. let audioBuffer = AudioBuffer( mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678)) UnsafeMutablePointer<AudioBuffer>( UnsafeMutablePointer<UInt8>(ablPtr) + ablHeaderSize ).pointee = audioBuffer ablPtrWrapper.count = 1 expectEqual(2, ablPtrWrapper[0].mNumberChannels) expectEqual(1024, ablPtrWrapper[0].mDataByteSize) expectEqual(audioBuffer.mData, ablPtrWrapper[0].mData) } do { // Test setter. let audioBuffer = AudioBuffer( mNumberChannels: 5, mDataByteSize: 256, mData: UnsafeMutablePointer<Void>(bitPattern: 0x8765_4321 as UInt)) ablPtrWrapper.count = 2 ablPtrWrapper[1] = audioBuffer let audioBufferPtr = UnsafeMutablePointer<AudioBuffer>( UnsafeMutablePointer<UInt8>(ablPtr) + ablHeaderSize) + 1 expectEqual(5, audioBufferPtr.pointee.mNumberChannels) expectEqual(256, audioBufferPtr.pointee.mDataByteSize) expectEqual(audioBuffer.mData, audioBufferPtr.pointee.mData) } ablPtr.deallocateCapacity(sizeInBytes) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)/trap") { let ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 4) ablPtrWrapper[0].mNumberChannels = 42 ablPtrWrapper[1].mNumberChannels = 42 ablPtrWrapper[2].mNumberChannels = 42 ablPtrWrapper[3].mNumberChannels = 42 expectCrashLater() ablPtrWrapper[4].mNumberChannels = 42 } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/Collection") { var ablPtrWrapper = AudioBufferList.allocate(maximumBuffers: 16) expectType(UnsafeMutableAudioBufferListPointer.self, &ablPtrWrapper) var expected: [AudioBuffer] = [] for i in 0..<16 { let audioBuffer = AudioBuffer( mNumberChannels: UInt32(2 + i), mDataByteSize: UInt32(1024 * i), mData: UnsafeMutablePointer<Void>(bitPattern: 0x1234_5678 + i * 10)) ablPtrWrapper[i] = audioBuffer expected.append(audioBuffer) } // FIXME: use checkMutableRandomAccessCollection, when we have that function. checkRandomAccessCollection(expected, ablPtrWrapper) free(ablPtrWrapper.unsafeMutablePointer) } runAllTests()
apache-2.0
dreamsxin/swift
validation-test/compiler_crashers_fixed/27728-swift-modulefile-loadextensions.swift
11
454
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse {{ struct B }struct A<T where g:e{ struct S<T{let a=B class B
apache-2.0
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Chapters/Document10.playgroundchapter/Pages/Challenge1.playgroundpage/Sources/SetUp.swift
1
3206
// // SetUp.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import Foundation // MARK: Globals public let world = loadGridWorld(named: "10.2") let actor = Actor() public var purplePortal = Portal(color: .purple) public func playgroundPrologue() { placeItems() placeActor() placePortals() // Must be called in `playgroundPrologue()` to update with the current page contents. registerAssessment(world, assessment: assessmentPoint) //// ---- // Any items added or removed after this call will be animated. finalizeWorldBuilding(for: world) //// ---- } // Called from LiveView.swift to initially set the LiveView. public func presentWorld() { setUpLiveViewWith(world) } // MARK: Epilogue public func playgroundEpilogue() { sendCommands(for: world) } func placeItems() { world.place(Switch(), at: Coordinate(column: 0, row: 1)) world.placeGems(at: world.coordinates(inColumns: [3,4,5], intersectingRows: [1])) world.placeGems(at: world.coordinates(inColumns: [3,4,5,6], intersectingRows: [4])) } func placePortals() { world.place(purplePortal, between: Coordinate(column: 2, row: 4), and: Coordinate(column: 2, row: 1)) } func placeActor() { world.place(actor, facing: east, at: Coordinate(column:0, row: 4)) } func placeBlocks() { world.removeNodes(at: world.coordinates(inColumns: [4,5,6], intersectingRows: [2,3,5,6])) world.placeWater(at: world.coordinates(inColumns: [4,5,6], intersectingRows: [2,3,5,6])) world.removeNodes(at: world.coordinates(inColumns: [6], intersectingRows: [0,1])) world.placeWater(at: world.coordinates(inColumns: [6], intersectingRows: [0,1])) world.removeNodes(at: world.coordinates(inColumns: [0,1,2,3], intersectingRows: [5])) world.placeWater(at: world.coordinates(inColumns: [0,1,2,3], intersectingRows: [5])) world.removeNodes(at: world.coordinates(inColumns: [4,5], intersectingRows: [0])) world.placeWater(at: world.coordinates(inColumns: [4,5], intersectingRows: [0])) world.placeBlocks(at: world.coordinates(inColumns: [0,1,2,3], intersectingRows: [7])) world.placeBlocks(at: world.coordinates(inColumns: [0,1,2,3], intersectingRows: [7])) world.placeBlocks(at: world.coordinates(inColumns: [1,2,3], intersectingRows: [6])) world.placeBlocks(at: world.coordinates(inColumns: [1,2,3], intersectingRows: [2,3])) world.placeBlocks(at: world.coordinates(inColumns: [0,1,2], intersectingRows: [2])) world.placeBlocks(at: world.coordinates(inColumns: [1,2,3], intersectingRows: [0])) let tiers = [ Coordinate(column: 1, row: 6), Coordinate(column: 2, row: 6), Coordinate(column: 2, row: 6), Coordinate(column: 3, row: 6), Coordinate(column: 3, row: 6), Coordinate(column: 3, row: 6), Coordinate(column: 0, row: 3) ] world.placeBlocks(at: tiers) world.removeNodes(at: world.coordinates(inColumns: [2,3], intersectingRows: [3])) world.placeWater(at: world.coordinates(inColumns: [2,3], intersectingRows: [3])) }
mit
codeforgreenville/trolley-tracker-ios-client
TrolleyTracker/Controllers/UI/Schedule/ScheduleController.swift
1
2865
// // ScheduleController.swift // TrolleyTracker // // Created by Austin Younts on 7/30/17. // Copyright © 2017 Code For Greenville. All rights reserved. // import UIKit class ScheduleController: FunctionController { enum DisplayType: Int { case route, day static var all: [DisplayType] { return [.route, .day] } static var `default`: DisplayType { return .route } } typealias Dependencies = HasModelController private let dependencies: Dependencies private let viewController: ScheduleViewController private let dataSource: ScheduleDataSource private var routeController: RouteController? private var lastFetchRequestDate: Date? init(dependencies: Dependencies) { self.dependencies = dependencies self.dataSource = ScheduleDataSource() self.viewController = ScheduleViewController() } func prepare() -> UIViewController { let type = DisplayType.default dataSource.displayType = type viewController.displayTypeControl.selectedSegmentIndex = type.rawValue dataSource.displayRouteAction = displayRoute(_:) viewController.tabBarItem.image = #imageLiteral(resourceName: "Schedule") viewController.tabBarItem.title = LS.scheduleTitle viewController.delegate = self let nav = UINavigationController(rootViewController: viewController) viewController.tableView.dataSource = dataSource viewController.tableView.delegate = dataSource loadSchedules() return nav } private func loadSchedulesIfNeeded() { guard let lastDate = lastFetchRequestDate else { loadSchedules() return } guard lastDate.isAcrossQuarterHourBoundryFromNow else { return } loadSchedules() } private func loadSchedules() { lastFetchRequestDate = Date() dependencies.modelController.loadTrolleySchedules(handleNewSchedules(_:)) } private func handleNewSchedules(_ schedules: [RouteSchedule]) { dataSource.set(schedules: schedules) viewController.tableView.reloadData() } private func displayRoute(_ routeID: Int) { routeController = RouteController(routeID: routeID, presentationContext: viewController, dependencies: dependencies) routeController?.present() } } extension ScheduleController: ScheduleVCDelegate { func viewDidAppear() { loadSchedulesIfNeeded() } func didSelectScheduleTypeIndex(_ index: Int) { let displayType = ScheduleController.DisplayType(rawValue: index)! dataSource.displayType = displayType viewController.tableView.reloadData() } }
mit
awslabs/aws-sdk-ios-samples
Lex-Sample/Swift/LexSwift/AppDelegate.swift
1
1967
// // Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://aws.amazon.com/apache2.0 // // or in the "license" file accompanying this file. This file 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 AWSCore import AWSLex import AWSMobileClient @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { AWSMobileClient.sharedInstance().initialize { (userState, error) in guard error == nil else { print("Error initializing AWSMobileClient. Error: \(error!.localizedDescription)") return } print("AWSMobileClient initialized.") } let configuration = AWSServiceConfiguration(region: LexRegion, credentialsProvider: AWSMobileClient.sharedInstance()) AWSServiceManager.default().defaultServiceConfiguration = configuration let chatConfig = AWSLexInteractionKitConfig.defaultInteractionKitConfig(withBotName: BotName, botAlias: BotAlias) AWSLexInteractionKit.register(with: configuration!, interactionKitConfiguration: chatConfig, forKey: "AWSLexVoiceButton") chatConfig.autoPlayback = false AWSLexInteractionKit.register(with: configuration!, interactionKitConfiguration: chatConfig, forKey: "chatConfig") // Override point for customization after application launch. return true } }
apache-2.0
incetro/NIO
Example/NioExample-iOS/Models/Plain/AdditivePlainObject.swift
1
825
// // AdditivePlainObject.swift // Nio // // Created by incetro on 16/07/2017. // // import NIO import Transformer // MARK: - AdditivePlainObject class AdditivePlainObject: TransformablePlain { var nioID: NioID { return NioID(value: id) } let id: Int64 let name: String let price: Double init(with name: String, price: Double, id: Int64) { self.name = name self.id = id self.price = price } var position: PositionPlainObject? = nil required init(with resolver: Resolver) throws { self.id = try resolver.value("id") self.name = try resolver.value("name") self.price = try resolver.value("price") self.position = try? resolver.value("position") } }
mit
ben-ng/swift
test/SILGen/optional_to_bool.swift
7
748
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime public protocol P {} extension Int: P {} public class A {} public class B: A { // CHECK-LABEL: sil @_TFC16optional_to_bool1Bg1x // CHECK: select_enum {{%.*}} : $Optional<Int> public lazy var x: Int = 0 // CHECK-LABEL: sil @_TFC16optional_to_bool1Bg1y // CHECK: select_enum_addr {{%.*}} : $*Optional<P> public lazy var y: P = 0 } // Collection casting is not implemented in non-ObjC runtime #if _runtime(_ObjC) // CHECK-objc-LABEL: sil @_TF16optional_to_bool3foo public func foo(x: inout [A]) -> Bool { // CHECK-objc: select_enum {{%.*}} : $Optional<Array<B>> return x is [B] } #endif
apache-2.0
raysarebest/TheDeck
The DeckTests/The_DeckTests.swift
1
906
// // The_DeckTests.swift // The DeckTests // // Created by Michael Hulet on 6/2/15. // Copyright (c) 2015 Michael Hulet. All rights reserved. // import UIKit import XCTest class The_DeckTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
agpl-3.0
quangvu1994/Exchange
Exchange/View/CreatePostCategoryCell.swift
1
370
// // CreatePostCategoryCell.swift // Exchange // // Created by Quang Vu on 7/7/17. // Copyright © 2017 Quang Vu. All rights reserved. // import UIKit class CreatePostCategoryCell: UITableViewCell { @IBOutlet weak var categoryName: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
adrfer/swift
validation-test/compiler_crashers_fixed/26496-swift-parser-skipsingle.swift
4
338
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where B:C{class d{func b{var f=b b{class b{struct B{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{a
apache-2.0
adrfer/swift
validation-test/stdlib/StdlibUnittestMisc.swift
4
580
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif // // Test OS version parsing // // CHECK: (10, 0, 0) print(_parseDottedVersionTriple("10")) // CHECK: (10, 9, 0) print(_parseDottedVersionTriple("10.9")) // CHECK: (10, 9, 3) print(_parseDottedVersionTriple("10.9.3"))
apache-2.0
mapsme/omim
iphone/Maps/Bookmarks/Catalog/Dialogs/SubscriptionExpiredViewController.swift
6
814
class SubscriptionExpiredViewController: UIViewController { private let transitioning = FadeTransitioning<AlertPresentationController>(cancellable: false) private let onSubscribe: MWMVoidBlock private let onDelete: MWMVoidBlock init(onSubscribe: @escaping MWMVoidBlock, onDelete: @escaping MWMVoidBlock) { self.onSubscribe = onSubscribe self.onDelete = onDelete super.init(nibName: nil, bundle: nil) transitioningDelegate = transitioning modalPresentationStyle = .custom } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } @IBAction func onSubscribe(_ sender: UIButton) { onSubscribe() } @IBAction func onDelete(_ sender: UIButton) { onDelete() } }
apache-2.0
CoderXiaoming/Ronaldo
SaleManager/SaleManager/Stock/Controller/SAMStockDetailController.swift
1
5147
// // SAMStockDetailController.swift // SaleManager // // Created by apple on 17/1/9. // Copyright © 2017年 YZH. All rights reserved. // import UIKit //库存明细重用标识符 private let SAMStockProductDetailCellReuseIdentifier = "SAMStockProductDetailCellReuseIdentifier" class SAMStockDetailController: UIViewController { //MARK: - 类工厂方法 class func instance(stockModel: SAMStockProductModel) -> SAMStockDetailController { let vc = SAMStockDetailController() vc.stockProductModel = stockModel //加载数据 vc.loadProductDeatilList() return vc } //MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() //设置圆角 view.layer.cornerRadius = 8 //设置标题 titleLabel.text = stockProductModel?.productIDName //设置collectionView setupCollectionView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) collectionView.reloadData() } ///设置collectionView fileprivate func setupCollectionView() { //设置数据源、代理 collectionView.dataSource = self collectionView.delegate = self collectionView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5) //注册cell collectionView.register(UINib(nibName: "SAMStockProductDetailCell", bundle: nil), forCellWithReuseIdentifier: SAMStockProductDetailCellReuseIdentifier) } //MARK: - 加载库存明细数据 fileprivate func loadProductDeatilList() { let parameters = ["productID": stockProductModel!.id, "storehouseID": "-1", "parentID": "-1"] //发送请求 SAMNetWorker.sharedNetWorker().get("getStockDetailList.ashx", parameters: parameters, progress: nil, success: {[weak self] (Task, json) in //获取模型数组 let Json = json as! [String: AnyObject] let dictArr = Json["body"] as? [[String: AnyObject]] let count = dictArr?.count ?? 0 //判断是否有模型数据 if count == 0 { //没有模型数据 }else {//有数据模型 self!.productDeatilList = SAMStockProductDeatil.mj_objectArray(withKeyValuesArray: dictArr)! } }) { (Task, Error) in } } //MARK: - 用户点击事件 @IBAction func dismissBtnClick(_ sender: UIButton) { dismiss(animated: true) { //发出通知 NotificationCenter.default.post(name: NSNotification.Name.init(SAMStockDetailControllerDismissSuccessNotification), object: nil) } } //MARK: - 属性 ///接收的库存模型 fileprivate var stockProductModel: SAMStockProductModel? ///模型数组 fileprivate var productDeatilList = NSMutableArray() //MARK: - XIB链接属性 @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var collectionView: UICollectionView! //MARK: - 其他方法 fileprivate init() { super.init(nibName: nil, bundle: nil) } fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { //从xib加载view view = Bundle.main.loadNibNamed("SAMStockDetailController", owner: self, options: nil)![0] as! UIView } } //MARK: - UICollectionViewDataSource extension SAMStockDetailController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return productDeatilList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SAMStockProductDetailCellReuseIdentifier, for: indexPath) as! SAMStockProductDetailCell //赋值模型 let model = productDeatilList[indexPath.row] as! SAMStockProductDeatil cell.productDetailModel = model return cell } } //MARK: - collectionView布局代理 extension SAMStockDetailController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 90, height: 35) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 7 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
apache-2.0
kusl/swift
validation-test/compiler_crashers_fixed/0836-resolvetypedecl.swift
13
288
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b: String { class func i<I : a { } private class a<T where T: Boole
apache-2.0
Bajocode/ExploringModerniOSArchitectures
Architectures/MVVM/ViewModel/ActorViewModel.swift
1
2811
// // ActorViewModel.swift // Architectures // // Created by Fabijan Bajo on 27/05/2017. // // import Foundation final class ActorViewModel: ViewModelInterface { // MARK: - Properties // Properties fileprivate var actors = [Actor]() { didSet { modelUpdate?() } } var count: Int { return actors.count } struct PresentableInstance: Transportable { let name: String let thumbnailURL: URL let fullSizeURL: URL let cornerRadius: Double } // MARK: - Binds typealias modelUpdateClosure = () -> Void typealias showDetailClosure = (URL, String) -> Void // Bind model updates and collectionview reload private var modelUpdate: modelUpdateClosure? func bindViewReload(with modelUpdate: @escaping modelUpdateClosure) { self.modelUpdate = modelUpdate } func fetchNewModelObjects() { DataManager.shared.fetchNewTmdbObjects(withType: .actor) { (result) in switch result { case let .success(transportables): self.actors = transportables as! [Actor] case let .failure(error): print(error) } } } // Bind collectionviewDidTap and detailVC presentation private var showDetail: showDetailClosure? func bindPresentation(with showDetail: @escaping showDetailClosure) { self.showDetail = showDetail } func showDetail(at indexPath: IndexPath) { let actor = actors[indexPath.row] let presentable = presentableInstance(from: actor) as! PresentableInstance showDetail?(presentable.fullSizeURL, presentable.name) } // MARK: - Helpers // Subscript: viewModel[i] -> PresentableInstance subscript (index: Int) -> Transportable { return presentableInstance(from: actors[index]) } func presentableInstance(from model: Transportable) -> Transportable { let actor = model as! Actor let thumbnailURL = TmdbAPI.tmdbImageURL(forSize: .thumb, path: actor.profilePath) let fullSizeURL = TmdbAPI.tmdbImageURL(forSize: .full, path: actor.profilePath) return PresentableInstance(name: actor.name, thumbnailURL: thumbnailURL, fullSizeURL: fullSizeURL, cornerRadius: 10.0) } } // MARK: - CollectionViewConfigurable extension ActorViewModel: CollectionViewConfigurable { // MARK: - Properties // Required var cellID: String { return "ActorCell" } var widthDivisor: Double { return 3.0 } var heightDivisor: Double { return 3.0 } // Optional var interItemSpacing: Double? { return 8 } var lineSpacing: Double? { return 8 } var topInset: Double? { return 8 } var horizontalInsets: Double? { return 8 } var bottomInset: Double? { return 49 } }
mit
KrishMunot/swift
test/IDE/print_ast_tc_decls.swift
2
51675
// RUN: rm -rf %t && mkdir %t // // Build swift modules this test depends on. // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift // // FIXME: BEGIN -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift // FIXME: END -enable-source-import hackaround // // This file should not have any syntax or type checker errors. // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse -verify %s -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=false -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE_TYPE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PREFER_TYPE_PRINTING -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-ast-typechecked -source-filename %s -F %S/Inputs/mock-sdk -function-definitions=false -prefer-type-repr=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_AST -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_RW_PROP_GET_SET -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2200 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE_TYPEREPR -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // // RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t -F %S/Inputs/mock-sdk -disable-objc-attr-requires-foundation-module %s // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_COMMON -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_RW_PROP_NO_GET_SET -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_2200_DESERIALIZED -strict-whitespace < %t.printed.txt // FIXME: rdar://15167697 // FIXME: FileCheck %s -check-prefix=PASS_2500 -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_ONE_LINE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PREFER_TYPE_REPR_PRINTING -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_UNQUAL -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -I %t -module-to-print=print_ast_tc_decls -synthesize-sugar-on-types=true -fully-qualified-types-if-ambiguous=true -print-implicit-attrs=true -disable-objc-attr-requires-foundation-module > %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_PRINT_MODULE_INTERFACE -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=PASS_QUAL_IF_AMBIGUOUS -strict-whitespace < %t.printed.txt // RUN: FileCheck %s -check-prefix=SYNTHESIZE_SUGAR_ON_TYPES -strict-whitespace < %t.printed.txt // FIXME: FileCheck %s -check-prefix=PASS_EXPLODE_PATTERN -strict-whitespace < %t.printed.txt // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Bar import ObjectiveC import class Foo.FooClassBase import struct Foo.FooStruct1 import func Foo.fooFunc1 @_exported import FooHelper import foo_swift_module // FIXME: enum tests //import enum FooClangModule.FooEnum1 // PASS_COMMON: {{^}}import Bar{{$}} // PASS_COMMON: {{^}}import class Foo.FooClassBase{{$}} // PASS_COMMON: {{^}}import struct Foo.FooStruct1{{$}} // PASS_COMMON: {{^}}import func Foo.fooFunc1{{$}} // PASS_COMMON: {{^}}@_exported import FooHelper{{$}} // PASS_COMMON: {{^}}import foo_swift_module{{$}} //===--- //===--- Helper types. //===--- struct FooStruct {} class FooClass {} class BarClass {} protocol FooProtocol {} protocol BarProtocol {} protocol BazProtocol { func baz() } protocol QuxProtocol { associatedtype Qux } protocol SubFooProtocol : FooProtocol { } class FooProtocolImpl : FooProtocol {} class FooBarProtocolImpl : FooProtocol, BarProtocol {} class BazProtocolImpl : BazProtocol { func baz() {} } //===--- //===--- Basic smoketest. //===--- struct d0100_FooStruct { // PASS_COMMON-LABEL: {{^}}struct d0100_FooStruct {{{$}} var instanceVar1: Int = 0 // PASS_COMMON-NEXT: {{^}} var instanceVar1: Int{{$}} var computedProp1: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} var computedProp1: Int { get }{{$}} func instanceFunc0() {} // PASS_COMMON-NEXT: {{^}} func instanceFunc0(){{$}} func instanceFunc1(a: Int) {} // PASS_COMMON-NEXT: {{^}} func instanceFunc1(a: Int){{$}} func instanceFunc2(a: Int, b: inout Double) {} // PASS_COMMON-NEXT: {{^}} func instanceFunc2(a: Int, b: inout Double){{$}} func instanceFunc3(a: Int, b: Double) { var a = a; a = 1; _ = a } // PASS_COMMON-NEXT: {{^}} func instanceFunc3(a: Int, b: Double){{$}} func instanceFuncWithDefaultArg1(a: Int = 0) {} // PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg1(a: Int = default){{$}} func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {} // PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = default, b: Double = default){{$}} func varargInstanceFunc0(v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc0(v: Int...){{$}} func varargInstanceFunc1(a: Float, v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc1(a: Float, v: Int...){{$}} func varargInstanceFunc2(a: Float, b: Double, v: Int...) {} // PASS_COMMON-NEXT: {{^}} func varargInstanceFunc2(a: Float, b: Double, v: Int...){{$}} func overloadedInstanceFunc1() -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Int{{$}} func overloadedInstanceFunc1() -> Double { return 0.0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc1() -> Double{{$}} func overloadedInstanceFunc2(x: Int) -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Int) -> Int{{$}} func overloadedInstanceFunc2(x: Double) -> Int { return 0; } // PASS_COMMON-NEXT: {{^}} func overloadedInstanceFunc2(x: Double) -> Int{{$}} func builderFunc1(a: Int) -> d0100_FooStruct { return d0100_FooStruct(); } // PASS_COMMON-NEXT: {{^}} func builderFunc1(a: Int) -> d0100_FooStruct{{$}} subscript(i: Int) -> Double { get { return Double(i) } } // PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Double { get }{{$}} subscript(i: Int, j: Int) -> Double { get { return Double(i + j) } } // PASS_COMMON-NEXT: {{^}} subscript(i: Int, j: Int) -> Double { get }{{$}} func bodyNameVoidFunc1(a: Int, b x: Float) {} // PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc1(a: Int, b x: Float){{$}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double) {} // PASS_COMMON-NEXT: {{^}} func bodyNameVoidFunc2(a: Int, b x: Float, c y: Double){{$}} func bodyNameStringFunc1(a: Int, b x: Float) -> String { return "" } // PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc1(a: Int, b x: Float) -> String{{$}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String { return "" } // PASS_COMMON-NEXT: {{^}} func bodyNameStringFunc2(a: Int, b x: Float, c y: Double) -> String{{$}} struct NestedStruct {} // PASS_COMMON-NEXT: {{^}} struct NestedStruct {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class NestedClass {} // PASS_COMMON-NEXT: {{^}} class NestedClass {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum NestedEnum {} // PASS_COMMON-NEXT: {{^}} enum NestedEnum {{{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} // Cannot declare a nested protocol. // protocol NestedProtocol {} typealias NestedTypealias = Int // PASS_COMMON-NEXT: {{^}} typealias NestedTypealias = Int{{$}} static var staticVar1: Int = 42 // PASS_COMMON-NEXT: {{^}} static var staticVar1: Int{{$}} static var computedStaticProp1: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} static var computedStaticProp1: Int { get }{{$}} static func staticFunc0() {} // PASS_COMMON-NEXT: {{^}} static func staticFunc0(){{$}} static func staticFunc1(a: Int) {} // PASS_COMMON-NEXT: {{^}} static func staticFunc1(a: Int){{$}} static func overloadedStaticFunc1() -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Int{{$}} static func overloadedStaticFunc1() -> Double { return 0.0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc1() -> Double{{$}} static func overloadedStaticFunc2(x: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Int) -> Int{{$}} static func overloadedStaticFunc2(x: Double) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} static func overloadedStaticFunc2(x: Double) -> Int{{$}} } // PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int){{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} extension d0100_FooStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct {{{$}} var extProp: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} var extProp: Int { get }{{$}} func extFunc0() {} // PASS_COMMON-NEXT: {{^}} func extFunc0(){{$}} static var extStaticProp: Int { get { return 42 } } // PASS_COMMON-NEXT: {{^}} static var extStaticProp: Int { get }{{$}} static func extStaticFunc0() {} // PASS_COMMON-NEXT: {{^}} static func extStaticFunc0(){{$}} struct ExtNestedStruct {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class ExtNestedClass {} // PASS_COMMON-NEXT: {{^}} class ExtNestedClass {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum ExtNestedEnum { case ExtEnumX(Int) } // PASS_COMMON-NEXT: {{^}} enum ExtNestedEnum {{{$}} // PASS_COMMON-NEXT: {{^}} case ExtEnumX(Int){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} typealias ExtNestedTypealias = Int // PASS_COMMON-NEXT: {{^}} typealias ExtNestedTypealias = Int{{$}} } // PASS_COMMON-NEXT: {{^}}}{{$}} extension d0100_FooStruct.NestedStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.NestedStruct {{{$}} struct ExtNestedStruct2 {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct2 {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} } extension d0100_FooStruct.ExtNestedStruct { // PASS_COMMON-LABEL: {{^}}extension d0100_FooStruct.ExtNestedStruct {{{$}} struct ExtNestedStruct3 {} // PASS_COMMON-NEXT: {{^}} struct ExtNestedStruct3 {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} } // PASS_COMMON-NEXT: {{^}}}{{$}} var fooObject: d0100_FooStruct = d0100_FooStruct() // PASS_ONE_LINE-DAG: {{^}}var fooObject: d0100_FooStruct{{$}} struct d0110_ReadWriteProperties { // PASS_RW_PROP_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}} // PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}struct d0110_ReadWriteProperties {{{$}} var computedProp1: Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp1: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp1: Int{{$}} subscript(i: Int) -> Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Int) -> Int{{$}} static var computedStaticProp1: Int { get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var computedStaticProp1: Int{{$}} var computedProp2: Int { mutating get { return 42 } set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp2: Int { mutating get set }{{$}} var computedProp3: Int { get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp3: Int { get nonmutating set }{{$}} var computedProp4: Int { mutating get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var computedProp4: Int { mutating get nonmutating set }{{$}} subscript(i: Float) -> Int { get { return 42 } nonmutating set {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} subscript(i: Float) -> Int { get nonmutating set }{{$}} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} init(){{$}} // PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} init(){{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}} extension d0110_ReadWriteProperties { // PASS_RW_PROP_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}} // PASS_RW_PROP_NO_GET_SET-LABEL: {{^}}extension d0110_ReadWriteProperties {{{$}} var extProp: Int { get { return 42 } set(v) {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} var extProp: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} var extProp: Int{{$}} static var extStaticProp: Int { get { return 42 } set(v) {} } // PASS_RW_PROP_GET_SET-NEXT: {{^}} static var extStaticProp: Int { get set }{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}} static var extStaticProp: Int{{$}} } // PASS_RW_PROP_GET_SET-NEXT: {{^}}}{{$}} // PASS_RW_PROP_NO_GET_SET-NEXT: {{^}}}{{$}} class d0120_TestClassBase { // PASS_COMMON-LABEL: {{^}}class d0120_TestClassBase {{{$}} required init() {} // PASS_COMMON-NEXT: {{^}} required init(){{$}} // FIXME: Add these once we can SILGen them reasonable. // init?(fail: String) { } // init!(iuoFail: String) { } final func baseFunc1() {} // PASS_COMMON-NEXT: {{^}} final func baseFunc1(){{$}} func baseFunc2() {} // PASS_COMMON-NEXT: {{^}} func baseFunc2(){{$}} subscript(i: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} subscript(i: Int) -> Int { get }{{$}} class var baseClassVar1: Int { return 0 } // PASS_COMMON-NEXT: {{^}} class var baseClassVar1: Int { get }{{$}} // FIXME: final class var not allowed to have storage, but static is? // final class var baseClassVar2: Int = 0 final class var baseClassVar3: Int { return 0 } // PASS_COMMON-NEXT: {{^}} final class var baseClassVar3: Int { get }{{$}} static var baseClassVar4: Int = 0 // PASS_COMMON-NEXT: {{^}} static var baseClassVar4: Int{{$}} static var baseClassVar5: Int { return 0 } // PASS_COMMON-NEXT: {{^}} static var baseClassVar5: Int { get }{{$}} class func baseClassFunc1() {} // PASS_COMMON-NEXT: {{^}} class func baseClassFunc1(){{$}} final class func baseClassFunc2() {} // PASS_COMMON-NEXT: {{^}} final class func baseClassFunc2(){{$}} static func baseClassFunc3() {} // PASS_COMMON-NEXT: {{^}} static func baseClassFunc3(){{$}} } class d0121_TestClassDerived : d0120_TestClassBase { // PASS_COMMON-LABEL: {{^}}class d0121_TestClassDerived : d0120_TestClassBase {{{$}} required init() { super.init() } // PASS_COMMON-NEXT: {{^}} required init(){{$}} final override func baseFunc2() {} // PASS_COMMON-NEXT: {{^}} {{(override |final )+}}func baseFunc2(){{$}} override final subscript(i: Int) -> Int { return 0 } // PASS_COMMON-NEXT: {{^}} override final subscript(i: Int) -> Int { get }{{$}} } protocol d0130_TestProtocol { // PASS_COMMON-LABEL: {{^}}protocol d0130_TestProtocol {{{$}} associatedtype NestedTypealias // PASS_COMMON-NEXT: {{^}} associatedtype NestedTypealias{{$}} var property1: Int { get } // PASS_COMMON-NEXT: {{^}} var property1: Int { get }{{$}} var property2: Int { get set } // PASS_COMMON-NEXT: {{^}} var property2: Int { get set }{{$}} func protocolFunc1() // PASS_COMMON-NEXT: {{^}} func protocolFunc1(){{$}} } @objc protocol d0140_TestObjCProtocol { // PASS_COMMON-LABEL: {{^}}@objc protocol d0140_TestObjCProtocol {{{$}} optional var property1: Int { get } // PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}} optional func protocolFunc1() // PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}} } protocol d0150_TestClassProtocol : class {} // PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : class {{{$}} @objc protocol d0151_TestClassProtocol {} // PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}} @noreturn @_silgen_name("exit") func d0160_testNoReturn() // PASS_COMMON-LABEL: {{^}}@_silgen_name("exit"){{$}} // PASS_COMMON-NEXT: {{^}}@noreturn func d0160_testNoReturn(){{$}} @noreturn func d0161_testNoReturn() { d0160_testNoReturn() } // PASS_COMMON-LABEL: {{^}}@noreturn func d0161_testNoReturn(){{$}} class d0162_TestNoReturn { // PASS_COMMON-LABEL: {{^}}class d0162_TestNoReturn {{{$}} @noreturn func instanceFunc() { d0160_testNoReturn() } // PASS_COMMON-NEXT: {{^}} @noreturn func instanceFunc(){{$}} @noreturn func classFunc() {d0160_testNoReturn() } // PASS_COMMON-NEXT: {{^}} @noreturn func classFunc(){{$}} } class d0170_TestAvailability { // PASS_COMMON-LABEL: {{^}}class d0170_TestAvailability {{{$}} @available(*, unavailable) func f1() {} // PASS_COMMON-NEXT: {{^}} @available(*, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} func f1(){{$}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee") func f2() {} // PASS_COMMON-NEXT: {{^}} @available(*, unavailable, message: "aaa \"bbb\" ccc\nddd\0eee"){{$}} // PASS_COMMON-NEXT: {{^}} func f2(){{$}} @available(iOS, unavailable) @available(OSX, unavailable) func f3() {} // PASS_COMMON-NEXT: {{^}} @available(iOS, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} @available(OSX, unavailable){{$}} // PASS_COMMON-NEXT: {{^}} func f3(){{$}} @available(iOS 8.0, OSX 10.10, *) func f4() {} // PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}} // PASS_COMMON-NEXT: {{^}} func f4(){{$}} // Convert long-form @available() to short form when possible. @available(iOS, introduced: 8.0) @available(OSX, introduced: 10.10) func f5() {} // PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, OSX 10.10, *){{$}} // PASS_COMMON-NEXT: {{^}} func f5(){{$}} } @objc class d0180_TestIBAttrs { // PASS_COMMON-LABEL: {{^}}@objc class d0180_TestIBAttrs {{{$}} @IBAction func anAction(_: AnyObject) {} // PASS_COMMON-NEXT: {{^}} @IBAction @objc func anAction(_: AnyObject){{$}} @IBDesignable class ADesignableClass {} // PASS_COMMON-NEXT: {{^}} @IBDesignable class ADesignableClass {{{$}} } @objc class d0181_TestIBAttrs { // PASS_EXPLODE_PATTERN-LABEL: {{^}}@objc class d0181_TestIBAttrs {{{$}} @IBOutlet weak var anOutlet: d0181_TestIBAttrs! // PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBOutlet @objc weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}} @IBInspectable var inspectableProp: Int = 0 // PASS_EXPLODE_PATTERN-NEXT: {{^}} @IBInspectable @objc var inspectableProp: Int{{$}} } struct d0190_LetVarDecls { // PASS_PRINT_AST-LABEL: {{^}}struct d0190_LetVarDecls {{{$}} // PASS_PRINT_MODULE_INTERFACE-LABEL: {{^}}struct d0190_LetVarDecls {{{$}} let instanceVar1: Int = 0 // PASS_PRINT_AST-NEXT: {{^}} let instanceVar1: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar1: Int{{$}} let instanceVar2 = 0 // PASS_PRINT_AST-NEXT: {{^}} let instanceVar2: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} let instanceVar2: Int{{$}} static let staticVar1: Int = 42 // PASS_PRINT_AST-NEXT: {{^}} static let staticVar1: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar1: Int{{$}} static let staticVar2 = 42 // FIXME: PRINTED_WITHOUT_TYPE // PASS_PRINT_AST-NEXT: {{^}} static let staticVar2: Int{{$}} // PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} static let staticVar2: Int{{$}} } struct d0200_EscapedIdentifiers { // PASS_COMMON-LABEL: {{^}}struct d0200_EscapedIdentifiers {{{$}} struct `struct` {} // PASS_COMMON-NEXT: {{^}} struct `struct` {{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} enum `enum` { case `case` } // PASS_COMMON-NEXT: {{^}} enum `enum` {{{$}} // PASS_COMMON-NEXT: {{^}} case `case`{{$}} // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} class `class` {} // PASS_COMMON-NEXT: {{^}} class `class` {{{$}} // PASS_COMMON-NEXT: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} typealias `protocol` = `class` // PASS_ONE_LINE_TYPE-DAG: {{^}} typealias `protocol` = d0200_EscapedIdentifiers.`class`{{$}} // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} typealias `protocol` = `class`{{$}} class `extension` : `class` {} // PASS_ONE_LINE_TYPE-DAG: {{^}} class `extension` : d0200_EscapedIdentifiers.`class` {{{$}} // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} class `extension` : `class` {{{$}} // PASS_COMMON: {{^}} @objc deinit{{$}} // PASS_COMMON-NEXT: {{^}} {{(override )?}}init(){{$}} // PASS_COMMON-NEXT: {{^}} }{{$}} func `func`<`let`: `protocol`, `where` where `where` : `protocol`>( class: Int, struct: `protocol`, foo: `let`, bar: `where`) {} // PASS_COMMON-NEXT: {{^}} func `func`<`let` : `protocol`, `where` where `where` : `protocol`>(class: Int, struct: `protocol`, foo: `let`, bar: `where`){{$}} var `var`: `struct` = `struct`() // PASS_COMMON-NEXT: {{^}} var `var`: {{(d0200_EscapedIdentifiers.)?}}`struct`{{$}} var tupleType: (`var`: Int, `let`: `struct`) // PASS_COMMON-NEXT: {{^}} var tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`){{$}} var accessors1: Int { get { return 0 } set(`let`) {} } // PASS_COMMON-NEXT: {{^}} var accessors1: Int{{( { get set })?}}{{$}} static func `static`(protocol: Int) {} // PASS_COMMON-NEXT: {{^}} static func `static`(protocol: Int){{$}} // PASS_COMMON-NEXT: {{^}} init(`var`: {{(d0200_EscapedIdentifiers.)?}}`struct`, tupleType: (`var`: Int, `let`: {{(d0200_EscapedIdentifiers.)?}}`struct`)){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} } struct d0210_Qualifications { // PASS_QUAL_UNQUAL: {{^}}struct d0210_Qualifications {{{$}} // PASS_QUAL_IF_AMBIGUOUS: {{^}}struct d0210_Qualifications {{{$}} var propFromStdlib1: Int = 0 // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromStdlib1: Int{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromStdlib1: Int{{$}} var propFromSwift1: FooSwiftStruct = FooSwiftStruct() // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromSwift1: FooSwiftStruct{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}} var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0) // PASS_QUAL_UNQUAL-NEXT: {{^}} var propFromClang1: FooStruct1{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} var propFromClang1: FooStruct1{{$}} func instanceFuncFromStdlib1(a: Int) -> Float { return 0.0 } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib1(a: Int) -> Float{{$}} func instanceFuncFromStdlib2(a: ObjCBool) {} // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromStdlib2(a: ObjCBool){{$}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct { return FooSwiftStruct() } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromSwift1(a: FooSwiftStruct) -> FooSwiftStruct{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromSwift1(a: foo_swift_module.FooSwiftStruct) -> foo_swift_module.FooSwiftStruct{{$}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1 { return FooStruct1(x: 0, y: 0.0) } // PASS_QUAL_UNQUAL-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}} // PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} func instanceFuncFromClang1(a: FooStruct1) -> FooStruct1{{$}} } // FIXME: this should be printed reasonably in case we use // -prefer-type-repr=true. Either we should print the types we inferred, or we // should print the initializers. class d0250_ExplodePattern { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0250_ExplodePattern {{{$}} var instanceVar1 = 0 var instanceVar2 = 0.0 var instanceVar3 = "" // PASS_EXPLODE_PATTERN: {{^}} var instanceVar1: Int{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar2: Double{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar3: String{{$}} var instanceVar4 = FooStruct() var (instanceVar5, instanceVar6) = (FooStruct(), FooStruct()) var (instanceVar7, instanceVar8) = (FooStruct(), FooStruct()) var (instanceVar9, instanceVar10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct()) final var (instanceVar11, instanceVar12) = (FooStruct(), FooStruct()) // PASS_EXPLODE_PATTERN: {{^}} var instanceVar4: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar5: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar6: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar7: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar8: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar9: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} var instanceVar10: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final var instanceVar11: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final var instanceVar12: FooStruct{{$}} let instanceLet1 = 0 let instanceLet2 = 0.0 let instanceLet3 = "" // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet1: Int{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet2: Double{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet3: String{{$}} let instanceLet4 = FooStruct() let (instanceLet5, instanceLet6) = (FooStruct(), FooStruct()) let (instanceLet7, instanceLet8) = (FooStruct(), FooStruct()) let (instanceLet9, instanceLet10) : (FooStruct, FooStruct) = (FooStruct(), FooStruct()) // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet4: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet5: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet6: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet7: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet8: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet9: FooStruct{{$}} // PASS_EXPLODE_PATTERN: {{^}} final let instanceLet10: FooStruct{{$}} } class d0260_ExplodePattern_TestClassBase { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0260_ExplodePattern_TestClassBase {{{$}} init() { baseProp1 = 0 } // PASS_EXPLODE_PATTERN-NEXT: {{^}} init(){{$}} final var baseProp1: Int // PASS_EXPLODE_PATTERN-NEXT: {{^}} final var baseProp1: Int{{$}} var baseProp2: Int { get { return 0 } set {} } // PASS_EXPLODE_PATTERN-NEXT: {{^}} var baseProp2: Int{{$}} } class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase { // PASS_EXPLODE_PATTERN-LABEL: {{^}}class d0261_ExplodePattern_TestClassDerived : d0260_ExplodePattern_TestClassBase {{{$}} override final var baseProp2: Int { get { return 0 } set {} } // PASS_EXPLODE_PATTERN-NEXT: {{^}} override final var baseProp2: Int{{$}} } //===--- //===--- Inheritance list in structs. //===--- struct StructWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithoutInheritance1 {{{$}} struct StructWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance1 : FooProtocol {{{$}} struct StructWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance2 : FooProtocol, BarProtocol {{{$}} struct StructWithInheritance3 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}struct StructWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in classes. //===--- class ClassWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithoutInheritance1 {{{$}} class ClassWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance1 : FooProtocol {{{$}} class ClassWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance2 : FooProtocol, BarProtocol {{{$}} class ClassWithInheritance3 : FooClass {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance3 : FooClass {{{$}} class ClassWithInheritance4 : FooClass, FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance4 : FooClass, FooProtocol {{{$}} class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {{{$}} class ClassWithInheritance6 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}class ClassWithInheritance6 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in enums. //===--- enum EnumWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithoutInheritance1 {{{$}} enum EnumWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance1 : FooProtocol {{{$}} enum EnumWithInheritance2 : FooProtocol, BarProtocol {} // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance2 : FooProtocol, BarProtocol {{{$}} enum EnumDeclWithUnderlyingType1 : Int { case X } // PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType1 : Int {{{$}} enum EnumDeclWithUnderlyingType2 : Int, FooProtocol { case X } // PASS_ONE_LINE-DAG: {{^}}enum EnumDeclWithUnderlyingType2 : Int, FooProtocol {{{$}} enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol { typealias Qux = Int } // PASS_ONE_LINE-DAG: {{^}}enum EnumWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in protocols. //===--- protocol ProtocolWithoutInheritance1 {} // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithoutInheritance1 {{{$}} protocol ProtocolWithInheritance1 : FooProtocol {} // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance1 : FooProtocol {{{$}} protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol { } // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance2 : FooProtocol, BarProtocol {{{$}} protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol { } // PASS_ONE_LINE-DAG: {{^}}protocol ProtocolWithInheritance3 : QuxProtocol, SubFooProtocol {{{$}} //===--- //===--- Inheritance list in extensions //===--- struct StructInherited { } // PASS_ONE_LINE-DAG: {{.*}}extension StructInherited : QuxProtocol, SubFooProtocol {{{$}} extension StructInherited : QuxProtocol, SubFooProtocol { typealias Qux = Int } //===--- //===--- Typealias printing. //===--- // Normal typealiases. typealias SimpleTypealias1 = FooProtocol // PASS_ONE_LINE-DAG: {{^}}typealias SimpleTypealias1 = FooProtocol{{$}} // Associated types. protocol AssociatedType1 { associatedtype AssociatedTypeDecl1 = Int // PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl1 = Int{{$}} associatedtype AssociatedTypeDecl2 : FooProtocol // PASS_ONE_LINE-DAG: {{^}} associatedtype AssociatedTypeDecl2 : FooProtocol{{$}} associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl3 : FooProtocol, BarProtocol{{$}} } //===--- //===--- Variable declaration printing. //===--- var d0300_topLevelVar1: Int = 42 // PASS_COMMON: {{^}}var d0300_topLevelVar1: Int{{$}} // PASS_COMMON-NOT: d0300_topLevelVar1 var d0400_topLevelVar2: Int = 42 // PASS_COMMON: {{^}}var d0400_topLevelVar2: Int{{$}} // PASS_COMMON-NOT: d0400_topLevelVar2 var d0500_topLevelVar2: Int { get { return 42 } } // PASS_COMMON: {{^}}var d0500_topLevelVar2: Int { get }{{$}} // PASS_COMMON-NOT: d0500_topLevelVar2 class d0600_InClassVar1 { // PASS_O600-LABEL: d0600_InClassVar1 var instanceVar1: Int // PASS_COMMON: {{^}} var instanceVar1: Int{{$}} // PASS_COMMON-NOT: instanceVar1 var instanceVar2: Int = 42 // PASS_COMMON: {{^}} var instanceVar2: Int{{$}} // PASS_COMMON-NOT: instanceVar2 // FIXME: this is sometimes printed without a type, see PASS_EXPLODE_PATTERN. // FIXME: PRINTED_WITHOUT_TYPE var instanceVar3 = 42 // PASS_COMMON: {{^}} var instanceVar3 // PASS_COMMON-NOT: instanceVar3 var instanceVar4: Int { get { return 42 } } // PASS_COMMON: {{^}} var instanceVar4: Int { get }{{$}} // PASS_COMMON-NOT: instanceVar4 // FIXME: uncomment when we have static vars. // static var staticVar1: Int init() { instanceVar1 = 10 } } //===--- //===--- Subscript declaration printing. //===--- class d0700_InClassSubscript1 { // PASS_COMMON-LABEL: d0700_InClassSubscript1 subscript(i: Int) -> Int { get { return 42 } } subscript(index i: Float) -> Int { return 42 } class `class` {} subscript(x: Float) -> `class` { return `class`() } // PASS_COMMON: {{^}} subscript(i: Int) -> Int { get }{{$}} // PASS_COMMON: {{^}} subscript(index i: Float) -> Int { get }{{$}} // PASS_COMMON: {{^}} subscript(x: Float) -> {{.*}} { get }{{$}} // PASS_COMMON-NOT: subscript // PASS_ONE_LINE_TYPE: {{^}} subscript(x: Float) -> d0700_InClassSubscript1.`class` { get }{{$}} // PASS_ONE_LINE_TYPEREPR: {{^}} subscript(x: Float) -> `class` { get }{{$}} } // PASS_COMMON: {{^}}}{{$}} //===--- //===--- Constructor declaration printing. //===--- struct d0800_ExplicitConstructors1 { // PASS_COMMON-LABEL: d0800_ExplicitConstructors1 init() {} // PASS_COMMON: {{^}} init(){{$}} init(a: Int) {} // PASS_COMMON: {{^}} init(a: Int){{$}} } struct d0900_ExplicitConstructorsSelector1 { // PASS_COMMON-LABEL: d0900_ExplicitConstructorsSelector1 init(int a: Int) {} // PASS_COMMON: {{^}} init(int a: Int){{$}} init(int a: Int, andFloat b: Float) {} // PASS_COMMON: {{^}} init(int a: Int, andFloat b: Float){{$}} } struct d1000_ExplicitConstructorsSelector2 { // PASS_COMMON-LABEL: d1000_ExplicitConstructorsSelector2 init(noArgs _: ()) {} // PASS_COMMON: {{^}} init(noArgs _: ()){{$}} init(_ a: Int) {} // PASS_COMMON: {{^}} init(_ a: Int){{$}} init(_ a: Int, withFloat b: Float) {} // PASS_COMMON: {{^}} init(_ a: Int, withFloat b: Float){{$}} init(int a: Int, _ b: Float) {} // PASS_COMMON: {{^}} init(int a: Int, _ b: Float){{$}} } //===--- //===--- Destructor declaration printing. //===--- class d1100_ExplicitDestructor1 { // PASS_COMMON-LABEL: d1100_ExplicitDestructor1 deinit {} // PASS_COMMON: {{^}} @objc deinit{{$}} } //===--- //===--- Enum declaration printing. //===--- enum d2000_EnumDecl1 { case ED1_First case ED1_Second } // PASS_COMMON: {{^}}enum d2000_EnumDecl1 {{{$}} // PASS_COMMON-NEXT: {{^}} case ED1_First{{$}} // PASS_COMMON-NEXT: {{^}} case ED1_Second{{$}} // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2100_EnumDecl2 { case ED2_A(Int) case ED2_B(Float) case ED2_C(Int, Float) case ED2_D(x: Int, y: Float) case ED2_E(x: Int, y: (Float, Double)) case ED2_F(x: Int, (y: Float, z: Double)) } // PASS_COMMON: {{^}}enum d2100_EnumDecl2 {{{$}} // PASS_COMMON-NEXT: {{^}} case ED2_A(Int){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_B(Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_C(Int, Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_D(x: Int, y: Float){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_E(x: Int, y: (Float, Double)){{$}} // PASS_COMMON-NEXT: {{^}} case ED2_F(x: Int, (y: Float, z: Double)){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2200_EnumDecl3 { case ED3_A, ED3_B case ED3_C(Int), ED3_D case ED3_E, ED3_F(Int) case ED3_G(Int), ED3_H(Int) case ED3_I(Int), ED3_J(Int), ED3_K } // PASS_2200: {{^}}enum d2200_EnumDecl3 {{{$}} // PASS_2200-NEXT: {{^}} case ED3_A, ED3_B{{$}} // PASS_2200-NEXT: {{^}} case ED3_C(Int), ED3_D{{$}} // PASS_2200-NEXT: {{^}} case ED3_E, ED3_F(Int){{$}} // PASS_2200-NEXT: {{^}} case ED3_G(Int), ED3_H(Int){{$}} // PASS_2200-NEXT: {{^}} case ED3_I(Int), ED3_J(Int), ED3_K{{$}} // PASS_2200-NEXT: {{^}}}{{$}} // PASS_2200_DESERIALIZED: {{^}}enum d2200_EnumDecl3 {{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_A{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_B{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_C(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_D{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_E{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_F(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_G(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_H(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_I(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_J(Int){{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}} case ED3_K{{$}} // PASS_2200_DESERIALIZED-NEXT: {{^}}}{{$}} enum d2300_EnumDeclWithValues1 : Int { case EDV2_First = 10 case EDV2_Second } // PASS_COMMON: {{^}}enum d2300_EnumDeclWithValues1 : Int {{{$}} // PASS_COMMON-NEXT: {{^}} case EDV2_First{{$}} // PASS_COMMON-NEXT: {{^}} case EDV2_Second{{$}} // PASS_COMMON-NEXT: {{^}} typealias RawValue = Int // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} init?(rawValue: Int){{$}} // PASS_COMMON-NEXT: {{^}} var rawValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} enum d2400_EnumDeclWithValues2 : Double { case EDV3_First = 10 case EDV3_Second } // PASS_COMMON: {{^}}enum d2400_EnumDeclWithValues2 : Double {{{$}} // PASS_COMMON-NEXT: {{^}} case EDV3_First{{$}} // PASS_COMMON-NEXT: {{^}} case EDV3_Second{{$}} // PASS_COMMON-NEXT: {{^}} typealias RawValue = Double // PASS_COMMON-NEXT: {{^}} var hashValue: Int { get }{{$}} // PASS_COMMON-NEXT: {{^}} init?(rawValue: Double){{$}} // PASS_COMMON-NEXT: {{^}} var rawValue: Double { get }{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} //===--- //===--- Custom operator printing. //===--- postfix operator <*> {} // PASS_2500-LABEL: {{^}}postfix operator <*> {{{$}} // PASS_2500-NEXT: {{^}}}{{$}} protocol d2600_ProtocolWithOperator1 { postfix func <*>(_: Int) } // PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}} // PASS_2500-NEXT: {{^}} postfix func <*>(_: Int){{$}} // PASS_2500-NEXT: {{^}}}{{$}} struct d2601_TestAssignment {} infix operator %%% { } func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int { return 0 } // PASS_2500-LABEL: {{^}}infix operator %%% { // PASS_2500-NOT: associativity // PASS_2500-NOT: precedence // PASS_2500-NOT: assignment // PASS_2500: {{^}}func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}} infix operator %%< { // PASS_2500-LABEL: {{^}}infix operator %%< {{{$}} associativity left // PASS_2500-NEXT: {{^}} associativity left{{$}} precedence 47 // PASS_2500-NEXT: {{^}} precedence 47{{$}} // PASS_2500-NOT: assignment } infix operator %%> { // PASS_2500-LABEL: {{^}}infix operator %%> {{{$}} associativity right // PASS_2500-NEXT: {{^}} associativity right{{$}} // PASS_2500-NOT: precedence // PASS_2500-NOT: assignment } infix operator %%<> { // PASS_2500-LABEL: {{^}}infix operator %%<> {{{$}} precedence 47 assignment // PASS_2500-NEXT: {{^}} precedence 47{{$}} // PASS_2500-NEXT: {{^}} assignment{{$}} // PASS_2500-NOT: associativity } // PASS_2500: {{^}}}{{$}} //===--- //===--- Printing of deduced associated types. //===--- protocol d2700_ProtocolWithAssociatedType1 { associatedtype TA1 func returnsTA1() -> TA1 } // PASS_COMMON: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}} // PASS_COMMON-NEXT: {{^}} associatedtype TA1{{$}} // PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 { func returnsTA1() -> Int { return 42 } } // PASS_COMMON: {{^}}struct d2800_ProtocolWithAssociatedType1Impl : d2700_ProtocolWithAssociatedType1 {{{$}} // PASS_COMMON-NEXT: {{^}} func returnsTA1() -> Int{{$}} // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}} typealias TA1 = Int // PASS_COMMON-NEXT: {{^}}}{{$}} //===--- //===--- Generic parameter list printing. //===--- struct GenericParams1< StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : protocol<FooProtocol, BarProtocol>, StructGenericBaz> { // PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : protocol<BarProtocol, FooProtocol>, StructGenericBaz> {{{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : protocol<FooProtocol, BarProtocol>, StructGenericBaz> {{{$}} init< GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) {} // PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<BarProtocol, FooProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} func genericParams1< GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) {} // PASS_ONE_LINE_TYPE-DAG: {{^}} func genericParams1<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<BarProtocol, FooProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : protocol<FooProtocol, BarProtocol>, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz){{$}} } struct GenericParams2<T : FooProtocol where T : BarProtocol> {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T : FooProtocol where T : BarProtocol> {{{$}} struct GenericParams3<T : FooProtocol where T : BarProtocol, T : QuxProtocol> {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T : FooProtocol where T : BarProtocol, T : QuxProtocol> {{{$}} struct GenericParams4<T : QuxProtocol where T.Qux : FooProtocol> {} // PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T : QuxProtocol where T.Qux : FooProtocol> {{{$}} struct GenericParams5<T : QuxProtocol where T.Qux : protocol<FooProtocol, BarProtocol>> {} // PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T : QuxProtocol where T.Qux : protocol<BarProtocol, FooProtocol>> {{{$}} // FIXME: in protocol compositions protocols are listed in reverse order. // // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T : QuxProtocol where T.Qux : protocol<FooProtocol, BarProtocol>> {{{$}} struct GenericParams6<T : QuxProtocol, U : QuxProtocol where T.Qux == U.Qux> {} // Because of the same type conformance, 'T.Qux' and 'U.Qux' types are // identical, so they are printed exactly the same way. Printing a TypeRepr // allows us to recover the original spelling. // // PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T : QuxProtocol, U : QuxProtocol where T.Qux == T.Qux> {{{$}} // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T : QuxProtocol, U : QuxProtocol where T.Qux == U.Qux> {{{$}} struct GenericParams7<T : QuxProtocol, U : QuxProtocol where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux> {} // PREFER_TYPE_PRINTING: {{^}}struct GenericParams7<T : QuxProtocol, U : QuxProtocol where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == T.Qux.Qux> {{{$}} // PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T : QuxProtocol, U : QuxProtocol where T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux> {{{$}} //===--- //===--- Tupe sugar for library types. //===--- struct d2900_TypeSugar1 { // PASS_COMMON-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}} // SYNTHESIZE_SUGAR_ON_TYPES-LABEL: {{^}}struct d2900_TypeSugar1 {{{$}} func f1(x: [Int]) {} // PASS_COMMON-NEXT: {{^}} func f1(x: [Int]){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f1(x: [Int]){{$}} func f2(x: Array<Int>) {} // PASS_COMMON-NEXT: {{^}} func f2(x: Array<Int>){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f2(x: [Int]){{$}} func f3(x: Int?) {} // PASS_COMMON-NEXT: {{^}} func f3(x: Int?){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f3(x: Int?){{$}} func f4(x: Optional<Int>) {} // PASS_COMMON-NEXT: {{^}} func f4(x: Optional<Int>){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f4(x: Int?){{$}} func f5(x: [Int]...) {} // PASS_COMMON-NEXT: {{^}} func f5(x: [Int]...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f5(x: [Int]...){{$}} func f6(x: Array<Int>...) {} // PASS_COMMON-NEXT: {{^}} func f6(x: Array<Int>...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f6(x: [Int]...){{$}} func f7(x: [Int : Int]...) {} // PASS_COMMON-NEXT: {{^}} func f7(x: [Int : Int]...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f7(x: [Int : Int]...){{$}} func f8(x: Dictionary<String, Int>...) {} // PASS_COMMON-NEXT: {{^}} func f8(x: Dictionary<String, Int>...){{$}} // SYNTHESIZE_SUGAR_ON_TYPES-NEXT: {{^}} func f8(x: [String : Int]...){{$}} } // PASS_COMMON-NEXT: {{^}} init(){{$}} // PASS_COMMON-NEXT: {{^}}}{{$}} // @warn_unused_result attribute public struct ArrayThingy { // PASS_PRINT_AST: @warn_unused_result(mutable_variant: "sort") // PASS_PRINT_AST-NEXT: public func sort() -> ArrayThingy @warn_unused_result(mutable_variant: "sort") public func sort() -> ArrayThingy { return self } public mutating func sort() { } // PASS_PRINT_AST: @warn_unused_result(message: "dummy", mutable_variant: "reverseInPlace") // PASS_PRINT_AST-NEXT: public func reverse() -> ArrayThingy @warn_unused_result(message: "dummy", mutable_variant: "reverseInPlace") public func reverse() -> ArrayThingy { return self } public mutating func reverseInPlace() { } // PASS_PRINT_AST: @warn_unused_result // PASS_PRINT_AST-NEXT: public func mineGold() -> Int @warn_unused_result public func mineGold() -> Int { return 0 } // PASS_PRINT_AST: @warn_unused_result(message: "oops") // PASS_PRINT_AST-NEXT: public func mineCopper() -> Int @warn_unused_result(message: "oops") public func mineCopper() -> Int { return 0 } } // @discardableResult attribute public struct DiscardableThingy { // PASS_PRINT_AST: @discardableResult // PASS_PRINT_AST-NEXT: public init() @discardableResult public init() {} // PASS_PRINT_AST: @discardableResult // PASS_PRINT_AST-NEXT: public func useless() -> Int @discardableResult public func useless() -> Int { return 0 } } // Parameter Attributes. // <rdar://problem/19775868> Swift 1.2b1: Header gen puts @autoclosure in the wrong place // PASS_PRINT_AST: public func ParamAttrs1(@autoclosure a: () -> ()) public func ParamAttrs1(@autoclosure a : () -> ()) { a() } // PASS_PRINT_AST: public func ParamAttrs2(@autoclosure(escaping) a: () -> ()) public func ParamAttrs2(@autoclosure(escaping) a : () -> ()) { a() } // PASS_PRINT_AST: public func ParamAttrs3(@noescape a: () -> ()) public func ParamAttrs3(@noescape a : () -> ()) { a() } // Protocol extensions protocol ProtocolToExtend { associatedtype Assoc } extension ProtocolToExtend where Self.Assoc == Int {} // PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int { #if true #elseif false #else #endif // PASS_PRINT_AST: #if // PASS_PRINT_AST: #elseif // PASS_PRINT_AST: #else // PASS_PRINT_AST: #endif public struct MyPair<A, B> { var a: A, b: B } public typealias MyPairI<B> = MyPair<Int, B> // PASS_PRINT_AST: public typealias MyPairI<B> = MyPair<Int, B> public typealias MyPairAlias<T, U> = MyPair<T, U> // PASS_PRINT_AST: public typealias MyPairAlias<T, U> = MyPair<T, U>
apache-2.0
Bartlebys/Bartleby
BartlebyKit/BartlebyKitMacOSTests/TransformTests.swift
1
584
// // TransformTests.swift // BartlebyKit // // Created by Martin Delille on 21/04/2016. // // import XCTest import BartlebyKit class TransformTests: XCTestCase { override static func setUp() { super.setUp() Bartleby.sharedInstance.configureWith(TestsConfiguration.self) } func test_CryptedStringTransform() { /* let transform = CryptedStringTransform() let s1 = "Coucou" let json = transform.transformToJSON(s1) let s2 = transform.transformFromJSON(json) XCTAssertEqual(s1, s2) */ } }
apache-2.0
ShenghaiWang/FolioReaderKit
Source/FolioReaderAudioPlayer.swift
3
16463
// // FolioReaderAudioPlayer.swift // FolioReaderKit // // Created by Kevin Jantzer on 1/4/16. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import AVFoundation import MediaPlayer open class FolioReaderAudioPlayer: NSObject { var isTextToSpeech = false var synthesizer: AVSpeechSynthesizer! var playing = false var player: AVAudioPlayer? var currentHref: String! var currentFragment: String! var currentSmilFile: FRSmilFile! var currentAudioFile: String! var currentBeginTime: Double! var currentEndTime: Double! var playingTimer: Timer! var registeredCommands = false var completionHandler: () -> Void = {} var utteranceRate: Float = 0 // MARK: Init override init() { super.init() UIApplication.shared.beginReceivingRemoteControlEvents() // this is needed to the audio can play even when the "silent/vibrate" toggle is on let session:AVAudioSession = AVAudioSession.sharedInstance() try! session.setCategory(AVAudioSessionCategoryPlayback) try! session.setActive(true) updateNowPlayingInfo() } deinit { UIApplication.shared.endReceivingRemoteControlEvents() } // MARK: Reading speed func setRate(_ rate: Int) { if let player = player { switch rate { case 0: player.rate = 0.5 break case 1: player.rate = 1.0 break case 2: player.rate = 1.5 break case 3: player.rate = 2 break default: break } updateNowPlayingInfo() } if synthesizer != nil { // Need to change between version IOS // http://stackoverflow.com/questions/32761786/ios9-avspeechutterance-rate-for-avspeechsynthesizer-issue if #available(iOS 9, *) { switch rate { case 0: utteranceRate = 0.42 break case 1: utteranceRate = 0.5 break case 2: utteranceRate = 0.53 break case 3: utteranceRate = 0.56 break default: break } } else { switch rate { case 0: utteranceRate = 0 break case 1: utteranceRate = 0.06 break case 2: utteranceRate = 0.15 break case 3: utteranceRate = 0.23 break default: break } } updateNowPlayingInfo() } } // MARK: Play, Pause, Stop controls func stop(immediate: Bool = false) { playing = false if !isTextToSpeech { if let player = player , player.isPlaying { player.stop() } } else { stopSynthesizer(immediate: immediate, completion: nil) } // UIApplication.sharedApplication().idleTimerDisabled = false } func stopSynthesizer(immediate: Bool = false, completion: (() -> Void)? = nil) { synthesizer.stopSpeaking(at: immediate ? .immediate : .word) completion?() } func pause() { playing = false if !isTextToSpeech { if let player = player , player.isPlaying { player.pause() } } else { if synthesizer.isSpeaking { synthesizer.pauseSpeaking(at: .word) } } // UIApplication.sharedApplication().idleTimerDisabled = false } func togglePlay() { isPlaying() ? pause() : play() } func play() { if book.hasAudio() { guard let currentPage = FolioReader.shared.readerCenter?.currentPage else { return } currentPage.webView.js("playAudio()") } else { readCurrentSentence() } // UIApplication.sharedApplication().idleTimerDisabled = true } func isPlaying() -> Bool { return playing } /** Play Audio (href/fragmentID) Begins to play audio for the given chapter (href) and text fragment. If this chapter does not have audio, it will delay for a second, then attempt to play the next chapter */ func playAudio(_ href: String, fragmentID: String) { isTextToSpeech = false stop() let smilFile = book.smilFileForHref(href) // if no smil file for this href and the same href is being requested, we've hit the end. stop playing if smilFile == nil && currentHref != nil && href == currentHref { return } playing = true currentHref = href currentFragment = "#"+fragmentID currentSmilFile = smilFile // if no smil file, delay for a second, then move on to the next chapter if smilFile == nil { Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(_autoPlayNextChapter), userInfo: nil, repeats: false) return } let fragment = smilFile?.parallelAudioForFragment(currentFragment) if fragment != nil { if _playFragment(fragment) { startPlayerTimer() } } } func _autoPlayNextChapter() { // if user has stopped playing, dont play the next chapter if isPlaying() == false { return } playNextChapter() } func playPrevChapter() { stopPlayerTimer() // Wait for "currentPage" to update, then request to play audio FolioReader.shared.readerCenter?.changePageToPrevious { if self.isPlaying() { self.play() } else { self.pause() } } } func playNextChapter() { stopPlayerTimer() // Wait for "currentPage" to update, then request to play audio FolioReader.shared.readerCenter?.changePageToNext { if self.isPlaying() { self.play() } } } /** Play Fragment of audio Once an audio fragment begins playing, the audio clip will continue playing until the player timer detects the audio is out of the fragment timeframe. */ @discardableResult fileprivate func _playFragment(_ smil: FRSmilElement!) -> Bool { if smil == nil { print("no more parallel audio to play") stop() return false } let textFragment = smil.textElement().attributes["src"] let audioFile = smil.audioElement().attributes["src"] currentBeginTime = smil.clipBegin() currentEndTime = smil.clipEnd() // new audio file to play, create the audio player if player == nil || (audioFile != nil && audioFile != currentAudioFile) { currentAudioFile = audioFile let fileURL = currentSmilFile.resource.basePath() + ("/"+audioFile!) let audioData = try? Data(contentsOf: URL(fileURLWithPath: fileURL)) do { player = try AVAudioPlayer(data: audioData!) guard let player = player else { return false } setRate(FolioReader.currentAudioRate) player.enableRate = true player.prepareToPlay() player.delegate = self updateNowPlayingInfo() } catch { print("could not read audio file:", audioFile ?? "nil") return false } } // if player is initialized properly, begin playing guard let player = player else { return false } // the audio may be playing already, so only set the player time if it is NOT already within the fragment timeframe // this is done to mitigate milisecond skips in the audio when changing fragments if player.currentTime < currentBeginTime || ( currentEndTime > 0 && player.currentTime > currentEndTime) { player.currentTime = currentBeginTime; updateNowPlayingInfo() } player.play() // get the fragment ID so we can "mark" it in the webview let textParts = textFragment!.components(separatedBy: "#") let fragmentID = textParts[1]; FolioReader.shared.readerCenter?.audioMark(href: currentHref, fragmentID: fragmentID) return true } /** Next Audio Fragment Gets the next audio fragment in the current smil file, or moves on to the next smil file */ fileprivate func nextAudioFragment() -> FRSmilElement! { let smilFile = book.smilFileForHref(currentHref) if smilFile == nil { return nil } let smil = currentFragment == nil ? smilFile?.parallelAudioForFragment(nil) : smilFile?.nextParallelAudioForFragment(currentFragment) if smil != nil { currentFragment = smil?.textElement().attributes["src"] return smil } currentHref = book.spine.nextChapter(currentHref)!.href currentFragment = nil currentSmilFile = smilFile if currentHref == nil { return nil } return nextAudioFragment() } func playText(_ href: String, text: String) { isTextToSpeech = true playing = true currentHref = href if synthesizer == nil { synthesizer = AVSpeechSynthesizer() synthesizer.delegate = self setRate(FolioReader.currentAudioRate) } let utterance = AVSpeechUtterance(string: text) utterance.rate = utteranceRate utterance.voice = AVSpeechSynthesisVoice(language: book.metadata.language) if synthesizer.isSpeaking { stopSynthesizer() } synthesizer.speak(utterance) updateNowPlayingInfo() } // MARK: TTS Sentence func speakSentence() { guard let readerCenter = FolioReader.shared.readerCenter, let currentPage = readerCenter.currentPage else { return } let sentence = currentPage.webView.js("getSentenceWithIndex('\(book.playbackActiveClass())')") if sentence != nil { let chapter = readerCenter.getCurrentChapter() let href = chapter != nil ? chapter!.href : ""; playText(href!, text: sentence!) } else { if readerCenter.isLastPage() { stop() } else { readerCenter.changePageToNext() } } } func readCurrentSentence() { guard synthesizer != nil else { return speakSentence() } if synthesizer.isPaused { playing = true synthesizer.continueSpeaking() } else { if synthesizer.isSpeaking { stopSynthesizer(immediate: false, completion: { if let currentPage = FolioReader.shared.readerCenter?.currentPage { currentPage.webView.js("resetCurrentSentenceIndex()") } self.speakSentence() }) } else { speakSentence() } } } // MARK: - Audio timing events fileprivate func startPlayerTimer() { // we must add the timer in this mode in order for it to continue working even when the user is scrolling a webview playingTimer = Timer(timeInterval: 0.01, target: self, selector: #selector(playerTimerObserver), userInfo: nil, repeats: true) RunLoop.current.add(playingTimer, forMode: RunLoopMode.commonModes) } fileprivate func stopPlayerTimer() { if playingTimer != nil { playingTimer.invalidate() playingTimer = nil } } func playerTimerObserver() { guard let player = player else { return } if currentEndTime != nil && currentEndTime > 0 && player.currentTime > currentEndTime { _playFragment(nextAudioFragment()) } } // MARK: - Now Playing Info and Controls /** Update Now Playing info Gets the book and audio information and updates on Now Playing Center */ func updateNowPlayingInfo() { var songInfo = [String: AnyObject]() // Get book Artwork if let coverImage = book.coverImage, let artwork = UIImage(contentsOfFile: coverImage.fullHref) { let albumArt = MPMediaItemArtwork(image: artwork) songInfo[MPMediaItemPropertyArtwork] = albumArt } // Get book title if let title = book.title() { songInfo[MPMediaItemPropertyAlbumTitle] = title as AnyObject? } // Get chapter name if let chapter = getCurrentChapterName() { songInfo[MPMediaItemPropertyTitle] = chapter as AnyObject? } // Get author name if let author = book.metadata.creators.first { songInfo[MPMediaItemPropertyArtist] = author.name as AnyObject? } // Set player times if let player = player , !isTextToSpeech { songInfo[MPMediaItemPropertyPlaybackDuration] = player.duration as AnyObject? songInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate as AnyObject? songInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime ] = player.currentTime as AnyObject? } // Set Audio Player info MPNowPlayingInfoCenter.default().nowPlayingInfo = songInfo registerCommandsIfNeeded() } /** Get Current Chapter Name This is done here and not in ReaderCenter because even though `currentHref` is accurate, the `currentPage` in ReaderCenter may not have updated just yet */ func getCurrentChapterName() -> String? { guard let chapter = FolioReader.shared.readerCenter?.getCurrentChapter() else { return nil } currentHref = chapter.href for item in book.flatTableOfContents { if let resource = item.resource , resource.href == currentHref { return item.title } } return nil } /** Register commands if needed, check if it's registered to avoid register twice. */ func registerCommandsIfNeeded() { guard !registeredCommands else { return } let command = MPRemoteCommandCenter.shared() command.previousTrackCommand.isEnabled = true command.previousTrackCommand.addTarget(self, action: #selector(playPrevChapter)) command.nextTrackCommand.isEnabled = true command.nextTrackCommand.addTarget(self, action: #selector(playNextChapter)) command.pauseCommand.isEnabled = true command.pauseCommand.addTarget(self, action: #selector(pause)) command.playCommand.isEnabled = true command.playCommand.addTarget(self, action: #selector(play)) command.togglePlayPauseCommand.isEnabled = true command.togglePlayPauseCommand.addTarget(self, action: #selector(togglePlay)) registeredCommands = true } } // MARK: AVSpeechSynthesizerDelegate extension FolioReaderAudioPlayer: AVSpeechSynthesizerDelegate { public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) { completionHandler() } public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { if isPlaying() { readCurrentSentence() } } } // MARK: AVAudioPlayerDelegate extension FolioReaderAudioPlayer: AVAudioPlayerDelegate { public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { _playFragment(nextAudioFragment()) } }
bsd-3-clause
mark-randall/APIClient
Example/APIClient/AppDelegate.swift
1
504
// // AppDelegate.swift // APIClient // // Created by mrandall on 09/21/2015. // Copyright (c) 2015 mrandall. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } }
mit
thewisecity/declarehome-ios
CookedApp/TableViewControllers/AlertsTableViewController.swift
1
5238
// // AlertsTableViewController.swift // CookedApp // // Created by Dexter Lohnes on 10/21/15. // Copyright © 2015 The Wise City. All rights reserved. // import UIKit class AlertsTableViewController: PFQueryTableViewController { var navDelegate: NavigationDelegate! var statusLabel: UILabel! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.paginationEnabled = true self.objectsPerPage = 10 } override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 80 statusLabel = UILabel() statusLabel.text = "Loading..." view.addSubview(statusLabel) statusLabel.sizeToFit() statusLabel.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2); statusLabel.hidden = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Stats.ScreenAlerts() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func objectsDidLoad(error: NSError?) { super.objectsDidLoad(error) if error != nil { statusLabel.lineBreakMode = .ByWordWrapping statusLabel.numberOfLines = 0 statusLabel.text = "Error while loading. Please try again." statusLabel.sizeToFit() let f = statusLabel.frame statusLabel.frame = CGRectMake(f.origin.x, f.origin.y, view.frame.size.width - 40, f.size.height * 2) statusLabel.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2); statusLabel.hidden = false } else if objects?.count == 0 { statusLabel.lineBreakMode = .ByWordWrapping statusLabel.numberOfLines = 0 statusLabel.text = "No alerts have been posted from your groups" statusLabel.sizeToFit() let f = statusLabel.frame statusLabel.frame = CGRectMake(f.origin.x, f.origin.y, view.frame.size.width - 40, f.size.height * 2) statusLabel.center = CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2); statusLabel.hidden = false } else { statusLabel.hidden = true } } override func queryForTable() -> PFQuery { let query = PFQuery(className: self.parseClassName!) query.orderByDescending("createdAt") query.whereKey(Message._IS_ALERT, equalTo: true) let adminOfQuery = PFUser.currentUser()?.relationForKey("adminOf").query() let memberOfQuery = PFUser.currentUser()?.relationForKey("memberOf").query() let groupsQuery = PFQuery.orQueryWithSubqueries([adminOfQuery!, memberOfQuery!]) query.whereKey(Message._GROUPS, matchesQuery: groupsQuery) query.includeKey(Message._CATEGORY) query.includeKey(Message._AUTHOR) query.includeKey(Message._AUTHOR_ADMIN_ARRAY) query.includeKey(Message._AUTHOR_MEMBER_ARRAY) return query } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? { let cellIdentifier = "MessageCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? MessageCell if cell == nil { cell = MessageCell(style: .Subtitle, reuseIdentifier: cellIdentifier) } // Configure the cell to show todo item with a priority at the bottom if let message = object as? Message { cell?.message = message } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print(indexPath.row) print(self.objects?.count) if indexPath.row >= self.objects?.count { loadNextPage() return } let selectedMessage = objectAtIndexPath(indexPath) as? Message let author = selectedMessage?.author navDelegate.performSegueWithId("ViewUserDetailsSegue", sender: author) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. // if let selectedGroup = sender as? Group{ // if let destinationController = segue.destinationViewController as? GroupDetailsViewController { // destinationController.group = selectedGroup // } // } } }
gpl-3.0
Jude309307972/JudeTest
Swift04-1/Swift04-1/Base.swift
1
304
// // Base.swift // Swift04-1 // // Created by 徐遵成 on 15/10/7. // Copyright © 2015年 Jude. All rights reserved. // import Foundation class Base:NSObject { var name: String? init(name: String) { self.name = name } deinit { print("base - deinit") } }
apache-2.0
tkremenek/swift
validation-test/compiler_crashers_2_fixed/rdar57003317.swift
25
186
// RUN: not %target-swift-frontend -typecheck %s protocol Iteratee { associatedtype Iterator } protocol BidirectionalAdvancingCollection: Iteratee { struct Iterator<Elements> {} }
apache-2.0
SwiftFMI/iOS_2017_2018
Upr/06.01.2018/PhotoLibraryDemo/PhotoLibraryDemo/PhotoLibrary.swift
1
5824
// // PhotoLibrary.swift // PhotoLibraryDemo // // Created by Dragomir Ivanov on 6.01.18. // Copyright © 2018 Swift FMI. All rights reserved. // import Foundation import Photos fileprivate protocol ImageRepresentable { var asset: PHAsset? { get } var size: CGSize { get } } public struct Photo { fileprivate let phAsset: PHAsset } extension Photo: ImageRepresentable { var asset: PHAsset? { return phAsset } var size: CGSize { return CGSize(width: 100, height: 100) } } public struct Album { let photos: [Photo] let title: String var thumbnailPhoto: Photo? { return photos.first } fileprivate init?(collection: PHAssetCollection?) { guard let assetCollection = collection else { return nil } let result = PHAsset.fetchAssets(in: assetCollection, options: nil) guard result.count != 0 else { return nil } var photos = [Photo]() result.enumerateObjects { (asset, index, stop) in photos.append(Photo(phAsset: asset)) } self.photos = photos self.title = assetCollection.localizedTitle ?? "Album" } } extension Album: ImageRepresentable { var asset: PHAsset? { return thumbnailPhoto?.phAsset } var size: CGSize { return CGSize(width: 75, height: 75) } } public final class PhotoLibrary { public static let library = PhotoLibrary() private init() {} private (set) var albums: [Album]? func loadAlbums(completionHandler: @escaping () -> Void) { guard PHPhotoLibrary.authorizationStatus() != .notDetermined else { PHPhotoLibrary.requestAuthorization() { [weak self] status in self?.loadAlbums(completionHandler: completionHandler) } return } DispatchQueue.global().async { [weak self] in var albums = [Album?]() func getSmartAlbum(of type: PHAssetCollectionSubtype) -> PHAssetCollection? { return PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: type, options: nil).firstObject } let all = Album(collection: getSmartAlbum(of: .smartAlbumUserLibrary)) albums.append(all) let favorites = Album(collection: getSmartAlbum(of: .smartAlbumFavorites)) albums.append(favorites) let selfies = Album(collection: getSmartAlbum(of: .smartAlbumSelfPortraits)) albums.append(selfies) let screenshots = Album(collection: getSmartAlbum(of: .smartAlbumScreenshots)) albums.append(screenshots) let userAlbums = PHCollectionList.fetchTopLevelUserCollections(with: nil) userAlbums.enumerateObjects { (collection, index, stop) in let userAlbum = Album(collection: collection as? PHAssetCollection ?? nil) albums.append(userAlbum) } self?.albums = albums.flatMap { $0 } DispatchQueue.main.async { completionHandler() } } } } public extension PhotoLibrary { private static var photoOptions: PHImageRequestOptions = { let options = PHImageRequestOptions() options.deliveryMode = .opportunistic options.isNetworkAccessAllowed = true options.isSynchronous = true return options }() private static let requestQueue = DispatchQueue(label: "photos.demo.queue") static func requestImage(for photo: Photo, targetSize: CGSize? = nil, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) { PhotoLibrary.requestQueue.async { executeImageRequest(for: photo, targetSize: targetSize, options: PhotoLibrary.photoOptions, resultHandler: { (image, info) in DispatchQueue.main.async { resultHandler(image, info) } }) } } private static var thumbnailOptions: PHImageRequestOptions = { let options = PHImageRequestOptions() options.deliveryMode = .opportunistic options.resizeMode = .exact options.isNetworkAccessAllowed = true return options }() static func requestThumbnail(for album: Album, targetSize: CGSize? = nil, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) { guard let asset = album.thumbnailPhoto?.phAsset else { return } let scale = CGAffineTransform(scaleX: CGFloat(1.0) / CGFloat(asset.pixelWidth), y: CGFloat(1.0) / CGFloat(asset.pixelHeight)) let cropSideLength = min(asset.pixelWidth, asset.pixelHeight) let square = CGRect(x: 0, y: 0, width: cropSideLength, height: cropSideLength) let cropRect = square.applying(scale) let options = PhotoLibrary.thumbnailOptions options.normalizedCropRect = cropRect executeImageRequest(for: album, targetSize: targetSize, options: options, resultHandler: resultHandler) } private static func executeImageRequest(for imageRepresentable: ImageRepresentable, targetSize: CGSize? = nil, options: PHImageRequestOptions, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) { guard let asset = imageRepresentable.asset else { return } let size = targetSize ?? imageRepresentable.size PHCachingImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options, resultHandler: resultHandler) } }
apache-2.0
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3Model/Sources/V3Model/Tag.swift
1
2761
// // Created by Jeffrey Bergier on 2022/06/17. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public struct Tag: Identifiable, Hashable, Equatable { public typealias Selection = Set<Tag.Identifier> public struct Identifier: Hashable, Equatable, Codable, RawRepresentable, Identifiable { public enum Kind: String { case systemAll, systemUnread, user } public var id: String public var kind: Kind = .user public init(_ rawValue: String, kind: Kind = .user) { self.id = rawValue self.kind = kind } public var rawValue: String { self.kind.rawValue + "|.|.|" + self.id } public init?(rawValue: String) { let comps = rawValue.components(separatedBy: "|.|.|") guard comps.count == 2, let kind = Kind(rawValue: comps[0]) else { return nil } self.id = comps[1] self.kind = kind } } public var id: Identifier public var name: String? public var websitesCount: Int? public var dateCreated: Date? public var dateModified: Date? public init(id: Identifier, name: String? = nil, websitesCount: Int? = nil, dateCreated: Date? = nil, dateModified: Date? = nil) { self.id = id self.name = name self.websitesCount = websitesCount self.dateCreated = dateCreated self.dateModified = dateModified } }
mit
hooliooo/Astral
Tests/GetRequestTests.swift
1
1057
// // APIClientRequestTests.swift // // // Created by Julio Alorro on 08.04.22. // import XCTest @testable import Astral class GetRequestTests: XCTestCase { public func testGetRequest() async throws { let (json, response): (GetResponse, URLResponse) = try await Constants.client .get(url: "https://httpbin.org/get") .query( items: [ URLQueryItem(name: "this", value: "that"), URLQueryItem(name: "what", value: "where"), URLQueryItem(name: "why", value: "what") ] ) .headers( headers: [ Header(key: Header.Key.custom("Get-Request"), value: Header.Value.custom("Yes")), Header(key: Header.Key.accept, value: Header.Value.mediaType(.applicationJSON)), Header(key: Header.Key.contentType, value: Header.Value.mediaType(.applicationJSON)) ] ) .send() dump(json) XCTAssertEqual("https://httpbin.org/get?this=that&what=where&why=what", response.url!.absoluteString) XCTAssertEqual(json.args.this, "that") } }
mit
AlanAherne/BabyTunes
BabyTunes/Pods/AAViewAnimator/AAViewAnimator/Classes/AAViewAnimator+UIKit.swift
1
770
// // AAViewAnimator+UIKit.swift // AAViewAnimator // // Created by Engr. Ahsan Ali on 16/02/2017. // Copyright © 2017 AA-Creations. All rights reserved. // // MARK: - UIView+AAViewAnimator extension UIView { /// UIView Animations /// /// - Parameters: /// - duration: Time interval /// - springDamping: AAViewDamping damping effect /// - animator: AAViewAnimators options /// - completion: animation completion closure open func aa_animate(duration: TimeInterval = 0.5, springDamping: AAViewDamping = .none,animation: AAViewAnimators, completion: ((_ isAnimating: Bool)->())? = nil) { let animator = AAViewAnimator(self, duration: duration, animation: animation) animator.animate(completion) } }
mit
WestlakeAPC/larry-platformer
SpriteKitTest/AppDelegate.swift
1
3200
/** * Copyright (c) 2017 Westlake APC * * 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. */ // // AppDelegate.swift // LarryPlatformer // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
alex4Zero/AZCustomCallout
AZCustomCallout/Maps/StatueOfLibertyAnnotation.swift
1
555
// // StatueOfLibertyAnnotation.swift // AZCustomCallout // // Created by Alexander Andronov on 23/06/16. // Copyright © 2016 Alexander Andronov. All rights reserved. // import Foundation import MapKit class StatueOfLibertyAnnotation : NSObject, MKAnnotation { internal fileprivate(set) var title: String? internal fileprivate(set) var coordinate: CLLocationCoordinate2D override init() { self.title = "The Statue of Liberty" self.coordinate = CLLocationCoordinate2D(latitude: 40.6892, longitude: -74.0445) } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/22757-swift-modulefile-getdecl.swift
11
248
// 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 a->{ func f:SequenceType func g:class a { class B{ class B<T where g:T>:d
mit
Finb/V2ex-Swift
Controller/LoginViewController.swift
1
17442
// // LoginViewController.swift // V2ex-Swift // // Created by huangfeng on 1/22/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import OnePasswordExtension import Kingfisher import SVProgressHUD import Alamofire public typealias LoginSuccessHandel = (String) -> Void class LoginViewController: UIViewController { var successHandel:LoginSuccessHandel? let backgroundImageView = UIImageView() let frostedView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) let userNameTextField:UITextField = { let userNameTextField = UITextField() userNameTextField.autocorrectionType = UITextAutocorrectionType.no userNameTextField.autocapitalizationType = UITextAutocapitalizationType.none userNameTextField.textColor = UIColor.white userNameTextField.backgroundColor = UIColor(white: 1, alpha: 0.1); userNameTextField.font = v2Font(15) userNameTextField.layer.cornerRadius = 3; userNameTextField.layer.borderWidth = 0.5 userNameTextField.keyboardType = .asciiCapable userNameTextField.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; userNameTextField.placeholder = "用户名" userNameTextField.clearButtonMode = .always let userNameIconImageView = UIImageView(image: UIImage(named: "ic_account_circle")!.withRenderingMode(.alwaysTemplate)); userNameIconImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 22) userNameIconImageView.tintColor = UIColor.white userNameIconImageView.contentMode = .scaleAspectFit let userNameIconImageViewPanel = UIView(frame: userNameIconImageView.frame) userNameIconImageViewPanel.addSubview(userNameIconImageView) userNameTextField.leftView = userNameIconImageViewPanel userNameTextField.leftViewMode = .always return userNameTextField }() let passwordTextField:UITextField = { let passwordTextField = UITextField() passwordTextField.textColor = UIColor.white passwordTextField.backgroundColor = UIColor(white: 1, alpha: 0.1); passwordTextField.font = v2Font(15) passwordTextField.layer.cornerRadius = 3; passwordTextField.layer.borderWidth = 0.5 passwordTextField.keyboardType = .asciiCapable passwordTextField.isSecureTextEntry = true passwordTextField.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; passwordTextField.placeholder = "密码" passwordTextField.clearButtonMode = .always let passwordIconImageView = UIImageView(image: UIImage(named: "ic_lock")!.withRenderingMode(.alwaysTemplate)); passwordIconImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 22) passwordIconImageView.contentMode = .scaleAspectFit passwordIconImageView.tintColor = UIColor.white let passwordIconImageViewPanel = UIView(frame: passwordIconImageView.frame) passwordIconImageViewPanel.addSubview(passwordIconImageView) passwordTextField.leftView = passwordIconImageViewPanel passwordTextField.leftViewMode = .always return passwordTextField }() let codeTextField:UITextField = { let codeTextField = UITextField() codeTextField.textColor = UIColor.white codeTextField.backgroundColor = UIColor(white: 1, alpha: 0.1); codeTextField.font = v2Font(15) codeTextField.layer.cornerRadius = 3; codeTextField.layer.borderWidth = 0.5 codeTextField.keyboardType = .asciiCapable codeTextField.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; codeTextField.placeholder = "验证码" codeTextField.clearButtonMode = .always let codeTextFieldImageView = UIImageView(image: UIImage(named: "ic_vpn_key")!.withRenderingMode(.alwaysTemplate)); codeTextFieldImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 22) codeTextFieldImageView.contentMode = .scaleAspectFit codeTextFieldImageView.tintColor = UIColor.white let codeTextFieldImageViewPanel = UIView(frame: codeTextFieldImageView.frame) codeTextFieldImageViewPanel.addSubview(codeTextFieldImageView) codeTextField.leftView = codeTextFieldImageViewPanel codeTextField.leftViewMode = .always return codeTextField }() let codeImageView = UIImageView() let loginButton = UIButton() let cancelButton = UIButton() init() { super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .fullScreen } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() //初始化界面 self.setupView() //初始化1Password if OnePasswordExtension.shared().isAppExtensionAvailable() { let onepasswordButton = UIImageView(image: UIImage(named: "onepassword-button")?.withRenderingMode(.alwaysTemplate)) onepasswordButton.isUserInteractionEnabled = true onepasswordButton.frame = CGRect(x: 0, y: 0, width: 34, height: 22) onepasswordButton.contentMode = .scaleAspectFit onepasswordButton.tintColor = UIColor.white self.passwordTextField.rightView = onepasswordButton self.passwordTextField.rightViewMode = .always onepasswordButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(LoginViewController.findLoginFrom1Password))) } //绑定事件 self.loginButton.addTarget(self, action: #selector(LoginViewController.loginClick(_:)), for: .touchUpInside) self.cancelButton.addTarget(self, action: #selector(LoginViewController.cancelClick), for: .touchUpInside) } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 2, animations: { () -> Void in self.backgroundImageView.alpha=1; }) UIView.animate(withDuration: 20, animations: { () -> Void in self.backgroundImageView.frame = CGRect(x: -1*( 1000 - SCREEN_WIDTH )/2, y: 0, width: SCREEN_HEIGHT+500, height: SCREEN_HEIGHT+500); }) } @objc func findLoginFrom1Password(){ OnePasswordExtension.shared().findLogin(forURLString: "v2ex.com", for: self, sender: nil) { (loginDictionary, errpr) -> Void in if let count = loginDictionary?.count , count > 0 { self.userNameTextField.text = loginDictionary![AppExtensionUsernameKey] as? String self.passwordTextField.text = loginDictionary![AppExtensionPasswordKey] as? String //密码赋值后,点确认按钮 self.loginClick(self.loginButton) } } } @objc func cancelClick (){ self.dismiss(animated: true, completion: nil) } @objc func loginClick(_ sneder:UIButton){ var userName:String var password:String if let len = self.userNameTextField.text?.Lenght , len > 0{ userName = self.userNameTextField.text! ; } else{ self.userNameTextField.becomeFirstResponder() return; } if let len = self.passwordTextField.text?.Lenght , len > 0 { password = self.passwordTextField.text! } else{ self.passwordTextField.becomeFirstResponder() return; } var code:String if let codeText = self.codeTextField.text, codeText.Lenght > 0 { code = codeText } else{ self.codeTextField.becomeFirstResponder() return } V2BeginLoadingWithStatus("正在登录") if let onceStr = onceStr , let usernameStr = usernameStr, let passwordStr = passwordStr, let codeStr = codeStr { UserModel.Login(userName, password: password, once: onceStr, usernameFieldName: usernameStr, passwordFieldName: passwordStr , codeFieldName:codeStr, code:code){ (response:V2ValueResponse<String> , is2FALoggedIn:Bool) -> Void in if response.success { V2Success("登录成功") let username = response.value! //保存下用户名 V2EXSettings.sharedInstance[kUserName] = username //将用户名密码保存进keychain (安全保存) V2UsersKeychain.sharedInstance.addUser(username, password: password) //调用登录成功回调 if let handel = self.successHandel { handel(username) } //获取用户信息 UserModel.getUserInfoByUsername(username,completionHandler: nil) self.dismiss(animated: true){ if is2FALoggedIn { let twoFaViewController = TwoFAViewController() V2Client.sharedInstance.centerViewController!.navigationController?.present(twoFaViewController, animated: true, completion: nil); } } } else{ V2Error(response.message) self.refreshCode() } } return; } else{ V2Error("不知道啥错误") } } var onceStr:String? var usernameStr:String? var passwordStr:String? var codeStr:String? @objc func refreshCode(){ Alamofire.request(V2EXURL+"signin", headers: MOBILE_CLIENT_HEADERS).responseJiHtml{ (response) -> Void in if let jiHtml = response .result.value{ //获取帖子内容 //取出 once 登录时要用 //self.onceStr = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"] self.usernameStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[1]/td[2]/input[@class='sl']")?.first?["name"] self.passwordStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[2]/td[2]/input[@class='sl']")?.first?["name"] self.codeStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[4]/td[2]/input[@class='sl']")?.first?["name"] if let once = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"]{ let codeUrl = "\(V2EXURL)_captcha?once=\(once)" self.onceStr = once Alamofire.request(codeUrl).responseData(completionHandler: { (dataResp) in self.codeImageView.image = UIImage(data: dataResp.data!) }) } else{ SVProgressHUD.showError(withStatus: "刷新验证码失败") } } } } } //MARK: - 点击文本框外收回键盘 extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } } //MARK: - 初始化界面 extension LoginViewController { func setupView(){ self.view.backgroundColor = UIColor.black self.backgroundImageView.image = UIImage(named: "32.jpg") self.backgroundImageView.frame = self.view.frame self.backgroundImageView.contentMode = .scaleToFill self.view.addSubview(self.backgroundImageView) backgroundImageView.alpha = 0 self.frostedView.frame = self.view.frame self.view.addSubview(self.frostedView) var blurEffect:UIBlurEffect.Style = .dark if #available(iOS 13.0, *) { blurEffect = .systemUltraThinMaterialDark } let vibrancy = UIVibrancyEffect(blurEffect: UIBlurEffect(style: blurEffect)) let vibrancyView = UIVisualEffectView(effect: vibrancy) vibrancyView.isUserInteractionEnabled = true vibrancyView.frame = self.frostedView.frame self.frostedView.contentView.addSubview(vibrancyView) let v2exLabel = UILabel() v2exLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 25)!; v2exLabel.text = "Explore" vibrancyView.contentView.addSubview(v2exLabel); v2exLabel.snp.makeConstraints{ (make) -> Void in make.centerX.equalTo(vibrancyView) make.top.equalTo(vibrancyView).offset(NavigationBarHeight) } let v2exSummaryLabel = UILabel() v2exSummaryLabel.font = v2Font(13); v2exSummaryLabel.text = "创意者的工作社区" vibrancyView.contentView.addSubview(v2exSummaryLabel); v2exSummaryLabel.snp.makeConstraints{ (make) -> Void in make.centerX.equalTo(vibrancyView) make.top.equalTo(v2exLabel.snp.bottom).offset(2) } vibrancyView.contentView.addSubview(self.userNameTextField); self.userNameTextField.snp.makeConstraints{ (make) -> Void in make.top.equalTo(v2exSummaryLabel.snp.bottom).offset(25) make.centerX.equalTo(vibrancyView) make.width.equalTo(300) make.height.equalTo(38) } vibrancyView.contentView.addSubview(self.passwordTextField); self.passwordTextField.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.userNameTextField.snp.bottom).offset(15) make.centerX.equalTo(vibrancyView) make.width.equalTo(300) make.height.equalTo(38) } vibrancyView.contentView.addSubview(self.codeTextField) self.codeTextField.snp.makeConstraints { (make) in make.top.equalTo(self.passwordTextField.snp.bottom).offset(15) make.left.equalTo(passwordTextField) make.width.equalTo(180) make.height.equalTo(38) } self.codeImageView.backgroundColor = UIColor(white: 1, alpha: 0.2) self.codeImageView.layer.cornerRadius = 3; self.codeImageView.clipsToBounds = true self.codeImageView.isUserInteractionEnabled = true self.view.addSubview(self.codeImageView) self.codeImageView.snp.makeConstraints { (make) in make.top.bottom.equalTo(self.codeTextField) make.left.equalTo(self.codeTextField.snp.right).offset(2) make.right.equalTo(self.passwordTextField) } self.codeImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(refreshCode))) self.loginButton.setTitle("登 录", for: .normal) self.loginButton.titleLabel!.font = v2Font(20) self.loginButton.layer.cornerRadius = 3; self.loginButton.layer.borderWidth = 0.5 self.loginButton.layer.borderColor = UIColor(white: 1, alpha: 0.8).cgColor; vibrancyView.contentView.addSubview(self.loginButton); self.loginButton.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.codeTextField.snp.bottom).offset(20) make.centerX.equalTo(vibrancyView) make.width.equalTo(300) make.height.equalTo(38) } let codeProblem = UILabel() codeProblem.alpha = 0.5 codeProblem.font = v2Font(12) codeProblem.text = "验证码不显示?" codeProblem.isUserInteractionEnabled = true codeProblem.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(codeProblemClick))) vibrancyView.contentView.addSubview(codeProblem); codeProblem.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.loginButton.snp.bottom).offset(14) make.right.equalTo(self.loginButton) } let footLabel = UILabel() footLabel.alpha = 0.5 footLabel.font = v2Font(12) footLabel.text = "© 2020 Fin" vibrancyView.contentView.addSubview(footLabel); footLabel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(vibrancyView).offset(-20) make.centerX.equalTo(vibrancyView) } self.cancelButton.contentMode = .center cancelButton .setImage(UIImage(named: "ic_cancel")!.withRenderingMode(.alwaysTemplate), for: .normal) vibrancyView.contentView.addSubview(cancelButton) cancelButton.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(footLabel) make.right.equalTo(vibrancyView).offset(-5) make.width.height.equalTo(40) } refreshCode() } @objc func codeProblemClick(){ UIAlertView(title: "验证码不显示?", message: "如果验证码输错次数过多,V2EX将暂时禁止你的登录。", delegate: nil, cancelButtonTitle: "知道了").show() } }
mit
radex/swift-compiler-crashes
crashes-duplicates/15488-swift-sourcemanager-getmessage.swift
11
206
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing deinit { case { var d { class case ,
mit
ConanMTHu/animated-tab-bar
RAMAnimatedTabBarController/Animations/FrameAnimation/RAMFrameItemAnimation.swift
1
3389
// RAMFrameItemAnimation.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.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 import QuartzCore class RAMFrameItemAnimation: RAMItemAnimation { var animationImages : Array<CGImage> = Array() var selectedImage : UIImage! @IBInspectable var isDeselectAnimation: Bool = true @IBInspectable var imagesPath: String! override func awakeFromNib() { let path = NSBundle.mainBundle().pathForResource(imagesPath, ofType:"plist") let dict : NSDictionary = NSDictionary(contentsOfFile: path!)! let animationImagesName = dict["images"] as Array<String> createImagesArray(animationImagesName) // selected image var selectedImageName = animationImagesName[animationImagesName.endIndex - 1] selectedImage = UIImage(named: selectedImageName) } func createImagesArray(imageNames : Array<String>) { for name : String in imageNames { let image = UIImage(named: name)?.CGImage animationImages.append(image!) } } override func playAnimation(icon : UIImageView, textLable : UILabel) { playFrameAnimation(icon, images:animationImages) textLable.textColor = textSelectedColor } override func deselectAnimation(icon : UIImageView, textLable : UILabel, defaultTextColor : UIColor) { if isDeselectAnimation { playFrameAnimation(icon, images:animationImages.reverse()) } textLable.textColor = defaultTextColor } override func selectedState(icon : UIImageView, textLable : UILabel) { icon.image = selectedImage textLable.textColor = textSelectedColor } func playFrameAnimation(icon : UIImageView, images : Array<CGImage>) { var frameAnimation = CAKeyframeAnimation(keyPath: "contents") frameAnimation.calculationMode = kCAAnimationDiscrete frameAnimation.duration = NSTimeInterval(duration) frameAnimation.values = images frameAnimation.repeatCount = 1; frameAnimation.removedOnCompletion = false; frameAnimation.fillMode = kCAFillModeForwards; icon.layer.addAnimation(frameAnimation, forKey: "frameAnimation") } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/11553-swift-genericparamlist-create.swift
11
228
// 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 A{ func d:B protocol B{ protocol A:A typealias A:A
mit
bugsnag/bugsnag-cocoa
Tests/BugsnagTests/BugsnagSwiftConfigurationTests.swift
1
2337
// // BugsnagSwiftConfigurationTests.swift // Tests // // Created by Robin Macharg on 22/01/2020. // Copyright © 2020 Bugsnag. All rights reserved. // import XCTest import Bugsnag class BugsnagSwiftConfigurationTests: XCTestCase { /** * Objective C trailing-NSError* initializers are translated into throwing * Swift methods, allowing us to fail gracefully (at the expense of a more-explicit * (read: longer) ObjC invocation). */ func testDesignatedInitializerHasCorrectNS_SWIFT_NAME() { let config = BugsnagConfiguration(DUMMY_APIKEY_16CHAR) XCTAssertEqual(config.apiKey, DUMMY_APIKEY_16CHAR) } func testRemoveOnSendError() { let config = BugsnagConfiguration(DUMMY_APIKEY_16CHAR) let onSendBlocks: NSMutableArray = config.value(forKey: "onSendBlocks") as! NSMutableArray XCTAssertEqual(onSendBlocks.count, 0) let onSendError = config.addOnSendError { _ in false } XCTAssertEqual(onSendBlocks.count, 1) config.removeOnSendError(onSendError) XCTAssertEqual(onSendBlocks.count, 0) } func testRemoveOnSendErrorBlockDoesNotWork() { let config = BugsnagConfiguration(DUMMY_APIKEY_16CHAR) let onSendBlocks: NSMutableArray = config.value(forKey: "onSendBlocks") as! NSMutableArray XCTAssertEqual(onSendBlocks.count, 0) let onSendErrorBlock: (BugsnagEvent) -> Bool = { _ in false } config.addOnSendError(block: onSendErrorBlock) XCTAssertEqual(onSendBlocks.count, 1) // Intentionally using the deprecated API config.removeOnSendError(block: onSendErrorBlock) // It's not possible to remove an OnSendError Swift closure because the compiler apparently // creates a new NSBlock each time a closure is passed to an Objective-C method. XCTAssertEqual(onSendBlocks.count, 1) } func testRemoveInvalidOnSendErrorDoesNotCrash() { let config = BugsnagConfiguration(DUMMY_APIKEY_16CHAR) let onSendErrorBlock: (BugsnagEvent) -> Bool = { _ in false } config.addOnSendError(block: onSendErrorBlock) // This does not compile: // config.removeOnSendError(onSendErrorBlock) config.removeOnSendError("" as NSString) } }
mit
multinerd/Mia
Mia/Sugar/On/UIBarButtonItem.swift
1
601
import UIKit public extension Container where Host: UIBarButtonItem { func tap(_ action: @escaping Action) { let target = BarButtonItemTarget(host: host, action: action) self.barButtonItemTarget = target } } class BarButtonItemTarget: NSObject { var action: Action? init(host: UIBarButtonItem, action: @escaping Action) { super.init() self.action = action host.target = self host.action = #selector(handleTap(_:)) } // MARK: - Action @objc func handleTap(_ sender: UIBarButtonItem) { action?() } }
mit
shorlander/firefox-ios
Client/Frontend/Home/HomePanels.swift
6
3089
/* 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 UIKit import Shared /** * Data for identifying and constructing a HomePanel. */ struct HomePanelDescriptor { let makeViewController: (_ profile: Profile) -> UIViewController let imageName: String let accessibilityLabel: String let accessibilityIdentifier: String } class HomePanels { let enabledPanels = [ HomePanelDescriptor( makeViewController: { profile in return ActivityStreamPanel(profile: profile) }, imageName: "TopSites", accessibilityLabel: NSLocalizedString("Top sites", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.TopSites"), HomePanelDescriptor( makeViewController: { profile in let bookmarks = BookmarksPanel() bookmarks.profile = profile let controller = UINavigationController(rootViewController: bookmarks) controller.setNavigationBarHidden(true, animated: false) // this re-enables the native swipe to pop gesture on UINavigationController for embedded, navigation bar-less UINavigationControllers // don't ask me why it works though, I've tried to find an answer but can't. // found here, along with many other places: // http://luugiathuy.com/2013/11/ios7-interactivepopgesturerecognizer-for-uinavigationcontroller-with-hidden-navigation-bar/ controller.interactivePopGestureRecognizer?.delegate = nil return controller }, imageName: "Bookmarks", accessibilityLabel: NSLocalizedString("Bookmarks", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.Bookmarks"), HomePanelDescriptor( makeViewController: { profile in let history = HistoryPanel() history.profile = profile let controller = UINavigationController(rootViewController: history) controller.setNavigationBarHidden(true, animated: false) controller.interactivePopGestureRecognizer?.delegate = nil return controller }, imageName: "History", accessibilityLabel: NSLocalizedString("History", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.History"), HomePanelDescriptor( makeViewController: { profile in let controller = ReadingListPanel() controller.profile = profile return controller }, imageName: "ReadingList", accessibilityLabel: NSLocalizedString("Reading list", comment: "Panel accessibility label"), accessibilityIdentifier: "HomePanels.ReadingList"), ] }
mpl-2.0
hstdt/GodEye
GodEye/Classes/Controller/TabController/MonitorController/MonitorContainerView.swift
2
8409
// // MonitorContainerView.swift // Pods // // Created by zixun on 17/1/6. // // import Foundation import UIKit import SystemEye protocol MonitorContainerViewDelegate: class { func container(container:MonitorContainerView, didSelectedType type:MonitorSystemType) } class MonitorContainerView: UIScrollView,FPSDelegate,NetDelegate { weak var delegateContainer: MonitorContainerViewDelegate? init() { super.init(frame: CGRect.zero) self.addSubview(self.deviceView) self.addSubview(self.sysNetView) self.fps.open() self.networkFlow.open() self.deviceView.configure(nameString: System.hardware.deviceModel, osString: System.hardware.systemName + " " + System.hardware.systemVersion) Store.shared.networkByteDidChange { [weak self] (byte:Double) in self?.appNetView.configure(byte: byte) } Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(MonitorContainerView.timerHandler), userInfo: nil, repeats: true) } override func layoutSubviews() { super.layoutSubviews() self.deviceView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: 100) for i in 0..<self.monitorAppViews.count { var rect = self.deviceView.frame rect.origin.y = rect.maxY rect.size.width = self.frame.size.width / 2.0 rect.size.height = 100 rect.origin.y += rect.size.height * CGFloat( i / 2) rect.origin.x += rect.size.width * CGFloat( i % 2) self.monitorAppViews[i].frame = rect } for i in 0..<self.monitorSysViews.count { var rect = self.monitorAppViews.last?.frame ?? CGRect.zero rect.origin.y += rect.size.height rect.origin.x = 0 rect.origin.y += rect.size.height * CGFloat( i / 2) rect.origin.x += rect.size.width * CGFloat( i % 2) self.monitorSysViews[i].frame = rect } var rect = self.monitorSysViews.last?.frame ?? CGRect.zero rect.origin.y += rect.size.height rect.origin.x = 0 rect.size.width = self.frame.size.width self.sysNetView.frame = rect self.contentSize = CGSize(width: self.frame.size.width, height: self.sysNetView.frame.maxY) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //-------------------------------------------------------------------------- // MARK: PRIVATE FUNCTION //-------------------------------------------------------------------------- @objc private func didTap(sender:MonitorBaseView) { self.delegateContainer?.container(container: self, didSelectedType: sender.type) } @objc private func didTapSysNetView(sender:MonitorSysNetFlowView) { self.delegateContainer?.container(container: self, didSelectedType: sender.type) } @objc private func timerHandler() { self.appCPUView.configure(percent: System.cpu.applicationUsage()) let cpuSystemUsage = System.cpu.systemUsage() self.sysCPUView.configure(percent: cpuSystemUsage.system + cpuSystemUsage.user + cpuSystemUsage.nice) self.appRAMView.configure(byte: System.memory.applicationUsage().used) let ramSysUsage = System.memory.systemUsage() let percent = (ramSysUsage.active + ramSysUsage.inactive + ramSysUsage.wired) / ramSysUsage.total self.sysRAMView.configure(percent: percent * 100.0) } func fps(fps:FPS, currentFPS:Double) { self.appFPSView.configure(fps: currentFPS) } func networkFlow(networkFlow:NetworkFlow,catchWithWifiSend wifiSend:UInt32,wifiReceived:UInt32,wwanSend:UInt32,wwanReceived:UInt32) { self.sysNetView.configure(wifiSend: wifiSend, wifiReceived: wifiReceived, wwanSend: wwanSend, wwanReceived: wwanReceived) } //-------------------------------------------------------------------------- // MARK: PRIVATE PROPERTY //-------------------------------------------------------------------------- private lazy var fps: FPS = { [unowned self] in let new = FPS() new.delegate = self return new }() private lazy var networkFlow: NetworkFlow = { let new = NetworkFlow() new.delegate = self return new }() private var deviceView = MonitorDeviceView() private lazy var appCPUView: MonitorBaseView = { [unowned self] in let new = MonitorBaseView(type: MonitorSystemType.appCPU) new.addTarget(self, action: #selector(MonitorContainerView.didTap(sender:)), for: .touchUpInside) return new }() private lazy var appRAMView: MonitorBaseView = { [unowned self] in let new = MonitorBaseView(type: MonitorSystemType.appRAM) new.addTarget(self, action: #selector(MonitorContainerView.didTap(sender:)), for: .touchUpInside) return new }() private lazy var appFPSView: MonitorBaseView = { [unowned self] in let new = MonitorBaseView(type: MonitorSystemType.appFPS) new.addTarget(self, action: #selector(MonitorContainerView.didTap(sender:)), for: .touchUpInside) return new }() private lazy var appNetView: MonitorBaseView = { [unowned self] in let new = MonitorBaseView(type: MonitorSystemType.appNET) new.addTarget(self, action: #selector(MonitorContainerView.didTap(sender:)), for: .touchUpInside) return new }() private lazy var sysCPUView: MonitorBaseView = { [unowned self] in let new = MonitorBaseView(type: MonitorSystemType.sysCPU) new.addTarget(self, action: #selector(MonitorContainerView.didTap(sender:)), for: .touchUpInside) return new }() private lazy var sysRAMView: MonitorBaseView = { [unowned self] in let new = MonitorBaseView(type: MonitorSystemType.sysRAM) new.addTarget(self, action: #selector(MonitorContainerView.didTap(sender:)), for: .touchUpInside) return new }() private lazy var sysNetView: MonitorSysNetFlowView = { [unowned self] in let new = MonitorSysNetFlowView(type: MonitorSystemType.sysNET) new.addTarget(self, action: #selector(MonitorContainerView.didTapSysNetView(sender:)), for: .touchUpInside) return new }() private lazy var monitorAppViews: [MonitorBaseView] = { [unowned self] in var new = [MonitorBaseView]() self.addSubview(self.appCPUView) self.addSubview(self.appRAMView) self.addSubview(self.appFPSView) self.addSubview(self.appNetView) new.append(self.appCPUView) new.append(self.appRAMView) new.append(self.appFPSView) new.append(self.appNetView) for i in 0..<new.count { new[i].firstRow = i < 2 new[i].position = i % 2 == 0 ? .left : .right } return new }() private lazy var monitorSysViews: [MonitorBaseView] = { [unowned self] in var new = [MonitorBaseView]() self.addSubview(self.sysCPUView) self.addSubview(self.sysRAMView) new.append(self.sysCPUView) new.append(self.sysRAMView) for i in 0..<new.count { new[i].firstRow = i < 2 new[i].position = i % 2 == 0 ? .left : .right } return new }() } //extension MonitorContainerView : SystemStoreDelegate { // func systemStoreDidCatch(cpu model:CPUModel) { // self.appCPUView.configure(application: model.application) // self.sysCPUView.configure(system: model.system) // } // func systemStoreDidCatch(memory model:MemoryModel) { // self.appRAMView.configure(appMemory: model.application) // self.sysRAMView.configure(systemRAM: model.system) // } // func systemStoreDidCatch(fps model:Double) { // self.appFPSView.configure(fps: model) // } // func systemStoreDidCatch(net model:NetModel) { // self.sysNetView.configure(net: model) // } //}
mit
sayheyrickjames/codepath-dev
week5/week5-homework-facebook-photos/week5-homework-facebook-photos/BaseTransition.swift
4
3433
// // BaseTransition.swift // transitionDemo // // Created by Timothy Lee on 2/22/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class BaseTransition: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning { var duration: NSTimeInterval = 0.4 var isPresenting: Bool = true var isInteractive: Bool = false var transitionContext: UIViewControllerContextTransitioning! var interactiveTransition: UIPercentDrivenInteractiveTransition! var percentComplete: CGFloat = 0 { didSet { interactiveTransition.updateInteractiveTransition(percentComplete) } } func animationControllerForPresentedController(presented: UIViewController!, presentingController presenting: UIViewController!, sourceController source: UIViewController!) -> UIViewControllerAnimatedTransitioning! { isPresenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController!) -> UIViewControllerAnimatedTransitioning! { isPresenting = false return self } func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return duration } func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if isInteractive { interactiveTransition = UIPercentDrivenInteractiveTransition() interactiveTransition.completionSpeed = 0.99 } else { interactiveTransition = nil } return interactiveTransition } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { var containerView = transitionContext.containerView() var toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! var fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! self.transitionContext = transitionContext if (isPresenting) { toViewController.view.bounds = fromViewController.view.bounds containerView.addSubview(toViewController.view) presentTransition(containerView, fromViewController: fromViewController, toViewController: toViewController) } else { dismissTransition(containerView, fromViewController: fromViewController, toViewController: toViewController) } } func presentTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) { } func dismissTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) { } func finish() { if isInteractive { interactiveTransition.finishInteractiveTransition() } if isPresenting == false { var fromViewController = transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)! fromViewController?.view.removeFromSuperview() } transitionContext?.completeTransition(true) } func cancel() { if isInteractive { interactiveTransition.cancelInteractiveTransition() } } }
gpl-2.0
dankogai/swift-numberkit
NumberKit/BigInt.swift
1
25581
// // BigInt.swift // NumberKit // // Created by Matthias Zenger on 12/08/2015. // Copyright © 2015 Matthias Zenger. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Darwin /// Class `BigInt` implements signed, arbitrary-precision integers. `BigInt` objects /// are immutable, i.e. all operations on `BigInt` objects return result objects. /// `BigInt` provides all the signed, integer arithmetic operations from Swift and /// implements the corresponding protocols. To make it easier to define large `BigInt` /// literals, `String` objects can be used for representing such numbers. They get /// implicitly coerced into `BigInt`. /// /// - Note: `BigInt` is internally implemented as a Swift array of UInt32 numbers /// and a boolean to represent the sign. Due to this overhead, for instance, /// representing a `UInt64` value as a `BigInt` will result in an object that /// requires more memory than the corresponding `UInt64` integer. public final class BigInt: Hashable, CustomStringConvertible, CustomDebugStringConvertible { // This is an array of `UInt32` words. The lowest significant word comes first in // the array. let words: [UInt32] // `negative` signals whether the number is positive or negative. let negative: Bool // All internal computations are based on 32-bit words; the base of this representation // is therefore `UInt32.max + 1`. private static let BASE: UInt64 = UInt64(UInt32.max) + 1 // `hiword` extracts the highest 32-bit value of a `UInt64`. private static func hiword(num: UInt64) -> UInt32 { return UInt32((num >> 32) & 0xffffffff) } // `loword` extracts the lowest 32-bit value of a `UInt64`. private static func loword(num: UInt64) -> UInt32 { return UInt32(num & 0xffffffff) } // `joinwords` combines two words into a `UInt64` value. private static func joinwords(lword: UInt32, _ hword: UInt32) -> UInt64 { return (UInt64(hword) << 32) + UInt64(lword) } /// Class `Base` defines a representation and type for the base used in computing /// `String` representations of `BigInt` objects. /// /// - Note: It is currently not possible to define custom `Base` objects. It needs /// to be figured out first what safety checks need to be put in place. public final class Base { private let digitSpace: [Character] private let digitMap: [Character: UInt8] private init(digitSpace: [Character], digitMap: [Character: UInt8]) { self.digitSpace = digitSpace self.digitMap = digitMap } private var radix: Int { return self.digitSpace.count } } /// Representing base 2 (binary) public static let BIN = Base( digitSpace: ["0", "1"], digitMap: ["0": 0, "1": 1] ) /// Representing base 8 (octal) public static let OCT = Base( digitSpace: ["0", "1", "2", "3", "4", "5", "6", "7"], digitMap: ["0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7] ) /// Representing base 10 (decimal) public static let DEC = Base( digitSpace: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], digitMap: ["0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9] ) /// Representing base 16 (hex) public static let HEX = Base( digitSpace: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"], digitMap: ["0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15] ) /// Maps a radix number to the corresponding `Base` object. Only 2, 8, 10, and 16 are /// supported. public static func base(radix: Int) -> Base { switch radix { case 2: return BigInt.BIN case 8: return BigInt.OCT case 10: return BigInt.DEC case 16: return BigInt.HEX default: preconditionFailure("unsupported base \(radix)") } } /// Internal primary constructor. It removes superfluous words and normalizes the /// representation of zero. private init(var _ words: [UInt32], negative: Bool) { while words.count > 1 && words[words.count - 1] == 0 { words.removeLast() } self.words = words self.negative = words.count == 1 && words[0] == 0 ? false : negative } private static let INT64_MAX = UInt64(Int64.max) /// Creates a `BigInt` from the given `UInt64` value public convenience init(_ value: UInt64) { self.init([BigInt.loword(value), BigInt.hiword(value)], negative: false) } /// Creates a `BigInt` from the given `Int64` value public convenience init(_ value: Int64) { let absvalue = value == Int64.min ? BigInt.INT64_MAX + 1 : UInt64(value < 0 ? -value : value) self.init([BigInt.loword(absvalue), BigInt.hiword(absvalue)], negative: value < 0) } /// Creates a `BigInt` from a sequence of digits for a given base. The first digit in the /// array of digits is the least significant one. `negative` is used to indicate negative /// `BigInt` numbers. public convenience init(var _ digits: [UInt8], negative: Bool = false, base: Base = BigInt.DEC) { var words: [UInt32] = [] var iterate: Bool repeat { var sum: UInt64 = 0 var res: [UInt8] = [] var j = 0 while j < digits.count && sum < BigInt.BASE { sum = sum * UInt64(base.radix) + UInt64(digits[j++]) } res.append(UInt8(BigInt.hiword(sum))) iterate = BigInt.hiword(sum) > 0 sum = UInt64(BigInt.loword(sum)) while j < digits.count { sum = sum * UInt64(base.radix) + UInt64(digits[j++]) res.append(UInt8(BigInt.hiword(sum))) iterate = true sum = UInt64(BigInt.loword(sum)) } words.append(BigInt.loword(sum)) digits = res } while iterate self.init(words, negative: negative) } /// Creates a `BigInt` from a string containing a number using the given base. public convenience init?(_ str: String, base: Base = BigInt.DEC) { var negative = false let chars = str.characters var i = chars.startIndex while i < chars.endIndex && chars[i] == " " { i++ } if i < chars.endIndex { if chars[i] == "-" { negative = true i++ } else if chars[i] == "+" { i++ } } if i < chars.endIndex && chars[i] == "0" { while i < chars.endIndex && chars[i] == "0" { i++ } if i == chars.endIndex { self.init(0) return } } var temp: [UInt8] = [] while i < chars.endIndex { if let digit = base.digitMap[chars[i]] { temp.append(digit) i++ } else { break } } while i < chars.endIndex && chars[i] == " " { i++ } guard i == chars.endIndex else { return nil } self.init(temp, negative: negative, base: base) } /// Converts the `BigInt` object into a string using the given base. `BigInt.DEC` is /// used as the default base. public func toString(base base: Base = BigInt.DEC) -> String { // Determine base let b = UInt64(base.digitSpace.count) precondition(b > 1 && b <= 36, "illegal base for BigInt string conversion") // Shortcut handling of zero if self.isZero { return String(base.digitSpace[0]) } // Build representation with base `b` in `str` var str: [UInt8] = [] var word = words[words.count - 1] while word > 0 { str.append(UInt8(word % UInt32(b))) word /= UInt32(b) } var temp: [UInt8] = [] if words.count > 1 { for i in 2...words.count { var carry: UInt64 = 0 // Multiply `str` with `BASE` and store in `temp` temp.removeAll() for s in str { carry += UInt64(s) * BigInt.BASE temp.append(UInt8(carry % b)) carry /= b } while carry > 0 { temp.append(UInt8(carry % b)) carry /= b } // Add `z` to `temp` and store in `str` word = words[words.count - i] var r = 0 str.removeAll() while r < temp.count || word > 0 { if r < temp.count { carry += UInt64(temp[r++]) } carry += UInt64(word) % b str.append(UInt8(carry % b)) carry /= b word /= UInt32(b) } if carry > 0 { str.append(UInt8(carry % b)) } } } // Convert representation in `str` into string var res = negative ? "-" : "" for i in 1...str.count { res.append(base.digitSpace[Int(str[str.count-i])]) } return res } /// Returns a string representation of this `BigInt` number using base 10. public var description: String { return toString() } /// Returns a string representation of this `BigInt` number for debugging purposes. public var debugDescription: String { var res = "{\(words.count): \(words[0])" for i in 1..<words.count { res += ", \(words[i])" } return res + "}" } /// Returns the `BigInt` as a `Int64` value if this is possible. If the number is outside /// the `Int64` range, the property will contain `nil`. public var intValue: Int64? { guard words.count <= 2 else { return nil } var value: UInt64 = UInt64(words[0]) if words.count == 2 { value += UInt64(words[1]) * BigInt.BASE } if negative && value == BigInt.INT64_MAX + 1 { return Int64.min } if value <= BigInt.INT64_MAX { return negative ? -Int64(value) : Int64(value) } return nil } /// Returns the `BigInt` as a `UInt64` value if this is possible. If the number is outside /// the `UInt64` range, the property will contain `nil`. public var uintValue: UInt64? { guard words.count <= 2 && !negative else { return nil } var value: UInt64 = UInt64(words[0]) if words.count == 2 { value += UInt64(words[1]) * BigInt.BASE } return value } /// Returns the `BigInt` as a `Double` value. This might lead to a significant loss of /// precision, but this operation is always possible. public var doubleValue: Double { var res: Double = 0.0 for word in words.reverse() { res = res * Double(BigInt.BASE) + Double(word) } return self.negative ? -res : res } /// The hash value of this `BigInt` object. public var hashValue: Int { var hash: Int = 0 for i in 0..<words.count { hash = (31 &* hash) &+ words[i].hashValue } return hash } /// Returns true if this `BigInt` is negative. public var isNegative: Bool { return negative } /// Returns true if this `BigInt` represents zero. public var isZero: Bool { return words.count == 1 && words[0] == 0 } /// Returns a `BigInt` with swapped sign. public var negate: BigInt { return BigInt(words, negative: !negative) } /// Returns the absolute value of this `BigInt`. public var abs: BigInt { return BigInt(words, negative: false) } /// Returns -1 if `self` is less than `rhs`, /// 0 if `self` is equals to `rhs`, /// +1 if `self` is greater than `rhs` public func compareTo(rhs: BigInt) -> Int { guard self.negative == rhs.negative else { return self.negative ? -1 : 1 } return self.negative ? rhs.compareDigits(self) : compareDigits(rhs) } private func compareDigits(rhs: BigInt) -> Int { guard words.count == rhs.words.count else { return words.count < rhs.words.count ? -1 : 1 } for i in 1...words.count { let a = words[words.count - i] let b = rhs.words[words.count - i] if a != b { return a < b ? -1 : 1 } } return 0 } /// Returns the sum of `self` and `rhs` as a `BigInt`. public func plus(rhs: BigInt) -> BigInt { guard self.negative == rhs.negative else { return self.minus(rhs.negate) } let (b1, b2) = self.words.count < rhs.words.count ? (rhs, self) : (self, rhs) var res = [UInt32]() res.reserveCapacity(b1.words.count) var sum: UInt64 = 0 for i in 0..<b2.words.count { sum += UInt64(b1.words[i]) sum += UInt64(b2.words[i]) res.append(BigInt.loword(sum)) sum = UInt64(BigInt.hiword(sum)) } for i in b2.words.count..<b1.words.count { sum += UInt64(b1.words[i]) res.append(BigInt.loword(sum)) sum = UInt64(BigInt.hiword(sum)) } if sum > 0 { res.append(BigInt.loword(sum)) } return BigInt(res, negative: self.negative) } /// Returns the difference between `self` and `rhs` as a `BigInt`. public func minus(rhs: BigInt) -> BigInt { guard self.negative == rhs.negative else { return self.plus(rhs.negate) } let cmp = compareDigits(rhs) guard cmp != 0 else { return 0 } let negative = cmp < 0 ? !self.negative : self.negative let (b1, b2) = cmp < 0 ? (rhs, self) : (self, rhs) var res = [UInt32]() var carry: UInt64 = 0 for i in 0..<b2.words.count { if UInt64(b1.words[i]) < UInt64(b2.words[i]) + carry { res.append(UInt32(BigInt.BASE + UInt64(b1.words[i]) - UInt64(b2.words[i]) - carry)) carry = 1 } else { res.append(b1.words[i] - b2.words[i] - UInt32(carry)) carry = 0 } } for i in b2.words.count..<b1.words.count { if b1.words[i] < UInt32(carry) { res.append(UInt32.max) carry = 1 } else { res.append(b1.words[i] - UInt32(carry)) carry = 0 } } return BigInt(res, negative: negative) } /// Returns the result of mulitplying `self` with `rhs` as a `BigInt` public func times(rhs: BigInt) -> BigInt { let (b1, b2) = self.words.count < rhs.words.count ? (rhs, self) : (self, rhs) var res = [UInt32](count: b1.words.count + b2.words.count, repeatedValue: 0) for i in 0..<b2.words.count { var sum: UInt64 = 0 for j in 0..<b1.words.count { sum += UInt64(res[i + j]) + UInt64(b1.words[j]) * UInt64(b2.words[i]) res[i + j] = BigInt.loword(sum) sum = UInt64(BigInt.hiword(sum)) } res[i + b1.words.count] = BigInt.loword(sum) } return BigInt(res, negative: b1.negative != b2.negative) } private static func multSub(approx: UInt32, _ divis: [UInt32], inout _ rem: [UInt32], _ from: Int) { var sum: UInt64 = 0 var carry: UInt64 = 0 for j in 0..<divis.count { sum += UInt64(divis[j]) * UInt64(approx) let x = UInt64(loword(sum)) + carry if UInt64(rem[from + j]) < x { rem[from + j] = UInt32(BigInt.BASE + UInt64(rem[from + j]) - x) carry = 1 } else { rem[from + j] = UInt32(UInt64(rem[from + j]) - x) carry = 0 } sum = UInt64(hiword(sum)) } } private static func subIfPossible(divis: [UInt32], inout _ rem: [UInt32], _ from: Int) -> Bool { var i = divis.count while i > 0 && divis[i - 1] >= rem[from + i - 1] { if divis[i - 1] > rem[from + i - 1] { return false } i-- } var carry: UInt64 = 0 for j in 0..<divis.count { let x = UInt64(divis[j]) + carry if UInt64(rem[from + j]) < x { rem[from + j] = UInt32(BigInt.BASE + UInt64(rem[from + j]) - x) carry = 1 } else { rem[from + j] = UInt32(UInt64(rem[from + j]) - x) carry = 0 } } return true } /// Divides `self` by `rhs` and returns the result as a `BigInt`. public func dividedBy(rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) { guard rhs.words.count <= self.words.count else { return (BigInt(0), self.abs) } let neg = self.negative != rhs.negative if rhs.words.count == self.words.count { let cmp = compareTo(rhs) if cmp == 0 { return (BigInt(neg ? -1 : 1), BigInt(0)) } else if cmp < 0 { return (BigInt(0), self.abs) } } var rem = [UInt32](self.words) rem.append(0) var divis = [UInt32](rhs.words) divis.append(0) var sizediff = self.words.count - rhs.words.count let div = UInt64(rhs.words[rhs.words.count - 1]) + 1 var res = [UInt32](count: sizediff + 1, repeatedValue: 0) var divident = rem.count - 2 repeat { var x = BigInt.joinwords(rem[divident], rem[divident + 1]) var approx = x / div res[sizediff] = 0 while approx > 0 { res[sizediff] += UInt32(approx) // Is this cast ok? BigInt.multSub(UInt32(approx), divis, &rem, sizediff) x = BigInt.joinwords(rem[divident], rem[divident + 1]) approx = x / div } if BigInt.subIfPossible(divis, &rem, sizediff) { res[sizediff]++ } divident-- sizediff-- } while sizediff >= 0 return (BigInt(res, negative: neg), BigInt(rem, negative: false)) } /// Raises this `BigInt` value to the power of `exp`. public func toPowerOf(exp: BigInt) -> BigInt { return pow(self, exp) } /// Computes the bitwise `and` between this value and `rhs`. public func and(rhs: BigInt) -> BigInt { let size = min(self.words.count, rhs.words.count) var res = [UInt32]() res.reserveCapacity(size) for i in 0..<size { res.append(self.words[i] & rhs.words[i]) } return BigInt(res, negative: self.negative && rhs.negative) } /// Computes the bitwise `or` between this value and `rhs`. public func or(rhs: BigInt) -> BigInt { let size = max(self.words.count, rhs.words.count) var res = [UInt32]() res.reserveCapacity(size) for i in 0..<size { let fst = i < self.words.count ? self.words[i] : 0 let snd = i < rhs.words.count ? rhs.words[i] : 0 res.append(fst | snd) } return BigInt(res, negative: self.negative || rhs.negative) } /// Computes the bitwise `xor` between this value and `rhs`. public func xor(rhs: BigInt) -> BigInt { let size = max(self.words.count, rhs.words.count) var res = [UInt32]() res.reserveCapacity(size) for i in 0..<size { let fst = i < self.words.count ? self.words[i] : 0 let snd = i < rhs.words.count ? rhs.words[i] : 0 res.append(fst ^ snd) } return BigInt(res, negative: self.negative || rhs.negative) } /// Inverts the bits in this `BigInt`. public var invert: BigInt { var res = [UInt32]() res.reserveCapacity(self.words.count) for word in self.words { res.append(~word) } return BigInt(res, negative: !self.negative) } } /// This extension implements all the boilerplate to make `BigInt` compatible /// to the applicable Swift 2 protocols. `BigInt` is convertible from integer literals, /// convertible from Strings, it's a signed number, equatable, comparable, and implements /// all integer arithmetic functions. extension BigInt: IntegerLiteralConvertible, StringLiteralConvertible, Equatable, IntegerArithmeticType, SignedIntegerType { public typealias Distance = BigInt public convenience init(_ value: UInt) { self.init(Int64(value)) } public convenience init(_ value: UInt8) { self.init(Int64(value)) } public convenience init(_ value: UInt16) { self.init(Int64(value)) } public convenience init(_ value: UInt32) { self.init(Int64(value)) } public convenience init(_ value: Int) { self.init(Int64(value)) } public convenience init(_ value: Int8) { self.init(Int64(value)) } public convenience init(_ value: Int16) { self.init(Int64(value)) } public convenience init(_ value: Int32) { self.init(Int64(value)) } public convenience init(integerLiteral value: Int64) { self.init(value) } public convenience init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) { self.init(Int64(_builtinIntegerLiteral: value)) } public convenience init(stringLiteral value: String) { if let bi = BigInt(value) { self.init(bi.words, negative: bi.negative) } else { self.init(0) } } public convenience init( extendedGraphemeClusterLiteral value: String.ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: String(value)) } public convenience init( unicodeScalarLiteral value: String.UnicodeScalarLiteralType) { self.init(stringLiteral: String(value)) } public static func addWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { return (lhs.plus(rhs), overflow: false) } public static func subtractWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { return (lhs.minus(rhs), overflow: false) } public static func multiplyWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { return (lhs.times(rhs), overflow: false) } public static func divideWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { let res = lhs.dividedBy(rhs) return (res.quotient, overflow: false) } public static func remainderWithOverflow(lhs: BigInt, _ rhs: BigInt) -> (BigInt, overflow: Bool) { let res = lhs.dividedBy(rhs) return (res.remainder, overflow: false) } /// The empty bitset. public static var allZeros: BigInt { return BigInt(0) } /// Returns this number as an `IntMax` number public func toIntMax() -> IntMax { if let res = self.intValue { return res } preconditionFailure("`BigInt` value cannot be converted to `IntMax`") } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. public func advancedBy(n: BigInt) -> BigInt { return self.plus(n) } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. public func distanceTo(other: BigInt) -> BigInt { return other.minus(self) } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. /// Returns the next consecutive value after `self`. /// /// - Requires: The next value is representable. public func successor() -> BigInt { return self.plus(1) } /// This is in preparation for making `BigInt` implement `SignedIntegerType`. /// Returns the previous consecutive value before `self`. /// /// - Requires: `self` has a well-defined predecessor. public func predecessor() -> BigInt { return self.minus(1) } } /// Returns the sum of `lhs` and `rhs` /// /// - Note: Without this declaration, the compiler complains that `+` is declared /// multiple times. public func +(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.plus(rhs) } /// Returns the difference between `lhs` and `rhs` /// /// - Note: Without this declaration, the compiler complains that `+` is declared /// multiple times. public func -(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.minus(rhs) } /// Adds `rhs` to `lhs` and stores the result in `lhs`. /// /// - Note: Without this declaration, the compiler complains that `+` is declared /// multiple times. public func +=(inout lhs: BigInt, rhs: BigInt) { lhs = lhs.plus(rhs) } /// Returns true if `lhs` is less than `rhs`, false otherwise. public func <(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) < 0 } /// Returns true if `lhs` is less than or equals `rhs`, false otherwise. public func <=(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) <= 0 } /// Returns true if `lhs` is greater or equals `rhs`, false otherwise. public func >=(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) >= 0 } /// Returns true if `lhs` is greater than equals `rhs`, false otherwise. public func >(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) > 0 } /// Returns true if `lhs` is equals `rhs`, false otherwise. public func ==(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) == 0 } /// Returns true if `lhs` is not equals `rhs`, false otherwise. public func !=(lhs: BigInt, rhs: BigInt) -> Bool { return lhs.compareTo(rhs) != 0 } /// Negates `self`. public prefix func -(num: BigInt) -> BigInt { return num.negate } /// Returns the intersection of bits set in `lhs` and `rhs`. public func &(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.and(rhs) } /// Returns the union of bits set in `lhs` and `rhs`. public func |(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.or(rhs) } /// Returns the bits that are set in exactly one of `lhs` and `rhs`. public func ^(lhs: BigInt, rhs: BigInt) -> BigInt { return lhs.xor(rhs) } /// Returns the bitwise inverted BigInt public prefix func ~(x: BigInt) -> BigInt { return x.invert } /// Returns the maximum of `fst` and `snd`. public func max(fst: BigInt, snd: BigInt) -> BigInt { return fst.compareTo(snd) >= 0 ? fst : snd } /// Returns the minimum of `fst` and `snd`. public func min(fst: BigInt, snd: BigInt) -> BigInt { return fst.compareTo(snd) <= 0 ? fst : snd }
apache-2.0
gkaimakas/SwiftyForms
SwiftyForms/Classes/Inputs/EmailInput.swift
1
184
// // EmailInput.swift // Pods // // Created by Γιώργος Καϊμακάς on 24/05/16. // // import Foundation import SwiftValidators open class EmailInput: TextInput { }
mit
onmyway133/Resolver
Pod/Classes/Container.swift
1
789
// // Container.swift // Pods // // Created by Khoa Pham on 12/18/15. // // import Foundation struct Container { var registrations = [RegistrationKey: RegistrationType]() mutating func register<F>(tag tag: String? = nil, factory: F) { let key = RegistrationKey(tag: tag ?? "", factoryType: F.self) let registration = Registration<F>(factory: factory) registrations[key] = registration } func resolve<T, F>(tag tag: String? = nil, builder: F -> T) throws -> T { let key = RegistrationKey(tag: tag ?? "", factoryType: F.self) if let registration = registrations[key] as? Registration<F> { return builder(registration.factory) } else { throw ResolverError.RegistrationNotFound } } }
mit
julien-c/swifter
Sources/Swifter/DemoServer.swift
1
3015
// // DemoServer.swift // Swifter // Copyright (c) 2015 Damian Kołakowski. All rights reserved. // import Foundation public func demoServer(publicDir: String?) -> HttpServer { let server = HttpServer() if let publicDir = publicDir { server["/resources/:file"] = HttpHandlers.directory(publicDir) } server["/files/:path"] = HttpHandlers.directoryBrowser("~/") server["/"] = { r in var listPage = "Available services:<br><ul>" listPage += server.routes.map({ "<li><a href=\"\($0)\">\($0)</a></li>"}).joinWithSeparator("") return .OK(.Html(listPage)) } server["/magic"] = { .OK(.Html("You asked for " + $0.url)) } server["/test/:param1/:param2"] = { r in var headersInfo = "" for (name, value) in r.headers { headersInfo += "\(name) : \(value)<br>" } var queryParamsInfo = "" for (name, value) in r.urlParams { queryParamsInfo += "\(name) : \(value)<br>" } var pathParamsInfo = "" for token in r.params { pathParamsInfo += "\(token.0) : \(token.1)<br>" } return .OK(.Html("<h3>Address: \(r.address)</h3><h3>Url:</h3> \(r.url)<h3>Method: \(r.method)</h3><h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)<h3>Path params:</h3>\(pathParamsInfo)")) } server["/login"] = { r in switch r.method.uppercaseString { case "GET": if let rootDir = publicDir { if let html = NSData(contentsOfFile:"\(rootDir)/login.html") { var array = [UInt8](count: html.length, repeatedValue: 0) html.getBytes(&array, length: html.length) return HttpResponse.RAW(200, "OK", nil, array) } else { return .NotFound } } case "POST": let formFields = r.parseForm() return HttpResponse.OK(.Html(formFields.map({ "\($0.0) = \($0.1)" }).joinWithSeparator("<br>"))) default: return .NotFound } return .NotFound } server["/demo"] = { r in return .OK(.Html("<center><h2>Hello Swift</h2><img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br></center>")) } server["/raw"] = { request in return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], [UInt8]("Sample Response".utf8)) } server["/json"] = { request in let jsonObject: NSDictionary = [NSString(string: "foo"): NSNumber(int: 3), NSString(string: "bar"): NSString(string: "baz")] return .OK(.Json(jsonObject)) } server["/redirect"] = { request in return .MovedPermanently("http://www.google.com") } server["/long"] = { request in var longResponse = "" for k in 0..<1000 { longResponse += "(\(k)),->" } return .OK(.Html(longResponse)) } return server }
bsd-3-clause
gkaimakas/ReactiveBluetooth
ReactiveBluetooth/Classes/CBPeripheral/CBPeripheral+ConnectionOption.swift
1
2053
// // CBPeripheral+ConnectionOption.swift // ReactiveCoreBluetooth // // Created by George Kaimakas on 02/03/2018. // import CoreBluetooth extension CBPeripheral { public enum ConnectionOption: Equatable, Hashable { public static func ==(lhs: ConnectionOption, rhs: ConnectionOption) -> Bool { switch (lhs, rhs){ case (.notifyOnConnection(let a), .notifyOnConnection(let b)): return a == b case (.notifyOnDisconnection(let a), .notifyOnDisconnection(let b)): return a == b case (.notifyOnNotification(let a), .notifyOnNotification(let b)): return a == b default: return false } } public var hashValue: Int { switch self { case .notifyOnConnection(_): return 4_000 case .notifyOnDisconnection(_): return 40_000 case .notifyOnNotification(_): return 400_000 } } public var key: String { switch self { case .notifyOnConnection(_): return CBConnectPeripheralOptionNotifyOnConnectionKey case .notifyOnDisconnection(_): return CBConnectPeripheralOptionNotifyOnDisconnectionKey case .notifyOnNotification(_): return CBConnectPeripheralOptionNotifyOnNotificationKey } } public var value: Any { switch self { case .notifyOnConnection(let value): return value as Any case .notifyOnDisconnection(let value): return value as Any case .notifyOnNotification(let value): return value as Any } } case notifyOnConnection(Bool) case notifyOnDisconnection(Bool) case notifyOnNotification(Bool) } } extension Set where Element == CBPeripheral.ConnectionOption { public func merge() -> [String: Any] { return reduce([String: Any]() ) { (partialResult, item) -> [String: Any] in var result = partialResult result[item.key] = item.value return result } } }
mit
jfosterdavis/FlashcardHero
FlashcardHero/GameProtocols.swift
1
1726
// // GameProtocols.swift // FlashcardHero // // Created by Jacob Foster Davis on 12/2/16. // Copyright © 2016 Zero Mu, LLC. All rights reserved. // import Foundation //These game protocols are applied to any given game. Games will be accessed using these protocols, which pass success and failure criteria. struct GameVariantProtocols { static let MaxPoints = "MaxPoints" static let PerfectGame = "PerfectGame" static let protocols : Set<String> = [GameVariantProtocols.MaxPoints, GameVariantProtocols.PerfectGame] //mirror so that can iterate over this list //adapted from http://stackoverflow.com/questions/37569098/iterate-over-struct-attributes-in-swift // var customMirror : Mirror { // get { // return Mirror(self, children: ["MaxPoints" : GameProtocols.MaxPoints, "PerfectGame" : GameProtocols.PerfectGame]) // } // } } protocol GameVariantBase: class { var gameCallerDelegate: GameCaller? {get set} func finishGame(_ didPlayerSucceed: Bool) } protocol GameVariantMaxPoints: GameVariantBase { func playGameUntil(playerScoreIs maxPoints: Int, unlessPlayerScoreReaches minPoints: Int?, sender: GameCaller) } protocol GameVariantConsecutivePoints: GameVariantBase { func playGameUntil(playerScores consecutivePoints: Int, unlessPlayerScoreReaches minPoints: Int?, sender: GameCaller) } protocol GameVariantPerfectGame: GameVariantBase { func playGameUntil(playerReaches maxPoints: Int, unlessPlayerMisses missedPoints: Int, sender: GameCaller) } //classes that call games to be played must conform to the following protocol GameCaller: class { func gameFinished(_ wasObjectiveAchieved: Bool, forGame sender: Game) }
apache-2.0
castial/Quick-Start-iOS
Quick-Start-iOS/Utils/Constants/Constants.swift
1
766
// // Constants.swift // Quick-Start-iOS // // Created by work on 2016/10/14. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit class Constants: NSObject { struct Rect { static let statusBarHeight = UIApplication.shared.statusBarFrame.size.height // 状态栏高度 static let navHeight: CGFloat = 44 // 默认导航栏高度 static let tabBarHeight: CGFloat = 49 // 默认TabBar高度 static let ScreenWidth = UIScreen.main.bounds.size.width // 屏幕宽度 static let ScreenHeight = UIScreen.main.bounds.size.height // 屏幕高度 } struct Notification { static let DISPATCH_AD_PAGE = NSNotification.Name("dispatch_ad_page") // 广告跳转通知 } }
mit
FirebaseExtended/firebase-video-samples
fundamentals/apple/auth-sign-in-with-apple/starter/Favourites/Shared/Auth/AuthenticationViewModel.swift
1
6808
// // AuthenticationViewModel.swift // Favourites // // Created by Peter Friese on 08.07.2022 // Copyright © 2022 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import FirebaseAuth // For Sign in with Apple import AuthenticationServices import CryptoKit enum AuthenticationState { case unauthenticated case authenticating case authenticated } enum AuthenticationFlow { case login case signUp } @MainActor class AuthenticationViewModel: ObservableObject { @Published var email = "" @Published var password = "" @Published var confirmPassword = "" @Published var flow: AuthenticationFlow = .login @Published var isValid = false @Published var authenticationState: AuthenticationState = .unauthenticated @Published var errorMessage = "" @Published var user: User? @Published var displayName = "" private var currentNonce: String? init() { registerAuthStateHandler() verifySignInWithAppleAuthenticationState() $flow .combineLatest($email, $password, $confirmPassword) .map { flow, email, password, confirmPassword in flow == .login ? !(email.isEmpty || password.isEmpty) : !(email.isEmpty || password.isEmpty || confirmPassword.isEmpty) } .assign(to: &$isValid) } private var authStateHandler: AuthStateDidChangeListenerHandle? func registerAuthStateHandler() { if authStateHandler == nil { authStateHandler = Auth.auth().addStateDidChangeListener { auth, user in self.user = user self.authenticationState = user == nil ? .unauthenticated : .authenticated self.displayName = user?.displayName ?? user?.email ?? "" } } } func switchFlow() { flow = flow == .login ? .signUp : .login errorMessage = "" } private func wait() async { do { print("Wait") try await Task.sleep(nanoseconds: 1_000_000_000) print("Done") } catch { } } func reset() { flow = .login email = "" password = "" confirmPassword = "" } } // MARK: - Email and Password Authentication extension AuthenticationViewModel { func signInWithEmailPassword() async -> Bool { authenticationState = .authenticating do { try await Auth.auth().signIn(withEmail: self.email, password: self.password) return true } catch { print(error) errorMessage = error.localizedDescription authenticationState = .unauthenticated return false } } func signUpWithEmailPassword() async -> Bool { authenticationState = .authenticating do { try await Auth.auth().createUser(withEmail: email, password: password) return true } catch { print(error) errorMessage = error.localizedDescription authenticationState = .unauthenticated return false } } func signOut() { do { try Auth.auth().signOut() } catch { print(error) errorMessage = error.localizedDescription } } func deleteAccount() async -> Bool { do { try await user?.delete() return true } catch { errorMessage = error.localizedDescription return false } } } // MARK: Sign in with Apple extension AuthenticationViewModel { func handleSignInWithAppleRequest(_ request: ASAuthorizationAppleIDRequest) { } func handleSignInWithAppleCompletion(_ result: Result<ASAuthorization, Error>) { } func updateDisplayName(for user: User, with appleIDCredential: ASAuthorizationAppleIDCredential, force: Bool = false) async { if let currentDisplayName = Auth.auth().currentUser?.displayName, currentDisplayName.isEmpty { let changeRequest = user.createProfileChangeRequest() changeRequest.displayName = appleIDCredential.displayName() do { try await changeRequest.commitChanges() self.displayName = Auth.auth().currentUser?.displayName ?? "" } catch { print("Unable to update the user's displayname: \(error.localizedDescription)") errorMessage = error.localizedDescription } } } func verifySignInWithAppleAuthenticationState() { let appleIDProvider = ASAuthorizationAppleIDProvider() let providerData = Auth.auth().currentUser?.providerData if let appleProviderData = providerData?.first(where: { $0.providerID == "apple.com" }) { Task { do { let credentialState = try await appleIDProvider.credentialState(forUserID: appleProviderData.uid) switch credentialState { case .authorized: break // The Apple ID credential is valid. case .revoked, .notFound: // The Apple ID credential is either revoked or was not found, so show the sign-in UI. self.signOut() default: break } } catch { } } } } } extension ASAuthorizationAppleIDCredential { func displayName() -> String { return [self.fullName?.givenName, self.fullName?.familyName] .compactMap( {$0}) .joined(separator: " ") } } // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce private func randomNonceString(length: Int = 32) -> String { precondition(length > 0) let charset: [Character] = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._") var result = "" var remainingLength = length while remainingLength > 0 { let randoms: [UInt8] = (0 ..< 16).map { _ in var random: UInt8 = 0 let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random) if errorCode != errSecSuccess { fatalError( "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)" ) } return random } randoms.forEach { random in if remainingLength == 0 { return } if random < charset.count { result.append(charset[Int(random)]) remainingLength -= 1 } } } return result } private func sha256(_ input: String) -> String { let inputData = Data(input.utf8) let hashedData = SHA256.hash(data: inputData) let hashString = hashedData.compactMap { String(format: "%02x", $0) }.joined() return hashString }
apache-2.0
Praesentia/MedKitDomain-Swift
Source/AccountManagerObserver.swift
1
1790
/* ----------------------------------------------------------------------------- This source file is part of MedKitDomain. Copyright 2017-2018 Jon Griffeth Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- */ import Foundation import MedKitCore /** AccountManager observer */ public protocol AccountManagerObserver: class { /** Account manager did add account. Notifies an observer a new account has been added to the manager. */ func accountManager(_ manager: AccountManager, didAdd account: Account) /** Account manager did remove account. Notifies an observer an existing account has been removed from the manager. */ func accountManager(_ manager: AccountManager, didRemove account: Account) /** Account manager did update. Notifies an observer that the manager has been reset, typically called after being initialized. */ func accountManagerDidUpdate(_ manager: AccountManager) /** Account manager did primary. Notifies an observer that the primary account has been updated. */ func accountManagerDidUpdatePrimary(_ manager: AccountManager) } // End of File
apache-2.0
Urinx/SublimeCode
Sublime/Sublime/Configure.swift
1
2037
// // Configure.swift // Sublime // // Created by Eular on 4/26/16. // Copyright © 2016 Eular. All rights reserved. // import Foundation struct Config { // Cycript开启监听 static var CycriptStartListen: Bool { get { return Global.Database.boolForKey("Config-CycriptStartListen") } set { Global.Database.setBool(newValue, forKey: "Config-CycriptStartListen") } } // 下滑全屏 static var FullScreenCodeReadingMode: Bool { get { return Global.Database.boolForKey("Config-FullScreenCodeReadingMode") } set { Global.Database.setBool(newValue, forKey: "Config-FullScreenCodeReadingMode") } } // 显示隐藏文件 static var ShowHiddenFiles: Bool { get { return Global.Database.boolForKey("Config-ShowHiddenFiles") } set { Global.Database.setBool(newValue, forKey: "Config-ShowHiddenFiles") } } // 是否为本项目点赞 static var Starred: Bool { get { return Global.Database.boolForKey("Donate-Starred") } set { Global.Database.setBool(newValue, forKey: "Donate-Starred") } } // 是否关注作者 static var FollowedAuthor: Bool { get { return Global.Database.boolForKey("Donate-FollowedAuthor") } set { Global.Database.setBool(newValue, forKey: "Donate-FollowedAuthor") } } static var WeixinDonated: Bool { get { return Global.Database.boolForKey("Donate-WeixinDonated") } set { Global.Database.setBool(newValue, forKey: "Donate-WeixinDonated") } } static var AlipayDonated: Bool { get { return Global.Database.boolForKey("Donate-AlipayDonated") } set { Global.Database.setBool(newValue, forKey: "Donate-AlipayDonated") } } }
gpl-3.0
Webtrekk/webtrekk-ios-sdk
Source/Internal/Reachability/Reachability.swift
1
11115
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // TODO: Although not part of watchOS target, still generates an error on cocoapods lib lint #if !os(watchOS) import SystemConfiguration import Foundation public enum ReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue case UnableToGetInitialFlags } @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged") public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") public extension Notification.Name { static let reachabilityChanged = Notification.Name("reachabilityChanged") } public class Reachability { public typealias NetworkReachable = (Reachability) -> Void public typealias NetworkUnreachable = (Reachability) -> Void @available(*, unavailable, renamed: "Connection") public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public enum Connection: CustomStringConvertible { case none, wifi, cellular public var description: String { switch self { case .cellular: return "Cellular" case .wifi: return "WiFi" case .none: return "No Connection" } } } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? @available(*, deprecated, renamed: "allowsCellularConnection") public let reachableOnWWAN: Bool = true /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default @available(*, deprecated, renamed: "connection.description") public var currentReachabilityString: String { return "\(connection)" } @available(*, unavailable, renamed: "connection") public var currentReachabilityStatus: Connection { return connection } public var connection: Connection { if flags == nil { try? setReachabilityFlags() } switch flags?.connection { case .none?, nil: return .none case .cellular?: return allowsCellularConnection ? .cellular : .none case .wifi?: return .wifi } } fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate let reachabilityRef: SCNetworkReachability fileprivate let reachabilitySerialQueue: DispatchQueue fileprivate(set) var flags: SCNetworkReachabilityFlags? { didSet { guard flags != oldValue else { return } reachabilityChanged() } } required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { self.allowsCellularConnection = true self.reachabilityRef = reachabilityRef self.reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability", qos: queueQoS, target: targetQueue) } public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil } self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue) } deinit { stopNotifier() } } public extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard !notifierRunning else { return } let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() reachability.flags = flags } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an initial check try setReachabilityFlags() notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** @available(*, message: "Please use `connection != .none`") var isReachable: Bool { return connection != .none } @available(*, message: "Please use `connection == .cellular`") var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return connection == .cellular } @available(*, message: "Please use `connection == .wifi`") var isReachableViaWiFi: Bool { return connection == .wifi } var description: String { guard let flags = flags else { return "unavailable flags" } let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X" let R = flags.isReachableFlagSet ? "R" : "-" let c = flags.isConnectionRequiredFlagSet ? "c" : "-" let t = flags.isTransientConnectionFlagSet ? "t" : "-" let i = flags.isInterventionRequiredFlagSet ? "i" : "-" let C = flags.isConnectionOnTrafficFlagSet ? "C" : "-" let D = flags.isConnectionOnDemandFlagSet ? "D" : "-" let l = flags.isLocalAddressFlagSet ? "l" : "-" let d = flags.isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func setReachabilityFlags() throws { try reachabilitySerialQueue.sync { [unowned self] in var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) { self.stopNotifier() throw ReachabilityError.UnableToGetInitialFlags } self.flags = flags } } func reachabilityChanged() { let block = connection != .none ? whenReachable : whenUnreachable DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } block?(strongSelf) strongSelf.notificationCenter.post(name: .reachabilityChanged, object: strongSelf) } } } extension SCNetworkReachabilityFlags { typealias Connection = Reachability.Connection var connection: Connection { guard isReachableFlagSet else { return .none } // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi #if targetEnvironment(simulator) return .wifi #else var connection = Connection.none if !isConnectionRequiredFlagSet { connection = .wifi } if isConnectionOnTrafficOrDemandFlagSet { if !isInterventionRequiredFlagSet { connection = .wifi } } if isOnWWANFlagSet { connection = .cellular } return connection #endif } var isOnWWANFlagSet: Bool { #if os(iOS) return contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return contains(.isLocalAddress) } var isDirectFlagSet: Bool { return contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } } #endif
mit
JeeLiu/tispr-card-stack
TisprCardStackExample/TisprCardStackExample/TisprCardStackDemoViewCell.swift
5
1847
/* Copyright 2015 BuddyHopp, 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. */ // // TisprCardStackDemoViewCell.swift // TisprCardStack // // Created by Andrei Pitsko on 7/12/15. // import UIKit import TisprCardStack class TisprCardStackDemoViewCell: TisprCardStackViewCell { @IBOutlet weak var text: UILabel! @IBOutlet weak var voteSmile: UIImageView! override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 12 clipsToBounds = false } override var center: CGPoint { didSet { updateSmileVote() } } override internal func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) { super.applyLayoutAttributes(layoutAttributes) updateSmileVote() } func updateSmileVote() { let rotation = atan2(transform.b, transform.a) * 100 var smileImageName = "smile_neutral" if rotation > 15 { smileImageName = "smile_face_2" } else if rotation > 0 { smileImageName = "smile_face_1" } else if rotation < -15 { smileImageName = "smile_rotten_2" } else if rotation < 0 { smileImageName = "smile_rotten_1" } voteSmile.image = UIImage(named: smileImageName) } }
apache-2.0
kharrison/CodeExamples
Playgrounds/ContentMode.playground/Pages/Right.xcplaygroundpage/Contents.swift
1
362
import UIKit import PlaygroundSupport /*: ### Right Fix the position of the content. Does not scale or stretch the content. */ let myView = StarView(frame: CGRect(x: 0, y: 0, width:200, height:350)) myView.starImageView.contentMode = .right myView PlaygroundPage.current.liveView = myView //: [Previous](@previous) //: [Index](contentMode) //: [Next](@next)
bsd-3-clause
yeziahehe/Gank
Pods/LeanCloud/Sources/Storage/DataType/Dictionary.swift
1
5892
// // LCDictionary.swift // LeanCloud // // Created by Tang Tianyong on 2/27/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation /** LeanCloud dictionary type. It is a wrapper of `Swift.Dictionary` type, used to store a dictionary value. */ @dynamicMemberLookup public final class LCDictionary: NSObject, LCValue, LCValueExtension, Collection, ExpressibleByDictionaryLiteral { public typealias Key = String public typealias Value = LCValue public typealias Index = DictionaryIndex<Key, Value> public private(set) var value: [Key: Value] = [:] var elementDidChange: ((Key, Value?) -> Void)? public override init() { super.init() } public convenience init(_ value: [Key: Value]) { self.init() self.value = value } public convenience init(_ value: [Key: LCValueConvertible]) { self.init() self.value = value.mapValue { value in value.lcValue } } /** Create copy of dictionary. - parameter dictionary: The dictionary to be copied. */ public convenience init(_ dictionary: LCDictionary) { self.init() self.value = dictionary.value } public convenience required init(dictionaryLiteral elements: (Key, Value)...) { self.init(Dictionary<Key, Value>(elements: elements)) } public convenience init(unsafeObject: Any) throws { self.init() guard let object = unsafeObject as? [Key: Any] else { throw LCError( code: .malformedData, reason: "Failed to construct LCDictionary with non-dictionary object.") } value = try object.mapValue { value in try ObjectProfiler.shared.object(jsonValue: value) } } public required init?(coder aDecoder: NSCoder) { /* Note: We have to make type casting twice here, or it will crash for unknown reason. It seems that it's a bug of Swift. */ value = (aDecoder.decodeObject(forKey: "value") as? [String: AnyObject] as? [String: LCValue]) ?? [:] } public func encode(with aCoder: NSCoder) { aCoder.encode(value, forKey: "value") } public func copy(with zone: NSZone?) -> Any { return LCDictionary(value) } public override func isEqual(_ object: Any?) -> Bool { if let object = object as? LCDictionary { return object === self || object.value == value } else { return false } } public func makeIterator() -> DictionaryIterator<Key, Value> { return value.makeIterator() } public var startIndex: DictionaryIndex<Key, Value> { return value.startIndex } public var endIndex: DictionaryIndex<Key, Value> { return value.endIndex } public func index(after i: DictionaryIndex<Key, Value>) -> DictionaryIndex<Key, Value> { return value.index(after: i) } public subscript(position: DictionaryIndex<Key, Value>) -> (key: Key, value: Value) { return value[position] } public subscript(key: Key) -> Value? { get { return value[key] } set { value[key] = newValue elementDidChange?(key, newValue) } } public subscript(dynamicMember key: String) -> LCValueConvertible? { get { return self[key] } set { self[key] = newValue?.lcValue } } /** Removes the given key and its associated value from dictionary. - parameter key: The key to remove along with its associated value. - returns: The value that was removed, or `nil` if the key was not found. */ @discardableResult public func removeValue(forKey key: Key) -> Value? { return value.removeValue(forKey: key) } func set(_ key: String, _ value: LCValue?) { self.value[key] = value } public var jsonValue: Any { return value.compactMapValue { value in value.jsonValue } } func formattedJSONString(indentLevel: Int, numberOfSpacesForOneIndentLevel: Int = 4) -> String { if value.isEmpty { return "{}" } let lastIndent = " " * (numberOfSpacesForOneIndentLevel * indentLevel) let bodyIndent = " " * (numberOfSpacesForOneIndentLevel * (indentLevel + 1)) let body = value .map { (key, value) in (key, (value as! LCValueExtension).formattedJSONString(indentLevel: indentLevel + 1, numberOfSpacesForOneIndentLevel: numberOfSpacesForOneIndentLevel)) } .sorted { (left, right) in left.0 < right.0 } .map { (key, value) in "\"\(key.doubleQuoteEscapedString)\": \(value)" } .joined(separator: ",\n" + bodyIndent) return "{\n\(bodyIndent)\(body)\n\(lastIndent)}" } public var jsonString: String { return formattedJSONString(indentLevel: 0) } public var rawValue: LCValueConvertible { let dictionary = value.mapValue { value in value.rawValue } return dictionary as! LCValueConvertible } var lconValue: Any? { return value.compactMapValue { value in (value as? LCValueExtension)?.lconValue } } static func instance() -> LCValue { return self.init([:]) } func forEachChild(_ body: (_ child: LCValue) throws -> Void) rethrows { try forEach { (_, element) in try body(element) } } func add(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be added.") } func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be concatenated.") } func differ(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be differed.") } }
gpl-3.0
sebreh/SquarePants
SquarePants/LazyProperty.swift
1
2504
// // LazyProperty.swift // SquarePants // // Created by Sebastian Rehnby on 28/08/15. // Copyright © 2015 Sebastian Rehnby. All rights reserved. // import UIKit public protocol LazyPropertyType { associatedtype ValueType var value: ValueType { get } } public struct LazyProperty<T>: LazyPropertyType { public typealias ValueType = T public var value: T { return evaluate() } fileprivate let evaluate: () -> T init(_ evaluate: @escaping () -> T) { self.evaluate = evaluate } } public extension LazyPropertyType { func map<U>(_ transform: @escaping (ValueType) -> U) -> LazyProperty<U> { return LazyProperty<U> { return transform(self.value) } } func flatMap<U>(_ transform: @escaping (ValueType) -> LazyProperty<U?>?) -> LazyProperty<U?> { return LazyProperty<U?> { return transform(self.value)?.value } } } // MARK: Extensions public extension LazyPropertyType where ValueType == UIView? { var superview: LazyProperty<UIView?> { return map { $0?.superview } } var frame: LazyProperty<CGRect?> { return map { $0?.frame } } var center: LazyProperty<CGPoint?> { return map { $0?.center } } var sp_contentCenter: LazyProperty<CGPoint?> { return flatMap { $0?.sp_contentCenter } } var alpha: LazyProperty<CGFloat?> { return map { $0?.alpha } } var transform: LazyProperty<CGAffineTransform?> { return map { $0?.transform } } } public extension LazyPropertyType where ValueType == CGRect { func withInsets(_ insets: UIEdgeInsets) -> LazyProperty<CGRect> { return map { UIEdgeInsetsInsetRect($0, insets) } } func withInset(_ inset: CGFloat) -> LazyProperty<CGRect> { return map { rect in let insets = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) return UIEdgeInsetsInsetRect(rect, insets) } } } public extension LazyPropertyType where ValueType == CGRect? { func withInsets(_ insets: UIEdgeInsets) -> LazyProperty<CGRect?> { return map { rect in if let rect = rect { return UIEdgeInsetsInsetRect(rect, insets) } else { return nil } } } func withInset(_ inset: CGFloat) -> LazyProperty<CGRect?> { return map { rect in if let rect = rect { let insets = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) return UIEdgeInsetsInsetRect(rect, insets) } else { return nil } } } }
mit