hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
d936f48c1e6e9cecc4cc4766c86c73a3d35620f0 | 207 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return m((() {
deinit {
class
case c,
| 23 | 87 | 0.743961 |
8fcaa3d9d22d05f0daafbe00aa8aa2adc3251f7a | 1,867 | // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input always
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import Dispatch
@available(SwiftStdlib 5.5, *)
func asyncEcho(_ value: Int) async -> Int {
value
}
@available(SwiftStdlib 5.5, *)
func test_taskGroup_cancel_then_add() async {
// CHECK: test_taskGroup_cancel_then_add
print("\(#function)")
let result: Int = await withTaskGroup(of: Int.self) { group in
let addedFirst = group.spawnUnlessCancelled { 1 }
print("added first: \(addedFirst)") // CHECK: added first: true
let one = await group.next()!
print("next first: \(one)") // CHECK: next first: 1
group.cancelAll()
print("cancelAll")
print("group isCancelled: \(group.isCancelled)") // CHECK: group isCancelled: true
let addedSecond = group.spawnUnlessCancelled { 2 }
print("added second: \(addedSecond)") // CHECK: added second: false
let none = await group.next()
print("next second: \(none)") // CHECK: next second: nil
group.spawn {
print("child task isCancelled: \(Task.isCancelled)") // CHECK: child task isCancelled: true
return 3
}
let three = await group.next()!
print("next third: \(three)") // CHECK: next third: 3
print("added third, unconditionally") // CHECK: added third, unconditionally
print("group isCancelled: \(group.isCancelled)") // CHECK: group isCancelled: true
return one + (none ?? 0)
}
print("result: \(result)") // CHECK: result: 1
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await test_taskGroup_cancel_then_add()
}
}
| 29.171875 | 193 | 0.684521 |
d52ddc051e54c7fad2e0a38e457a8bc2258d7f06 | 371 | //// IZButton.swift
// iMeiJu_Mac
//
// Created by iizvv on 2019/2/12.
// QQ群: 577506623
// GitHub: https://github.com/iizvv
// Copyright © 2019 iizvv. All rights reserved.
//
import Cocoa
class IZButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
(cell as! NSButtonCell).highlightsBy = .contentsCellMask
}
}
| 20.611111 | 64 | 0.663073 |
14ad1009c01a3095fde2aa4200dd822c914fac48 | 5,763 | //
// ISImageViewerDemo.swift
// ISImageViewer
//
// Created by VSquare on 17/12/2015.
// Copyright © 2015 IgorSokolovsky. All rights reserved.
//
import UIKit
class ISImageViewerDemo: UIViewController,ISImageViewerDelegate {
var imageView:UIImageView?
var image:UIImage = UIImage(named: "ogame_space.jpg")!
var ivvc:ISImageViewer!
var label:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
//self.edgesForExtendedLayout = .None
setUpImageView()
print(image.size)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
let labelWidth = label.frame.size.width
let labelHeight = label.frame.size.height
let labelWidthRatio = self.view.frame.width / labelWidth
let labelHeightRatio = self.view.frame.height / labelHeight
let labelxPosRatio = self.view.frame.width / label.frame.origin.x
let labelyPosRatio = self.view.frame.height / label.frame.origin.y
let labelNewWidth = size.width / labelWidthRatio
let labelNewHeight = size.height / labelHeightRatio
let labelNewXPos = size.width / labelxPosRatio
let labelNewYPos = size.height / labelyPosRatio
label.frame = CGRectMake(labelNewXPos, labelNewYPos, labelNewWidth, labelNewHeight)
if imageView != nil {
let imageViewWidth = imageView!.frame.size.width
let imageViewHeight = imageView!.frame.size.height
let imageViewWidthRatio = self.view.frame.width / imageViewWidth
let imageViewHeightRatio = self.view.frame.height / imageViewHeight
let imageViewxPosRatio = self.view.frame.width / imageView!.frame.origin.x
let imageViewyPosRatio = self.view.frame.height / imageView!.frame.origin.y
let imageViewNewWidth = size.width / imageViewWidthRatio
let imageViewNewHeight = size.height / imageViewHeightRatio
let imageViewNewXPos = size.width / imageViewxPosRatio
let imageViewNewYPos = size.height / imageViewyPosRatio
var cornerRadiusRatio:CGFloat
var newCornerRadius:CGFloat
if imageView!.layer.cornerRadius > 0{
if UIDevice.currentDevice().orientation.isLandscape{
cornerRadiusRatio = imageViewWidth / imageView!.layer.cornerRadius
newCornerRadius = imageViewNewHeight / cornerRadiusRatio
}else{
cornerRadiusRatio = imageViewHeight / imageView!.layer.cornerRadius
newCornerRadius = imageViewNewWidth / cornerRadiusRatio
}
}else{
newCornerRadius = 0.0
}
imageView!.frame = CGRectMake(imageViewNewXPos, imageViewNewYPos, imageViewNewWidth, imageViewNewHeight)
imageView?.contentMode = .ScaleAspectFit
imageView?.layer.cornerRadius = newCornerRadius
}
self.view.frame = CGRectMake(0, 0, size.width, size.height)
ivvc?.rotationHandling(size)
if UIDevice.currentDevice().orientation.isLandscape{
UIApplication.sharedApplication().statusBarHidden = true
UIApplication.sharedApplication().statusBarHidden = false
}
}
func setUpImageView(){
imageView = UIImageView(image: image)
if UIDevice.currentDevice().orientation.isLandscape{
label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width/3, height: self.view.frame.height/2))
imageView?.frame = CGRectMake(0, 0, self.view.bounds.height/2, self.view.bounds.height/2)
}else{
label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width/2, height: self.view.frame.width/4))
imageView?.frame = CGRectMake(0, 0, self.view.bounds.width/2, self.view.bounds.width/2)
}
label.text = "Tap On The Image To Open The ImageViewer"
label.numberOfLines = 2
label.lineBreakMode = .ByWordWrapping
label.textAlignment = .Center
label.center = CGPoint(x: self.view.center.x, y: self.view.frame.height/4)
label.font = UIFont.systemFontOfSize(17)
self.view.addSubview(label)
let gesture = UITapGestureRecognizer(target: self, action: "oneTapGestureReconizer:")
gesture.numberOfTapsRequired = 1
gesture.enabled = true
imageView?.center = self.view.center
imageView?.contentMode = .ScaleAspectFit
imageView?.userInteractionEnabled = true
imageView?.addGestureRecognizer(gesture)
imageView?.layer.cornerRadius = (imageView?.frame.width)!/2
imageView?.layer.masksToBounds = true
self.view.addSubview(imageView!)
}
func oneTapGestureReconizer(sender:UITapGestureRecognizer){
print("Image View Was Tapped")
ivvc = ISImageViewer(imageView: self.imageView!)
ivvc.setNavigationBar(nil, navBarTitle: "ImageViewer", rightNavBarItemTitle: "Edit")
ivvc.prepareViewToBeLoaded(self)
}
func didPickNewImage(image: UIImage) {
}
}
| 38.677852 | 136 | 0.638556 |
396d6ae390d9dbb0c0e6a250baf5e518755f69ce | 9,750 | //
// AppDelegate.swift
// masai
//
// Created by Bartomiej Burzec on 19.01.2017.
// Copyright © 2017 Embiq sp. z o.o. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import Auth0
import IQKeyboardManagerSwift
import AlamofireNetworkActivityIndicator
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
private var isFreshLaunch = false
var pushNotificationHandler = PushNotifications()
var window: UIWindow?
// MARK: Lifecycle
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
isFreshLaunch = true
Fabric.with([Crashlytics.self])
// Start network reachability scanning
_ = ReachabilityManager.shared
// Begin listening for history changes
_ = HistoryManager.shared
// let textAttributes = [NSForegroundColorAttributeName:UIColor.greyMasai]
// UINavigationBar.appearance().titleTextAttributes = textAttributes
// UINavigationBar.appearance().tintColor = UIColor.greyMasai
// UINavigationBar.appearance().backgroundColor = UIColor.navigationWhite
UITabBar.appearance().backgroundColor = UIColor(red: 254/255, green: 254/255, blue: 254/255, alpha: 1.0)
UITabBar.appearance().tintColor = UIColor.orangeMasai
UITabBar.appearance().layer.borderWidth = 0.0
UITabBar.appearance().clipsToBounds = true
IQKeyboardManager.sharedManager().enable = true
// Configure Alamofire network indicator
NetworkActivityIndicatorManager.shared.isEnabled = true
// Setup push handler
pushNotificationHandler.setup()
// Register for remote notifications
PushNotifications.registerForPushNotifications()
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.
let userProfile = CacheManager.retrieveUserProfile()
userProfile?.postToBackendIfNeeded()
}
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.
// HostConnectionManager.shared.clearCachedHosts()
// When we background we'll remove userLoginTokens, so next time we foreground the app we'll register on livechats again
HostConnectionManager.shared.clearUserLoginTokens()
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
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.
HTTPCookieStorage.shared.cookieAcceptPolicy = .always
// Save our profile to backend if necessary
if !isFreshLaunch {
let userProfile = CacheManager.retrieveUserProfile()
userProfile?.postToBackendIfNeeded()
}
let freshLaunch = isFreshLaunch
AuthManager.validateAuth0Session(completion: { [unowned self] (didSucceed, error) in
guard didSucceed == true else {
self.logout()
return
}
// Retrieve profile from backend, but ignore responses (since if we are logged out, we'll retrieve profile immediately after login anyways)
AwsBackendManager.getUserProfile()
// If we're re-opening the app, we'll reconnect to all active hosts
if !freshLaunch {
HostConnectionManager.shared.connectToAllActiveHosts { [unowned self] (didSucceed: Bool) in
guard didSucceed else {
DispatchQueue.main.async {
guard let vc = self.window?.rootViewController else {
return
}
AlertManager.showError("serverConnectError".localized, controller: vc)
}
return
}
// Trigger existing push requests if necessary
if let request = self.pushNotificationHandler.existingPushRequest {
Constants.Notification.openChatPushRequest(request: request).post()
self.pushNotificationHandler.clearExistingPushRequest()
}
}
}
})
isFreshLaunch = false
// Reset notification badge
UIApplication.shared.applicationIconBadgeNumber = 0
// Register for remote notifications
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
PushNotifications.registerForPushNotifications()
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return Auth0.resumeAuth(url, options: options)
}
// MARK: Push Notifications
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
pushNotificationHandler.set(deviceTokenData: deviceToken)
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
// MARK: Other
static func openSearch(_ search: String) {
if let keyWords = search.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed), let url = URL(string:"http://www.google.com/search?q=\(keyWords)") {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
static func callNumber(_ number: String) {
if let url = URL(string: "tel://\(number)") {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
static func openWebsite(_ address: String!) {
UIApplication.shared.openURL(URL(string: address)!)
}
func onReconnectToHost() {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: Constants.Notification.reconnect), object: nil)
// CRNotifications.showNotification(type: .success, title: "success".localized, message: "reconnect".localized, dismissDelay: 5)
}
static func logout(withMessage message: String? = nil) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.logout(withMessage: message)
}
func logout(withMessage message: String? = nil) {
let showMessageClosure = { (rootVC: UIViewController?) in
if let m = message {
let alert = UIAlertController(title: nil, message: m, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
DispatchQueue.main.async {
rootVC?.present(alert, animated: true, completion: nil)
}
}
}
AuthManager.logout()
CacheManager.clearUserProfile()
HostConnectionManager.shared.clearCachedHosts(persist: true)
pushNotificationHandler.clearExistingPushRequest()
let rootVC = self.window?.rootViewController
if let navigationController = rootVC as? UINavigationController {
if !(navigationController.topViewController is LoginViewController) &&
!(navigationController.topViewController is RegisterViewController) &&
!(navigationController.topViewController is ResetPassViewController) {
navigationController.topViewController?.dismiss(animated: true, completion: nil)
navigationController.popToRootViewController(animated: true)
}
}
if rootVC?.presentedViewController != nil {
rootVC?.dismiss(animated: true, completion: {
showMessageClosure(rootVC)
})
} else {
showMessageClosure(rootVC)
}
}
static func get() -> AppDelegate {
let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
return appDelegate
}
}
| 40.966387 | 285 | 0.637846 |
ed3554da270ab26cfcb1de4e697949ca432cce33 | 2,584 | //
// ReduxMessageViewController.swift
// RxStateDemo
//
// Created by LZephyr on 2018/4/4.
// Copyright © 2018年 LZephyr. All rights reserved.
//
import UIKit
import RxSwift
import ReSwift
class ReduxMessageViewController: UIViewController, StoreSubscriber {
let disposeBag = DisposeBag()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshButtonPressed))
// 让当前的VC订阅messageStore
messageStore.subscribe(self)
// 使用ActionCreator来做网络请求
messageStore.dispatch(reduxMessageRequest)
}
@objc func refreshButtonPressed() {
messageStore.dispatch(reduxMessageRequest)
}
// MARK: - StoreSubscriber
/// 任何Action引起数据改变后都会调用这个方法通知View更新
func newState(state: ReduxMessageState) {
// 加载状态
if state.loadingState == .loading {
self.startLoading()
} else if state.loadingState == .normal {
self.stopLoading()
}
// 列表数据
tableView.reloadData()
}
}
extension ReduxMessageViewController: UITableViewDataSource {
/// View不会直接修改Model的数据,而是通过向Store发送Action的形式间接的去修改
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// 发送一个修改数据的action
messageStore.dispatch(ActionRemoveMessage(index: indexPath.row))
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageStore.state.newsList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
let news = messageStore.state.newsList[indexPath.row]
cell?.textLabel?.text = "\(news.title) \(news.index)"
return cell!
}
}
extension ReduxMessageViewController: UITableViewDelegate {
}
| 29.033708 | 147 | 0.654025 |
23dc43a663cc90f044a339fcf275553b2ed514b5 | 1,034 | //
// ZappAnalyticsPluginsSDKTests.swift
// ZappAnalyticsPluginsSDKTests
//
// Created by Alex Zchut on 17/07/2018.
// Copyright © 2018 Applicaster. All rights reserved.
//
import XCTest
@testable import ZappAnalyticsPluginsSDK
class ZappAnalyticsPluginsSDKTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.945946 | 111 | 0.655706 |
2f8166aa63ffe11dbe7f979b63fd43754f7fe7ab | 1,212 | /*
* Reverse Only Letters.swift
* Question Link: https://leetcode.com/problems/reverse-only-letters/
* Primary idea: <String & Array>
* 1. 반복 : left index가 right index보다 작을 떄까지 반복
* 2. left index : 왼쪽 문자열이 문자인지 판별(isLetter) 후, 문자가 아니면 다음칸으로 이동
* 3. right index : 오른쪽 문자열이 문자인지 판별(isLetter) 후, 문자가 아니면 다음칸으로 이동
* 4. swap : 상대적로 같은 위치에 있는 문자만 서로 위치를 바꾼다.
*
* Time Complexity : O(n)
* Space Complexity : O(n)
* Runtime: 8 ms
* Memory Usage: 21.2 MB
*
* Created by gunhyeong on 2020/04/10.
*/
import Foundation
class Solution {
func reverseOnlyLetters(_ S: String) -> String {
var strArr = Array(S)
var left = 0
var right = S.count - 1
while left < right { // 1. 반복
if !strArr[left].isLetter { // 2. left index
left += 1
continue
}
if !strArr[right].isLetter { // 3. right index
right -= 1
continue
}
strArr.swapAt(left, right) // 4 swap
left += 1
right -= 1
}
return String(strArr)
}
}
| 26.933333 | 82 | 0.494224 |
fb0c1d530e9148b76a25bd965d6cf8d020ad147c | 1,804 | // Copyright 2020 by Ryan Ferrell. All rights reserved. Contact at github.com/wingovers
import Foundation
class DirectoryDeletor {
init(directories: RootDirectoriesRepo, preferences: PreferencesRepo) {
self.roots = directories
self.preferences = preferences
}
let roots: RootDirectoriesRepo
let preferences: PreferencesRepo
}
extension DirectoryDeletor: DirectoryInteractor {
func delete(temp id: UUID, in root: UUID, completion: @escaping (Bool) -> Void) {
DispatchQueue.global().async { [weak self] in
guard let target = self?.getTempDirectoryURL(for: id, in: root),
let didDelete = self?.delete(target)
else { return }
if didDelete { self?.roots.unlist(tempDirectory: id, in: root) }
completion(didDelete)
}
}
private func getTempDirectoryURL(for id: UUID, in root: UUID) -> URL? {
guard let root = roots.liveRootDirectories.firstIndex(where: { $0.id == root }),
let temp = roots.liveRootDirectories[root].tempDirectories.firstIndex(where: { $0.id == id })
else {
NSLog(#filePath, #function, #line, "Precondition failure")
return nil
}
return roots.liveRootDirectories[root].tempDirectories[temp].url
}
private func delete(_ url: URL) -> Bool {
let fm = FileManager.default
var trashedURL: NSURL?
do {
if preferences.deletesPermanently {
try fm.removeItem(at: url)
} else {
try fm.trashItem(at: url, resultingItemURL: &trashedURL)
}
return true
}
catch (let error) {
NSLog(error.localizedDescription)
return false
}
}
}
| 33.407407 | 107 | 0.600333 |
e523a0325c139d5f6825d229760104c3a00e1b0b | 425 | //
// RankingRepository.swift
// NicoApp
//
// Created by 林達也 on 2016/03/22.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import Foundation
import NicoAPI
import NicoEntity
import RxSwift
public protocol RankingRepository {
func categories() -> [GetRanking.Category]
func list(category: GetRanking.Category, period: GetRanking.Period, target: GetRanking.Target) -> Observable<[Video]>
}
| 20.238095 | 121 | 0.72 |
fc1090b18de3c1b00f0931609e0a6c75ecf00fc3 | 2,309 | //
// DrawingViewController.swift
// My Demo App
//
// Created by Mubashir on 17/09/21.
//
import UIKit
class DrawingViewController: UIViewController, YPSignatureDelegate {
@IBOutlet weak var signatureView: YPDrawSignatureView!
@IBOutlet weak var cartCountContView: UIView!
@IBOutlet weak var cartCountLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
cartCountLbl.text = String(Engine.sharedInstance.cartCount)
if Engine.sharedInstance.cartCount < 1 {
cartCountContView.isHidden = true
}
signatureView.delegate = self
}
@IBAction func backButton(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
@IBAction func clearButton(_ sender: Any) {
self.signatureView.clear()
}
@IBAction func saveButton(_ sender: Any) {
if let signatureImage = self.signatureView.getSignature(scale: 10) {
UIImageWriteToSavedPhotosAlbum(signatureImage, nil, nil, nil)
// self.signatureView.clear()
}
}
func didStart(_ view : YPDrawSignatureView) {
print("Started Drawing")
}
func didFinish(_ view : YPDrawSignatureView) {
print("Finished Drawing")
}
@IBAction func catalogButton(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "TabBar", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "CatalogViewController") as! CatalogViewController
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func cartButton(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "TabBar", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MyCartViewController") as! MyCartViewController
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func moreButton(_ sender: Any) {
let storyboard = UIStoryboard.init(name: "Menu", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 31.630137 | 120 | 0.663491 |
237942574dcbf43bca6471840ae5d4e18d65fa39 | 539 | //
// RSITF14Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import CoreGraphics
// http://www.gs1au.org/assets/documents/info/user_manuals/barcode_technical_details/ITF_14_Barcode_Structure.pdf
// http://www.barcodeisland.com/int2of5.phtml
@available(macCatalyst 14.0, *)
open class RSITF14Generator: RSITFGenerator {
override open func isValid(_ contents: String) -> Bool {
return super.isValid(contents) && contents.length() == 14
}
}
| 28.368421 | 113 | 0.727273 |
167705a2b5522c69f7145cfa049a654696e4382b | 1,378 | //
// PryvApiSwiftKitExampleUITests.swift
// PryvApiSwiftKitExampleUITests
//
// Created by Sara Alemanno on 05.06.20.
// Copyright © 2020 Pryv. All rights reserved.
//
import XCTest
import Mocker
@testable import PryvApiSwiftKitExample
class ServiceInfoUITests: XCTestCase {
var app: XCUIApplication!
override func setUp() {
super.setUp()
mockResponses()
continueAfterFailure = false
app = XCUIApplication()
app.launch()
}
func testAuthAndBackButton() {
app.buttons["authButton"].tap()
XCTAssert(app.webViews["webView"].exists)
app.navigationBars.buttons.element(boundBy: 0).tap()
XCTAssert(app.staticTexts["welcomeLabel"].exists)
}
func testBadServiceInfoUrl() {
app.textFields["serviceInfoUrlField"].tap()
app.textFields["serviceInfoUrlField"].typeText("hello")
app.buttons["authButton"].tap()
XCTAssertFalse(app.webViews["webView"].exists)
XCTAssertEqual(app.alerts.element.label, "Invalid URL")
}
private func mockResponses() {
let mockAccessEndpoint = Mock(url: URL(string: "https://reg.pryv.me/access")!, dataType: .json, statusCode: 200, data: [
.post: MockedData.authResponse
])
mockAccessEndpoint.register()
}
}
| 26.5 | 128 | 0.630624 |
0eb64008e3508dd3034963ec5b8adf7d1bf2ca9d | 3,265 | //
// ImageImageFaceBluringAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
public class ImageImageFaceBluringAPI: APIBase {
/**
* enum for parameter model
*/
public enum Model_applyImageImageFaceBluringPost: String {
case Ageitgey = "ageitgey"
}
/**
Apply model for the face-bluring task for a given models
- parameter image: (form)
- parameter model: (query) (optional)
- parameter completion: completion handler to receive the data and the error objects
*/
public class func applyImageImageFaceBluringPost(image image: NSURL, model: Model_applyImageImageFaceBluringPost? = nil, completion: ((data: AnyObject?, error: ErrorType?) -> Void)) {
applyImageImageFaceBluringPostWithRequestBuilder(image: image, model: model).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Apply model for the face-bluring task for a given models
- POST /image/image/face-bluring/ - parameter image: (form)
- parameter model: (query) (optional)
- returns: RequestBuilder<AnyObject>
*/
public class func applyImageImageFaceBluringPostWithRequestBuilder(image image: NSURL, model: Model_applyImageImageFaceBluringPost? = nil) -> RequestBuilder<AnyObject> {
let path = "/image/image/face-bluring/"
let URLString = OpenAPIClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"model": model?.rawValue
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<AnyObject>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: falsefalse)
}
/**
Get list of models available for face-bluring
- parameter completion: completion handler to receive the data and the error objects
*/
public class func getVersionsImageImageFaceBluringGet(completion: ((data: AnyObject?, error: ErrorType?) -> Void)) {
getVersionsImageImageFaceBluringGetWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Get list of models available for face-bluring
- GET /image/image/face-bluring/
- returns: RequestBuilder<AnyObject>
*/
public class func getVersionsImageImageFaceBluringGetWithRequestBuilder() -> RequestBuilder<AnyObject> {
let path = "/image/image/face-bluring/"
let URLString = OpenAPIClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<AnyObject>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}
| 35.879121 | 187 | 0.69464 |
384bc57b523bdb97d46d94fde728401f3073d8b9 | 3,556 | //
// Redux+MockInjector.swift
// CompleteRedux
//
// Created by Hai Pham on 12/11/18.
// Copyright © 2018 Hai Pham. All rights reserved.
//
import UIKit
/// Prop injector subclass that can be used for testing. For example:
///
/// class ViewController: ReduxCompatibleView {
/// var staticProps: StaticProps?
/// ...
/// }
///
/// func test() {
/// ...
/// let injector = MockInjector(...)
/// vc.staticProps = StaticProps(injector)
/// ...
/// }
///
/// This class keeps track of the injection count for each Redux-compatible
/// view.
public final class MockInjector<State>: PropInjector<State> {
private let lock = NSRecursiveLock()
private var _injectCount: [String : Int] = [:]
/// Initialize with a mock store that does not have any functionality.
convenience public init(forState: State.Type, runner: MainThreadRunnerType) {
let store: DelegateStore<State> = .init(
{fatalError()},
{_ in fatalError()},
{_,_ in fatalError()},
{_ in fatalError()}
)
self.init(store: store, runner: runner)
}
/// Access the internal inject count statistics.
public var injectCount: [String : Int] {
return self._injectCount
}
/// Add one count for a compatible view injectee.
///
/// - Parameters:
/// - cv: A Redux-compatible view.
/// - outProps: An OutProps instance.
/// - mapper: A Redux prop mapper.
public override func injectProps<CV, MP>(_ cv: CV, _ op: CV.OutProps, _ mapper: MP.Type)
-> ReduxSubscription where
MP: PropMapperType,
MP.PropContainer == CV,
CV.GlobalState == State
{
self.addInjecteeCount(cv)
return ReduxSubscription.noop
}
/// Check if a Redux view has been injected as many times as specified.
///
/// - Parameters:
/// - view: A Redux-compatible view.
/// - times: An Int value.
/// - Returns: A Bool value.
public func didInject<View>(_ view: View, times: Int) -> Bool where
View: PropContainerType
{
return self.getInjecteeCount(view) == times
}
/// Check if a Redux view has been injected as many times as specified.
///
/// - Parameters:
/// - view: A Redux-compatible view.
/// - times: An Int value.
/// - Returns: A Bool value.
public func didInject<View>(_ type: View.Type, times: Int) -> Bool where
View: PropContainerType
{
return self.getInjecteeCount(type) == times
}
/// Reset all internal statistics.
public func reset() {
self.lock.lock()
defer { self.lock.unlock() }
self._injectCount = [:]
}
private func addInjecteeCount(_ id: String) {
self.lock.lock()
defer { self.lock.unlock() }
self._injectCount[id] = self.injectCount[id, default: 0] + 1
}
/// Only store the class name because generally we only need to check how
/// many times views/view controllers of a certain class have received
/// injection.
private func addInjecteeCount<View>(_ view: View) where View: PropContainerType {
self.addInjecteeCount(String(describing: View.self))
}
private func getInjecteeCount(_ id: String) -> Int {
self.lock.lock()
defer { self.lock.unlock() }
return self.injectCount[id, default: 0]
}
private func getInjecteeCount<View>(_ type: View.Type) -> Int where
View: PropContainerType
{
return self.getInjecteeCount(String(describing: type))
}
private func getInjecteeCount<View>(_ view: View) -> Int where
View: PropContainerType
{
return self.getInjecteeCount(View.self)
}
}
| 28.222222 | 90 | 0.643701 |
6935641c3643154a991c5614aed2fa2e4bec16d3 | 1,019 | //
// OuterComposite.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct OuterComposite: Codable, Hashable {
public var myNumber: Double?
public var myString: String?
public var myBoolean: Bool?
public init(myNumber: Double? = nil, myString: String? = nil, myBoolean: Bool? = nil) {
self.myNumber = myNumber
self.myString = myString
self.myBoolean = myBoolean
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case myNumber = "my_number"
case myString = "my_string"
case myBoolean = "my_boolean"
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(myNumber, forKey: .myNumber)
try container.encodeIfPresent(myString, forKey: .myString)
try container.encodeIfPresent(myBoolean, forKey: .myBoolean)
}
}
| 26.128205 | 91 | 0.677134 |
f4278370533304b0358715bb795cc685ae0c17cc | 731 | //
// UIImage+Utils.swift
// Weike
//
// Created by Weiyu Zhou on 8/8/16.
// Copyright © 2016 Cameric. All rights reserved.
//
extension UIImage {
static func fromColor(_ color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
guard let context = UIGraphicsGetCurrentContext() else {
assertionFailure()
return UIImage()
}
context.setFillColor(color.cgColor)
context.fill(rect)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
assertionFailure()
return UIImage()
}
UIGraphicsEndImageContext()
return img
}
}
| 25.206897 | 74 | 0.606019 |
7512121ead6cc5b23066b8021ca3b58ad9accb23 | 2,411 | //
// UniversalLinkTests.swift
// KeymanEngineTests
//
// Created by Joshua Horton on 7/27/20.
// Copyright © 2020 SIL International. All rights reserved.
//
import XCTest
@testable import KeymanEngine
class UniversalLinkTests: XCTestCase {
func testTryLinkParse() {
var parsedLink = UniversalLinks.tryParseKeyboardInstallLink(URL.init(string: "\(KeymanHosts.KEYMAN_COM)/randomURL")!)
XCTAssertNil(parsedLink)
parsedLink = UniversalLinks.tryParseKeyboardInstallLink(URL.init(string: "\(KeymanHosts.KEYMAN_COM)/keyboards/install/khmer_angkor")!)
if let parsedLink = parsedLink {
XCTAssertEqual(parsedLink.keyboard_id, "khmer_angkor")
XCTAssertNil(parsedLink.lang_id)
} else {
XCTFail()
}
parsedLink = UniversalLinks.tryParseKeyboardInstallLink(URL.init(string: "\(KeymanHosts.KEYMAN_COM)/keyboards/install/khmer_angkor?bcp47=km")!)
if let parsedLink = parsedLink {
XCTAssertEqual(parsedLink.keyboard_id, "khmer_angkor")
XCTAssertEqual(parsedLink.lang_id, "km")
} else {
XCTFail()
}
parsedLink = UniversalLinks.tryParseKeyboardInstallLink(URL.init(string: "\(KeymanHosts.KEYMAN_COM)/keyboards/install/sil_euro_latin")!)
if let parsedLink = parsedLink {
XCTAssertEqual(parsedLink.keyboard_id, "sil_euro_latin")
XCTAssertNil(parsedLink.lang_id)
} else {
XCTFail()
}
parsedLink = UniversalLinks.tryParseKeyboardInstallLink(URL.init(string: "\(KeymanHosts.KEYMAN_COM)/keyboards/install/foo?bcp47=bar")!)
if let parsedLink = parsedLink {
XCTAssertEqual(parsedLink.keyboard_id, "foo")
XCTAssertEqual(parsedLink.lang_id, "bar")
} else {
XCTFail()
}
}
func testTryLinkParseWithExtraneousComponents() {
var parsedLink = UniversalLinks.tryParseKeyboardInstallLink(URL.init(string: "\(KeymanHosts.KEYMAN_COM)/keyboards/install/foo?bcp47=bar&baz=nope")!)
if let parsedLink = parsedLink {
XCTAssertEqual(parsedLink.keyboard_id, "foo")
XCTAssertEqual(parsedLink.lang_id, "bar")
} else {
XCTFail()
}
parsedLink = UniversalLinks.tryParseKeyboardInstallLink(URL.init(string: "\(KeymanHosts.KEYMAN_COM)/keyboards/install/foo?_t=123&bcp47=bar")!)
if let parsedLink = parsedLink {
XCTAssertEqual(parsedLink.keyboard_id, "foo")
XCTAssertEqual(parsedLink.lang_id, "bar")
} else {
XCTFail()
}
}
}
| 32.146667 | 152 | 0.718789 |
e67f6e83415c2858cb9ee07eea2b41a58ea3132a | 2,176 | //
// AppDelegate.swift
// HLLCountDownLabel
//
// Created by bochb on 2018/1/16.
// Copyright © 2018年 com.heron. 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 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:.
}
}
| 46.297872 | 285 | 0.755515 |
abffb82ed3a7c01180be3f84e8f012361c5e3e9e | 1,253 | //
// File.swift
// ProjectUpKit
//
// Created by Jonathan Jemson on 7/6/18.
// Copyright © 2018 Jonathan Jemson.
//
import Foundation
import Stencil
public struct File: FileElement, CustomStringConvertible {
private(set) public var filename: String
public var content: String
public init(_ filename: String, content: String = "") {
self.filename = filename
self.content = content
}
public init(_ filename: String, templateContent: String = "", context: [String: String] = [:]) {
self.filename = filename
let template = Template(templateString: templateContent)
do {
self.content = try template.render(context)
} catch {
print("Templating Error: \(error)")
self.content = ""
}
}
public func create(at url: URL) throws {
do {
print("Creating file \(filename)")
try self.content.write(to: url.appendingPathComponent(filename), atomically: true, encoding: .utf8)
} catch {
throw ProjectUpError.fileWriteError(reason: "Could not write contents to file", underlyingError: error)
}
}
public var description: String {
return "File: \(filename)"
}
}
| 27.844444 | 115 | 0.614525 |
eb04257b209bd56a9471d8f0c3079bcb94e2c77b | 343 | //
// BlePeripheral.swift
// levo
//
// Created by Antonio Kim on 2021-07-07.
//
import Foundation
import CoreBluetooth
class BlePeripheral {
static var connectedPeripheral: CBPeripheral?
static var connectedService: CBService?
static var connectedTXChar: CBCharacteristic?
static var connectedRXChar: CBCharacteristic?
}
| 20.176471 | 49 | 0.752187 |
ab47b1850eb949845772ac38bf98cfce05d62c81 | 2,202 | //
// PrimerCardNumberFieldView.swift
// PrimerSDK
//
// Created by Evangelos Pittas on 29/6/21.
//
#if canImport(UIKit)
import UIKit
public final class PrimerCardNumberFieldView: PrimerTextFieldView {
private(set) public var cardNetwork: CardNetwork = .unknown
internal var cardnumber: String {
return (textField._text ?? "").replacingOccurrences(of: " ", with: "").withoutWhiteSpace
}
override func xibSetup() {
super.xibSetup()
textField.keyboardType = .numberPad
textField.isAccessibilityElement = true
textField.accessibilityIdentifier = "card_txt_fld"
textField.delegate = self
isValid = { text in
return text.isValidCardNumber
}
}
public override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let primerTextField = textField as? PrimerTextField else { return true }
let currentText = primerTextField._text ?? ""
if string != "" && currentText.withoutWhiteSpace.count == 19 { return false }
let newText = (currentText as NSString).replacingCharacters(in: range, with: string) as String
if !newText.withoutWhiteSpace.isNumeric && !string.isEmpty { return false }
primerTextField._text = newText
cardNetwork = CardNetwork(cardNumber: primerTextField._text ?? "")
if newText.isEmpty {
delegate?.primerTextFieldView(self, didDetectCardNetwork: nil)
} else {
delegate?.primerTextFieldView(self, didDetectCardNetwork: cardNetwork)
}
validation = (self.isValid?(primerTextField._text?.withoutWhiteSpace ?? "") ?? false) ? PrimerTextField.Validation.valid : PrimerTextField.Validation.invalid(PrimerError.invalidCardnumber)
switch validation {
case .valid:
delegate?.primerTextFieldView(self, isValid: true)
default:
delegate?.primerTextFieldView(self, isValid: nil)
}
primerTextField.text = newText.withoutWhiteSpace.separate(every: 4, with: " ")
return false
}
}
#endif
| 36.7 | 196 | 0.663034 |
de377cad61aa9674bcd91b07467457a9a0d41249 | 1,876 | //
// TokenManager.swift
// Mongli
//
// Created by DaEun Kim on 2020/03/17.
// Copyright © 2020 DaEun Kim. All rights reserved.
//
import Foundation
import SwiftJWT
struct TokenManager {
struct TokenClaims: Claims {
var exp: Date?
var id: Int
var name: String
}
enum TokenType {
case access, refresh
}
// swiftlint:disable force_try
private static let privateKey = try! Data(contentsOf: getPath(), options: .alwaysMapped)
private static let jwtSigner = JWTSigner.hs256(key: privateKey)
private static let jwtVerifier = JWTVerifier.hs256(key: privateKey)
private static let jwtEncoder = JWTEncoder(jwtSigner: jwtSigner)
private static let jwtDecoder = JWTDecoder(jwtVerifier: jwtVerifier)
static var currentToken: Token? {
return StorageManager.shared.readUser()?.token
}
static func userID() -> Int? {
guard let token = currentToken?.accessToken else { return nil }
return try? JWT<TokenClaims>(jwtString: token).claims.id
}
static func userName(_ token: String?) -> String? {
guard let token = token else { return nil }
return try? JWT<TokenClaims>(jwtString: token).claims.name
}
static func accessTokenIsVaildate() -> Bool {
guard let token = currentToken?.accessToken else { return false }
return isVaildate(token)
}
static func refreshTokenIsVaildate() -> Bool {
guard let token = currentToken?.refreshToken else { return false }
return isVaildate(token)
}
static private func isVaildate(_ token: String) -> Bool {
if !JWT<TokenClaims>.verify(token, using: jwtVerifier) { return false }
let result
= try? JWT<TokenClaims>(jwtString: token, verifier: jwtVerifier).validateClaims() == .success
return result ?? false
}
private static func getPath() -> URL {
return Bundle.main.url(forResource: "privateKey", withExtension: nil)!
}
}
| 28 | 99 | 0.703092 |
20195183a77e34c2a574906cd1155229dfaa892b | 559 | //: [Previous](@previous)
class Node<T> {
var value: T
var next: Node?
init(value: T, next: Node?) {
self.value = value
self.next = next
}
}
struct LinkedList<T> {
var head: Node<T>?
var tail: Node<T>?
// MARK: - Append
public mutating func append(_ value: T) {
guard head == nil else {
head = Node(value: value, next: nil)
tail = head
return
}
tail!.next = Node(value: value, next: nil)
tail = tail!.next
}
}
//: [Next](@next)
| 15.527778 | 50 | 0.493739 |
e03eed928ca7268f96240d0c171b476f1473af17 | 2,626 | //
// Carte.swift
// Carte
//
// Created by Suyeol Jeon on 06/06/2017.
//
import Foundation
public class Carte {
public static var infoDictionary: [String: Any]? = Bundle.main.infoDictionary {
didSet {
self._items = nil
}
}
private static var _items: [CarteItem]? = nil
public static var items: [CarteItem] {
if let items = self._items {
return items
}
let items = Carte.appendingCarte(to: Carte.items(from: Carte.infoDictionary) ?? [])
self._items = items
return items
}
static func items(from infoDictionary: [String: Any]?) -> [CarteItem]? {
return (infoDictionary?["Carte"] as? [[String: Any]])?
.compactMap { dict -> CarteItem? in
guard let name = dict["name"] as? String else { return nil }
var item = CarteItem(name: name)
item.licenseText = (dict["text"] as? String)
.flatMap { Data(base64Encoded: $0) }
.flatMap { String(data: $0, encoding: .utf8) }
return item
}
.sorted { $0.name < $1.name }
}
static func appendingCarte(to items: [CarteItem]) -> [CarteItem] {
guard items.lazy.filter({ $0.name == "Carte" }).first == nil else { return items }
var item = CarteItem(name: "Carte")
item.licenseText = [
"The MIT License (MIT)",
"",
"Copyright (c) 2015 Suyeol Jeon (xoul.kr)",
"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.",
].joined(separator: "\n")
return (items + [item]).sorted { $0.name < $1.name }
}
}
| 38.617647 | 88 | 0.643184 |
ff7ef7d7f738855bc060d984b0d558556ae1e869 | 4,872 | //
// SettingsViewController.swift
// tip
//
// Created by Jimmy Kittiyachavalit on 1/18/16.
// Copyright © 2016 Jimmy Kittiyachavalit. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var defaultTipControl: UISegmentedControl!
@IBOutlet weak var currencyPicker: UIPickerView!
@IBOutlet weak var localePicker: UIPickerView!
@IBOutlet weak var currencyButton: UIButton!
@IBOutlet weak var localeButton: UIButton!
let defaults = NSUserDefaults.standardUserDefaults()
let defaultTipIndexKey = "defaultTipIndex"
let currencyCodeKey = "currencyCode"
let currencyPickerData = NSLocale.ISOCurrencyCodes()
let localeKey = "localeKey"
let localePickerData = SettingsViewController.localeIdentifiersSortedByDisplayName()
override func viewDidLoad() {
super.viewDidLoad()
let tipIndex = defaults.integerForKey(defaultTipIndexKey)
defaultTipControl.selectedSegmentIndex = tipIndex
currencyPicker.dataSource = self
currencyPicker.delegate = self
localePicker.dataSource = self
localePicker.delegate = self
var locale = NSLocale.currentLocale()
if defaults.objectForKey(localeKey) != nil {
let localeIdentifier = defaults.objectForKey(localeKey) as! String
locale = NSLocale(localeIdentifier: localeIdentifier)
}
var localePickerIndex = 0
if localePickerData.indexOf(locale.localeIdentifier) != nil {
localePickerIndex = localePickerData.indexOf(locale.localeIdentifier)!
}
localePicker.selectRow(localePickerIndex, inComponent: 0, animated: false)
// Default to currency of current locale
var currencyCode = NSLocale.currentLocale().objectForKey(NSLocaleCurrencyCode) as! String
// If they saved a specific currency, use that
if defaults.objectForKey(currencyCodeKey) != nil {
currencyCode = defaults.objectForKey(currencyCodeKey) as! String
}
var currencyPickerIndex = 0
if currencyPickerData.indexOf(currencyCode) != nil {
currencyPickerIndex = currencyPickerData.indexOf(currencyCode)!
}
currencyPicker.selectRow(currencyPickerIndex, inComponent: 0, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func onValueChange(sender: AnyObject) {
defaults.setInteger(defaultTipControl.selectedSegmentIndex, forKey: defaultTipIndexKey)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == currencyPicker {
return currencyPickerData.count
} else {
return localePickerData.count
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == currencyPicker {
return currencyPickerData[row]
} else {
return NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: localePickerData[row])
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == currencyPicker {
defaults.setObject(currencyPickerData[row], forKey: currencyCodeKey)
} else {
defaults.setObject(localePickerData[row], forKey: localeKey)
}
}
@IBAction func onCurrencyButtonTap(sender: AnyObject) {
let currencyCode = NSLocale.currentLocale().objectForKey(NSLocaleCurrencyCode) as! String
var index = 0
if currencyPickerData.indexOf(currencyCode) != nil {
index = currencyPickerData.indexOf(currencyCode)!
}
currencyPicker.selectRow(index, inComponent: 0, animated: false)
defaults.setObject(currencyCode, forKey: currencyCodeKey)
}
@IBAction func onLocaleButtonTap(sender: AnyObject) {
let localeIdentifier = NSLocale.currentLocale().localeIdentifier
var index = 0
if localePickerData.indexOf(localeIdentifier) != nil {
index = localePickerData.indexOf(localeIdentifier)!
}
localePicker.selectRow(index, inComponent: 0, animated: false)
defaults.setObject(localeIdentifier, forKey: localeKey)
}
static func localeIdentifiersSortedByDisplayName() -> [String] {
return NSLocale.availableLocaleIdentifiers().sort {
return NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: $0) <
NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: $1)
}
}
}
| 38.666667 | 111 | 0.694787 |
f8cc352d2920c0500905dfdb7149ec2733668031 | 2,187 | //
// AppDelegate.swift
// Example
//
// Created by André Abou Chami Campana on 12/10/2016.
// Copyright © 2016 Bell App Lab. 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 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:.
}
}
| 46.531915 | 285 | 0.755373 |
4a1895c4f624d09b102c5b650381064d58ad3508 | 147 | import Foundation
public protocol UserSettings {
func get(setting: String) -> Data?
func set(value: [String], for setting: String)
}
| 18.375 | 50 | 0.680272 |
9cb386f05dae258cdacde6242b57956d8d592301 | 2,159 | //
// PieChartDataSetProtocol.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
public protocol PieChartDataSetProtocol: ChartDataSetProtocol {
// MARK: - Styling functions and accessors
/// the space in pixels between the pie-slices
/// **default**: 0
/// **maximum**: 20
var sliceSpace: CGFloat { get set }
/// When enabled, slice spacing will be 0.0 when the smallest value is going to be smaller than the slice spacing itself.
var automaticallyDisableSliceSpacing: Bool { get set }
/// indicates the selection distance of a pie slice
var selectionShift: CGFloat { get set }
var xValuePosition: PieChartDataSet.ValuePosition { get set }
var yValuePosition: PieChartDataSet.ValuePosition { get set }
/// When valuePosition is OutsideSlice, indicates line color
var valueLineColor: NSUIColor? { get set }
/// When valuePosition is OutsideSlice and enabled, line will have the same color as the slice
var useValueColorForLine: Bool { get set }
/// When valuePosition is OutsideSlice, indicates line width
var valueLineWidth: CGFloat { get set }
/// When valuePosition is OutsideSlice, indicates offset as percentage out of the slice size
var valueLinePart1OffsetPercentage: CGFloat { get set }
/// When valuePosition is OutsideSlice, indicates length of first half of the line
var valueLinePart1Length: CGFloat { get set }
/// When valuePosition is OutsideSlice, indicates length of second half of the line
var valueLinePart2Length: CGFloat { get set }
/// When valuePosition is OutsideSlice, this allows variable line length
var valueLineVariableLength: Bool { get set }
/// the font for the slice-text labels
var entryLabelFont: NSUIFont? { get set }
/// the color for the slice-text labels
var entryLabelColor: NSUIColor? { get set }
/// get/sets the color for the highlighted sector
var highlightColor: NSUIColor? { get set }
}
| 34.822581 | 125 | 0.719778 |
61f99ba09f4759231333cc09d3d642de51897afb | 1,244 | //
// TwitterzUITests.swift
// TwitterzUITests
//
// Created by Nidhi Manoj on 6/27/16.
// Copyright © 2016 Nidhi Manoj. All rights reserved.
//
import XCTest
class TwitterzUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.621622 | 182 | 0.662379 |
ccc9f32d5dfa2ad045968d98a01c4e844c535151 | 2,474 | //
// FirebaseAuth.swift
// FoodieDiary
//
// Created by Aniket Ghode on 5/17/17.
// Copyright © 2017 Aniket Ghode. All rights reserved.
//
import Foundation
import FirebaseAuth
extension FirebaseHelper {
func loginUser(_ email: String, _ password: String, completionHandler: @escaping (_ error: Error?) -> Void) {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
self.getCurrentUserInfo(user!)
completionHandler(nil)
} else {
completionHandler(error!)
}
})
}
private func getCurrentUserInfo(_ activeUser: FIRUser) {
if user != activeUser {
user = activeUser
let name = user!.email!.components(separatedBy: "@")[0]
self.displayName = name
}
}
func getCurrentUser() -> Bool {
if let activeUser = FIRAuth.auth()?.currentUser {
getCurrentUserInfo(activeUser)
print(activeUser.email!)
return true
}
else {
return false
}
}
func createAccount(_ email: String, _ password: String, completionHandler: @escaping (_ error: Error?) -> Void) {
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
self.getCurrentUserInfo(user!)
completionHandler(nil)
} else {
completionHandler(error!)
}
})
}
func signOutUser(_ completionHandler: @escaping (_ error: NSError?) -> Void) {
if FIRAuth.auth()?.currentUser != nil {
do {
try FIRAuth.auth()?.signOut()
// Remove posts from data source to avoid duplicates.
self.posts.removeAll()
completionHandler(nil)
} catch let error as NSError {
completionHandler(error)
}
}
}
func resetPassword(_ email: String, completionHandler: @escaping (_ error: Error?) -> Void) {
FIRAuth.auth()?.sendPasswordReset(withEmail: email, completion: { (error) in
if error == nil {
//Print into the console if successfully logged in
completionHandler(nil)
} else {
completionHandler(error!)
}
})
}
}
| 31.316456 | 117 | 0.54325 |
fb4032d4bc12feb4c186bd7b16c3fbd3e42070ac | 498 | //
// SettingsInitializer.swift
// gabbie-ios
//
// Created by noppefoxwolf on 28/10/2018.
// Copyright © 2018 . All rights reserved.
//
import UIKit
class SettingsModuleInitializer: NSObject {
//Connect with object on storyboard
@IBOutlet weak var settingsViewController: SettingsViewController!
override func awakeFromNib() {
let configurator = SettingsModuleConfigurator()
configurator.configureModuleForViewInput(viewInput: settingsViewController)
}
}
| 21.652174 | 83 | 0.73494 |
e0865ebd59b315b9a471029229d091a3cf017a12 | 1,770 | import Foundation
import CoreMotion
@objc(Clipboard)
public class Clipboard : CAPPlugin {
@objc func set(_ call: CAPPluginCall) {
guard let options = call.getObject("options") else {
call.error("No options provided")
return
}
if let string = options["string"] as? String {
UIPasteboard.general.string = string
return
}
if let urlString = options["url"] as? String {
if let url = URL(string: urlString) {
UIPasteboard.general.url = url
}
}
if let imageBase64 = options["image"] as? String {
print(imageBase64)
if let data = Data(base64Encoded: imageBase64) {
let image = UIImage(data: data)
print("Loaded image", image!.size.width, image!.size.height)
UIPasteboard.general.image = image
} else {
print("Unable to encode image")
}
}
call.success()
}
@objc func get(_ call: CAPPluginCall) {
guard let options = call.getObject("options") else {
call.error("No options provided")
return
}
let type = options["type"] as? String ?? "string"
if type == "string" && UIPasteboard.general.hasStrings {
call.success([
"value": UIPasteboard.general.string!
])
return
}
if type == "url" && UIPasteboard.general.hasURLs {
let url = UIPasteboard.general.url!
call.success([
"value": url.absoluteString
])
return
}
if type == "image" && UIPasteboard.general.hasImages {
let image = UIPasteboard.general.image!
let data = UIImagePNGRepresentation(image)
if let base64 = data?.base64EncodedString() {
call.success([
"value": base64
])
}
return
}
}
}
| 24.246575 | 68 | 0.588701 |
bb5b466d18bfcf1fb84fffda0892e2d4d4fac0c1 | 4,364 | //
// RuntimeManipulationDetailsViewController.swift
// DVIA - Damn Vulnerable iOS App (damnvulnerableiosapp.com)
// Created by Prateek Gianchandani on 25/11/17.
// Copyright © 2018 HighAltitudeHacks. All rights reserved.
// You are free to use this app for commercial or non-commercial purposes
// You are also allowed to use this in trainings
// However, if you benefit from this project and want to make a contribution, please consider making a donation to The Juniper Fund (www.thejuniperfund.org/)
// The Juniper fund is focusing on Nepali workers involved with climbing and expedition support in the high mountains of Nepal. When a high altitude worker has an accident (death or debilitating injury), the impact to the family is huge. The juniper fund provides funds to the affected families and help them set up a sustainable business.
// For more information, visit www.thejuniperfund.org
// Or watch this video https://www.youtube.com/watch?v=HsV6jaA5J2I
// And this https://www.youtube.com/watch?v=6dHXcoF590E
import UIKit
class RuntimeManipulationDetailsViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
@IBOutlet var codeTextField: UITextField!
let numToolbar: UIToolbar = UIToolbar()
let tutorialUrl:String = "http://highaltitudehacks.com/2013/11/08/ios-application-security-part-21-arm-and-gdb-basics"
override func viewDidLoad() {
super.viewDidLoad()
//For the done and cancel button in Validate code input
numToolbar.barStyle = UIBarStyle.default
numToolbar.items=[
UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(doneOrCancelTapped)),
UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(doneOrCancelTapped))
]
numToolbar.sizeToFit()
codeTextField.inputAccessoryView = numToolbar
usernameTextField.delegate = self
passwordTextField.delegate = self
//Bug Fix if view goes under the navigation bar
self.edgesForExtendedLayout = []
self.navigationItem.title = "Runtime Manipulation"
}
@objc func doneOrCancelTapped () {
codeTextField.resignFirstResponder()
}
@IBAction func loginMethod1Tapped(_ sender: Any) {
if usernameTextField.text?.isEmpty ?? true || passwordTextField.text?.isEmpty ?? true {
DVIAUtilities.showAlert(title: "Error", message: "One or more input fields is empty.", viewController: self)
return
}
if LoginValidate.isLoginValidated() {
DVIAUtilities.showAlert(title: "Congratulations", message: "You have successfully bypassed the authentication check.", viewController: self)
} else {
DVIAUtilities.showAlert(title: "Oops", message: "Incorrect Username or Password", viewController: self)
}
}
@IBAction func loginMethod2Tapped(_ sender: Any) {
if usernameTextField.text?.isEmpty ?? true || passwordTextField.text?.isEmpty ?? true {
DVIAUtilities.showAlert(title: "Error", message: "One or more input fields is empty.", viewController: self)
return
}
// TODO: change username and password text in this code.
if usernameTextField.text == "admin13412" && passwordTextField.text == "S@g@rm@7h@8848" {
DVIAUtilities.showAlert(title: "Congratulations", message: "You have successfully bypassed the authentication check.", viewController: self)
} else {
DVIAUtilities.showAlert(title: "Oops", message: "Incorrect Username or Password", viewController: self)
}
}
@IBAction func readTutorialTapped(_ sender: Any) {
DVIAUtilities.loadWebView(withURL:tutorialUrl , viewController: self)
}
@IBAction func validateCodeTapped(_ sender: Any) {
LoginValidate.validateCode(Int(codeTextField.text!)!, viewController: self)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 49.033708 | 340 | 0.702108 |
6105bab78caafe4d344306a50ecdb519a84f508b | 3,496 | //
// SideMenuVC.swift
// xeviet
//
// Created by Admin on 5/29/20.
// Copyright © 2020 eagle. All rights reserved.
//
import UIKit
import SafariServices
class SideMenuVC: BaseViewController {
@IBOutlet weak var height_tb: NSLayoutConstraint!
@IBOutlet weak var tableView: UITableView!
let menus = ["Thông tin tài khoản","Chia sẻ bạn bè", "Đăng xuất","Giới thiệu","Điều khoản dịch vụ","Đăng ký làm lái xe","Ý kiến khách hàng"]
init() {
super.init(nibName: "SideMenuVC", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.height_tb.constant = self.tableView.contentSize.height
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.navigationBar.isTranslucent = true
self.navigationController!.navigationBar.isHidden = true
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib.init(nibName: SideMenuCell.nameOfClass, bundle: nil), forCellReuseIdentifier: SideMenuCell.nameOfClass)
self.tableView.estimatedRowHeight = 60
self.tableView.rowHeight = UITableView.automaticDimension
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension SideMenuVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menus.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:SideMenuCell = tableView.dequeueReusableCell(withIdentifier: SideMenuCell.nameOfClass, for: indexPath) as! SideMenuCell
cell.selectionStyle = .none
cell.lb_title.text = menus[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
//thong tin tk
let userInfoVC = UserInfoVC()
self.dismiss(animated: true) {
UIApplication.getTopViewController()?.navigationController?.pushViewController(userInfoVC, animated: true)
}
case 4:
//privacy
let webVC = SFSafariViewController.init(url: URL.init(string: "http://policies.xeviet.net.vn/passenger/privacy/")!)
self.present(webVC, animated: true, completion: nil)
case 5:
//driver
let webVC = SFSafariViewController.init(url: URL.init(string: "http://driver.xeviet.net.vn")!)
self.present(webVC, animated: true, completion: nil)
case 2:
self.dismiss(animated: true) {
AppManager.shared.reset()
AppDelegate.shared().appCoordinator.showLoginScreen()
}
default:
print("nothing...")
}
}
}
| 37.191489 | 144 | 0.631865 |
e5a016a68082c5b8f40d99bd8764cd9e359514d1 | 745 | import XCTest
import Scaffold
class 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 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.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.689655 | 111 | 0.6 |
293d719c9e1a818283d7cbfe76f629ecb72f1b7d | 64 | //
// File.swift
// VideoZoomSdkExample
//
import Foundation
| 9.142857 | 23 | 0.6875 |
2108fdf8874519cfa845d3c9cfef07b880bd5974 | 503 | import UIKit
final class SegmentedControl: UISegmentedControl {
public typealias Action = (Int) -> Swift.Void
fileprivate var action: Action?
func action(new: Action?) {
if action == nil {
addTarget(self, action: #selector(segmentedControlValueChanged(segment:)), for: .valueChanged)
}
action = new
}
@objc func segmentedControlValueChanged(segment: UISegmentedControl) {
action?(segment.selectedSegmentIndex)
}
}
| 25.15 | 106 | 0.644135 |
56b754d0430579a518e099e5738dd1270cf9245b | 286 | //
// SequenceInfo.swift
// wallpapper
//
// Created by Marcin Czachurski on 03/07/2018.
// Copyright © 2018 Marcin Czachurski. All rights reserved.
//
import Foundation
class SequenceInfo : Codable {
var si: [SequenceItem]?
var ti: [TimeItem]?
var ap = Apperance()
}
| 17.875 | 60 | 0.671329 |
e0b52aaf687034dd797d0fb1fdaa044ebed5b18d | 644 | //
// AppDelegate.swift
// NeutronGeometry
//
// Created by Andrey Isaev on 16/01/2018.
// Copyright © 2018 Flerov Laboratory. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 22.206897 | 91 | 0.71118 |
e0b6f3840c4065d671e68b8ac8ab24ec6b41bce8 | 4,042 | //
// MessagesViewController.swift
// Diary
//
// Created by 莫晓豪 on 2016/12/3.
// Copyright © 2016年 moxiaohao. All rights reserved.
//
import UIKit
class MessagesViewController: UIViewController, UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource {
var messagesList: Dictionary<Int, [String]>?
var messagesImgData = [
["icon":"messagesAT.png"],
["icon":"messagesSystem.png"]
]
@IBOutlet weak var MessagesNavigationBar: UINavigationBar!
@IBOutlet weak var MessageTopView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
createMessagesTableView()
}
func createMessagesTableView() {
self.messagesList = [0:[String](["赞我的","系统消息"])]
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height), style: .grouped)
tableView.delegate = self
tableView.dataSource = self;
tableView.backgroundColor = UIColor.init(red: 245/255, green: 248/255, blue: 249/255, alpha: 1.0)
tableView.separatorColor = UIColor.init(red: 228/255, green: 228/255, blue: 228/255, alpha: 1.0)
tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
view.addSubview(tableView)
//去除Navigation Bar 底部黑线
MessagesNavigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
MessagesNavigationBar.shadowImage = UIImage()
MessagesNavigationBar?.py_add(toThemeColorPool: "barTintColor")
MessageTopView?.py_add(toThemeColorPool: "backgroundColor")
tableView.addSubview(MessageTopView)
tableView.addSubview(MessagesNavigationBar)
tableView.tableFooterView = UIView(frame:CGRect.zero)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
//返回行高
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return 54
}
//每组的头部高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1
}
//每组的底部高度
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
//cell 数据
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = "messagesCellID"
var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
cell = UITableViewCell(style: .value1, reuseIdentifier: cellID)
let data = self.messagesList?[indexPath.section]
let messagesItem = messagesImgData[indexPath.row]
let rightIcon1 = UIImageView.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
rightIcon1.image = UIImage(named: "arrow_Right")
cell?.accessoryView = rightIcon1
cell?.textLabel?.text = data![indexPath.row]
cell?.textLabel?.font = UIFont.systemFont(ofSize: 14)
cell?.imageView?.image = UIImage(named: messagesItem["icon"]!)
// cell?.detailTextLabel?.text = "\(indexPath.row)"
cell?.detailTextLabel?.font = UIFont.systemFont(ofSize: 13)
//修改cell选中的背景色
cell?.selectedBackgroundView = UIView.init()
cell?.selectedBackgroundView?.backgroundColor = UIColor.init(red: 245/255, green: 248/255, blue: 249/255, alpha: 1.0)
return cell!
}
//
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
//设置statusBar颜色
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 38.132075 | 133 | 0.67145 |
3acadf11307d4b046f9f66a8f058373bfa05cca7 | 1,969 | //
// Copyright (C) 2021 Twilio, Inc.
//
import Alamofire
import Foundation
class API: ObservableObject {
private let session = Session()
private let jsonEncoder = JSONEncoder(keyEncodingStrategy: .convertToSnakeCase)
private let jsonDecoder = JSONDecoder(keyDecodingStrategy: .convertFromSnakeCase)
private var backendURL: String!
private var passcode: String!
func configure(backendURL: String, passcode: String) {
self.backendURL = backendURL
self.passcode = passcode
}
/// Send a request to the reference backend.
///
/// - Parameter request: The request to send.
/// - Parameter completion: Called on the main queue with result when the request is completed.
func request<Request: APIRequest>(
_ request: Request,
completion: ((Result<Request.Response, Error>) -> Void)? = nil
) {
session.request(
backendURL + "/" + request.path,
method: .post, // Twilio Functions does not care about method
parameters: request.parameters,
encoder: JSONParameterEncoder(encoder: jsonEncoder),
headers: [.authorization(passcode)]
)
.validate()
.responseDecodable(of: request.responseType, decoder: jsonDecoder) { [weak self] response in
guard let self = self else { return }
switch response.result {
case let .success(response):
completion?(.success(response))
case let .failure(error):
guard
let data = response.data,
let errorResponse = try? self.jsonDecoder.decode(APIErrorResponse.self, from: data)
else {
completion?(.failure(error))
return
}
completion?(.failure(LiveVideoError.backendError(message: errorResponse.error.explanation)))
}
}
}
}
| 35.160714 | 108 | 0.600813 |
c1e9899d6aee6257bfd6906b45028f800de91794 | 383 | //
// Adapter.swift
// FastAdapter
//
// Created by Fabian Terhorst on 12.07.18.
// Copyright © 2018 everHome. All rights reserved.
//
public class Adapter<Itm: Item> {
public var order: Int = -1
public var itemList: ItemList<Itm>!
weak var fastAdapter: FastAdapter<Itm>? {
didSet {
itemList.fastAdapter = fastAdapter
}
}
}
| 19.15 | 51 | 0.603133 |
de6ebc12563960755f1118e96d56d37305d9275d | 519 | //
// ViewController.swift
// YSToolsSwift
//
// Created by peanutgao on 12/07/2020.
// Copyright (c) 2020 peanutgao. All rights reserved.
//
import UIKit
import YSToolsSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let imgV = UIImageView()
.ys_inView(view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 17.896552 | 58 | 0.645472 |
e8e96e35429ed9b63afb465ec4a1f756588ac9bf | 3,882 | //
// Example_02_ChangeAppearanceTests.swift
// SwiftSimctlExampleUITests
//
// Created by Christian Treffs on 25.03.20.
// Copyright © 2020 Christian Treffs. All rights reserved.
//
import Simctl
import SnapshotTesting
import XCTest
class Example_02_ChangeAppearanceTests: XCTestCase {
// run on iPhone 11 Pro
func testDifferentAppearances() throws {
let app = XCUIApplication.exampleApp
app.launch()
_ = app.waitForExistence(timeout: 2.0)
let expDark = expectation(description: "set_appearance_dark")
simctl.setDeviceAppearance(.dark) {
switch $0 {
case .success:
expDark.fulfill()
case let .failure(error):
XCTFail("\(error)")
}
}
wait(for: [expDark], timeout: 5.0)
let label = app.staticTexts.element(boundBy: 0)
_ = label.waitForExistence(timeout: 1.0)
assertSnapshot(matching: label.screenshot().image,
as: .image)
let expLight = expectation(description: "set_appearance_light")
simctl.setDeviceAppearance(.light) {
switch $0 {
case .success:
expLight.fulfill()
case let .failure(error):
XCTFail("\(error)")
}
}
wait(for: [expLight], timeout: 5.0)
_ = label.waitForExistence(timeout: 1.0)
assertSnapshot(matching: label.screenshot().image,
as: .image)
XCUIApplication.exampleApp.terminate()
}
func testDifferentAppearancesFullscreen() {
let app = XCUIApplication.exampleApp
app.launch()
_ = app.waitForExistence(timeout: 2.0)
let setOverridesExp = expectation(description: "set-overrides")
simctl.setStatusBarOverrides([
.batteryLevel(33),
.time("11:11"),
.cellularBars(.three),
.dataNetwork(.lte),
.operatorName("SwiftSimctl"),
.cellularMode(.active)
]) {
switch $0 {
case .success:
setOverridesExp.fulfill()
case let .failure(error):
XCTFail("\(error)")
}
}
wait(for: [setOverridesExp], timeout: 5.0)
let expDark = expectation(description: "set_appearance_dark")
simctl.setDeviceAppearance(.dark) {
switch $0 {
case .success:
expDark.fulfill()
case let .failure(error):
XCTFail("\(error)")
}
}
wait(for: [expDark], timeout: 5.0)
let label = app.staticTexts.element(boundBy: 0)
_ = label.waitForExistence(timeout: 1.0)
// we do have a comparsion problem here since the virtual home bar indicator is not under our control and changes appearance
assertSnapshot(matching: app.screenshot().image,
as: .image)
let expLight = expectation(description: "set_appearance_light")
simctl.setDeviceAppearance(.light) {
switch $0 {
case .success:
expLight.fulfill()
case let .failure(error):
XCTFail("\(error)")
}
}
wait(for: [expLight], timeout: 5.0)
_ = label.waitForExistence(timeout: 1.0)
assertSnapshot(matching: app.screenshot().image,
as: .image)
let clearOverridesExp = expectation(description: "clear-overrides")
simctl.clearStatusBarOverrides {
switch $0 {
case .success:
clearOverridesExp.fulfill()
case let .failure(error):
XCTFail("\(error)")
}
}
wait(for: [clearOverridesExp], timeout: 3.0)
XCUIApplication.exampleApp.terminate()
}
}
| 30.093023 | 132 | 0.555384 |
201a517619ce539a350dba04aa38289ad8d8a923 | 366 | //
// Blacksmith.swift
// WanderingSeoulBeta1.0
//
// Created by Hung Cun on 12/7/20.
// Copyright © 2020 Matheo. All rights reserved.
//
import Foundation
class Blacksmith {
init() {
inventory = ["무기": 10, "갑옷": 15]
// 무기:mugi(weapon), 갑옷:gabos(armor), value of inventory is the price of the item
}
var inventory: [String: Int]
}
| 19.263158 | 88 | 0.617486 |
1ce7bc7617875fd37ec2fdf7f98b74793200093e | 2,401 | //
// User.swift
// Twitter
//
// Created by Maggie Gates on 2/21/16.
// Copyright © 2016 CodePath. All rights reserved.
//
import UIKit
var _currentUser: User?
class User: NSObject {
var name: NSString?
var screenname: NSString!
var profileUrl: NSURL?
var coverString: String?
var coverUrl: NSURL?
var tagline: NSString?
var dictionary: NSDictionary?
let userDidTweetNotification = "userDidTweetNotification"
init(dictionary: NSDictionary) {
self.dictionary = dictionary
name = dictionary["name"] as? String
screenname = dictionary["screen_name"] as? String
coverString = dictionary["profile_banner_url"] as? String
if coverString != nil {
coverUrl = NSURL(string: coverString!)!
}
let imageURLString = dictionary["profile_image_url_https"] as? String
if imageURLString != nil {
profileUrl = NSURL(string: imageURLString!)!
}
tagline = dictionary["description"] as? String
}
static let userDidLogoutNotification = "UserDidLogout"
static var _currentUser: User?
class var currentUser: User? {
get {
if _currentUser == nil {
let defaults = NSUserDefaults.standardUserDefaults()
let userData = defaults.objectForKey("currentUserData") as? NSData
if let userData = userData {
let dictionary = try! NSJSONSerialization.JSONObjectWithData(userData, options: []) as! NSDictionary
_currentUser = User(dictionary: dictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
let defaults = NSUserDefaults.standardUserDefaults()
if let user = user {
let data = try! NSJSONSerialization.dataWithJSONObject(user.dictionary!, options: [])
defaults.setObject(data, forKey: "currentUserData")
} else {
defaults.setObject(nil, forKey: "currentUserData")
}
defaults.synchronize()
}
}
func tweeted() {
NSNotificationCenter.defaultCenter().postNotificationName(userDidTweetNotification, object: nil)
}
}
| 27.284091 | 108 | 0.579342 |
ab0d5ca4e43c88523aa9b980caefaaa14ea38ac7 | 2,135 | //
// History.swift
// LonaStudio
//
// Created by Devin Abbott on 2/2/20.
// Copyright © 2020 Devin Abbott. All rights reserved.
//
import Foundation
// MARK: - History
public struct History<Item: Equatable> {
public var back: [Item] = []
public var current: Item?
public var forward: [Item] = []
public var maxLength: Int = 20
public var allowsConsecutiveDuplicates = false
public init(_ current: Item? = nil) {
self.current = current
}
public mutating func navigateTo(_ item: Item) {
if let current = current {
if current == item && !allowsConsecutiveDuplicates {
return
}
back.insert(current, at: 0)
}
current = item
forward.removeAll()
evict()
}
public mutating func goBack(offset: Int = 0) {
for _ in 0..<offset + 1 {
goBack()
}
}
public mutating func goBack() {
if let current = current {
forward.insert(current, at: 0)
}
if let first = back.first {
current = first
back.remove(at: 0)
}
evict()
}
public mutating func goForward(offset: Int = 0) {
for _ in 0..<offset + 1 {
goForward()
}
}
public mutating func goForward() {
if let current = current {
back.insert(current, at: 0)
}
if let first = forward.first {
current = first
forward.remove(at: 0)
}
evict()
}
public func canGoBack(offset: Int = 0) -> Bool {
return back.count > offset
}
public func canGoForward(offset: Int = 0) -> Bool {
return forward.count > offset
}
public mutating func reset() {
current = nil
back.removeAll()
forward.removeAll()
}
private mutating func evict() {
if back.count > maxLength {
back = Array(back.prefix(upTo: maxLength))
}
if forward.count > maxLength {
forward = Array(forward.prefix(upTo: maxLength))
}
}
}
| 21.138614 | 64 | 0.528806 |
d6369d87dbab3fda608729c8f51b82c1fc414211 | 564 | //
// NSHostingController.swift
// Helium
//
// Created by Jaden Geller on 5/2/20.
// Copyright © 2020 Jaden Geller. All rights reserved.
//
import Cocoa
import OpenCombine
class HostingMenu: NSMenu {
let rootMenu: () -> Menu
init(rootMenu: @escaping () -> Menu) {
self.rootMenu = rootMenu
super.init(title: "")
update()
}
override func update() {
items = rootMenu().makeNSMenuItems()
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 19.448276 | 59 | 0.595745 |
332f690bcc7ec98929537965133c898354163935 | 1,890 | //
// LogSeverity.swift
// CleanroomLogger
//
// Created by Evan Maloney on 3/18/15.
// Copyright © 2015 Gilt Groupe. All rights reserved.
//
/**
Used to indicate the *severity*, or importance, of a log message.
Severity is a continuum, from `.verbose` being least severe to `.error` being
most severe.
The logging system may be configured so that messages lower than a given
severity are ignored.
*/
public enum LogSeverity: Int
{
/** The lowest severity, used for detailed or frequently occurring
debugging and diagnostic information. Not intended for use in production
code. */
case verbose = 1
/** Used for debugging and diagnostic information. Not intended for use
in production code. */
case debug = 2
/** Used to indicate something of interest that is not problematic. */
case info = 3
/** Used to indicate a user action. */
case user = 4
/** Used to indicate that something appears amiss and potentially
problematic. The situation bears looking into before a larger problem
arises. */
case warning = 5
/** The highest severity, used to indicate that something has gone wrong;
a fatal error may be imminent. */
case error = 6
}
extension LogSeverity: CustomStringConvertible
{
/** Returns a human-readable textual representation of the receiver. */
public var description: String {
switch self {
case .verbose: return "Verbose"
case .debug: return "Debug"
case .info: return "Info"
case .user: return "User"
case .warning: return "Warning"
case .error: return "Error"
}
}
}
/// :nodoc:
extension LogSeverity: Comparable {}
/// :nodoc:
public func <(lhs: LogSeverity, rhs: LogSeverity) -> Bool {
return lhs.rawValue < rhs.rawValue
}
| 27.794118 | 78 | 0.644444 |
de9d1a4d4c6abbb94072dbc26203664b06c6ebb7 | 57,109 | // RUN: %empty-directory(%t)
//
// Build swift modules this test depends on.
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/foo_swift_module.swift -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// 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 -enable-objc-interop -disable-objc-attr-requires-foundation-module
// 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) -swift-version 4 -typecheck -verify %s -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module
//
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -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 -enable-objc-interop -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-prefixes=PASS_PRINT_AST,PASS_PRINT_AST_TYPE -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) -swift-version 4 -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 -enable-objc-interop -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-prefixes=PASS_PRINT_AST,PASS_PRINT_AST_TYPEREPR -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) -swift-version 4 -emit-module -o %t -F %S/Inputs/mock-sdk -enable-objc-interop -disable-objc-attr-requires-foundation-module %s
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -swift-version 4 -skip-deinit=false -print-module -source-filename %s -F %S/Inputs/mock-sdk -module-to-print=print_ast_tc_decls -print-implicit-attrs=true -enable-objc-interop -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 -enable-objc-interop -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 -enable-objc-interop -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
// REQUIRES: objc_interop
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: {{^}} @_hasInitialValue 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 = 0){{$}}
func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0) {}
// PASS_COMMON-NEXT: {{^}} func instanceFuncWithDefaultArg2(a: Int = 0, b: Double = 0){{$}}
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 }{{$}}
static subscript(i: Int) -> Double {
get {
return Double(i)
}
}
// PASS_COMMON-NEXT: {{^}} static subscript(i: 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: {{^}} @_hasInitialValue 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(){{$}}
// PASS_COMMON-NEXT: {{^}} init(instanceVar1: Int = 0){{$}}
// 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: {{^}}@_hasInitialValue 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: {{^}} @_hasInitialValue 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: {{^}}@_inheritsConvenienceInitializers {{()?}}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 {{{$}}
@objc optional var property1: Int { get }
// PASS_COMMON-NEXT: {{^}} @objc optional var property1: Int { get }{{$}}
@objc optional func protocolFunc1()
// PASS_COMMON-NEXT: {{^}} @objc optional func protocolFunc1(){{$}}
}
protocol d0150_TestClassProtocol : class {}
// PASS_COMMON-LABEL: {{^}}protocol d0150_TestClassProtocol : AnyObject {{{$}}
@objc protocol d0151_TestClassProtocol {}
// PASS_COMMON-LABEL: {{^}}@objc protocol d0151_TestClassProtocol {{{$}}
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(macOS, unavailable){{$}}
// PASS_COMMON-NEXT: {{^}} func f3(){{$}}
@available(iOS 8.0, OSX 10.10, *)
func f4() {}
// PASS_COMMON-NEXT: {{^}} @available(iOS 8.0, macOS 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, macOS 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: {{^}} @objc @IBAction func anAction(_: AnyObject){{$}}
@IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any? { fatalError() }
// PASS_COMMON-NEXT: {{^}} @objc @IBSegueAction func aSegueAction(_ coder: AnyObject, sender: AnyObject, identifier: AnyObject?) -> Any?{{$}}
@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: {{^}} @objc @IBOutlet @_hasInitialValue weak var anOutlet: @sil_weak d0181_TestIBAttrs!{{$}}
@IBInspectable var inspectableProp: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @IBInspectable @_hasInitialValue var inspectableProp: Int{{$}}
@GKInspectable var inspectableProp2: Int = 0
// PASS_EXPLODE_PATTERN-NEXT: {{^}} @objc @GKInspectable @_hasInitialValue var inspectableProp2: 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: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar1: Int{{$}}
let instanceVar2 = 0
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue let instanceVar2: Int{{$}}
static let staticVar1: Int = 42
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue static let staticVar1: Int{{$}}
static let staticVar2 = 42
// FIXME: PRINTED_WITHOUT_TYPE
// PASS_PRINT_AST-NEXT: {{^}} @_hasInitialValue static let staticVar2: Int{{$}}
// PASS_PRINT_MODULE_INTERFACE-NEXT: {{^}} @_hasInitialValue 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: {{^}} {{.*}}static func __derived_enum_equals(_ a: d0200_EscapedIdentifiers.`enum`, _ b: d0200_EscapedIdentifiers.`enum`) -> Bool
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// 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: {{^}} @_inheritsConvenienceInitializers class `extension` : d0200_EscapedIdentifiers.`class` {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} @_inheritsConvenienceInitializers class `extension` : `class` {{{$}}
// PASS_COMMON: {{^}} {{(override )?}}init(){{$}}
// PASS_COMMON-NEXT: {{^}} @objc deinit{{$}}
// PASS_COMMON-NEXT: {{^}} }{{$}}
func `func`<`let`: `protocol`, `where`>(
class: Int, struct: `protocol`, foo: `let`, bar: `where`) where `where` : `protocol` {}
// PASS_COMMON-NEXT: {{^}} func `func`<`let`, `where`>(class: Int, struct: {{(d0200_EscapedIdentifiers.)?}}`protocol`, foo: `let`, bar: `where`) where `let` : {{(d0200_EscapedIdentifiers.)?}}`class`, `where` : {{(d0200_EscapedIdentifiers.)?}}`class`{{$}}
var `var`: `struct` = `struct`()
// PASS_COMMON-NEXT: {{^}} @_hasInitialValue 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` = {{(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: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromStdlib1: Int{{$}}
var propFromSwift1: FooSwiftStruct = FooSwiftStruct()
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromSwift1: FooSwiftStruct{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue var propFromSwift1: foo_swift_module.FooSwiftStruct{{$}}
var propFromClang1: FooStruct1 = FooStruct1(x: 0, y: 0.0)
// PASS_QUAL_UNQUAL-NEXT: {{^}} @_hasInitialValue var propFromClang1: FooStruct1{{$}}
// PASS_QUAL_IF_AMBIGUOUS-NEXT: {{^}} @_hasInitialValue 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: {{^}} @_hasInitialValue var instanceVar1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue 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: {{^}} @_hasInitialValue var instanceVar4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue var instanceVar10: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar11: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final var instanceVar12: FooStruct{{$}}
let instanceLet1 = 0
let instanceLet2 = 0.0
let instanceLet3 = ""
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet1: Int{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet2: Double{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue 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: {{^}} @_hasInitialValue final let instanceLet4: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet5: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet6: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet7: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet8: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue final let instanceLet9: FooStruct{{$}}
// PASS_EXPLODE_PATTERN: {{^}} @_hasInitialValue 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: {{^}}@_inheritsConvenienceInitializers 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: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance3 : FooClass {{{$}}
class ClassWithInheritance4 : FooClass, FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers class ClassWithInheritance4 : FooClass, FooProtocol {{{$}}
class ClassWithInheritance5 : FooClass, FooProtocol, BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}@_inheritsConvenienceInitializers 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 : BarProtocol, FooProtocol {{{$}}
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 : BarProtocol, FooProtocol{{$}}
associatedtype AssociatedTypeDecl4 where AssociatedTypeDecl4 : QuxProtocol, AssociatedTypeDecl4.Qux == Int
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl4 : QuxProtocol where Self.AssociatedTypeDecl4.Qux == Int{{$}}
associatedtype AssociatedTypeDecl5: FooClass
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} associatedtype AssociatedTypeDecl5 : FooClass{{$}}
}
//===---
//===--- Variable declaration printing.
//===---
var d0300_topLevelVar1: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue var d0300_topLevelVar1: Int{{$}}
// PASS_COMMON-NOT: d0300_topLevelVar1
var d0400_topLevelVar2: Int = 42
// PASS_COMMON: {{^}}@_hasInitialValue 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: {{^}} @_hasInitialValue 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: {{^}} @_hasInitialValue 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: {{^}} {{.*}}static func __derived_enum_equals(_ a: d2000_EnumDecl1, _ b: d2000_EnumDecl1) -> Bool
// PASS_COMMON-NEXT: {{^}} func hash(into hasher: inout Hasher)
// 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-DAG: {{^}} typealias RawValue = Int
// PASS_COMMON-DAG: {{^}} init?(rawValue: Int){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Int { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
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-DAG: {{^}} typealias RawValue = Double
// PASS_COMMON-DAG: {{^}} init?(rawValue: Double){{$}}
// PASS_COMMON-DAG: {{^}} var rawValue: Double { get }{{$}}
// PASS_COMMON: {{^}}}{{$}}
//===---
//===--- Custom operator printing.
//===---
postfix operator <*>
// PASS_2500-LABEL: {{^}}postfix operator <*>{{$}}
protocol d2600_ProtocolWithOperator1 {
static postfix func <*>(_: Self)
}
// PASS_2500: {{^}}protocol d2600_ProtocolWithOperator1 {{{$}}
// PASS_2500-NEXT: {{^}} postfix static func <*> (_: Self){{$}}
// PASS_2500-NEXT: {{^}}}{{$}}
struct d2601_TestAssignment {}
infix operator %%%
func %%%(lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int {
return 0
}
// PASS_2500-LABEL: {{^}}infix operator %%% : DefaultPrecedence{{$}}
// PASS_2500: {{^}}func %%% (lhs: inout d2601_TestAssignment, rhs: d2601_TestAssignment) -> Int{{$}}
precedencegroup BoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringPrecedence {{{$}}
associativity: left
// PASS_2500-NEXT: {{^}} associativity: left{{$}}
higherThan: AssignmentPrecedence
// PASS_2500-NEXT: {{^}} higherThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: assignment
// PASS_2500-NOT: lowerThan
}
precedencegroup ReallyBoringPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup ReallyBoringPrecedence {{{$}}
associativity: right
// PASS_2500-NEXT: {{^}} associativity: right{{$}}
// PASS_2500-NOT: higherThan
// PASS_2500-NOT: lowerThan
// PASS_2500-NOT: assignment
}
precedencegroup BoringAssignmentPrecedence {
// PASS_2500-LABEL: {{^}}precedencegroup BoringAssignmentPrecedence {{{$}}
lowerThan: AssignmentPrecedence
assignment: true
// PASS_2500-NEXT: {{^}} assignment: true{{$}}
// PASS_2500-NEXT: {{^}} lowerThan: AssignmentPrecedence{{$}}
// PASS_2500-NOT: associativity
// PASS_2500-NOT: higherThan
}
// PASS_2500: {{^}}}{{$}}
//===---
//===--- Printing of deduced associated types.
//===---
protocol d2700_ProtocolWithAssociatedType1 {
associatedtype TA1
func returnsTA1() -> TA1
}
// PREFER_TYPE_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}} func returnsTA1() -> Self.TA1{{$}}
// PREFER_TYPE_PRINTING-NEXT: {{^}}}{{$}}
// PREFER_TYPEREPR_PRINTING: {{^}}protocol d2700_ProtocolWithAssociatedType1 {{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} associatedtype TA1{{$}}
// PREFER_TYPEREPR_PRINTING-NEXT: {{^}} func returnsTA1() -> TA1{{$}}
// PREFER_TYPEREPR_PRINTING-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: {{^}} typealias TA1 = Int
// PASS_COMMON-NEXT: {{^}} init(){{$}}
// PASS_COMMON-NEXT: {{^}}}{{$}}
//===---
//===--- Generic parameter list printing.
//===---
struct GenericParams1<
StructGenericFoo : FooProtocol,
StructGenericFooX : FooClass,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
// PASS_ONE_LINE_TYPE-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}}struct GenericParams1<StructGenericFoo, StructGenericFooX, StructGenericBar, StructGenericBaz> where StructGenericFoo : FooProtocol, StructGenericFooX : FooClass, StructGenericBar : BarProtocol, StructGenericBar : FooProtocol {{{$}}
init<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz,
d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz)
{}
// PASS_ONE_LINE_TYPE-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} init<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func genericParams1<
GenericFoo : FooProtocol,
GenericFooX : FooClass,
GenericBar : 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, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
// FIXME: in protocol compositions protocols are listed in reverse order.
//
// PASS_ONE_LINE_TYPEREPR-DAG: {{^}} func genericParams1<GenericFoo, GenericFooX, GenericBar, GenericBaz>(a: StructGenericFoo, b: StructGenericBar, c: StructGenericBaz, d: GenericFoo, e: GenericFooX, f: GenericBar, g: GenericBaz) where GenericFoo : FooProtocol, GenericFooX : FooClass, GenericBar : BarProtocol, GenericBar : FooProtocol{{$}}
func contextualWhereClause1() where StructGenericBaz == Never {}
// PASS_PRINT_AST: func contextualWhereClause1() where StructGenericBaz == Never{{$}}
subscript(index: Int) -> Never where StructGenericBaz: FooProtocol {
return fatalError()
}
// PASS_PRINT_AST: subscript(index: Int) -> Never where StructGenericBaz : FooProtocol { get }{{$}}
}
extension GenericParams1 where StructGenericBaz: FooProtocol {
static func contextualWhereClause2() where StructGenericBaz: FooClass {}
// PASS_PRINT_AST: static func contextualWhereClause2() where StructGenericBaz : FooClass{{$}}
typealias ContextualWhereClause3 = Never where StructGenericBaz: QuxProtocol, StructGenericBaz.Qux == Void
// PASS_PRINT_AST: typealias ContextualWhereClause3 = Never where StructGenericBaz : QuxProtocol, StructGenericBaz.Qux == Void{{$}}
}
struct GenericParams2<T : FooProtocol> where T : BarProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams2<T> where T : BarProtocol, T : FooProtocol {{{$}}
struct GenericParams3<T : FooProtocol> where T : BarProtocol, T : QuxProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams3<T> where T : BarProtocol, T : FooProtocol, T : QuxProtocol {{{$}}
struct GenericParams4<T : QuxProtocol> where T.Qux : FooProtocol {}
// PASS_ONE_LINE-DAG: {{^}}struct GenericParams4<T> where T : QuxProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams5<T : QuxProtocol> where T.Qux : FooProtocol & BarProtocol {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams5<T> where T : QuxProtocol, T.Qux : BarProtocol, T.Qux : FooProtocol {{{$}}
struct GenericParams6<T : QuxProtocol, U : QuxProtocol> where T.Qux == U.Qux {}
// PREFER_TYPE_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams6<T, U> where T : QuxProtocol, U : QuxProtocol, 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, U> where T : QuxProtocol, U : QuxProtocol, T.Qux : QuxProtocol, U.Qux : QuxProtocol, T.Qux.Qux == U.Qux.Qux {{{$}}
// PREFER_TYPE_REPR_PRINTING: {{^}}struct GenericParams7<T, U> where T : QuxProtocol, U : QuxProtocol, 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: {{^}}}{{$}}
// @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(a: @autoclosure () -> ())
public func ParamAttrs1(a : @autoclosure () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs2(a: @autoclosure @escaping () -> ())
public func ParamAttrs2(a : @autoclosure @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs3(a: () -> ())
public func ParamAttrs3(a : () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs4(a: @escaping () -> ())
public func ParamAttrs4(a : @escaping () -> ()) {
a()
}
// PASS_PRINT_AST: public func ParamAttrs5(a: (@escaping () -> ()) -> ())
public func ParamAttrs5(a : (@escaping () -> ()) -> ()) {
}
// PASS_PRINT_AST: public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
public typealias ParamAttrs6 = (@autoclosure () -> ()) -> ()
// The following type only has the internal paramter name inferred from the
// closure on the right-hand side of `=`. Thus, it is only part of the `Type`
// and not part of the `TypeRepr`.
// PASS_PRINT_AST_TYPE: public var ParamAttrs7: (_ f: @escaping () -> ()) -> ()
// PASS_PRINT_AST_TYPEREPR: public var ParamAttrs7: (@escaping () -> ()) -> ()
public var ParamAttrs7: (@escaping () -> ()) -> () = { f in f() }
// PASS_PRINT_AST: public var ParamAttrs8: (_ f: @escaping () -> ()) -> ()
public var ParamAttrs8: (_ f: @escaping () -> ()) -> () = { f in f() }
// Setter
// PASS_PRINT_AST: class FooClassComputed {
class FooClassComputed {
// PASS_PRINT_AST: var stored: (((Int) -> Int) -> Int)?
var stored : (((Int) -> Int) -> Int)? = nil
// PASS_PRINT_AST: var computed: ((Int) -> Int) -> Int { get set }
var computed : ((Int) -> Int) -> Int {
get { return stored! }
set { stored = newValue }
}
// PASS_PRINT_AST: }
}
// PASS_PRINT_AST: struct HasDefaultTupleOfNils {
// PASS_PRINT_AST: var x: (Int?, Int?)
// PASS_PRINT_AST: var y: Int?
// PASS_PRINT_AST: var z: Int
// PASS_PRINT_AST: var w: ((Int?, (), Int?), (Int?, Int?))
// PASS_PRINT_AST: init(x: (Int?, Int?) = (nil, nil), y: Int? = nil, z: Int, w: ((Int?, (), Int?), (Int?, Int?)) = ((nil, (), nil), (nil, nil)))
// PASS_PRINT_AST: }
struct HasDefaultTupleOfNils {
var x: (Int?, Int?)
var y: Int?
var z: Int
var w: ((Int?, (), Int?), (Int?, Int?))
}
// Protocol extensions
protocol ProtocolToExtend {
associatedtype Assoc
}
extension ProtocolToExtend where Self.Assoc == Int {}
// PREFER_TYPE_REPR_PRINTING: extension ProtocolToExtend where Self.Assoc == Int {
// Protocol with where clauses
protocol ProtocolWithWhereClause : QuxProtocol where Qux == Int {}
// PREFER_TYPE_REPR_PRINTING: protocol ProtocolWithWhereClause : QuxProtocol where Self.Qux == Int {
protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Qux == Int {
// PREFER_TYPE_REPR_PRINTING-DAG: protocol ProtocolWithWhereClauseAndAssoc : QuxProtocol where Self.Qux == Int {
associatedtype A1 : QuxProtocol where A1 : FooProtocol, A1.Qux : QuxProtocol, Int == A1.Qux.Qux
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A1 : FooProtocol, QuxProtocol where Self.A1.Qux : QuxProtocol, Self.A1.Qux.Qux == Int{{$}}
// FIXME: this same type requirement with Self should be printed here
associatedtype A2 : QuxProtocol where A2.Qux == Self
// PREFER_TYPE_REPR_PRINTING-DAG: {{^}} associatedtype A2 : QuxProtocol where Self == Self.A2.Qux{{$}}
}
#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>
typealias MyPairAlias2<T: FooProtocol, U> = MyPair<T, U> where U: BarProtocol
// PASS_PRINT_AST: typealias MyPairAlias2<T, U> = MyPair<T, U> where T : FooProtocol, U : BarProtocol
| 40.048387 | 385 | 0.671418 |
3365da9b6dc3d010a39b003f8afdcd3912553c79 | 422 | //
// IngredientAPIModels.swift
// Food-Doods-Prototype
//
// Created by Wren Liang on 2020-04-01.
// Copyright © 2020 Wren Liang. All rights reserved.
//
import Foundation
// MARK: - UserIngredientsModel
struct UserIngredientsModel: Codable {
let id: String
let ingredients: [IngredientModel]
}
// MARK: - Ingredient
struct IngredientModel: Codable {
let id: Int
let name, quantity, unit: String
}
| 19.181818 | 53 | 0.703791 |
ebea2d023df807c7e1f8ce762cbcf853c492e7ec | 264 | // 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 S<T where g:P{
let c{
class A{
protocol b{
typealias b:d
class d<T where g:b
}
func g:a
| 20.307692 | 87 | 0.742424 |
fc604cb6c93707cabf187d1354cd6f8fb3210fb1 | 2,646 | //
// Autogenerated by Scrooge
//
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
//
import Foundation
import TwitterApacheThrift
@objc(TESTMyUnion)
@objcMembers
public class MyUnion: NSObject, ThriftCodable {
public enum Union: ThriftCodable, Hashable {
case unionClassA(UnionClassA)
case unionClassB(UnionClassB)
enum CodingKeys: Int, CodingKey {
case unionClassA = 1
case unionClassB = 2
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let decodedClass = try container.decodeIfPresent(UnionClassA.self, forKey: .unionClassA) {
self = .unionClassA(decodedClass)
} else if let decodedClass = try container.decodeIfPresent(UnionClassB.self, forKey: .unionClassB) {
self = .unionClassB(decodedClass)
} else {
throw DecodingError.valueNotFound(MyUnion.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "MyUnion not decodable"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .unionClassA(let codedClass):
try container.encode(codedClass, forKey: .unionClassA)
case .unionClassB(let codedClass):
try container.encode(codedClass, forKey: .unionClassB)
}
}
}
public let value: Union
public init(unionClassA value: UnionClassA) {
self.value = .unionClassA(value)
}
public init(unionClassB value: UnionClassB) {
self.value = .unionClassB(value)
}
required public init(from decoder: Decoder) throws {
self.value = try Union(from: decoder)
}
public func encode(to encoder: Encoder) throws {
try self.value.encode(to: encoder)
}
public override var hash: Int {
var hasher = Hasher()
hasher.combine(self.value)
return hasher.finalize()
}
public override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? Self else {
return false
}
return self.value == other.value
}
public var unionClassA: UnionClassA? {
guard case .unionClassA(let value) = self.value else {
return nil
}
return value
}
public var unionClassB: UnionClassB? {
guard case .unionClassB(let value) = self.value else {
return nil
}
return value
}
}
| 35.28 | 162 | 0.619426 |
71f96e748e8b5d33da77cc32e8d737b50ee07d50 | 5,471 | /*
* BufferSizeCalculator.swift
* classgenerator
*
* Created by Callum McColl on 22/08/2017.
* Copyright © 2017 Callum McColl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgement:
*
* This product includes software developed by Callum McColl.
*
* 4. Neither the name of the author nor the names of contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* 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.
*
* -----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or
* modify it under the above terms or under the terms of the GNU
* General Public License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses/
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
import Data
public final class BufferSizeCalculator {
fileprivate let lengths: [String: Int] = [
"bit": 1,
"bool": 5,
"char": 1,
"signed char": 2,
"unsigned char": 1,
"signed": 11,
"signed int": 11,
"unsigned": 11,
"unsigned int": 11,
"uint8_t": 3,
"uint16_t": 5,
"uint32_t": 10,
"uint64_t": 20,
"int8_t": 4,
"int16_t": 6,
"int32_t": 11,
"int64_t": 20,
"int": 11,
"uint": 10,
"short": 6,
"short int": 6,
"signed short": 6,
"signed short int": 6,
"unsigned short": 6,
"unsigned short int": 6,
"long": 11,
"long int": 11,
"signed long": 11,
"signed long int": 11,
"unsigned long": 10,
"unsigned long int": 10,
"long long": 20,
"long long int": 20,
"signed long long": 20,
"signed long long int": 20,
"unsigned long long": 20,
"unsigned long long int": 20,
"long64_t": 20,
"float": 64,
"float_t": 64,
"double": 64,
"double_t": 64,
"long double": 80,
"double double": 80
]
public init() {}
/**
* This determines the description string buffer size which will be declared
* as a constant in the generated files.
*
* - Paramter vars: The array of variables that the `Class` contains.
*
* - Parameter buffer: The size of the toString buffer.
*
* - Returns: The size of the buffer.
*/
func getDescriptionBufferSize(fromVariables vars: [Variable], withToStringBufferSize buffer: Int) -> Int {
return vars.count + vars.reduce(buffer) { $0 + $1.label.count }
}
/**
* This determines the tostring buffer size which will be declared as a
* constant in the generated files. It uses information about the variables
* as stored in the dictionary.
*
* - Paramter vars: The array of variables that the `Class` contains.
*
* - Returns: The size of the buffer.
*/
func getToStringBufferSize(fromVariables vars: [Variable]) -> Int {
if true == vars.isEmpty {
return 0
}
return (vars.count - 1) * 2 + vars.reduce(1) {
switch $1.type {
case .array, .pointer, .unknown:
return $0 + 512
case .string(let length):
if let num = Int(length) {
return $0 + num
}
return $0 + 255
default:
return $0 + (self.lengths[$1.cType] ?? 512)
}
}
}
}
| 35.525974 | 110 | 0.614696 |
62cd1302ccf03aadb18f9a3da89218431db9e62f | 9,504 | //
// MainChat.swift
// chata
//
// Created by Vicente Rincon on 22/09/20.
//
import Foundation
protocol MainChatDelegate: class {
func callTips()
}
public class MainChat: UIView, ToolbarViewDelegate, QBTipsDelegate, QTMainViewDelegate {
var vwToolbar = ToolbarView()
let newChat = Chat()
let viewNot = UIView()
let newTips = QTMainView()
let vwNotifications = NotificationView()
var vwDynamicView = UIView()
var vwMain = UIView()
let svButtons = UIStackView()
var csMain: DViewSafeArea = .safeChat
var csTrasparent: DViewSafeArea = .safeFH
var csBottoms: DViewSafeArea = .safeButtons
var buttonAxis: NSLayoutConstraint.Axis = .vertical
var heightButtonsStack: CGFloat = 150
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(frame: CGRect) {
super.init(frame: frame)
vwToolbar.delegate = self
}
public func show(query: String = "") {
getMainChatPosition()
let vwFather: UIView = UIApplication.shared.keyWindow!
self.center = CGPoint(x: vwFather.center.x, y: vwFather.frame.height + self.frame.height/2)
vwFather.addSubview(self)
self.backgroundColor = UIColor.gray.withAlphaComponent(0.5)
self.edgeTo(vwFather, safeArea: .safe)
self.addSubview(vwMain)
vwMain.edgeTo(self, safeArea: csMain, padding: 30)
self.newChat.tag = 1
self.newTips.tag = 2
self.vwNotifications.tag = 3
self.newTips.delegate = self
UIView.animate(withDuration: 0.50, delay: 0, usingSpringWithDamping: 0.7,
initialSpringVelocity: 10, options: UIView.AnimationOptions(rawValue: 0), animations: {
self.center = vwFather.center
self.start(query: query)
}, completion: nil)
}
func getMainChatPosition(){
switch DataConfig.placement {
case "right":
csMain = .safeChat
csTrasparent = .safeFH
csBottoms = .safeButtons
buttonAxis = .vertical
heightButtonsStack = 150
case "left":
csMain = .safeChatLeft
csTrasparent = .safeFHLeft
csBottoms = .safeButtonsLeft
buttonAxis = .vertical
heightButtonsStack = 150
case "top":
csMain = .safeChatTop
csTrasparent = .safeFHTop
csBottoms = .safeButtonsTop
buttonAxis = .horizontal
heightButtonsStack = 150
case "bottom":
csMain = .safeChatBottom
csTrasparent = .safeFHBottom
csBottoms = .safeButtonsBottom
buttonAxis = .horizontal
heightButtonsStack = 150
default:
print("defaultPosition")
}
}
func addNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(ToogleNotification),
name: notifAlert,
object: nil)
}
@objc func closeAction(sender: UITapGestureRecognizer) {
dismiss(animated: DataConfig.clearOnClose)
}
@objc func nothing(sender: UITapGestureRecognizer) {
}
public func dismiss(animated: Bool) {
self.layoutIfNeeded()
if animated {
UIView.animate(withDuration: 0.50, delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 10, options: UIView.AnimationOptions(rawValue: 0), animations: {
self.center = CGPoint(x: self.center.x,
y: self.frame.height + self.frame.height/2)
}, completion: { (_) in
self.exit()
})
} else {
self.exit()
}
}
func exit() {
removeFromSuperview()
}
private func loadButtonsSide() {
svButtons.getSide(spacing: 0, axis: buttonAxis)
let newView = UIView()
let tap = UITapGestureRecognizer(target: self, action: #selector(closeAction) )
newView.addGestureRecognizer(tap)
self.addSubview(newView)
let referer = DataConfig.placement == "bottom" ? vwMain : vwDynamicView
newView.edgeTo(self, safeArea: csTrasparent, referer)
let buttons: [SideBtn] = [
SideBtn(imageStr: "icSideChat", action: #selector(changeViewChat), tag: 1),
SideBtn(imageStr: "icSideExplore", action: #selector(changeViewTips), tag: 2),
SideBtn(imageStr: "icSideNotification", action: #selector(changeViewNotifications), tag: 3)
]
for btn in buttons {
let newButton = UIButton()
newButton.backgroundColor = chataDrawerAccentColor
let image = UIImage(named: btn.imageStr, in: Bundle(for: type(of: self)), compatibleWith: nil)!
let image2 = image.resizeT(maxWidthHeight: 30)
newButton.setImage(image2, for: .normal)
newButton.tag = btn.tag
newButton.addTarget(self, action: btn.action, for: .touchUpInside)
newButton.setImage(newButton.imageView?.changeColor(color: UIColor.white).image, for: .normal)
newButton.imageView?.contentMode = .scaleAspectFit
svButtons.addArrangedSubview(newButton)
}
newView.addSubview(svButtons)
svButtons.edgeTo(newView, safeArea: csBottoms, height: heightButtonsStack, referer, padding: 0)
}
@objc func changeViewChat() {
loadChat()
}
@objc func changeViewTips() {
loadTips()
}
@objc func changeViewNotifications() {
loadSelectBtn(tag: 3)
vwToolbar.updateTitle(text: "Notifications", noDeleteBtn: true)
NotificationServices.instance.readNotification()
}
func loadChat() {
loadSelectBtn(tag: 1)
vwToolbar.updateTitle(text: DataConfig.title)
}
func loadTips(){
loadSelectBtn(tag: 2)
vwToolbar.updateTitle(text: "Explore Queries", noDeleteBtn: true)
}
func delete() {
newChat.delete()
}
}
extension MainChat {
private func loadToolbar() {
vwMain.addSubview(vwToolbar)
vwToolbar.edgeTo(vwMain, safeArea: .topView, height: 40.0)
}
private func loadMainView() {
vwDynamicView.backgroundColor = chataDrawerBackgroundColorSecondary
vwMain.addSubview(vwDynamicView)
vwDynamicView.edgeTo(vwMain, safeArea: .fullState, vwToolbar)
}
func start(query: String) {
loadToolbar()
loadMainView()
loadButtonsSide()
self.newChat.show(vwFather: self.vwDynamicView, query: query)
self.newChat.delegateQB = self
self.newTips.show(vwFather: self.vwDynamicView)
self.vwNotifications.show(vwFather: self.vwDynamicView)
loadSelectBtn(tag: 1)
addNotifications()
initLogin()
}
func loadSelectBtn(tag: Int) {
svButtons.subviews.forEach { (view) in
let viewT = view as? UIButton ?? UIButton()
if viewT.tag == tag{
viewT.backgroundColor = chataDrawerBackgroundColorSecondary
viewT.setImage(viewT.imageView?.changeColor().image, for: .normal)
} else {
viewT.backgroundColor = chataDrawerAccentColor
viewT.setImage(viewT.imageView?.changeColor(color: UIColor.white).image, for: .normal)
}
}
vwDynamicView.subviews.forEach { (view) in
view.isHidden = tag != view.tag
}
}
func callTips() {
loadTips()
}
@objc func ToogleNotification(_ notification: NSNotification) {
let valid = notification.object as? Bool ?? false
if !valid {
DispatchQueue.main.async {
self.removeView(tag: 100)
}
} else {
DispatchQueue.main.async {
self.viewNot.backgroundColor = .red
self.viewNot.tag = 100
self.viewNot.cardView(border: true, borderRadius: 10)
self.svButtons.subviews.forEach { (btn) in
let originalBtn = btn as? UIButton ?? UIButton()
if originalBtn.tag == 3 {
self.addSubview(self.viewNot)
self.viewNot.edgeTo(originalBtn, safeArea: .widthRightY, height: 15, padding: 0)
}
}
}
}
}
func initLogin() {
if LOGIN {
DispatchQueue.main.async {
NotificationServices.instance.getStateNotifications(number: 0)
Timer.scheduledTimer(withTimeInterval: 30, repeats: true) {
(time) in
if LOGIN{
if notificationsAttempts < 6 {
NotificationServices.instance.getStateNotifications(number: 0)
} else {
time.invalidate()
}
}
else{
time.invalidate()
}
}
}
}
}
func loadQueryTips(query: TypingSend) {
loadChat()
NotificationCenter.default.post(name: notifTypingText,
object: query)
}
}
| 38.168675 | 114 | 0.575442 |
bb2f3a3d03ba28f877656f9c9fde4e22f552dd5f | 6,999 | //
// SwitchRApp.swift
// SwitchR
//
// Created by Mark Keinhörster on 06.03.21.
//
import SwiftUI
import AppKit
import Foundation
import Cocoa
import HotKey
import RxSwift
import RxRelay
enum ControlAction{
case next
case previous
case confirm
case abort
}
struct ActiveControlKeys {
private let next: HotKey = HotKey(keyCombo: KeyCombo(key: .n, modifiers: [.control, .option]))
private let previous: HotKey = HotKey(keyCombo: KeyCombo(key: .p, modifiers: [.control, .option]))
private let confirm: HotKey = HotKey(keyCombo: KeyCombo(key: .return, modifiers: [.control, .option]))
private let disposeBag = DisposeBag()
private let relay: PublishRelay<ControlAction> = PublishRelay<ControlAction>()
init(){
register()
}
func register() {
next.keyDownHandler = {relay.accept(.next)}
previous.keyDownHandler = {relay.accept(.previous)}
confirm.keyDownHandler = {relay.accept(.confirm)}
}
func stream() -> Observable<ControlAction>{
return relay.asObservable()
}
func trigger(cmd: ControlAction){
relay.accept(cmd)
}
}
@main
struct SwitchR: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
Settings{
EmptyView()
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
var statusBarItem: NSStatusItem!
var windowFinder: WindowFinder!
var popover: NSPopover!
let hotkeys: ActiveControlKeys = ActiveControlKeys()
let disposableBag: DisposeBag = DisposeBag()
func applicationDidFinishLaunching(_ notification: Notification) {
self.initializeStatusbar()
self.initializePopover()
self.initializeStreams()
}
func initializeStatusbar(){
let statusBar = NSStatusBar.system
statusBarItem = statusBar.statusItem(withLength: NSStatusItem.squareLength)
statusBarItem.button?.image = NSImage(named: "Icon")
let statusBarMenu = NSMenu()
statusBarItem.menu = statusBarMenu
if !gotAXIAccess(){
let warningItem = NSMenuItem(title: "Missing Accessibility Permissions!", action: #selector(AppDelegate.togglePermissionsAlert), keyEquivalent: "")
warningItem.attributedTitle = NSAttributedString(string: "Missing Accessibility Permissions!", attributes: [NSAttributedString.Key.foregroundColor: NSColor.red])
statusBarMenu.addItem(warningItem)
}
if !gotCaptureAccess(){
let warningItem = NSMenuItem(title: "Missing Screen Capturing Permissions!", action: #selector(AppDelegate.togglePermissionsAlert), keyEquivalent: "")
warningItem.attributedTitle = NSAttributedString(string: "Missing Screen Capturing Permissions!", attributes: [NSAttributedString.Key.foregroundColor: NSColor.red])
statusBarMenu.addItem(warningItem)
}
let previous = NSMenuItem(title: "Previous", action: #selector(AppDelegate.triggerPrevious), keyEquivalent: "p")
previous.keyEquivalentModifierMask = [.control, .option]
statusBarMenu.addItem(previous)
let next = NSMenuItem(title: "Next", action: #selector(AppDelegate.triggerNext), keyEquivalent: "n")
next.keyEquivalentModifierMask = [.control, .option]
statusBarMenu.addItem(next)
let confirm = NSMenuItem(title: "Confirm", action: #selector(AppDelegate.triggerConfirm), keyEquivalent: "\r")
confirm.keyEquivalentModifierMask = [.control, .option]
statusBarMenu.addItem(confirm)
statusBarMenu.addItem(NSMenuItem.separator())
statusBarMenu.addItem(withTitle: "Quit", action: #selector(AppDelegate.quit), keyEquivalent: "")
}
func initializePopover(){
let popover = NSPopover()
popover.behavior = .semitransient
popover.animates = false
popover.contentViewController = NSHostingController(rootView: EmptyView())
self.popover = popover
}
func initializeStreams(){
windowFinder = WindowFinder(stream: hotkeys.stream())
windowFinder.stream
.filter({ $0 == .abort })
.subscribe(onNext: { a in self.togglePermissionsAlert() })
.disposed(by: disposableBag)
windowFinder.imageStream
.map { (self.resizeNsImage(img: $0.0), $0.1, $0.2) }
.subscribe(onNext: { self.toggleWithImageAndText(img: $0.0, name: $0.1, title: $0.2 ) })
.disposed(by: disposableBag)
windowFinder.confirmationStream
.subscribe(onNext: {self.popover.performClose($0)}).disposed(by: disposableBag)
}
func toggleWithImageAndText(img: NSImage?, name: String, title: String){
if let img = img {
NSApp.activate(ignoringOtherApps: true)
if let button = self.statusBarItem.button {
let width = img.size.width
let height = img.size.height
let textView = NSTextField(labelWithString: "\(name) - \(title)")
let gridView = NSGridView(views: [[textView],[NSImageView(image: img)]])
gridView.row(at: 0).topPadding = 10
gridView.row(at: 0).bottomPadding = 5
gridView.row(at: 0).cell(at: 0).xPlacement = .center
self.popover.contentViewController!.view = gridView
self.popover.contentSize = NSSize(width: width, height: height)
self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
}
func resizeNsImage(img: NSImage?) -> NSImage? {
guard let img = img else { return .none }
let destSize = NSMakeSize(CGFloat(img.size.width/2), CGFloat(img.size.height/2))
let newImage = NSImage(size: destSize)
newImage.lockFocus()
img.draw(in: NSMakeRect(0, 0, destSize.width, destSize.height),
from: NSMakeRect(0, 0, img.size.width, img.size.height),
operation: NSCompositingOperation.sourceOver,
fraction: CGFloat(1))
newImage.unlockFocus()
newImage.size = destSize
return newImage
}
func applicationWillResignActive(_ notification: Notification) {
self.popover.close()
}
@objc func togglePermissionsAlert() {
let alert = NSAlert()
alert.messageText = "Missing Permissions"
alert.informativeText = "Make sure to enable Accessibility and Screencapturing."
alert.alertStyle = NSAlert.Style.warning
alert.runModal()
}
@objc func triggerNext(){
hotkeys.trigger(cmd: .next)
}
@objc func triggerPrevious(){
hotkeys.trigger(cmd: .previous)
}
@objc func triggerConfirm(){
hotkeys.trigger(cmd: .confirm)
}
@objc func quit() {
NSApp.terminate(self)
}
}
| 36.643979 | 176 | 0.641234 |
d571ecb3e8f9f5f6a76e5d18cbf0935ffa029aad | 729 | // This class is automatically included in FastlaneRunner during build
// This autogenerated file will be overwritten or replaced during build time, or when you initialize `deliver`
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
class Deliverfile: DeliverfileProtocol {
// If you want to enable `deliver`, run `fastlane deliver init`
// After, this file will be replaced with a custom implementation that contains values you supplied
// during the `init` process, and you won't see this message
}
// Generated with fastlane 2.108.0
| 33.136364 | 110 | 0.750343 |
c1d2b080764e9cfcc21cead675b1cb41d924774e | 911 | //
// EBHeaderView.swift
// ebanjia
//
// Created by Chris on 2018/8/2.
// Copyright © 2018年 ebanjia. All rights reserved.
//
import UIKit
import SnapKit
class EBHeaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setupUI() {
self.backgroundColor = UIColor(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1)
addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) -> Void in
make.center.equalTo(self)
}
}
lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
return label
}()
}
| 23.358974 | 99 | 0.591658 |
21eac22afbe571eb19bfe654bcf18c0c6bf7d5b8 | 2,158 | //
// SceneDelegate.swift
// Brightwheel
//
// Created by Jorge Sanmartin on 19/12/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.313725 | 141 | 0.7595 |
2f0c9f8008bfa6a141324f1ef95fd1af3403a69b | 492 | import SwiftUI
struct TableColumnView: View {
var model: TableColumn
private let boldText: Bool
init(model: TableColumn) {
self.model = model
self.boldText = model.identifier ?? false
}
var body: some View {
SafeText(model.value)
.foregroundColor(.forStatus(status: model.state))
.font(.system(size: 12, weight: self.boldText ? .bold : .regular, design: .default))
.frame(alignment: .leading)
}
}
| 25.894737 | 96 | 0.603659 |
338b8e3df54421f7a50ad1b4f073be6f6da62daa | 1,615 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// 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.
/*
* This is a simply multi-tool front-end for the Anarchy Tools toolset.
*/
#if os(Linux)
import Glibc
#else
import Darwin
#endif
let tools: [Tool] = [BuildTool(), TestTool()]
func showVersion() {
print("Chaos v\(AppVersion) - Anarchy Tools Front-End\n")
}
func showUsage(withVersion show: Bool = true) {
if (show) {
showVersion()
}
print("usage: chaos [command] [command-options]\n")
print("commands:")
for tool in tools {
print(" \(tool.name) - \(tool.description)")
}
print()
}
if Process.arguments.count == 1 {
print("error: invalid usage")
showUsage()
exit(-1)
}
let command = Process.arguments[1]
switch command {
case "help", "--help", "-help":
showUsage(withVersion: true)
break
default:
let tool = tools.filter { $0.name == command }.first
if let tool = tool {
tool.run(Process.arguments)
}
else {
print("unknown command: \(command)")
showUsage(withVersion: false)
}
}
| 24.469697 | 75 | 0.658824 |
f4da11b27f598e0f77f51f19a342c9f3d16430bd | 4,515 | import Foundation
public struct _DynamicTupleElement: DynamicElement {
public var content: Never { fatalError() }
public var elements: [AnyDynamicElement]
public var node: DynamicElementNode {
get { .group(elements.map(\.node)) }
}
public init<
T0: DynamicElement
>(
_ t0: T0
) {
self.elements = [
AnyDynamicElement(t0)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement
>(
_ t0: T0,
_ t1: T1
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement,
T3: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2,
_ t3: T3
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2),
AnyDynamicElement(t3)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement,
T3: DynamicElement,
T4: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2,
_ t3: T3,
_ t4: T4
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2),
AnyDynamicElement(t3),
AnyDynamicElement(t4)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement,
T3: DynamicElement,
T4: DynamicElement,
T5: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2,
_ t3: T3,
_ t4: T4,
_ t5: T5
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2),
AnyDynamicElement(t3),
AnyDynamicElement(t4),
AnyDynamicElement(t5)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement,
T3: DynamicElement,
T4: DynamicElement,
T5: DynamicElement,
T6: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2,
_ t3: T3,
_ t4: T4,
_ t5: T5,
_ t6: T6
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2),
AnyDynamicElement(t3),
AnyDynamicElement(t4),
AnyDynamicElement(t5),
AnyDynamicElement(t6)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement,
T3: DynamicElement,
T4: DynamicElement,
T5: DynamicElement,
T6: DynamicElement,
T7: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2,
_ t3: T3,
_ t4: T4,
_ t5: T5,
_ t6: T6,
_ t7: T7
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2),
AnyDynamicElement(t3),
AnyDynamicElement(t4),
AnyDynamicElement(t5),
AnyDynamicElement(t6),
AnyDynamicElement(t7)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement,
T3: DynamicElement,
T4: DynamicElement,
T5: DynamicElement,
T6: DynamicElement,
T7: DynamicElement,
T8: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2,
_ t3: T3,
_ t4: T4,
_ t5: T5,
_ t6: T6,
_ t7: T7,
_ t8: T8
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2),
AnyDynamicElement(t3),
AnyDynamicElement(t4),
AnyDynamicElement(t5),
AnyDynamicElement(t6),
AnyDynamicElement(t7),
AnyDynamicElement(t8)
]
}
public init<
T0: DynamicElement,
T1: DynamicElement,
T2: DynamicElement,
T3: DynamicElement,
T4: DynamicElement,
T5: DynamicElement,
T6: DynamicElement,
T7: DynamicElement,
T8: DynamicElement,
T9: DynamicElement
>(
_ t0: T0,
_ t1: T1,
_ t2: T2,
_ t3: T3,
_ t4: T4,
_ t5: T5,
_ t6: T6,
_ t7: T7,
_ t8: T8,
_ t9: T9
) {
self.elements = [
AnyDynamicElement(t0),
AnyDynamicElement(t1),
AnyDynamicElement(t2),
AnyDynamicElement(t3),
AnyDynamicElement(t4),
AnyDynamicElement(t5),
AnyDynamicElement(t6),
AnyDynamicElement(t7),
AnyDynamicElement(t8),
AnyDynamicElement(t9)
]
}
}
| 18.353659 | 52 | 0.57608 |
39fa57f88a536e25e6d9fd4f4472e09860da8576 | 457 | // 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 --crash %target-swift-frontend %s -parse
if{func b:a protocol a{{}associatedtype d:d
func b->Self
| 41.545455 | 78 | 0.748359 |
4b99f4ab21731add983d8166e92cdf34a310fa2f | 750 | import Foundation
import Combine
import PhoenixShared
import os.log
#if DEBUG && true
fileprivate var log = Logger(
subsystem: Bundle.main.bundleIdentifier!,
category: "KotlinFutures"
)
#else
fileprivate var log = Logger(OSLog.disabled)
#endif
extension DatabaseManager {
func getDatabases() -> Future<Lightning_kmpDatabases, Never> {
return Future { promise in
let flow = SwiftStateFlow<Lightning_kmpDatabases>(origin: self.databases)
var watcher: Ktor_ioCloseable? = nil
watcher = flow.watch { (databases: Lightning_kmpDatabases?) in
if let databases = databases {
promise(.success(databases))
let _watcher = watcher
DispatchQueue.main.async {
_watcher?.close()
}
}
}
}
}
}
| 20.27027 | 76 | 0.702667 |
f9b750da39d5c8784c0b59f5f709d1c7b09b6336 | 953 | //
// SlarderTests.swift
// SlarderTests
//
// Created by 万圣 on 2017/6/21.
// Copyright © 2017年 万圣. All rights reserved.
//
import XCTest
@testable import Slarder
class SlarderTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 25.756757 | 111 | 0.627492 |
dbdba1fd38b824c4aa32e2ddeedf144b507a1ab2 | 312 | //
// AppDelegate.swift
// DataStructures
//
// Created by Ellen Shapiro on 8/2/14.
// Copyright (c) 2014 Ray Wenderlich Tutorial Team. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| 18.352941 | 73 | 0.660256 |
bf921eb4c3b383ce9703a01d7e153bacfd8e5ce2 | 814 | //
// MVVM-C_with_Swift
//
// Copyright © 2017 Marco Santarossa. All rights reserved.
//
import UIKit
protocol ControllerDelegate {
func viewDidLoad()
}
protocol ModelListener {
func modelChanged()
}
class BaseViewController<T>: UIViewController {
private(set) var viewModel: T
private(set) var delegate: ControllerDelegate
init(viewModel: T, delegate: ControllerDelegate) {
self.viewModel = viewModel
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
configure()
}
override func viewDidLoad() {
delegate.viewDidLoad()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure() {}
}
extension BaseViewController : ModelListener {
func modelChanged() {
DispatchQueue.main.async {
self.configure()
}
}
}
| 16.958333 | 59 | 0.713759 |
697698d1c56c67db3f7ca99124a3bc2e72db8675 | 12,029 | //
// Created by Huynh Quang Thao on 4/7/16.
// Copyright (c) 2016 Pakr. All rights reserved.
//
import Foundation
import Parse
let DemoMode = true
public class AddressServiceParseImpl: NSObject, AddressService {
func getNearByParkingLotByLocation(latitude: Double!, longitude: Double, radius: Double, success: ([Topic] -> Void), fail: (NSError -> Void)) {
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
let innerQuery = PFQuery(className: Constants.Table.Parking)
innerQuery.whereKey(Parking.PKCoordinate, nearGeoPoint: PFGeoPoint(latitude: latitude, longitude: longitude), withinKilometers: radius / 1000)
query.whereKey(Topic.PKParking, matchesQuery: innerQuery)
query.findObjectsInBackgroundWithBlock { (objects, error) in
print("Near by count: \(objects?.count)")
print("Error: \(error)")
if let error = error {
fail(error)
} else if let objs = objects {
var topics = [Topic]()
for pfobj in objs {
let topic = Topic(pfObject: pfobj)
topics.append(topic)
}
success(topics)
}
}
}
func getNearByParkingByAddressName(address: String, radius: Double, success: ([Topic] -> Void), fail: (NSError -> Void)) {
if (DemoMode) {
let lowerAddress = address.lowercaseString
if (lowerAddress.containsString("ho con rua")
|| lowerAddress.containsString("con rua")
|| lowerAddress.containsString("ho rua")
|| lowerAddress.containsString("con rùa")
|| lowerAddress.containsString("hồ con rùa")
|| lowerAddress.containsString("hồ rùa")) {
let coord = Coordinate(latitude: 10.782661, longitude: 106.695915)
self.getNearByParkingLotByLocation(coord.latitude,
longitude: coord.longitude,
radius: radius,
success: { topic in
success(topic)
}, fail: { error in
fail(error)
})
return
}
}
GMServices.requestAddressSearchWithAddress(address) { (successGMS, locationGMS) in
var coord:Coordinate? = nil
if (successGMS) {
if locationGMS?.count > 0 {
let firstPlace = locationGMS![0]
print("Search nearby: \(firstPlace.geometry.latitude),\(firstPlace.geometry.longitude)")
coord = Coordinate(latitude: firstPlace.geometry.latitude, longitude: firstPlace.geometry.longitude)
}
}
if let coord = coord {
self.getNearByParkingLotByLocation(coord.latitude,
longitude: coord.longitude,
radius: radius,
success: { topic in
success(topic)
}, fail: { error in
fail(error)
})
} else {
fail(NSError(domain: "", code: 0, userInfo: nil))
}
}
}
func postTopic(topic:Topic, complete:(Topic?,NSError?) -> Void) {
topic.toPFObject().saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock({ (objects, error) in
if error != nil {
complete(nil, error)
}else{
let topic = Topic(pfObject: objects![0])
complete(topic, nil)
}
})
} else {
complete(nil, error)
}
}
}
func getAllParkingByUser(userId: String, success:([Topic] -> Void), failure:(NSError -> Void)) {
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
let user = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
query.whereKey(Topic.PKPostUser, equalTo: user)
query.findObjectsInBackgroundWithBlock { (objects, error) in
print("User count: \(objects?.count)")
print("Error: \(error)")
if let error = error {
failure(error)
} else if let objs = objects {
var topics = [Topic]()
for pfobj in objs {
let topic = Topic(pfObject: pfobj)
topics.append(topic)
}
success(topics)
}
}
}
// MARK: API comment
func postComment(comment: Comment, complete:(comment: Comment?, error: NSError?) -> Void){
comment.toPFObject().saveInBackgroundWithBlock { (success: Bool, error: NSError?) in
if success {
let query = PFQuery(className: Constants.Table.Comment)
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock({ (comments, error) in
if let error = error {
complete(comment: nil, error: error)
} else if let comments = comments {
let comment = Comment(pfObject: comments.first!)
complete(comment: comment, error: nil)
}
})
}else{
complete(comment: nil, error: error)
}
}
}
func getAllCommentsByTopic(topicId: String, success:([Comment] -> Void), failure:(NSError -> Void)){
let query = PFQuery(className: Constants.Table.Comment)
query.includeKey(".")
query.orderByDescending("createdAt")
let topic = PFObject(withoutDataWithClassName: Constants.Table.Topic, objectId: topicId)
query.whereKey(Comment.PKTopic, equalTo: topic)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if let error = error {
failure(error)
} else if let objs = objects {
var comments = [Comment]()
for pfobj in objs {
let comment = Comment(pfObject: pfobj)
comments.append(comment)
}
success(comments)
}
}
}
func getUserById(userId: String, complete:(success: User?, error: NSError?) -> Void){
let query = PFQuery(className: Constants.Table.User)
query.whereKey("objectId", equalTo: userId)
query.findObjectsInBackgroundWithBlock { (users, error) in
if let error = error {
complete(success:nil, error: error)
}else{
if let users = users {
complete(success: users[0] as? User, error: error)
return
}else{
complete(success:nil, error: NSError(domain: "", code: -1, userInfo: nil))
}
}
}
}
func postBookMark(bookMark: Bookmark, complete:(bookMark: Bookmark?, error: NSError?) -> Void){
bookMark.toPFObject().saveInBackgroundWithBlock { (success, error) in
if success{
let query = PFQuery(className: Constants.Table.Bookmark)
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock({ (bookMarks, error) in
if let error = error {
complete(bookMark: nil, error: error)
} else if let bookMarks = bookMarks {
let bookMark = Bookmark(pfObject: bookMarks.first!)
self.getTopicById(bookMark, complete: { (bookMark) in
complete(bookMark: bookMark, error: error)
})
}
})
}else{
complete(bookMark: nil, error: error)
}
}
}
func getAllBookMarksByUser(userId: String, complete:(bookMarks: [Bookmark]?, error: NSError?) -> Void){
let query = PFQuery(className: Constants.Table.Bookmark)
query.orderByDescending("createdAt")
let user = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
query.whereKey(Bookmark.PKPostUser, equalTo: user)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if let error = error {
complete(bookMarks: nil, error: error)
} else if let objects = objects {
var bookmarks = [Bookmark]()
if objects.count == 0 {
complete(bookMarks: nil, error: error)
}else{
for object in objects {
let bookMark = Bookmark(pfObject: object)
self.getTopicById(bookMark, complete: { (bookMark) in
if let bookMark = bookMark {
bookmarks.append(bookMark)
if objects.count == bookmarks.count {
complete(bookMarks: bookmarks, error: nil)
}
}else{
complete(bookMarks: nil, error: error)
}
})
}
}
}else{
complete(bookMarks: nil, error: error)
}
}
}
func getTopicById(bookMark: Bookmark, complete:(bookMark: Bookmark!) -> Void){
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
query.whereKey("objectId", equalTo: bookMark.topicId)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if let objects = objects {
if objects.count > 0 {
let topic = Topic(pfObject: objects[0])
bookMark.topic = topic
complete(bookMark: bookMark)
}else{
complete(bookMark: nil)
}
}else{
complete(bookMark: nil)
}
}
}
func checkIsBookMarkTopicByUser(userId: String, topicId: String, complete:(isBookMark: Bool) -> Void){
let query = PFQuery(className: Constants.Table.Bookmark)
let user = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
query.whereKey(Bookmark.PKPostUser, equalTo: user)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if error != nil {
complete(isBookMark: false)
}else{
if let objects = objects {
for obj in objects {
let bookMark = Bookmark(pfObject: obj)
if bookMark.topicId == topicId {
complete(isBookMark: true)
return
}
}
complete(isBookMark: false)
}else{
complete(isBookMark: false)
}
}
}
}
}
| 42.059441 | 150 | 0.500208 |
396da8379650f9ac5e22b76cdd57227278a8713a | 1,083 | //
// PassiveLinkTests.swift
//
// Copyright © 2016 Sean Henry. All rights reserved.
//
import XCTest
@testable import Chain
class PassiveLinkTests: XCTestCase {
var link: PassiveLink<String>!
var mockedNext: MockLink<String, String>!
override func setUp() {
super.setUp()
mockedNext = MockLink()
link = PassiveLink()
link.next = mockedNext
}
// MARK: - initial
func test_initial_shouldSetResult() {
link.initial = .success("some")
XCTAssertTrue(link.result.isSuccessWithResult(link.initial.result))
}
// MARK: - finish
func test_finish_shouldSetInitialOnNext() {
link.initial = .success("hurrah")
link.finish()
XCTAssertTrue(link.next!.initial.isSuccessWithResult(link.result.result))
}
func test_finish_shouldRunNext() {
link.finish()
XCTAssertTrue(mockedNext.didCallRun)
}
func test_finish_shouldSetPreviousToNil() {
link.previous = link
link.finish()
XCTAssertNil(link.previous)
}
}
| 22.5625 | 81 | 0.633426 |
f5eabc6d46fd81b14cdae5eba0fbcb707e8c2a9b | 730 | //
// MyDelegateViewController.swift
// Swift_stu
//
// Created by William on 2018/8/15.
// Copyright © 2018年 William. All rights reserved.
//
import UIKit
class MyDelegateVC: UIViewController, DelegateName, TestProtocol {
func testMethod(str: String) {
print("MyDelegateVC:\(str)")
}
func mymethod(str:String) {
print("MyDelegateVC:\(str)")
}
override func viewDidLoad() {
super.viewDidLoad()
let myview:MyDelegateView = MyDelegateView.init(frame: CGRect(x: 100, y: 200, width: 200, height: 150))
myview.backgroundColor = UIColor.red
self.view.addSubview(myview)
myview.delegate = self
myview.myDelegate = self
}
}
| 23.548387 | 111 | 0.632877 |
56e7eca85fdb340e1bc2934e1b9653c99ee2d2ec | 2,670 | //
// GLNetworkManagerTests.swift
// GLNetworkingTests
//
// Created by Lukas Vavrek on 28.7.18.
// Copyright © 2018 Lukas Vavrek. All rights reserved.
//
import XCTest
@testable import GLNetworking
class GLNetworkManagerTests: XCTestCase {
var networkManager: GLNetworkManager!
var reachability: GLReachability!
private class Authenticator : GLRequestAuthenticator {
func authenticate(request: GLRequest) {}
}
private class ReachabilityDelegate : GLReachabilityDelegate {
func dnsCheckRequest(sender: GLReachability) -> GLRequest {
return GLRequest.create(url: "http://dnstest.com")!
}
func serviceCheckRequest(sender: GLReachability) -> GLRequest {
return GLRequest.create(url: "http://servicetest.com")!
}
}
private class FakeConnectionStatusProvider : GLConnectionStatusProvider {
var connectionStatus: GLConnectionStatus = GLConnectionStatus.unknown
func getConnectionStatus() -> GLConnectionStatus {
return connectionStatus
}
}
private class FakeRequest : GLRequest {
public var requestSend = false
override init?(url: String) {
super.init(url: url)
}
override func send() {
requestSend = true
}
}
override func setUp() {
super.setUp()
reachability = GLReachability(
delegate: ReachabilityDelegate(),
updateInterval: 1,
connectionStatusProvider: FakeConnectionStatusProvider()
)
networkManager = GLNetworkManager(
networkResponseHandler: GLNetworkResponseHandler(),
requestAuthenticator: Authenticator(),
reachability: reachability
)
}
override func tearDown() {
networkManager = nil
reachability = nil
super.tearDown()
}
func testRequestFailedNoNetwork() {
reachability.multicastCenter.networkAvailability.setStatus(.notAvailable)
var error = false
let request = GLRequest.create(url: "http://testing.com")!
request.error { response in
error = true
}
networkManager.execute(request: request)
XCTAssertTrue(error)
}
func testRequestSent() {
reachability.multicastCenter.networkAvailability.setStatus(.available)
let request = FakeRequest(url: "http://testing.com")!
networkManager.execute(request: request)
XCTAssertTrue(request.requestSend)
}
}
| 27.8125 | 81 | 0.61573 |
f8357aa67f28e0d6818195a1c92f9be726782522 | 1,109 | //
// RSwatchOSDelegation.swift
// RudderStack
//
// Created by Pallab Maiti on 24/02/22.
// Copyright © 2021 Rudder Labs India Pvt Ltd. All rights reserved.
//
#if os(watchOS)
import Foundation
import WatchKit
extension RSClient {
@objc
public func registeredForRemoteNotifications(deviceToken: Data) {
setDeviceToken(deviceToken.hexString)
apply { plugin in
if let p = plugin as? RSPushNotifications {
p.registeredForRemoteNotifications(deviceToken: deviceToken)
}
}
}
@objc
public func failedToRegisterForRemoteNotification(error: Error?) {
apply { plugin in
if let p = plugin as? RSPushNotifications {
p.failedToRegisterForRemoteNotification(error: error)
}
}
}
@objc
public func receivedRemoteNotification(userInfo: [AnyHashable: Any]) {
apply { plugin in
if let p = plugin as? RSPushNotifications {
p.receivedRemoteNotification(userInfo: userInfo)
}
}
}
}
#endif
| 23.595745 | 76 | 0.612263 |
76d083bb237ff7046ab47f4a5d5870354bd2234d | 2,378 | //
// DefaultInput.swift
// SwiftScript
//
// Created by Dennis Hernandez on 10/14/19.
// Copyright © 2019 Dennis Hernandez. All rights reserved.
//
import Foundation
// MARK: - Test Input
/// Current ``SwiftScript`` version
///
/// Major number should only change for first release or a major expansion in supported operators/functions. Minor number changes when default input updates to show new support. Revision changed when defualt input changes.
public let Version = "0.1.1"
/// Test string.
///
/// This is considered the ``SwiftScript`` version of the Acid2 test. The compiler should support creating and assigning all the `var`/`let` operation, creating functions(`func foo() {...}`), and executing functions (`print()`)
///
/// **Note:**
/// The compiler is considered to have passed when:
/// - a = `12`
/// - b = `2`
/// - c = `6`
/// - d = `false`
/// - e = `-3.14`
/// - f = `10`
/// - g = `-5`
/// - h = `"Hou se"`
/// - i = `"ion"`
/// - j = `"jet"`
/// - k = `"red. Kite"`
/// - l = `01234567891011`
/// - m = `200e50`
/// - n = `9`
/// - 0 = `0`
public let TestString = """
var a = 5
var b = 1
var c = a + b
let d = false
let e = -3.14
var f = 9 - 0
let g = -a
let h = "Hou se"
let i = "ion"
let j = "jet"
let k = "red. Kite"
let l = 01234567891011
let m = 200e50
let n = f
let o = 0
func foo() {
if a == 5 {
a = b + a
}
f += 1
b = b + 1
a += a
print(a)
print(b)
print(c)
print(f)
foo()
}
"""
var TestBlock: () -> Void = {
var a = 5
var b = 1
var c = a + b
let d = false
let e = -3.14
var f = 9 - 0
let g = -a
let h = "Hou se"
let i = "ion"
let j = "jet"
let k = "red. Kite"
let l = 01234567891011
let m = 200e50
let n = f
let o = 0
func foo() {
if a == 5 {
a = b + a
}
f += 1
b = b + 1
a += a
print("Var Values\r")
print("a:\(a)")
print("b:\(b)")
print("c:\(c)")
print("d:\(d)")
print("e:\(e)")
print("f:\(f)")
print("g:\(g)")
print("h:\(h)")
print("i:\(i)")
print("j:\(j)")
print("k:\(k)")
print("l:\(l)")
print("m:\(m)")
print("n:\(n)")
print("o:\(o)")
}
foo()
}
| 18.873016 | 227 | 0.465517 |
f7fdc9d2ffc73a76141117a8543934718adeb59c | 406 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "QuickConstraint",
platforms: [
.macOS(.v10_14),
.iOS(.v10),
.tvOS(.v10)
],
products: [
.library(name: "QuickConstraint",
targets: ["QuickConstraint"])
],
targets: [
.target(name: "QuickConstraint")
],
swiftLanguageVersions: [.v5]
)
| 19.333333 | 46 | 0.549261 |
8f7fd8bae9d84ca9d81777c0103e702c479adfbd | 2,510 | //
// WebController.swift
// PaySms
//
// Created by Irakli Shelia on 08.12.21.
//
import Foundation
import WebKit
import UIKit
protocol WebControllerDelegate {
func redirected(with result: TwoFAResponse)
}
class MyWebView: UIView, WKNavigationDelegate {
private let webView: WKWebView = WKWebView()
var webDelegate: WebControllerDelegate?
var iFrameUrl: String
init(url: String) {
iFrameUrl = url
super.init(frame: .zero)
setupWebView()
setupCloseButton()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupWebView() {
self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
let webView = WKWebView(frame: frame)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] //It assigns Custom View height and width
webView.navigationDelegate = self
self.addSubview(webView)
guard let url = URL(string: iFrameUrl) else { return }
webView.load(URLRequest(url: url))
}
private func setupCloseButton() {
let button = UIButton(type: .system) as UIButton
button.translatesAutoresizingMaskIntoConstraints = false
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.setTitle("X", for: .normal)
button.autoresizingMask = [.flexibleWidth,.flexibleHeight]
button.backgroundColor = .purple
button.layer.cornerRadius = 15
self.addSubview(button)
button.topAnchor.constraint(equalTo: self.topAnchor, constant: 35).isActive = true
button.rightAnchor.constraint(equalTo: self.rightAnchor,constant: -25).isActive = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(closeClicked(sender:)))
button.addGestureRecognizer(gesture)
}
@objc func closeClicked(sender: UITapGestureRecognizer) {
webDelegate?.redirected(with: .failure(HTTPNetworkError.userClosed))
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
if webView.url?.absoluteString.contains("payze.io") != nil {
webDelegate?.redirected(with: .success(true))
print("Redirected")
} else {
webDelegate?.redirected(with: .failure(HTTPNetworkError.badRequest))
print("Failed to redirect")
}
}
}
| 33.466667 | 116 | 0.666534 |
b966bbd480d3962be34dc6af9a76c9048d328ad8 | 8,982 | //
// FLLTest3ViewController.swift
// TangramKit
//
// Created by apple on 16/7/18.
// Copyright © 2016年 youngsoft. All rights reserved.
//
import UIKit
/**
*3.FlowLayout - Drag
*/
class FLLTest3ViewController: UIViewController {
weak var flowLayout: TGFlowLayout!
var oldIndex: Int = 0
var currentIndex: Int = 0
var hasDrag: Bool = false
weak var addButton: UIButton!
override func loadView() {
/*
这个例子用来介绍布局视图对动画的支持,以及通过布局视图的autoresizesSubviews属性,以及子视图的扩展属性tg_useFrame和tg_noLayout来实现子视图布局的个性化设置。
布局视图的autoresizesSubviews属性用来设置当布局视图被激发要求重新布局时,是否会对里面的所有子视图进行重新布局。
子视图的扩展属性tg_useFrame表示某个子视图不受布局视图的布局控制,而是用最原始的frame属性设置来实现自定义的位置和尺寸的设定。
子视图的扩展属性tg_noLayout表示某个子视图会参与布局,但是并不会正真的调整布局后的frame值。
*/
let rootLayout = TGLinearLayout(.vert)
rootLayout.backgroundColor = .white
rootLayout.tg_gravity = TGGravity.horz.fill
self.view = rootLayout
let tipLabel = UILabel()
tipLabel.font = CFTool.font(13)
tipLabel.text = NSLocalizedString(" You can drag the following tag to adjust location in layout, MyLayout can use subview's useFrame,noLayout property and layout view's autoresizesSubviews propery to complete some position adjustment and the overall animation features: \n useFrame set to YES indicates subview is not controlled by the layout view but use its own frame to set the location and size instead.\n \n autoresizesSubviews set to NO indicate layout view will not do any layout operation, and will remain in the position and size of all subviews.\n \n noLayout set to YES indicate subview in the layout view just only take up the position and size but not real adjust the position and size when layouting.", comment: "")
tipLabel.textColor = CFTool.color(4)
tipLabel.tg_height.equal(.wrap) //高度动态确定。
tipLabel.tg_top.equal(self.topLayoutGuide)
rootLayout.addSubview(tipLabel)
let tip2Label = UILabel()
tip2Label.text = NSLocalizedString("double click to remove tag", comment: "")
tip2Label.font = CFTool.font(13)
tip2Label.textColor = CFTool.color(3)
tip2Label.textAlignment = .center
tip2Label.sizeToFit()
tip2Label.tg_top.equal(3)
rootLayout.addSubview(tip2Label)
let flowLayout = TGFlowLayout.init(.vert, arrangedCount: 4)
flowLayout.backgroundColor = CFTool.color(0)
flowLayout.tg_padding = UIEdgeInsetsMake(10, 10, 10, 10)
flowLayout.tg_space = 10 //流式布局里面的子视图的水平和垂直间距设置为10
flowLayout.tg_gravity = TGGravity.horz.fill //流式布局里面的子视图的宽度将平均分配。
flowLayout.tg_height.equal(.fill) //占用剩余的高度。
flowLayout.tg_top.equal(10)
rootLayout.addSubview(flowLayout)
self.flowLayout = flowLayout
}
override func viewDidLoad() {
super.viewDidLoad()
for index in 0...10 {
let label = NSLocalizedString("drag me \(index)", comment: "")
self.flowLayout.addSubview(self.createTagButton(text: label))
}
//最后添加添加按钮。
let addButton = self.createAddButton()
self.flowLayout.addSubview(addButton)
self.addButton = addButton
}
//创建标签按钮
internal func createTagButton(text: String) -> UIButton
{
let tagButton = UIButton()
tagButton.setTitle(text, for: .normal)
tagButton.titleLabel?.font = CFTool.font(14)
tagButton.layer.cornerRadius = 20
tagButton.backgroundColor = UIColor(red: CGFloat(arc4random()%256)/255.0, green: CGFloat(arc4random()%256)/255.0, blue: CGFloat(arc4random()%256)/255.0, alpha: 1.0)
tagButton.tg_height.equal(44)
tagButton.addTarget(self, action: #selector(handleTouchDrag(sender:event:)), for: .touchDragInside) //注册拖动事件。
tagButton.addTarget(self, action: #selector(handleTouchDrag(sender:event:)), for: .touchDragOutside) //注册拖动事件。
tagButton.addTarget(self, action: #selector(handleTouchDown(sender:event:)), for: .touchDown) //注册按下事件
tagButton.addTarget(self, action: #selector(handleTouchUp), for: .touchUpInside) //注册抬起事件
tagButton.addTarget(self, action: #selector(handleTouchUp), for: .touchCancel) //注册抬起事件
tagButton.addTarget(self, action: #selector(handleTouchDownRepeat(sender:event:)), for: .touchDownRepeat) //注册多次点击事件
return tagButton;
}
//创建添加按钮
private func createAddButton() -> UIButton
{
let addButton = UIButton()
addButton.setTitle(NSLocalizedString("add tag", comment: ""), for: .normal)
addButton.titleLabel?.font = CFTool.font(14)
addButton.setTitleColor(.blue, for: .normal)
addButton.layer.cornerRadius = 20
addButton.layer.borderWidth = 0.5
addButton.layer.borderColor = UIColor.lightGray.cgColor
addButton.tg_height.equal(44)
addButton.addTarget(self, action: #selector(handleAddTagButton(sender:)), for: .touchUpInside)
return addButton
}
}
extension FLLTest3ViewController {
@objc func handleAddTagButton(sender: AnyObject)
{
let label = NSLocalizedString("drag me \(self.flowLayout.subviews.count-1)", comment: "")
self.flowLayout.insertSubview(self.createTagButton(text: label), at: self.flowLayout.subviews.count-1)
}
@objc func handleTouchDrag(sender: UIButton, event: UIEvent) {
self.hasDrag = true
//取出拖动时当前的位置点。
let touch: UITouch = (event.touches(for: sender)! as NSSet).anyObject() as! UITouch
let pt = touch.location(in: self.flowLayout)
var sbv2: UIView! //sbv2保存拖动时手指所在的视图。
//判断当前手指在具体视图的位置。这里要排除self.addButton的位置(因为这个按钮将固定不调整)。
for sbv: UIView in self.flowLayout.subviews
{
if sbv != sender && sender.tg_useFrame && sbv != self.addButton
{
let rect1 = sbv.frame
if rect1.contains(pt) {
sbv2 = sbv
break
}
}
}
//如果拖动的控件sender和手指下当前其他的兄弟控件有重合时则意味着需要将当前控件插入到手指下的sbv2所在的位置,并且调整sbv2的位置。
if sbv2 != nil
{
self.flowLayout.tg_layoutAnimationWithDuration(0.2)
//得到要移动的视图的位置索引。
self.currentIndex = self.flowLayout.subviews.index(of: sbv2)!
if self.oldIndex != self.currentIndex {
self.oldIndex = self.currentIndex
}
else {
self.currentIndex = self.oldIndex + 1
}
//因为sender在bringSubviewToFront后变为了最后一个子视图,因此要调整正确的位置。
for index in ((self.currentIndex + 1)...self.flowLayout.subviews.count-1).reversed() {
self.flowLayout.exchangeSubview(at: index, withSubviewAt: index-1)
}
//经过上面的sbv2的位置调整完成后,需要重新激发布局视图的布局,因此这里要设置autoresizesSubviews为YES。
self.flowLayout.autoresizesSubviews = true
sender.tg_useFrame = false
sender.tg_noLayout = true //这里设置为true表示布局时不会改变sender的真实位置而只是在布局视图中占用一个位置和尺寸,正是因为只是占用位置,因此会调整其他视图的位置。
self.flowLayout.layoutIfNeeded()
}
//在进行sender的位置调整时,要把sender移动到最顶端,也就子视图数组的的最后,这时候布局视图不能布局,因此要把autoresizesSubviews设置为false,同时因为要自定义
//sender的位置,因此要把tg_useFrame设置为true,并且恢复tg_noLayout为false。
self.flowLayout.bringSubview(toFront: sender) //把拖动的子视图放在最后,这样这个子视图在移动时就会在所有兄弟视图的上面。
self.flowLayout.autoresizesSubviews = false //在拖动时不要让布局视图激发布局
sender.tg_useFrame = true //因为拖动时,拖动的控件需要自己确定位置,不能被布局约束,因此必须要将useFrame设置为YES下面的center设置才会有效。
sender.tg_noLayout = false //因为useFrame设置为了YES所有这里可以直接调整center,从而实现了位置的自定义设置。
sender.center = pt //因为tg_useFrame设置为了YES所有这里可以直接调整center,从而实现了位置的自定义设置。
}
@objc func handleTouchDown(sender: UIButton, event: UIEvent)
{
//在按下时记录当前要拖动的控件的索引。
self.oldIndex = self.flowLayout.subviews.index(of: sender)!
self.currentIndex = self.oldIndex
self.hasDrag = false
}
@objc func handleTouchUp(sender: UIButton, event: UIEvent) {
if !self.hasDrag {
return
}
//当抬起时,需要让拖动的子视图调整到正确的顺序,并重新参与布局,因此这里要把拖动的子视图的tg_useFrame设置为false,同时把布局视图的autoresizesSubviews还原为YES。
//调整索引。
for index in ((self.currentIndex+1)...(self.flowLayout.subviews.count-1)).reversed() {
self.flowLayout.exchangeSubview(at: index, withSubviewAt: index-1)
}
sender.tg_useFrame = false //让拖动的子视图重新参与布局,将tg_useFrame设置为false
self.flowLayout.autoresizesSubviews = true //让布局视图可以重新激发布局,这里还原为true。
}
@objc func handleTouchDownRepeat(sender: UIButton, event: UIEvent) {
sender.removeFromSuperview()
self.flowLayout.tg_layoutAnimationWithDuration(0.2)
}
}
| 41.583333 | 738 | 0.656981 |
725e6effa8f0dad79de9f0c6961158c0faba3633 | 735 | //
// collecImageCell.swift
// Alamofire
//
// Created by HIPL-GLOBYLOG on 8/22/19.
//
import UIKit
class collecImageCell: UICollectionViewCell {
@IBOutlet weak var crossBtn:UIButton!
@IBOutlet weak var iconeImage:UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
let image1 = UIImage(named: "acount_cross_error")
self.crossBtn.setImage(image1, for: .selected)
self.crossBtn.setImage(image1, for: .normal)
self.crossBtn.setImage(image1, for: .highlighted)
self.iconeImage.layer.borderWidth = 1
self.iconeImage.layer.borderColor = UIColor(red:222/255, green:225/255, blue:227/255, alpha: 1).cgColor
// Initialization code
}
}
| 28.269231 | 111 | 0.67483 |
b9871fa196c69e54a61b39166394d84060895df5 | 9,043 | //
// TweakStore+Tests.swift
// TweaKitTests
//
// Created by cokile
//
import XCTest
@testable import TweaKit
class TweakStoreTests: XCTestCase {
let store1 = TweakStore(name: "Test_Store_1")
let store2 = TweakStore(name: "Test_Store_2")
override func setUp() {
super.setUp()
store1.removeAll()
store2.removeAll()
}
func testCRUD() {
XCTAssertFalse(store1.hasValue(forKey: "k1"))
XCTAssertFalse(store1.hasValue(forKey: "k2"))
XCTAssertFalse(store1.hasValue(forKey: "k3"))
store1.setValue(1, forKey: "k1")
store1.setValue(2, forKey: "k2")
XCTAssertEqual(store1.int(forKey: "k1"), 1)
XCTAssertTrue(store1.hasValue(forKey: "k1"))
XCTAssertEqual(store1.int(forKey: "k2"), 2)
XCTAssertTrue(store1.hasValue(forKey: "k2"))
store1.removeValue(forKey: "k3")
XCTAssertEqual(store1.int(forKey: "k1"), 1)
XCTAssertTrue(store1.hasValue(forKey: "k1"))
XCTAssertEqual(store1.int(forKey: "k2"), 2)
XCTAssertTrue(store1.hasValue(forKey: "k2"))
store1.removeValue(forKey: "k1")
XCTAssertNil(store1.int(forKey: "k1"))
XCTAssertFalse(store1.hasValue(forKey: "k1"))
XCTAssertEqual(store1.int(forKey: "k2"), 2)
XCTAssertTrue(store1.hasValue(forKey: "k2"))
store1.removeAll()
XCTAssertNil(store1.int(forKey: "k1"))
XCTAssertFalse(store1.hasValue(forKey: "k1"))
XCTAssertNil(store1.int(forKey: "k2"))
XCTAssertFalse(store1.hasValue(forKey: "k2"))
}
func testStoreIsolation() {
XCTAssertFalse(store1.hasValue(forKey: "k1"))
XCTAssertFalse(store2.hasValue(forKey: "k1"))
store1.setValue(1, forKey: "k1")
XCTAssertEqual(store1.int(forKey: "k1"), 1)
XCTAssertTrue(store1.hasValue(forKey: "k1"))
XCTAssertNil(store2.int(forKey: "k1"))
XCTAssertFalse(store2.hasValue(forKey: "k1"))
store2.setValue(2, forKey: "k1")
XCTAssertEqual(store1.int(forKey: "k1"), 1)
XCTAssertTrue(store1.hasValue(forKey: "k1"))
XCTAssertEqual(store2.int(forKey: "k1"), 2)
XCTAssertTrue(store2.hasValue(forKey: "k1"))
store1.removeValue(forKey: "k1")
XCTAssertNil(store1.int(forKey: "k1"))
XCTAssertFalse(store1.hasValue(forKey: "k1"))
XCTAssertEqual(store2.int(forKey: "k1"), 2)
XCTAssertTrue(store2.hasValue(forKey: "k1"))
}
func testNotifyNew() {
let exp1 = expectation(description: "k1 notify 1")
let exp2 = expectation(description: "k1 notify 2")
let exp3 = expectation(description: "k1 notify 3")
let exp4 = expectation(description: "k1 notify nil")
_ = store1.startNotifying(forKey: "k1") { _, new, _ in
let int = new.flatMap(Int.convert(from:))
if int == 1 {
exp1.fulfill()
} else if int == 2 {
exp2.fulfill()
} else if int == 3 {
exp3.fulfill()
} else if int == nil {
exp4.fulfill()
}
}
store1.setValue(1, forKey: "k1")
store1.setValue(2, forKey: "k1")
store1.setValue(3, forKey: "k1")
store1.removeValue(forKey: "k1")
wait(for: [exp1, exp2, exp3, exp4], timeout: 1, enforceOrder: false)
}
func testNotifyOld() {
let exp1 = expectation(description: "k1 notify nil")
let exp2 = expectation(description: "k1 notify 1")
let exp3 = expectation(description: "k1 notify 2")
let exp4 = expectation(description: "k1 notify 3")
_ = store1.startNotifying(forKey: "k1") { old, _, _ in
let int = old.flatMap(Int.convert(from:))
if old == nil {
exp1.fulfill()
} else if int == 1 {
exp2.fulfill()
} else if int == 2 {
exp3.fulfill()
} else if int == 3 {
exp4.fulfill()
}
}
store1.setValue(1, forKey: "k1")
store1.setValue(2, forKey: "k1")
store1.setValue(3, forKey: "k1")
store1.removeValue(forKey: "k1")
wait(for: [exp1, exp2, exp3, exp4], timeout: 1, enforceOrder: false)
}
func testNotifyManually() {
let exp = expectation(description: "k1 notify 1")
_ = store1.startNotifying(forKey: "k1") { _, new, manually in
if new.flatMap(Int.convert(from:)) == 1 {
XCTAssertTrue(manually)
exp.fulfill()
}
}
store1.setValue(1, forKey: "k1", manually: true)
wait(for: [exp], timeout: 1)
}
func testNotifyNotManually() {
let exp = expectation(description: "k1 notify 1")
_ = store1.startNotifying(forKey: "k1") { _, new, manually in
if new.flatMap(Int.convert(from:)) == 1 {
XCTAssertFalse(manually)
exp.fulfill()
}
}
store1.setValue(1, forKey: "k1", manually: false)
wait(for: [exp], timeout: 1)
}
func testNotifyRemoveAll() {
let exp1 = expectation(description: "k1 notify")
let exp2 = expectation(description: "k2 notify")
let exp3 = expectation(description: "k3 notify")
exp3.isInverted = true
store1.setValue(1, forKey: "k1")
store1.setValue(2, forKey: "k2")
_ = store1.startNotifying(forKey: "k1") { _, new, _ in
if new == nil {
exp1.fulfill()
}
}
_ = store1.startNotifying(forKey: "k2") { _, new, _ in
if new == nil {
exp2.fulfill()
}
}
_ = store1.startNotifying(forKey: "k3") { _, new, _ in
if new == nil {
exp3.fulfill()
}
}
store1.removeAll()
wait(for: [exp1, exp2, exp3], timeout: 1, enforceOrder: false)
}
func testStopNotifyingKey() {
let exp1 = expectation(description: "k1 notify 1")
exp1.expectedFulfillmentCount = 2
let exp2 = expectation(description: "k1 notify 2")
exp2.expectedFulfillmentCount = 2
let exp3 = expectation(description: "k1 notify 3")
exp3.isInverted = true
_ = store1.startNotifying(forKey: "k1") { _, new, _ in
let int = new.flatMap(Int.convert(from:))
if int == 1 {
exp1.fulfill()
} else if int == 2 {
exp2.fulfill()
} else if int == 3 {
exp3.fulfill()
}
}
_ = store1.startNotifying(forKey: "k1") { _, new, _ in
let int = new.flatMap(Int.convert(from:))
if int == 1 {
exp1.fulfill()
} else if int == 2 {
exp2.fulfill()
} else if int == 3 {
exp3.fulfill()
}
}
store1.setValue(1, forKey: "k1")
store1.setValue(2, forKey: "k1")
store1.stopNotifying(forKey: "k1")
store1.setValue(3, forKey: "k1")
wait(for: [exp1, exp2, exp3], timeout: 1, enforceOrder: false)
}
func testStopNotifyingToken() {
let exp1 = expectation(description: "k1 notify 1")
exp1.expectedFulfillmentCount = 2
let exp2 = expectation(description: "k1 notify 2")
exp2.expectedFulfillmentCount = 2
let exp3 = expectation(description: "k1 notify 3")
_ = store1.startNotifying(forKey: "k1") { _, new, _ in
let int = new.flatMap(Int.convert(from:))
if int == 1 {
exp1.fulfill()
} else if int == 2 {
exp2.fulfill()
} else if int == 3 {
exp3.fulfill()
}
}
let token = store1.startNotifying(forKey: "k1") { _, new, _ in
let int = new.flatMap(Int.convert(from:))
if int == 1 {
exp1.fulfill()
} else if int == 2 {
exp2.fulfill()
} else if int == 3 {
exp3.fulfill()
}
}
store1.setValue(1, forKey: "k1")
store1.setValue(2, forKey: "k1")
store1.stopNotifying(ForToken: token)
store1.setValue(3, forKey: "k1")
wait(for: [exp1, exp2, exp3], timeout: 1, enforceOrder: false)
}
func testRawData() {
XCTAssertNil(store1.rawData(forKey: "k1"))
store1.setValue(1, forKey: "k1")
XCTAssertNotNil(store1.rawData(forKey: "k1"))
XCTAssertEqual(store1.rawData(forKey: "k1"), 1.convertToData())
}
}
private extension TweakStore {
func int(forKey key: String) -> Int? {
value(forKey: key)
}
}
| 32.883636 | 76 | 0.526485 |
611d57ca59755e835abea3a35141c7ea3210a30e | 2,165 | //
// AppDelegate.swift
// DRFAiOS
//
// Created by 윤진서 on 2018. 2. 9..
// Copyright © 2018년 rinndash. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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:.
}
}
| 46.06383 | 285 | 0.753349 |
ddd9c1f82e600afbf61ccf2a134ca7bf83a68913 | 887 | //
// ExampleTests.swift
// ExampleTests
//
// Created by syxc on 16/2/24.
// Copyright © 2016年 syxc. All rights reserved.
//
import XCTest
@testable import Example
class ExampleTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 23.972973 | 107 | 0.676437 |
79a8871e6b81b0e214629b90f55353b1a5d756db | 7,757 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
import MatrixSDK
@available(iOS 14.0, *)
class RoomAccessTypeChooserService: RoomAccessTypeChooserServiceProtocol {
// MARK: - Properties
// MARK: Private
private let roomId: String
private let allowsRoomUpgrade: Bool
private let session: MXSession
private var replacementRoom: MXRoom?
private var didBuildSpaceGraphObserver: Any?
private var accessItems: [RoomAccessTypeChooserAccessItem] = []
private var roomUpgradeRequired = false {
didSet {
for (index, item) in accessItems.enumerated() {
if item.id == .restricted {
accessItems[index].badgeText = roomUpgradeRequired ? VectorL10n.roomAccessSettingsScreenUpgradeRequired : VectorL10n.roomAccessSettingsScreenEditSpaces
}
}
accessItemsSubject.send(accessItems)
}
}
private(set) var selectedType: RoomAccessTypeChooserAccessType = .private {
didSet {
for (index, item) in accessItems.enumerated() {
accessItems[index].isSelected = selectedType == item.id
}
accessItemsSubject.send(accessItems)
}
}
private var roomJoinRule: MXRoomJoinRule = .private
private var currentOperation: MXHTTPOperation?
// MARK: Public
private(set) var accessItemsSubject: CurrentValueSubject<[RoomAccessTypeChooserAccessItem], Never>
private(set) var roomUpgradeRequiredSubject: CurrentValueSubject<Bool, Never>
private(set) var waitingMessageSubject: CurrentValueSubject<String?, Never>
private(set) var errorSubject: CurrentValueSubject<Error?, Never>
private(set) var currentRoomId: String
private(set) var versionOverride: String?
// MARK: - Setup
init(roomId: String, allowsRoomUpgrade: Bool, session: MXSession) {
self.roomId = roomId
self.allowsRoomUpgrade = allowsRoomUpgrade
self.session = session
self.currentRoomId = roomId
self.versionOverride = session.homeserverCapabilitiesService.versionOverrideForFeature(.restricted)
roomUpgradeRequiredSubject = CurrentValueSubject(false)
waitingMessageSubject = CurrentValueSubject(nil)
accessItemsSubject = CurrentValueSubject(accessItems)
errorSubject = CurrentValueSubject(nil)
setupAccessItems()
readRoomState()
}
deinit {
currentOperation?.cancel()
if let observer = self.didBuildSpaceGraphObserver {
NotificationCenter.default.removeObserver(observer)
}
}
// MARK: - Public
func updateSelection(with selectedType: RoomAccessTypeChooserAccessType) {
self.selectedType = selectedType
if selectedType == .restricted {
if roomUpgradeRequired && roomUpgradeRequiredSubject.value == false {
roomUpgradeRequiredSubject.send(true)
}
}
}
func applySelection(completion: @escaping () -> Void) {
guard let room = session.room(withRoomId: currentRoomId) else {
MXLog.error("[RoomAccessTypeChooserService] applySelection: room with ID \(currentRoomId) not found")
return
}
let _joinRule: MXRoomJoinRule?
switch self.selectedType {
case .private:
_joinRule = .private
case .public:
_joinRule = .public
case .restricted:
_joinRule = nil
if roomUpgradeRequired && roomUpgradeRequiredSubject.value == false {
roomUpgradeRequiredSubject.send(true)
} else {
completion()
}
}
if let joinRule = _joinRule {
self.waitingMessageSubject.send(VectorL10n.roomAccessSettingsScreenSettingRoomAccess)
room.setJoinRule(joinRule) { [weak self] response in
guard let self = self else { return }
self.waitingMessageSubject.send(nil)
switch response {
case .failure(let error):
self.errorSubject.send(error)
case .success:
completion()
}
}
}
}
func updateRoomId(with roomId: String) {
self.currentRoomId = roomId
readRoomState()
}
// MARK: - Private
private func setupAccessItems() {
guard let spaceService = session.spaceService, let ancestors = spaceService.ancestorsPerRoomId[currentRoomId], !ancestors.isEmpty, allowsRoomUpgrade || !roomUpgradeRequired else {
self.accessItems = [
RoomAccessTypeChooserAccessItem(id: .private, isSelected: false, title: VectorL10n.private, detail: VectorL10n.roomAccessSettingsScreenPrivateMessage, badgeText: nil),
RoomAccessTypeChooserAccessItem(id: .public, isSelected: false, title: VectorL10n.public, detail: VectorL10n.roomAccessSettingsScreenPublicMessage, badgeText: nil),
]
return
}
self.accessItems = [
RoomAccessTypeChooserAccessItem(id: .private, isSelected: false, title: VectorL10n.private, detail: VectorL10n.roomAccessSettingsScreenPrivateMessage, badgeText: nil),
RoomAccessTypeChooserAccessItem(id: .restricted, isSelected: false, title: VectorL10n.createRoomTypeRestricted, detail: VectorL10n.roomAccessSettingsScreenRestrictedMessage, badgeText: roomUpgradeRequired ? VectorL10n.roomAccessSettingsScreenUpgradeRequired : VectorL10n.roomAccessSettingsScreenEditSpaces),
RoomAccessTypeChooserAccessItem(id: .public, isSelected: false, title: VectorL10n.public, detail: VectorL10n.roomAccessSettingsScreenPublicMessage, badgeText: nil),
]
accessItemsSubject.send(accessItems)
}
private func readRoomState() {
guard let room = session.room(withRoomId: currentRoomId) else {
MXLog.error("[RoomAccessTypeChooserService] readRoomState: room with ID \(currentRoomId) not found")
return
}
room.state { [weak self] state in
guard let self = self else { return }
if let roomVersion = state?.stateEvents(with: .roomCreate)?.last?.wireContent["room_version"] as? String, let homeserverCapabilitiesService = self.session.homeserverCapabilitiesService {
self.roomUpgradeRequired = self.versionOverride != nil && !homeserverCapabilitiesService.isFeatureSupported(.restricted, by: roomVersion)
}
self.roomJoinRule = state?.joinRule ?? .private
self.setupDefaultSelectionType()
}
}
private func setupDefaultSelectionType() {
switch roomJoinRule {
case .restricted:
selectedType = .restricted
case .public:
selectedType = .public
default:
selectedType = .private
}
if selectedType != .restricted {
roomUpgradeRequiredSubject.send(false)
}
}
}
| 38.979899 | 319 | 0.652572 |
2079a657badef35e8fad6b0053f3d527eaba025a | 3,821 | //
// IMUIGalleryContainerCell.swift
// sample
//
// Created by oshumini on 2017/10/12.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import Photos
private var CellIdentifier = ""
class IMUIGalleryContainerCell: UICollectionViewCell, IMUIFeatureCellProtocol {
var featureDelegate: IMUIFeatureViewDelegate?
@IBOutlet weak var permissionDenyedView: IMUIPermissionDenyedView!
@IBOutlet weak var galleryCollectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
self.setupAllView()
self.addPhotoObserver()
}
func addPhotoObserver() {
PHPhotoLibrary.requestAuthorization { (status) in
DispatchQueue.main.async {
switch status {
case .authorized:
PHPhotoLibrary.shared().register(self)
self.permissionDenyedView.isHidden = true
break
default:
self.permissionDenyedView.type = "相册"
self.permissionDenyedView.isHidden = false
break
}
}
}
}
func setupAllView() {
let bundle = Bundle.imuiInputViewBundle()
self.galleryCollectionView.register(UINib(nibName: "IMUIGalleryCell", bundle: bundle), forCellWithReuseIdentifier: "IMUIGalleryCell")
self.galleryCollectionView.delegate = self
self.galleryCollectionView.dataSource = self
self.galleryCollectionView.reloadData()
}
func activateMedia() {
self.galleryCollectionView.reloadDataHorizontalNoScroll()
if IMUIGalleryDataManager.allAssets.count > 0 {
// self.galleryCollectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: false)
}
}
func inactivateMedia() {
}
}
extension IMUIGalleryContainerCell: UICollectionViewDelegate {
}
extension IMUIGalleryContainerCell: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return IMUIGalleryDataManager.allAssets.count
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
collectionView.collectionViewLayout.invalidateLayout()
return 1
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let galleryHeight = 254
return CGSize(width: galleryHeight, height: galleryHeight)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize.zero
}
public func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
CellIdentifier = "IMUIGalleryCell"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier, for: indexPath) as! IMUIGalleryCell
cell.asset = IMUIGalleryDataManager.allAssets[indexPath.row]
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if cell is IMUIGalleryCell {
let galleryCell = cell as! IMUIGalleryCell
galleryCell.clicked()
self.featureDelegate?.didSelectPhoto(with: [])
}
}
}
extension IMUIGalleryContainerCell: PHPhotoLibraryChangeObserver {
public func photoLibraryDidChange(_ changeInstance: PHChange) {
DispatchQueue.global(qos: .background).async {
IMUIGalleryDataManager.updateAssets()
DispatchQueue.main.async {
self.galleryCollectionView.reloadData()
}
}
}
}
| 31.319672 | 137 | 0.716305 |
fe8ec5a83f462c50548526a46007b1ede8ac575b | 2,385 | final class KeyboardViewController: UIViewController {
private let messageHelper: SystemMessageHelper? = SystemMessageHelper()
@IBOutlet private weak var searchBar: UISearchBar!
@IBOutlet private weak var firstnameText: UITextField!
@IBOutlet private weak var lastnameText: UITextField!
@IBOutlet private weak var mobileNumberText: UITextField!
@IBOutlet private weak var addressLabel: UILabel!
private lazy var keyboardHelper: KeyboardHelper = {
let keyboardHelper = KeyboardHelper()
keyboardHelper.delegate = self
return keyboardHelper
}()
@IBAction func submit(_ sender: Any) {
let firstname = firstnameText.text ?? .empty
let lastname = lastnameText.text ?? .empty
let mobileNumber = mobileNumberText.text ?? .empty
let address = addressLabel.text ?? .empty
let info = String(format: Self.submissionPattern, firstname, lastname, mobileNumber, address)
messageHelper?.showInfo(info)
}
override func viewDidLoad() {
super.viewDidLoad()
firstnameText.activateUnderline(withNormal: Self.underlineColor, withHignlighted: Self.highlightedUnderlineColor)
lastnameText.activateUnderline(withNormal: Self.underlineColor, withHignlighted: Self.highlightedUnderlineColor)
mobileNumberText.activateUnderline(withNormal: Self.underlineColor, withHignlighted: Self.highlightedUnderlineColor)
keyboardHelper.rootView = view
keyboardHelper.inputViews = [searchBar, firstnameText, lastnameText, mobileNumberText]
keyboardHelper.startObservingKeyboard()
}
}
extension KeyboardViewController: KeyboardHelperDelegate {
func keyboardHelperDidConfirmInput(_ keyboardHelper: KeyboardHelper) {
submit(self)
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, didEditOn view: UIView) {
if view == searchBar {
addressLabel.text = searchBar.text
}
}
}
private extension KeyboardViewController {
static let highlightedUnderlineColor = UIColor(red: 125/255, green: 182/255, blue: 216/255, alpha: 1)
static let underlineColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 0.6)
static let submissionPattern = "Firstname: %@\nLastname: %@\nMobile: %@\nAddress: %@"
}
import AdvancedUIKit
import AdvancedFoundation
import UIKit
| 40.423729 | 124 | 0.720335 |
0950a055a229e2e9a82bd2c42e24418ec1f0e35e | 1,909 | //
// RHPreviewTableViewCellTilesAnimator.swift
// RHPreviewCell
//
// Created by Robert Herdzik on 25/09/2016.
// Copyright © 2016 Robert. All rights reserved.
//
import UIKit
class RHPreviewTableViewCellTilesAnimator: RHPreviewTableViewCellTilesAnimationProtocol {
func performShowAnimation(for tiles: [RHPreviewTileView], completion: @escaping RHTilesAnimationComplitionBlock) {
for tile in tiles {
tile.isHidden = false
UIView.animate(withDuration: 0.3,
animations: {
tile.alpha = CGFloat(0.3)
}, completion: { _ in
if tile == tiles.last {
completion()
}
})
}
}
func performHideAnimation(for tiles: [RHPreviewTileView], completion: @escaping RHTilesAnimationComplitionBlock) {
for tile in tiles {
UIView.animate(withDuration: 0.2,
animations: {
tile.alpha = CGFloat(0.0)
}, completion: { _ in
tile.isHidden = true
if tile == tiles.last {
completion()
}
})
}
}
func performMagnifyAnimation(for tile: RHPreviewTileView) {
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.4,
initialSpringVelocity: 0.9,
options: UIViewAnimationOptions(),
animations: {
let scale = CGFloat(0.89)
tile.transform = CGAffineTransform(scaleX: scale, y: scale)
}, completion: nil)
}
}
| 35.351852 | 118 | 0.475118 |
bbd2251c8d1417f2848490d9f6534a873701cfee | 834 | //
// SavedItemsHostingController.swift
// Project03
//
// Created by Lam Nguyen on 6/6/21.
//
import UIKit
import SwiftUI
class SavedItemsHostingController: UIHostingController<UserSaveItemsSwiftUIswift> {
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder, rootView: UserSaveItemsSwiftUIswift())
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 24.529412 | 106 | 0.679856 |
1dd67bcefb259e5845283c9a2992ac2d4f360146 | 1,357 | import UIKit
public protocol Enableable {
@discardableResult
func enabled() -> Self
@discardableResult
func enabled(_ value: Bool) -> Self
@discardableResult
func enabled(_ binding: UIKitPlus.State<Bool>) -> Self
@discardableResult
func enabled<V>(_ expressable: ExpressableState<V, Bool>) -> Self
}
protocol _Enableable: Enableable {
func _setEnabled(_ v: Bool)
}
extension Enableable {
@discardableResult
public func enabled() -> Self {
enabled(true)
}
@discardableResult
public func enabled(_ binding: UIKitPlus.State<Bool>) -> Self {
binding.listen { self.enabled($0) }
return enabled(binding.wrappedValue)
}
@discardableResult
public func enabled<V>(_ expressable: ExpressableState<V, Bool>) -> Self {
enabled(expressable.unwrap())
}
}
@available(iOS 13.0, *)
extension Enableable {
@discardableResult
public func enabled(_ value: Bool) -> Self {
guard let s = self as? _Enableable else { return self }
s._setEnabled(value)
return self
}
}
// for iOS lower than 13
extension _Enableable {
@discardableResult
public func enabled(_ value: Bool) -> Self {
guard let s = self as? _Enableable else { return self }
s._setEnabled(value)
return self
}
}
| 23.396552 | 78 | 0.640383 |
e9fc2612dd9744b69b823c59b07e2b47e82aaa89 | 1,377 | import XCTest
import class Foundation.Bundle
final class swampgenTests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
// Some of the APIs that we use below are available in macOS 10.13 and above.
guard #available(macOS 10.13, *) else {
return
}
let fooBinary = productsDirectory.appendingPathComponent("swampgen")
let process = Process()
process.executableURL = fooBinary
let pipe = Pipe()
process.standardOutput = pipe
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
XCTAssertEqual(output, "Hello, world!\n")
}
/// Returns path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
static var allTests = [
("testExample", testExample),
]
}
| 28.6875 | 87 | 0.635439 |
0e659dcdc9081e52b0f64acb41fa3bc2c2b604b4 | 1,213 | //
// APIServiceMock.swift
// MusicPlayerTests
//
// Created by Judar Lima on 06/03/19.
// Copyright © 2019 raduJ. All rights reserved.
//
import Foundation
@testable import MusicPlayer
class APIServiceMock: ServiceProtocol {
var serviceError: ServiceError? = nil
var fileName: String?
func requestData(with setup: ServiceSetup, completion: @escaping (Result<Data>) -> Void) {
guard let error = serviceError else {
completion(.success(generateData()))
return
}
if serviceError == ServiceError.couldNotParseObject {
completion(.success(generateData()))
} else {
completion(.failure(error))
}
}
private func generateData() -> Data {
guard
let filename = fileName,
let filePath = Bundle.main.path(forResource: filename, ofType: "json")
else { fatalError("Could not mock data!") }
do {
let jsonData = try Data(contentsOf: URL(fileURLWithPath: filePath),
options: .mappedIfSafe)
return jsonData
} catch {
fatalError(error.localizedDescription)
}
}
}
| 28.880952 | 94 | 0.588623 |
26aa3a02cf6bc26e45806a6ae149856c99a4e81e | 2,798 | //
// UserInfo.swift
// Pods
//
// Created by Tommy Rogers on 1/26/16.
//
//
import Foundation
public class Session {
public let accessToken: String!
public let expiresIn: Int!
public let scope: String!
public let userInfo: UserInfo!
public init?(dictionary: [String: AnyObject]) {
guard let accessToken = dictionary["access_token"] as? String,
expiresIn = dictionary["expires_in"] as? Int,
scope = dictionary["scope"] as? String,
userDict = dictionary["user"] as? [String: AnyObject],
userInfo = UserInfo(dictionary: userDict)
else {
// TODO remove once upgraded to Swift 2.2 which fixes this bug
self.accessToken = ""
self.expiresIn = 0
self.scope = ""
self.userInfo = UserInfo(dictionary: [String: AnyObject]())
return nil
}
self.accessToken = accessToken
self.expiresIn = expiresIn
self.scope = scope
self.userInfo = userInfo
}
}
public class UserInfo {
public let id: Int
public let email: String
public let firstName: String
public let lastName: String
public let roles: [String]
public let address1: String?
public let address2: String?
public let zip: String?
public let country: String?
public let city: String?
public let state: String?
public let phone: String?
public init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? Int,
firstName = dictionary["firstname"] as? String,
lastName = dictionary["lastname"] as? String,
email = dictionary["email"] as? String
else {
// TODO remove once upgraded to Swift 2.2 which fixes this bug
self.id = 0
self.email = ""
self.firstName = ""
self.lastName = ""
self.roles = []
self.address1 = nil
self.address2 = nil
self.zip = nil
self.country = nil
self.city = nil
self.state = nil
self.phone = nil
return nil
}
self.id = id
self.email = email
self.firstName = firstName
self.lastName = lastName
self.roles = (dictionary["roles"] as? [String]) ?? []
self.address1 = dictionary["address1"] as? String
self.address2 = dictionary["address2"] as? String
self.zip = dictionary["zip"] as? String
self.country = dictionary["country"] as? String
self.city = dictionary["city"] as? String
self.state = dictionary["state"] as? String
self.phone = dictionary["phone"] as? String
}
} | 27.98 | 78 | 0.561115 |
eb02a82ea8b93e31424a6356707f1d7ef9aff7e7 | 339 | //
// File.swift
//
//
// Created by Dan_Koza on 5/26/21.
//
import Foundation
import PopNetworking
public class CancellableQueue: Cancellable {
private let queue: OperationQueue
internal init(queue: OperationQueue) {
self.queue = queue
}
public func cancel() {
queue.cancelAllOperations()
}
}
| 14.73913 | 44 | 0.648968 |
7228473d0a83757765d053bbdce5b564b4ad8aec | 5,099 | //
// UIViewControllerExtensions.swift
// EAKit
//
// Created by Emirhan Erdogan on 07/08/16.
// Copyright © 2016 EAKit
//
#if os(iOS) || os(tvOS)
import UIKit
// MARK: - Properties
public extension UIViewController {
/// EAKit: Add array of subviews to `self.view`.
///
/// - Parameter subviews: array of subviews to add to `self.view`.
public func addSubviews(_ svs: [UIView]) {
self.view.addSubviews(svs)
}
/// EAKit: Add array of subviews to `self.view`.
///
/// - Parameter subviews: list of subviews to add to `self.view`.
public func addSubviews(_ svs: UIView...) {
self.view.addSubviews(svs)
}
/// EAKit: Check if ViewController is onscreen and not hidden.
public var isVisible: Bool {
// http://stackoverflow.com/questions/2777438/how-to-tell-if-uiviewcontrollers-view-is-visible
return self.isViewLoaded && view.window != nil
}
}
// MARK: - Methods
public extension UIViewController {
/// EAKit: Assign as listener to notification.
///
/// - Parameters:
/// - name: notification name.
/// - selector: selector to run with notified.
public func addNotificationObserver(name: Notification.Name, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: name, object: nil)
}
/// EAKit: Unassign as listener to notification.
///
/// - Parameter name: notification name.
public func removeNotificationObserver(name: Notification.Name) {
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
/// EAKit: Unassign as listener from all notifications.
public func removeNotificationsObserver() {
NotificationCenter.default.removeObserver(self)
}
/// EAKit: Helper method to display an alert on any UIViewController subclass. Uses UIAlertController to show an alert
///
/// - Parameters:
/// - title: title of the alert
/// - message: message/body of the alert
/// - buttonTitles: (Optional)list of button titles for the alert. Default button i.e "OK" will be shown if this paramter is nil
/// - highlightedButtonIndex: (Optional) index of the button from buttonTitles that should be highlighted. If this parameter is nil no button will be highlighted
/// - completion: (Optional) completion block to be invoked when any one of the buttons is tapped. It passes the index of the tapped button as an argument
/// - Returns: UIAlertController object (discardable).
@discardableResult public func showAlert(title: String?, message: String?, buttonTitles: [String]? = nil, highlightedButtonIndex: Int? = nil, completion: ((Int) -> Void)? = nil) -> UIAlertController {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
var allButtons = buttonTitles ?? [String]()
if allButtons.count == 0 {
allButtons.append("OK")
}
for index in 0..<allButtons.count {
let buttonTitle = allButtons[index]
let action = UIAlertAction(title: buttonTitle, style: .default, handler: { (_) in
completion?(index)
})
alertController.addAction(action)
// Check which button to highlight
if let highlightedButtonIndex = highlightedButtonIndex, index == highlightedButtonIndex {
if #available(iOS 9.0, *) {
alertController.preferredAction = action
}
}
}
present(alertController, animated: true, completion: nil)
return alertController
}
}
public extension UIViewController {
public var extendedLayout: Bool {
set {
extendedLayoutIncludesOpaqueBars = !newValue
edgesForExtendedLayout = newValue ? .all : []
}
get {
return edgesForExtendedLayout != []
}
}
}
public extension UIViewController {
public class func instance(storyboard sbname: String, bundle: Bundle? = nil, identifier: String?) -> Self? {
return self._instance(storyboard: sbname, bundle: bundle, identifier: identifier)
}
private class func _instance<T>(storyboard sbname: String, bundle: Bundle?, identifier: String?) -> T? {
let storyboard = UIStoryboard.init(name: sbname, bundle: bundle)
guard let id = identifier else {
return storyboard.instantiateInitialViewController() as? T
}
return storyboard.instantiateViewController(withIdentifier: id) as? T
}
}
#endif
| 41.795082 | 208 | 0.5909 |
1d0338bb44d646caffeb18ccc0e25a111d84359b | 19,604 | //
// ChatViewController.swift
// Dark Chat
//
// Created by elusive on 8/27/17.
// Copyright © 2017 Knyazik. All rights reserved.
//
import UIKit
import Firebase
import JSQMessagesViewController
import Photos
final class ChatViewController: JSQMessagesViewController {
lazy var outgoingBubbleImageView: JSQMessagesBubbleImage? = self.setupOutgoingBubble()
lazy var incomingBubbleImageView: JSQMessagesBubbleImage? = self.setupIncomingBubble()
private lazy var messageRef: DatabaseReference = self.channelRef!.child("messages")
private var newMessageRefHandle: DatabaseHandle?
private lazy var userIsTypingRef: DatabaseReference =
self.channelRef!.child("typingIndicator").child(self.senderId)
private var localTyping = false
var isTyping: Bool {
get {
return localTyping
}
set {
localTyping = newValue
userIsTypingRef.setValue(newValue)
}
}
private lazy var usersTypingQuery: DatabaseQuery = self.channelRef!.child("typingIndicator")
.queryOrderedByValue()
.queryEqual(toValue: true)
lazy var storageRef: StorageReference = Storage
.storage()
.reference(forURL: "gs://dark-chat-a832a.appspot.com/")
private let imageURLNotSetKey = "NOTSET"
private var updatedMessageRefHandle: DatabaseHandle?
var channelRef: DatabaseReference?
var channel: Channel? {
didSet {
title = channel?.name
}
}
private var messages = [JSQMessage]() {
didSet {
if messages.isEmpty {
setupBackground()
} else {
collectionView.backgroundView = nil
}
}
}
private var photoMessageMap: [String: JSQPhotoMediaItem] = [:]
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupBackground()
senderId = Auth.auth().currentUser?.uid
collectionView.collectionViewLayout.incomingAvatarViewSize = .zero
collectionView.collectionViewLayout.outgoingAvatarViewSize = .zero
observeMessages()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
observeTyping()
}
deinit {
removeAllObservers()
}
// MARK: - <UICollectionViewDataSource>
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return messages.count
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!,
messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
return messages[indexPath.item]
}
override func collectionView(
_ collectionView: JSQMessagesCollectionView!,
messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let message = messages[indexPath.item]
return (message.senderId == senderId)
? outgoingBubbleImageView
: incomingBubbleImageView
}
override func collectionView(
_ collectionView: JSQMessagesCollectionView!,
avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
return nil
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard
let cell =
super.collectionView(collectionView,
cellForItemAt: indexPath) as? JSQMessagesCollectionViewCell
else {
return UICollectionViewCell()
}
let message = messages[indexPath.item]
cell.textView?.textColor = (message.senderId == senderId)
? .white
: .black
return cell
}
override func didPressSend(_ button: UIButton!,
withMessageText text: String!,
senderId: String!,
senderDisplayName: String!,
date: Date!) {
let itemRef = messageRef.childByAutoId()
let messageItem = [
"senderId": senderId!,
"senderName": senderDisplayName!,
"text": text!,
]
itemRef.setValue(messageItem)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
finishSendingMessage()
isTyping = false
}
override func didPressAccessoryButton(_ sender: UIButton) {
let alert = UIAlertController(title: nil,
message: nil,
preferredStyle: .actionSheet)
let photoAction = UIAlertAction(title: "PhotoLibrary",
style: .default) {
[weak self] (alert: UIAlertAction!) -> Void in
self?.photoFromLibrary()
}
let cameraAction = UIAlertAction(title: "Camera",
style: .default) {
[weak self] (alert: UIAlertAction!) -> Void in
self?.takePhoto()
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .destructive,
handler: nil)
alert.addAction(photoAction)
alert.addAction(cameraAction)
alert.addAction(cancelAction)
if UIDevice.current.userInterfaceIdiom == .pad {
alert.popoverPresentationController?.sourceView = self.view
let sourceRect = CGRect(x: sender.frame.maxX,
y: sender.frame.minY - 100,
width: 1.0, height: 1.0)
alert.popoverPresentationController?.sourceRect = sourceRect
alert.popoverPresentationController?.permittedArrowDirections = .down
}
present(alert, animated: true, completion:nil)
}
// MARK: - UI and Interaction
private func setupOutgoingBubble() -> JSQMessagesBubbleImage {
let bubbleImageFactory = JSQMessagesBubbleImageFactory()
return bubbleImageFactory!
.outgoingMessagesBubbleImage(with: .black)
}
private func setupIncomingBubble() -> JSQMessagesBubbleImage {
let bubbleImageFactory = JSQMessagesBubbleImageFactory()
return bubbleImageFactory!
.incomingMessagesBubbleImage(with: .lightGray)
}
// MARK: - <UITextViewDelegate>
override func textViewDidChange(_ textView: UITextView) {
super.textViewDidChange(textView)
isTyping = !textView.text.isEmpty
}
// MARK: - Private
private func removeAllObservers() {
if let refHandle = newMessageRefHandle {
messageRef.removeObserver(withHandle: refHandle)
}
if let refHandle = updatedMessageRefHandle {
messageRef.removeObserver(withHandle: refHandle)
}
}
private func setupBackground() {
let imageView = UIImageView(image: UIImage(named: "logo-light-theme.png"))
imageView.contentMode = .center
collectionView.backgroundView = imageView
}
private func addMessage(withId id: String, name: String, text: String) {
if let message = JSQMessage(senderId: id,
displayName: name,
text: text) {
messages.append(message)
}
}
private func addPhotoMessage(withId id: String, key: String, mediaItem: JSQPhotoMediaItem) {
if let message = JSQMessage(senderId: id,
displayName: "",
media: mediaItem) {
messages.append(message)
if (mediaItem.image == nil) {
photoMessageMap[key] = mediaItem
}
collectionView.reloadData()
}
}
private func observeMessages() {
messageRef = channelRef!.child("messages")
let messageQuery = messageRef.queryLimited(toLast:25)
newMessageRefHandle =
messageQuery.observe(.childAdded,
with: { [weak self] (snapshot) -> Void in
if let messageData = snapshot.value as?
Dictionary<String, String> {
if let id = messageData["senderId"] as String?,
let name = messageData["senderName"] as String?,
let text = messageData["text"] as String?,
text.characters.count > 0 {
self?.addMessage(withId: id,
name: name,
text: text)
self?.finishReceivingMessage()
}
else if let id = messageData["senderId"] as String?,
let photoURL = messageData["photoURL"] as String? {
if let mediaItem = JSQPhotoMediaItem(
maskAsOutgoing: id == self?.senderId) {
self?.addPhotoMessage(withId: id,
key: snapshot.key,
mediaItem: mediaItem)
if photoURL.hasPrefix("gs://") {
self?.fetchImageDataAtURL(
photoURL,
forMediaItem: mediaItem,
clearsPhotoMessageMapOnSuccessForKey: nil
)
}
}
}
} else {
print("Error! Could not decode message data")
}
}
)
updatedMessageRefHandle =
messageRef.observe(.childChanged, with: { [weak self] (snapshot) in
guard
let messageData = snapshot.value as? Dictionary<String, String>
else {
return
}
let key = snapshot.key
if let photoURL = messageData["photoURL"] as String? {
if let mediaItem = self?.photoMessageMap[key] {
self?.fetchImageDataAtURL(photoURL,
forMediaItem: mediaItem,
clearsPhotoMessageMapOnSuccessForKey: key)
}
}
}
)
}
private func observeTyping() {
let typingIndicatorRef = channelRef!.child("typingIndicator")
userIsTypingRef = typingIndicatorRef.child(senderId)
userIsTypingRef.onDisconnectRemoveValue()
usersTypingQuery.observe(.value) { [weak self] (data: DataSnapshot) in
guard let safeSelf = self else { return }
if data.childrenCount == 1 && safeSelf.isTyping {
return
}
safeSelf.showTypingIndicator = data.childrenCount > 0
safeSelf.scrollToBottom(animated: true)
}
}
fileprivate func sendPhotoMessage() -> String? {
let itemRef = messageRef.childByAutoId()
let messageItem = [
"photoURL": imageURLNotSetKey,
"senderId": senderId!,
]
itemRef.setValue(messageItem)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
finishSendingMessage()
return itemRef.key
}
fileprivate func setImageURL(_ url: String,
forPhotoMessageWithKey key: String) {
let itemRef = messageRef.child(key)
itemRef.updateChildValues(["photoURL": url])
}
private func fetchImageDataAtURL(_ photoURL: String,
forMediaItem mediaItem: JSQPhotoMediaItem,
clearsPhotoMessageMapOnSuccessForKey key: String?) {
let storageRef = Storage.storage().reference(forURL: photoURL)
storageRef.getData(maxSize: INT64_MAX){ (data, error) in
if let error = error {
print("Error downloading image data: \(error)")
return
}
storageRef.getMetadata(completion: { (metadata, metadataErr) in
if let error = metadataErr {
print("Error downloading metadata: \(error)")
return
}
if (metadata?.contentType == "image/gif") {
mediaItem.image = UIImage.gifWithData(data!)
} else {
mediaItem.image = UIImage.init(data: data!)
}
self.collectionView.reloadData()
guard
let key = key
else {
return
}
self.photoMessageMap.removeValue(forKey: key)
})
}
}
private func photoFromLibrary() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
present(picker, animated: true, completion:nil)
}
private func takePhoto() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = (UIImagePickerController
.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
? UIImagePickerControllerSourceType.camera
: UIImagePickerControllerSourceType.photoLibrary
present(picker, animated: true, completion:nil)
}
}
// MARK: - <UIImagePickerControllerDelegate>
extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion:nil)
if let photoReferenceUrl = info[UIImagePickerControllerReferenceURL] as? URL {
let assets = PHAsset.fetchAssets(withALAssetURLs: [photoReferenceUrl], options: nil)
let asset = assets.firstObject
guard
let key = sendPhotoMessage()
else {
return
}
asset?
.requestContentEditingInput(
with: nil,
completionHandler: { (contentEditingInput, info) in
let imageFileURL = contentEditingInput?.fullSizeImageURL
let path = "\(String(describing: Auth.auth().currentUser?.uid))/" +
"\(Int(Date.timeIntervalSinceReferenceDate * 1000))/" +
"\(photoReferenceUrl.lastPathComponent)"
self.storageRef
.child(path)
.putFile(from: imageFileURL!,
metadata: nil) { (metadata, error) in
if let error = error {
print("Error uploading photo: " +
"\(error.localizedDescription)")
return
}
self.setImageURL(
self.storageRef
.child((metadata?.path)!)
.description,
forPhotoMessageWithKey: key
)
}
}
)
} else {
guard
let image = info[UIImagePickerControllerOriginalImage] as? UIImage,
let key = sendPhotoMessage()
else {
return
}
let imageData = UIImageJPEGRepresentation(image, 1.0)
let imagePath = Auth.auth().currentUser!.uid +
"/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
storageRef
.child(imagePath)
.putData(imageData!,
metadata: metadata) { (metadata, error) in
if let error = error {
print("Error uploading photo: \(error)")
return
}
self.setImageURL(
self.storageRef
.child((metadata?.path)!)
.description,
forPhotoMessageWithKey: key
)
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion:nil)
}
}
| 37.340952 | 100 | 0.465619 |
fe6be966f6a6701600957a9304fa51b9f6e0e524 | 2,105 | //
// MenuViewControllerTests.swift
// PracticeProjectsTests
//
// Created by Michael Ho on 11/26/20.
//
import XCTest
@testable import PracticeProjects
class MenuViewControllerTests: XCTestCase {
var menuVC: MenuViewController!
let window: UIWindow = UIWindow(frame: UIScreen.main.bounds)
override func setUpWithError() throws {
// Add the view controller to the hierarchy
menuVC = MenuViewController()
window.makeKeyAndVisible()
window.rootViewController = menuVC
_ = menuVC.view
// Run view controller life cycle
menuVC.viewDidLoad()
menuVC.viewDidLayoutSubviews()
menuVC.viewDidAppear(false)
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testJSONParserExampleAccessible() {
for view in menuVC.stackView.arrangedSubviews {
if let button = view as? UIButton, button.titleLabel?.text == Constants.Example.jsonDecoding.title {
menuVC.buttonClicked(button)
break
}
}
XCTAssertTrue(window.rootViewController?.presentedViewController is ListViewController)
}
func testImageDisplayExampleAccessible() {
for view in menuVC.stackView.arrangedSubviews {
if let button = view as? UIButton, button.titleLabel?.text == Constants.Example.imageLoader.title {
menuVC.buttonClicked(button)
break
}
}
XCTAssertTrue(window.rootViewController?.presentedViewController is ImageDisplayViewController)
}
func testRestAPIExampleAccessible() {
for view in menuVC.stackView.arrangedSubviews {
if let button = view as? UIButton, button.titleLabel?.text == Constants.Example.restAPI.title {
menuVC.buttonClicked(button)
break
}
}
XCTAssertTrue(window.rootViewController?.presentedViewController is ContactsViewController)
}
}
| 34.508197 | 112 | 0.659382 |
080b190b5338697ff91cc190695ccbb2bb2bfb18 | 35,746 | // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
import Swift
var zero = 0
// <rdar://problem/15921334>
// CHECK-LABEL: sil hidden @_TF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <A, R> () -> @owned @callee_owned (@in A) -> @out R {
func return_local_generic_function_without_captures<A, R>() -> (A) -> R {
func f(_: A) -> R {
Builtin.int_trap()
}
// CHECK: [[FN:%.*]] = function_ref @_TFF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1
// CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1
// CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_owned (@in A) -> @out R
return f
}
func return_local_generic_function_with_captures<A, R>(_ a: A) -> (A) -> R {
func f(_: A) -> R {
_ = a
}
return f
}
// CHECK-LABEL: sil hidden @_TF8closures17read_only_captureFSiSi : $@convention(thin) (Int) -> Int {
func read_only_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// SEMANTIC ARC TODO: This is incorrect. We need to do the project_box on the copy.
// CHECK: [[PROJECT:%.*]] = project_box [[XBOX]]
// CHECK: store [[X]] to [trivial] [[PROJECT]]
func cap() -> Int {
return x
}
return cap()
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// SEMANTIC ARC TODO: See above. This needs to happen on the copy_valued box.
// CHECK: mark_function_escape [[PROJECT]]
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures17read_only_capture.*]] : $@convention(thin) (@owned { var Int }) -> Int
// CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX_COPY]])
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: } // end sil function '_TF8closures17read_only_captureFSiSi'
// CHECK: sil shared @[[CAP_NAME]]
// CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }):
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[X:%[0-9]+]] = load [trivial] [[XADDR]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[X]]
// } // end sil function '[[CAP_NAME]]'
// SEMANTIC ARC TODO: This is a place where we have again project_box too early.
// CHECK-LABEL: sil hidden @_TF8closures16write_to_captureFSiSi : $@convention(thin) (Int) -> Int {
func write_to_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: store [[X]] to [trivial] [[XBOX_PB]]
// CHECK: [[X2BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[X2BOX_PB:%.*]] = project_box [[X2BOX]]
// CHECK: copy_addr [[XBOX_PB]] to [initialization] [[X2BOX_PB]]
// CHECK: [[X2BOX_COPY:%.*]] = copy_value [[X2BOX]]
// SEMANTIC ARC TODO: This next mark_function_escape should be on a projection from X2BOX_COPY.
// CHECK: mark_function_escape [[X2BOX_PB]]
var x2 = x
func scribble() {
x2 = zero
}
scribble()
// CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:_TFF8closures16write_to_capture.*]] : $@convention(thin) (@owned { var Int }) -> ()
// CHECK: apply [[SCRIB]]([[X2BOX_COPY]])
// SEMANTIC ARC TODO: This should load from X2BOX_COPY project. There is an
// issue here where after a copy_value, we need to reassign a projection in
// some way.
// CHECK: [[RET:%[0-9]+]] = load [trivial] [[X2BOX_PB]]
// CHECK: destroy_value [[X2BOX]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
return x2
}
// CHECK: } // end sil function '_TF8closures16write_to_captureFSiSi'
// CHECK: sil shared @[[SCRIB_NAME]]
// CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }):
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: copy_addr {{%[0-9]+}} to [[XADDR]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return
// CHECK: } // end sil function '[[SCRIB_NAME]]'
// CHECK-LABEL: sil hidden @_TF8closures21multiple_closure_refs
func multiple_closure_refs(_ x: Int) -> (() -> Int, () -> Int) {
var x = x
func cap() -> Int {
return x
}
return (cap, cap)
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned { var Int }) -> Int
// CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [[CAP]]
// CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned { var Int }) -> Int
// CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [[CAP]]
// CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}})
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_TF8closures18capture_local_funcFSiFT_FT_Si : $@convention(thin) (Int) -> @owned @callee_owned () -> @owned @callee_owned () -> Int {
func capture_local_func(_ x: Int) -> () -> () -> Int {
// CHECK: bb0([[ARG:%.*]] : $Int):
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: store [[ARG]] to [trivial] [[XBOX_PB]]
func aleph() -> Int { return x }
func beth() -> () -> Int { return aleph }
// CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_4bethfT_FT_Si]] : $@convention(thin) (@owned { var Int }) -> @owned @callee_owned () -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// SEMANTIC ARC TODO: This is incorrect. This should be a project_box from XBOX_COPY.
// CHECK: mark_function_escape [[XBOX_PB]]
// CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [[BETH_REF]]([[XBOX_COPY]])
return beth
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[BETH_CLOSURE]]
}
// CHECK: } // end sil function '_TF8closures18capture_local_funcFSiFT_FT_Si'
// CHECK: sil shared @[[ALEPH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_5alephfT_Si]] : $@convention(thin) (@owned { var Int }) -> Int {
// CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }):
// CHECK: sil shared @[[BETH_NAME]] : $@convention(thin) (@owned { var Int }) -> @owned @callee_owned () -> Int {
// CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }):
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@owned { var Int }) -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// SEMANTIC ARC TODO: This should be on a PB from XBOX_COPY.
// CHECK: mark_function_escape [[XBOX_PB]]
// CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [[ALEPH_REF]]([[XBOX_COPY]])
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[ALEPH_CLOSURE]]
// CHECK: } // end sil function '[[BETH_NAME]]'
// CHECK-LABEL: sil hidden @_TF8closures22anon_read_only_capture
func anon_read_only_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
return ({ x })()
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures22anon_read_only_capture.*]] : $@convention(thin) (@inout_aliasable Int) -> Int
// -- apply expression
// CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]])
// -- cleanup
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: sil shared @[[CLOSURE_NAME]]
// CHECK: bb0([[XADDR:%[0-9]+]] : $*Int):
// CHECK: [[X:%[0-9]+]] = load [trivial] [[XADDR]]
// CHECK: return [[X]]
// CHECK-LABEL: sil hidden @_TF8closures21small_closure_capture
func small_closure_capture(_ x: Int) -> Int {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : $Int):
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
return { x }()
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures21small_closure_capture.*]] : $@convention(thin) (@inout_aliasable Int) -> Int
// -- apply expression
// CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]])
// -- cleanup
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
}
// CHECK: sil shared @[[CLOSURE_NAME]]
// CHECK: bb0([[XADDR:%[0-9]+]] : $*Int):
// CHECK: [[X:%[0-9]+]] = load [trivial] [[XADDR]]
// CHECK: return [[X]]
// CHECK-LABEL: sil hidden @_TF8closures35small_closure_capture_with_argument
func small_closure_capture_with_argument(_ x: Int) -> (_ y: Int) -> Int {
var x = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
return { x + $0 }
// -- func expression
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @owned { var Int }) -> Int
// CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]]
// CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [[ANON]]([[XBOX_COPY]])
// -- return
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[ANON_CLOSURE_APP]]
}
// CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int, @owned { var Int }) -> Int
// CHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : ${ var Int }):
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[PLUS:%[0-9]+]] = function_ref @_TFsoi1pFTSiSi_Si{{.*}}
// CHECK: [[LHS:%[0-9]+]] = load [trivial] [[XADDR]]
// CHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]])
// CHECK: destroy_value [[XBOX]]
// CHECK: return [[RET]]
// CHECK-LABEL: sil hidden @_TF8closures24small_closure_no_capture
func small_closure_no_capture() -> (_ y: Int) -> Int {
// CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures24small_closure_no_captureFT_FSiSiU_FSiSi]] : $@convention(thin) (Int) -> Int
// CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_owned (Int) -> Int
// CHECK: return [[ANON_THICK]]
return { $0 }
}
// CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int
// CHECK: bb0([[YARG:%[0-9]+]] : $Int):
// CHECK-LABEL: sil hidden @_TF8closures17uncaptured_locals{{.*}} :
func uncaptured_locals(_ x: Int) -> (Int, Int) {
var x = x
// -- locals without captures are stack-allocated
// CHECK: bb0([[XARG:%[0-9]+]] : $Int):
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[XADDR]]
// CHECK: store [[XARG]] to [trivial] [[PB]]
var y = zero
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
return (x, y)
}
class SomeClass {
var x : Int = zero
init() {
x = { self.x }() // Closing over self.
}
}
// Closures within destructors <rdar://problem/15883734>
class SomeGenericClass<T> {
deinit {
var i: Int = zero
// CHECK: [[C1REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout_aliasable Int) -> Int
// CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]) : $@convention(thin) (@inout_aliasable Int) -> Int
var x = { i + zero } ()
// CHECK: [[C2REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int
// CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int
var y = { zero } ()
// CHECK: [[C3REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <τ_0_0> () -> ()
// CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> ()
var z = { _ = T.self } ()
}
// CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout_aliasable Int) -> Int
// CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int
// CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <T> () -> ()
}
// This is basically testing that the constraint system ranking
// function conversions as worse than others, and therefore performs
// the conversion within closures when possible.
class SomeSpecificClass : SomeClass {}
func takesSomeClassGenerator(_ fn : () -> SomeClass) {}
func generateWithConstant(_ x : SomeSpecificClass) {
takesSomeClassGenerator({ x })
}
// CHECK-LABEL: sil shared @_TFF8closures20generateWithConstantFCS_17SomeSpecificClassT_U_FT_CS_9SomeClass : $@convention(thin) (@owned SomeSpecificClass) -> @owned SomeClass {
// CHECK: bb0([[T0:%.*]] : $SomeSpecificClass):
// CHECK: debug_value [[T0]] : $SomeSpecificClass, let, name "x", argno 1
// CHECK: [[T0_COPY:%.*]] = copy_value [[T0]]
// CHECK: [[T0_COPY_CASTED:%.*]] = upcast [[T0_COPY]] : $SomeSpecificClass to $SomeClass
// CHECK: destroy_value [[T0]]
// CHECK: return [[T0_COPY_CASTED]]
// CHECK: } // end sil function '_TFF8closures20generateWithConstantFCS_17SomeSpecificClassT_U_FT_CS_9SomeClass'
// Check the annoying case of capturing 'self' in a derived class 'init'
// method. We allocate a mutable box to deal with 'self' potentially being
// rebound by super.init, but 'self' is formally immutable and so is captured
// by value. <rdar://problem/15599464>
class Base {}
class SelfCapturedInInit : Base {
var foo : () -> SelfCapturedInInit
// CHECK-LABEL: sil hidden @_TFC8closures18SelfCapturedInInitc{{.*}} : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit {
// CHECK: [[VAL:%.*]] = load_borrow {{%.*}} : $*SelfCapturedInInit
// CHECK: [[VAL:%.*]] = load_borrow {{%.*}} : $*SelfCapturedInInit
// CHECK: [[VAL:%.*]] = load [copy] {{%.*}} : $*SelfCapturedInInit
// CHECK: partial_apply {{%.*}}([[VAL]]) : $@convention(thin) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit
override init() {
super.init()
foo = { self }
}
}
func takeClosure(_ fn: () -> Int) -> Int { return fn() }
class TestCaptureList {
var x = zero
func testUnowned() {
let aLet = self
takeClosure { aLet.x }
takeClosure { [unowned aLet] in aLet.x }
takeClosure { [weak aLet] in aLet!.x }
var aVar = self
takeClosure { aVar.x }
takeClosure { [unowned aVar] in aVar.x }
takeClosure { [weak aVar] in aVar!.x }
takeClosure { self.x }
takeClosure { [unowned self] in self.x }
takeClosure { [weak self] in self!.x }
takeClosure { [unowned newVal = TestCaptureList()] in newVal.x }
takeClosure { [weak newVal = TestCaptureList()] in newVal!.x }
}
}
class ClassWithIntProperty { final var x = 42 }
func closeOverLetLValue() {
let a : ClassWithIntProperty
a = ClassWithIntProperty()
takeClosure { a.x }
}
// The let property needs to be captured into a temporary stack slot so that it
// is loadable even though we capture the value.
// CHECK-LABEL: sil shared @_TFF8closures18closeOverLetLValueFT_T_U_FT_Si : $@convention(thin) (@owned ClassWithIntProperty) -> Int {
// CHECK: bb0([[ARG:%.*]] : $ClassWithIntProperty):
// CHECK: [[TMP_CLASS_ADDR:%.*]] = alloc_stack $ClassWithIntProperty, let, name "a", argno 1
// CHECK: store [[ARG]] to [init] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: [[BORROWED_LOADED_CLASS:%.*]] = begin_borrow [[LOADED_CLASS]]
// CHECK: [[INT_IN_CLASS_ADDR:%.*]] = ref_element_addr [[BORROWED_LOADED_CLASS]] : $ClassWithIntProperty, #ClassWithIntProperty.x
// CHECK: [[INT_IN_CLASS:%.*]] = load [trivial] [[INT_IN_CLASS_ADDR]] : $*Int
// CHECK: end_borrow [[BORROWED_LOADED_CLASS]] from [[LOADED_CLASS]]
// CHECK: destroy_value [[LOADED_CLASS]]
// CHECK: destroy_addr [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty
// CHECK: dealloc_stack %1 : $*ClassWithIntProperty
// CHECK: return [[INT_IN_CLASS]]
// CHECK: } // end sil function '_TFF8closures18closeOverLetLValueFT_T_U_FT_Si'
// Use an external function so inout deshadowing cannot see its body.
@_silgen_name("takesNoEscapeClosure")
func takesNoEscapeClosure(fn : () -> Int)
struct StructWithMutatingMethod {
var x = 42
mutating func mutatingMethod() {
// This should not capture the refcount of the self shadow.
takesNoEscapeClosure { x = 42; return x }
}
}
// Check that the address of self is passed in, but not the refcount pointer.
// CHECK-LABEL: sil hidden @_TFV8closures24StructWithMutatingMethod14mutatingMethod
// CHECK: bb0(%0 : $*StructWithMutatingMethod):
// CHECK: [[CLOSURE:%[0-9]+]] = function_ref @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int
// CHECK: partial_apply [[CLOSURE]](%0) : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int
// Check that the closure body only takes the pointer.
// CHECK-LABEL: sil shared @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int {
// CHECK: bb0(%0 : $*StructWithMutatingMethod):
class SuperBase {
func boom() {}
}
class SuperSub : SuperBase {
override func boom() {}
// CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1afT_T_ : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : $SuperSub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1a.*]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: apply [[INNER]]([[SELF_COPY]])
// CHECK: } // end sil function '_TFC8closures8SuperSub1afT_T_'
func a() {
// CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]])
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func a1() {
self.boom()
super.boom()
}
a1()
}
// CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1bfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : $SuperSub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1b.*]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: = apply [[INNER]]([[SELF_COPY]])
// CHECK: } // end sil function '_TFC8closures8SuperSub1bfT_T_'
func b() {
// CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1b.*]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: = apply [[INNER]]([[ARG_COPY]])
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func b1() {
// CHECK: sil shared @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> ()
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase)
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
func b2() {
self.boom()
super.boom()
}
b2()
}
b1()
}
// CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1cfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1c.*]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]])
// CHECK: [[PA_COPY:%.*]] = copy_value [[PA]]
// CHECK: apply [[PA_COPY]]()
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '_TFC8closures8SuperSub1cfT_T_'
func c() {
// CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[CLASS_METHOD:%.*]] = class_method [[ARG]] : $SuperSub, #SuperSub.boom!1
// CHECK: = apply [[CLASS_METHOD]]([[ARG]]) : $@convention(method) (@guaranteed SuperSub) -> ()
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let c1 = { () -> Void in
self.boom()
super.boom()
}
c1()
}
// CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1dfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1d.*]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]])
// CHECK: [[PA_COPY:%.*]] = copy_value [[PA]]
// CHECK: apply [[PA_COPY]]()
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '_TFC8closures8SuperSub1dfT_T_'
func d() {
// CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1d.*]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: = apply [[INNER]]([[ARG_COPY]])
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let d1 = { () -> Void in
// CHECK: sil shared @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
func d2() {
super.boom()
}
d2()
}
d1()
}
// CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1efT_T_ : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : $SuperSub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME1:_TFFC8closures8SuperSub1e.*]] : $@convention(thin)
// CHECK: = apply [[INNER]]([[SELF_COPY]])
// CHECK: } // end sil function '_TFC8closures8SuperSub1efT_T_'
func e() {
// CHECK: sil shared @[[INNER_FUNC_NAME1]] : $@convention(thin)
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME2:_TFFFC8closures8SuperSub1e.*]] : $@convention(thin)
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]])
// CHECK: [[PA_COPY:%.*]] = copy_value [[PA]]
// CHECK: apply [[PA_COPY]]() : $@callee_owned () -> ()
// CHECK: destroy_value [[PA]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_NAME1]]'
func e1() {
// CHECK: sil shared @[[INNER_FUNC_NAME2]] : $@convention(thin)
// ChECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPERCAST:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPERCAST]])
// CHECK: destroy_value [[ARG_COPY_SUPERCAST]]
// CHECK: destroy_value [[ARG]]
// CHECK: return
// CHECK: } // end sil function '[[INNER_FUNC_NAME2]]'
let e2 = {
super.boom()
}
e2()
}
e1()
}
// CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1ffT_T_ : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : $SuperSub):
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1fFT_T_U_FT_T_]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]])
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '_TFC8closures8SuperSub1ffT_T_'
func f() {
// CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () {
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @_TFsoi2qqurFzTGSqx_KzT_x_x : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1fFT_T_U_FT_T_u_KzT_T_]] : $@convention(thin) (@owned SuperSub) -> @error Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]])
// CHECK: [[REABSTRACT_PA:%.*]] = partial_apply {{.*}}([[PA]])
// CHECK: try_apply [[TRY_APPLY_AUTOCLOSURE]]<()>({{.*}}, {{.*}}, [[REABSTRACT_PA]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
// CHECK: [[NORMAL_BB]]{{.*}}
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
let f1 = {
// CHECK: sil shared [transparent] @[[INNER_FUNC_2]]
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
nil ?? super.boom()
}
}
// CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1gfT_T_ : $@convention(method) (@guaranteed SuperSub) -> () {
// CHECK: bb0([[SELF:%.*]] : $SuperSub):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_TFFC8closures8SuperSub1g.*]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: = apply [[INNER]]([[SELF_COPY]])
// CHECK: } // end sil function '_TFC8closures8SuperSub1gfT_T_'
func g() {
// CHECK: sil shared @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> ()
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[TRY_APPLY_FUNC:%.*]] = function_ref @_TFsoi2qqurFzTGSqx_KzT_x_x : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error)
// CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_TFFFC8closures8SuperSub1g.*]] : $@convention(thin) (@owned SuperSub) -> @error Error
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]])
// CHECK: [[REABSTRACT_PA:%.*]] = partial_apply {{%.*}}([[PA]]) : $@convention(thin) (@owned @callee_owned () -> @error Error) -> (@out (), @error Error)
// CHECK: try_apply [[TRY_APPLY_FUNC]]<()>({{.*}}, {{.*}}, [[REABSTRACT_PA]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]]
// CHECK: [[NORMAL_BB]]{{.*}}
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_1]]'
func g1() {
// CHECK: sil shared [transparent] @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> @error Error {
// CHECK: bb0([[ARG:%.*]] : $SuperSub):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase
// CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> ()
// CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]])
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '[[INNER_FUNC_2]]'
nil ?? super.boom()
}
g1()
}
}
// CHECK-LABEL: sil hidden @_TFC8closures24UnownedSelfNestedCapture13nestedCapture{{.*}} : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> ()
// -- We enter with an assumed strong +1.
// CHECK: bb0([[SELF:%.*]] : $UnownedSelfNestedCapture):
// CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box ${ var @sil_unowned UnownedSelfNestedCapture }
// CHECK: [[PB:%.*]] = project_box [[OUTER_SELF_CAPTURE]]
// -- strong +2
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_COPY]] :
// -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here.
// -- strong +2, unowned +1
// CHECK: unowned_retain [[UNOWNED_SELF]]
// CHECK: store [[UNOWNED_SELF]] to [init] [[PB]]
// SEMANTIC ARC TODO: This destroy_value should probably be /after/ the load from PB on the next line.
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[UNOWNED_SELF:%.*]] = load [take] [[PB]]
// -- strong +2, unowned +1
// CHECK: strong_retain_unowned [[UNOWNED_SELF]]
// CHECK: [[SELF:%.*]] = unowned_to_ref [[UNOWNED_SELF]]
// CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]]
// -- strong +2, unowned +2
// CHECK: unowned_retain [[UNOWNED_SELF2]]
// -- strong +1, unowned +2
// CHECK: destroy_value [[SELF]]
// -- closure takes unowned ownership
// CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply {{%.*}}([[UNOWNED_SELF2]])
// -- call consumes closure
// -- strong +1, unowned +1
// CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CLOSURE]]
// CHECK: [[CONSUMED_RESULT:%.*]] = apply [[INNER_CLOSURE]]()
// CHECK: destroy_value [[CONSUMED_RESULT]]
// -- destroy_values unowned self in box
// -- strong +1, unowned +0
// CHECK: destroy_value [[OUTER_SELF_CAPTURE]]
// -- strong +0, unowned +0
// CHECK: } // end sil function '_TFC8closures24UnownedSelfNestedCapture13nestedCapture{{.*}}'
// -- outer closure
// -- strong +0, unowned +1
// CHECK: sil shared @[[OUTER_CLOSURE_FUN:_TFFC8closures24UnownedSelfNestedCapture13nestedCaptureFT_T_U_FT_FT_S0_]] : $@convention(thin) (@owned @sil_unowned UnownedSelfNestedCapture) -> @owned @callee_owned () -> @owned UnownedSelfNestedCapture {
// CHECK: bb0([[CAPTURED_SELF:%.*]] : $@sil_unowned UnownedSelfNestedCapture):
// -- strong +0, unowned +2
// CHECK: [[CAPTURED_SELF_COPY:%.*]] = copy_value [[CAPTURED_SELF]] :
// -- closure takes ownership of unowned ref
// CHECK: [[INNER_CLOSURE:%.*]] = partial_apply {{%.*}}([[CAPTURED_SELF_COPY]])
// -- strong +0, unowned +1 (claimed by closure)
// CHECK: destroy_value [[CAPTURED_SELF]]
// CHECK: return [[INNER_CLOSURE]]
// CHECK: } // end sil function '[[OUTER_CLOSURE_FUN]]'
// -- inner closure
// -- strong +0, unowned +1
// CHECK: sil shared @[[INNER_CLOSURE_FUN:_TFFFC8closures24UnownedSelfNestedCapture13nestedCapture.*]] : $@convention(thin) (@owned @sil_unowned UnownedSelfNestedCapture) -> @owned UnownedSelfNestedCapture {
// CHECK: bb0([[CAPTURED_SELF:%.*]] : $@sil_unowned UnownedSelfNestedCapture):
// -- strong +1, unowned +1
// CHECK: strong_retain_unowned [[CAPTURED_SELF:%.*]] :
// CHECK: [[SELF:%.*]] = unowned_to_ref [[CAPTURED_SELF]]
// -- strong +1, unowned +0 (claimed by return)
// CHECK: destroy_value [[CAPTURED_SELF]]
// CHECK: return [[SELF]]
// CHECK: } // end sil function '[[INNER_CLOSURE_FUN]]'
class UnownedSelfNestedCapture {
func nestedCapture() {
{[unowned self] in { self } }()()
}
}
// Check that capturing 'self' via a 'super' call also captures the generic
// signature if the base class is concrete and the derived class is generic
class ConcreteBase {
func swim() {}
}
// CHECK-LABEL: sil shared @_TFFC8closures14GenericDerived4swimFT_T_U_FT_T_ : $@convention(thin) <Ocean> (@owned GenericDerived<Ocean>) -> ()
// CHECK: bb0([[ARG:%.*]] : $GenericDerived<Ocean>):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $GenericDerived<Ocean> to $ConcreteBase
// CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures12ConcreteBase4swimfT_T_
// CHECK: apply [[METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed ConcreteBase) -> ()
// CHECK: destroy_value [[ARG_COPY_SUPER]]
// CHECK: destroy_value [[ARG]]
// CHECK: } // end sil function '_TFFC8closures14GenericDerived4swimFT_T_U_FT_T_'
class GenericDerived<Ocean> : ConcreteBase {
override func swim() {
withFlotationAid {
super.swim()
}
}
func withFlotationAid(_ fn: () -> ()) {}
}
// Don't crash on this
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258() {
r25993258_helper { _ in () }
}
// rdar://29810997
//
// Using a let from a closure in an init was causing the type-checker
// to produce invalid AST: 'self.fn' was an l-value, but 'self' was already
// loaded to make an r-value. This was ultimately because CSApply was
// building the member reference correctly in the context of the closure,
// where 'fn' is not settable, but CSGen / CSSimplify was processing it
// in the general DC of the constraint system, i.e. the init, where
// 'fn' *is* settable.
func r29810997_helper(_ fn: (Int) -> Int) -> Int { return fn(0) }
struct r29810997 {
private let fn: (Int) -> Int
private var x: Int
init(function: @escaping (Int) -> Int) {
fn = function
x = r29810997_helper { fn($0) }
}
}
// DI will turn this into a direct capture of the specific stored property.
// CHECK-LABEL: sil hidden @_TF8closures16r29810997_helperFFSiSiSi : $@convention(thin) (@owned @callee_owned (Int) -> Int) -> Int
| 47.852744 | 276 | 0.617384 |
0afff7b4b541d41a13a67db9277861936b1be3a4 | 756 | //
// OfferProgressStack.swift
// EvidationCommonUI
//
// Created by Helena McGahagan on 1/29/21.
//
import Foundation
public struct OfferProgressStack: Codable, Equatable {
public var pages: [SectionPage] = []
public init() {}
}
public struct SectionPage: Codable, Equatable {
public let sectionIdentifier: String
/// Index of the section within the offer
public let sectionIndex: Int
/// E.g., store the slide index for a slideshow section
public let subSectionIndex: Int
public init(sectionIdentifier: String, sectionIndex: Int, subSectionIndex: Int = 0) {
self.sectionIdentifier = sectionIdentifier
self.sectionIndex = sectionIndex
self.subSectionIndex = subSectionIndex
}
}
| 25.2 | 89 | 0.698413 |
b9e2f59008fe253b04373d70ace015ec2d741661 | 1,557 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import libc
/// Extensions to the libc `stat` structure to interpret the contents in more readable ways.
extension libc.stat {
/// File system entity kind.
public enum Kind {
case file, directory, symlink, fifo, blockdev, chardev, socket, unknown
fileprivate init(mode: mode_t) {
switch mode {
case S_IFREG: self = .file
case S_IFDIR: self = .directory
case S_IFLNK: self = .symlink
case S_IFBLK: self = .blockdev
case S_IFCHR: self = .chardev
case S_IFSOCK: self = .socket
default:
self = .unknown
}
}
}
/// Kind of file system entity.
public var kind: Kind {
return Kind(mode: st_mode & S_IFMT)
}
}
public func stat(_ path: String) throws -> libc.stat {
var sbuf = libc.stat()
let rv = stat(path, &sbuf)
guard rv == 0 else { throw SystemError.stat(errno, path) }
return sbuf
}
public func lstat(_ path: String) throws -> libc.stat {
var sbuf = libc.stat()
let rv = lstat(path, &sbuf)
guard rv == 0 else { throw SystemError.stat(errno, path) }
return sbuf
}
| 29.377358 | 92 | 0.604367 |
de8d115d77e0e24343b794e24d1c119f1a1e492b | 296 | import Foundation
private let oneMicroSecond: NSTimeInterval = 0.000_001
extension NSRunLoop {
static func advance(by timeInterval: NSTimeInterval = oneMicroSecond) {
let stopDate = NSDate().dateByAddingTimeInterval(timeInterval)
mainRunLoop().runUntilDate(stopDate)
}
} | 29.6 | 75 | 0.753378 |
e6528dbb15489d0c5473cf2a30ccfb71d4efc94d | 23,839 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY1 | %FileCheck %s -check-prefix=AVAILABILITY1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY2 | %FileCheck %s -check-prefix=AVAILABILITY2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD2 | %FileCheck %s -check-prefix=KEYWORD2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3 | %FileCheck %s -check-prefix=KEYWORD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3_2 | %FileCheck %s -check-prefix=KEYWORD3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD4 | %FileCheck %s -check-prefix=KEYWORD4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD5 | %FileCheck %s -check-prefix=KEYWORD5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_GLOBALVAR | %FileCheck %s -check-prefix=ON_GLOBALVAR
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_INIT | %FileCheck %s -check-prefix=ON_INIT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PROPERTY | %FileCheck %s -check-prefix=ON_PROPERTY
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_METHOD | %FileCheck %s -check-prefix=ON_METHOD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PARAM_1 | %FileCheck %s -check-prefix=ON_PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_PARAM_2 | %FileCheck %s -check-prefix=ON_PARAM
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_INDEPENDENT_1 | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_INDEPENDENT_2 | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ON_MEMBER_LAST | %FileCheck %s -check-prefix=ON_MEMBER_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_INDEPENDENT_1 | %FileCheck %s -check-prefix=KEYWORD_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_INDEPENDENT_2 | %FileCheck %s -check-prefix=KEYWORD_LAST
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_LAST | %FileCheck %s -check-prefix=KEYWORD_LAST
struct MyStruct {}
@available(#^AVAILABILITY1^#)
// NOTE: Please do not include the ", N items" after "Begin completions". The
// item count creates needless merge conflicts given that we use the "-NEXT"
// feature of FileCheck and because an "End completions" line exists for each
// test.
// AVAILABILITY1: Begin completions
// AVAILABILITY1-NEXT: Keyword/None: *[#Platform#]; name=*{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOS[#Platform#]; name=iOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOS[#Platform#]; name=tvOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOS[#Platform#]; name=watchOS{{$}}
// AVAILABILITY1-NEXT: Keyword/None: OSX[#Platform#]; name=OSX{{$}}
// AVAILABILITY1-NEXT: Keyword/None: iOSApplicationExtension[#Platform#]; name=iOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: tvOSApplicationExtension[#Platform#]; name=tvOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: watchOSApplicationExtension[#Platform#]; name=watchOSApplicationExtension{{$}}
// AVAILABILITY1-NEXT: Keyword/None: OSXApplicationExtension[#Platform#]; name=OSXApplicationExtension{{$}}
// AVAILABILITY1-NEXT: End completions
@available(*, #^AVAILABILITY2^#)
// AVAILABILITY2: Begin completions
// AVAILABILITY2-NEXT: Keyword/None: unavailable; name=unavailable{{$}}
// AVAILABILITY2-NEXT: Keyword/None: message: [#Specify message#]; name=message{{$}}
// AVAILABILITY2-NEXT: Keyword/None: renamed: [#Specify replacing name#]; name=renamed{{$}}
// AVAILABILITY2-NEXT: Keyword/None: introduced: [#Specify version number#]; name=introduced{{$}}
// AVAILABILITY2-NEXT: Keyword/None: deprecated: [#Specify version number#]; name=deprecated{{$}}
// AVAILABILITY2-NEXT: End completions
@#^KEYWORD2^# func method(){}
// KEYWORD2: Begin completions
// KEYWORD2-NEXT: Keyword/None: available[#Func Attribute#]; name=available{{$}}
// KEYWORD2-NEXT: Keyword/None: objc[#Func Attribute#]; name=objc{{$}}
// KEYWORD2-NEXT: Keyword/None: IBAction[#Func Attribute#]; name=IBAction{{$}}
// KEYWORD2-NEXT: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged{{$}}
// KEYWORD2-NEXT: Keyword/None: inline[#Func Attribute#]; name=inline{{$}}
// KEYWORD2-NEXT: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc{{$}}
// KEYWORD2-NEXT: Keyword/None: inlinable[#Func Attribute#]; name=inlinable{{$}}
// KEYWORD2-NEXT: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access{{$}}
// KEYWORD2-NEXT: Keyword/None: usableFromInline[#Func Attribute#]; name=usableFromInline
// KEYWORD2-NEXT: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult
// KEYWORD2-NEXT: Keyword/None: differentiable[#Func Attribute#]; name=differentiable
// KEYWORD2-NEXT: Keyword/None: IBSegueAction[#Func Attribute#]; name=IBSegueAction{{$}}
// KEYWORD2-NEXT: Keyword/None: derivative[#Func Attribute#]; name=derivative
// KEYWORD2-NEXT: Keyword/None: transpose[#Func Attribute#]; name=transpose
// KEYWORD2-NOT: Keyword
// KEYWORD2: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD2: End completions
@#^KEYWORD3^# class C {}
// KEYWORD3: Begin completions
// KEYWORD3-NEXT: Keyword/None: available[#Class Attribute#]; name=available{{$}}
// KEYWORD3-NEXT: Keyword/None: objc[#Class Attribute#]; name=objc{{$}}
// KEYWORD3-NEXT: Keyword/None: dynamicCallable[#Class Attribute#]; name=dynamicCallable{{$}}
// KEYWORD3-NEXT: Keyword/None: dynamicMemberLookup[#Class Attribute#]; name=dynamicMemberLookup{{$}}
// KEYWORD3-NEXT: Keyword/None: IBDesignable[#Class Attribute#]; name=IBDesignable{{$}}
// KEYWORD3-NEXT: Keyword/None: UIApplicationMain[#Class Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: requires_stored_property_inits[#Class Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD3-NEXT: Keyword/None: objcMembers[#Class Attribute#]; name=objcMembers{{$}}
// KEYWORD3-NEXT: Keyword/None: NSApplicationMain[#Class Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD3-NEXT: Keyword/None: usableFromInline[#Class Attribute#]; name=usableFromInline
// KEYWORD3-NEXT: Keyword/None: propertyWrapper[#Class Attribute#]; name=propertyWrapper
// KEYWORD3-NEXT: Keyword/None: _functionBuilder[#Class Attribute#]; name=_functionBuilder
// KEYWORD3-NEXT: End completions
@#^KEYWORD3_2^#IB class C2 {}
// Same as KEYWORD3.
@#^KEYWORD4^# enum E {}
// KEYWORD4: Begin completions
// KEYWORD4-NEXT: Keyword/None: available[#Enum Attribute#]; name=available{{$}}
// KEYWORD4-NEXT: Keyword/None: objc[#Enum Attribute#]; name=objc{{$}}
// KEYWORD4-NEXT: Keyword/None: dynamicCallable[#Enum Attribute#]; name=dynamicCallable
// KEYWORD4-NEXT: Keyword/None: dynamicMemberLookup[#Enum Attribute#]; name=dynamicMemberLookup
// KEYWORD4-NEXT: Keyword/None: usableFromInline[#Enum Attribute#]; name=usableFromInline
// KEYWORD4-NEXT: Keyword/None: frozen[#Enum Attribute#]; name=frozen
// KEYWORD4-NEXT: Keyword/None: propertyWrapper[#Enum Attribute#]; name=propertyWrapper
// KEYWORD4-NEXT: Keyword/None: _functionBuilder[#Enum Attribute#]; name=_functionBuilder
// KEYWORD4-NEXT: End completions
@#^KEYWORD5^# struct S{}
// KEYWORD5: Begin completions
// KEYWORD5-NEXT: Keyword/None: available[#Struct Attribute#]; name=available{{$}}
// KEYWORD5-NEXT: Keyword/None: dynamicCallable[#Struct Attribute#]; name=dynamicCallable
// KEYWORD5-NEXT: Keyword/None: dynamicMemberLookup[#Struct Attribute#]; name=dynamicMemberLookup
// KEYWORD5-NEXT: Keyword/None: usableFromInline[#Struct Attribute#]; name=usableFromInline
// KEYWORD5-NEXT: Keyword/None: frozen[#Struct Attribute#]; name=frozen
// KEYWORD5-NEXT: Keyword/None: propertyWrapper[#Struct Attribute#]; name=propertyWrapper
// KEYWORD5-NEXT: Keyword/None: _functionBuilder[#Struct Attribute#]; name=_functionBuilder
// KEYWORD5-NEXT: End completions
@#^ON_GLOBALVAR^# var globalVar
// ON_GLOBALVAR: Begin completions
// ON_GLOBALVAR-DAG: Keyword/None: available[#Var Attribute#]; name=available
// ON_GLOBALVAR-DAG: Keyword/None: objc[#Var Attribute#]; name=objc
// ON_GLOBALVAR-DAG: Keyword/None: NSCopying[#Var Attribute#]; name=NSCopying
// ON_GLOBALVAR-DAG: Keyword/None: IBInspectable[#Var Attribute#]; name=IBInspectable
// ON_GLOBALVAR-DAG: Keyword/None: IBOutlet[#Var Attribute#]; name=IBOutlet
// ON_GLOBALVAR-DAG: Keyword/None: NSManaged[#Var Attribute#]; name=NSManaged
// ON_GLOBALVAR-DAG: Keyword/None: inline[#Var Attribute#]; name=inline
// ON_GLOBALVAR-DAG: Keyword/None: nonobjc[#Var Attribute#]; name=nonobjc
// ON_GLOBALVAR-DAG: Keyword/None: inlinable[#Var Attribute#]; name=inlinable
// ON_GLOBALVAR-DAG: Keyword/None: usableFromInline[#Var Attribute#]; name=usableFromInline
// ON_GLOBALVAR-DAG: Keyword/None: GKInspectable[#Var Attribute#]; name=GKInspectable
// ON_GLOBALVAR-DAG: Keyword/None: differentiable[#Var Attribute#]; name=differentiable
// ON_GLOBALVAR-NOT: Keyword
// ON_GLOBALVAR: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_GLOBALVAR: End completions
struct _S {
@#^ON_INIT^# init()
// ON_INIT: Begin completions
// ON_INIT-DAG: Keyword/None: available[#Constructor Attribute#]; name=available
// ON_INIT-DAG: Keyword/None: objc[#Constructor Attribute#]; name=objc
// ON_INIT-DAG: Keyword/None: inline[#Constructor Attribute#]; name=inline
// ON_INIT-DAG: Keyword/None: nonobjc[#Constructor Attribute#]; name=nonobjc
// ON_INIT-DAG: Keyword/None: inlinable[#Constructor Attribute#]; name=inlinable
// ON_INIT-DAG: Keyword/None: usableFromInline[#Constructor Attribute#]; name=usableFromInline
// ON_INIT-DAG: Keyword/None: discardableResult[#Constructor Attribute#]; name=discardableResult
// ON_INIT: End completions
@#^ON_PROPERTY^# var foo
// ON_PROPERTY: Begin completions
// ON_PROPERTY-DAG: Keyword/None: available[#Var Attribute#]; name=available
// ON_PROPERTY-DAG: Keyword/None: objc[#Var Attribute#]; name=objc
// ON_PROPERTY-DAG: Keyword/None: NSCopying[#Var Attribute#]; name=NSCopying
// ON_PROPERTY-DAG: Keyword/None: IBInspectable[#Var Attribute#]; name=IBInspectable
// ON_PROPERTY-DAG: Keyword/None: IBOutlet[#Var Attribute#]; name=IBOutlet
// ON_PROPERTY-DAG: Keyword/None: NSManaged[#Var Attribute#]; name=NSManaged
// ON_PROPERTY-DAG: Keyword/None: inline[#Var Attribute#]; name=inline
// ON_PROPERTY-DAG: Keyword/None: nonobjc[#Var Attribute#]; name=nonobjc
// ON_PROPERTY-DAG: Keyword/None: inlinable[#Var Attribute#]; name=inlinable
// ON_PROPERTY-DAG: Keyword/None: usableFromInline[#Var Attribute#]; name=usableFromInline
// ON_PROPERTY-DAG: Keyword/None: GKInspectable[#Var Attribute#]; name=GKInspectable
// ON_PROPERTY-DAG: Keyword/None: differentiable[#Var Attribute#]; name=differentiable
// ON_PROPERTY-NOT: Keyword
// ON_PROPERTY: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_PROPERTY-NOT: Decl[PrecedenceGroup]
// ON_PROPERTY: End completions
@#^ON_METHOD^# private
func foo()
// ON_METHOD: Begin completions
// ON_METHOD-DAG: Keyword/None: available[#Func Attribute#]; name=available
// ON_METHOD-DAG: Keyword/None: objc[#Func Attribute#]; name=objc
// ON_METHOD-DAG: Keyword/None: IBAction[#Func Attribute#]; name=IBAction
// ON_METHOD-DAG: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged
// ON_METHOD-DAG: Keyword/None: inline[#Func Attribute#]; name=inline
// ON_METHOD-DAG: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc
// ON_METHOD-DAG: Keyword/None: inlinable[#Func Attribute#]; name=inlinable
// ON_METHOD-DAG: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access
// ON_METHOD-DAG: Keyword/None: usableFromInline[#Func Attribute#]; name=usableFromInline
// ON_METHOD-DAG: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult
// ON_METHOD-DAG: Keyword/None: IBSegueAction[#Func Attribute#]; name=IBSegueAction
// ON_METHOD-DAG: Keyword/None: differentiable[#Func Attribute#]; name=differentiable
// ON_METHOD-DAG: Keyword/None: derivative[#Func Attribute#]; name=derivative
// ON_METHOD-DAG: Keyword/None: transpose[#Func Attribute#]; name=transpose
// ON_METHOD-NOT: Keyword
// ON_METHOD: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_METHOD: End completions
func bar(@#^ON_PARAM_1^#)
// ON_PARAM: Begin completions
// ON_PARAM-NOT: Keyword
// ON_PARAM: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_PARAM-NOT: Keyword
// ON_PARAM: End completions
func bar(
@#^ON_PARAM_2^#
arg: Int
)
// Same as ON_PARAM.
@#^ON_MEMBER_INDEPENDENT_1^#
func dummy1() {}
// Same as ON_MEMBER_LAST.
@#^ON_MEMBER_INDEPENDENT_2^#
func dummy2() {}
// Same as ON_MEMBER_LAST.
@#^ON_MEMBER_LAST^#
// ON_MEMBER_LAST: Begin completions
// ON_MEMBER_LAST-DAG: Keyword/None: available[#Declaration Attribute#]; name=available
// ON_MEMBER_LAST-DAG: Keyword/None: objc[#Declaration Attribute#]; name=objc
// ON_MEMBER_LAST-DAG: Keyword/None: dynamicCallable[#Declaration Attribute#]; name=dynamicCallable
// ON_MEMBER_LAST-DAG: Keyword/None: dynamicMemberLookup[#Declaration Attribute#]; name=dynamicMemberLookup
// ON_MEMBER_LAST-DAG: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying
// ON_MEMBER_LAST-DAG: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction
// ON_MEMBER_LAST-DAG: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable
// ON_MEMBER_LAST-DAG: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable
// ON_MEMBER_LAST-DAG: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet
// ON_MEMBER_LAST-DAG: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged
// ON_MEMBER_LAST-DAG: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain
// ON_MEMBER_LAST-DAG: Keyword/None: inline[#Declaration Attribute#]; name=inline
// ON_MEMBER_LAST-DAG: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits
// ON_MEMBER_LAST-DAG: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc
// ON_MEMBER_LAST-DAG: Keyword/None: inlinable[#Declaration Attribute#]; name=inlinable
// ON_MEMBER_LAST-DAG: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers
// ON_MEMBER_LAST-DAG: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain
// ON_MEMBER_LAST-DAG: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access
// ON_MEMBER_LAST-DAG: Keyword/None: usableFromInline[#Declaration Attribute#]; name=usableFromInline
// ON_MEMBER_LAST-DAG: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult
// ON_MEMBER_LAST-DAG: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable
// ON_MEMBER_LAST-DAG: Keyword/None: IBSegueAction[#Declaration Attribute#]; name=IBSegueAction
// ON_MEMBER_LAST-DAG: Keyword/None: propertyWrapper[#Declaration Attribute#]; name=propertyWrapper
// ON_MEMBER_LAST-DAG: Keyword/None: _functionBuilder[#Declaration Attribute#]; name=_functionBuilder
// ON_MEMBER_LAST-DAG: Keyword/None: differentiable[#Declaration Attribute#]; name=differentiable
// ON_MEMBER_LAST-DAG: Keyword/None: derivative[#Declaration Attribute#]; name=derivative
// ON_MEMBER_LAST-DAG: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// ON_MEMBER_LAST-NOT: Keyword
// ON_MEMBER_LAST: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_MEMBER_LAST-NOT: Decl[PrecedenceGroup]
// ON_MEMBER_LAST: End completions
}
@#^KEYWORD_INDEPENDENT_1^#
func dummy1() {}
// Same as KEYWORD_LAST.
@#^KEYWORD_INDEPENDENT_2^#
func dummy2() {}
// Same as KEYWORD_LAST.
@#^KEYWORD_LAST^#
// KEYWORD_LAST: Begin completions
// KEYWORD_LAST-NEXT: Keyword/None: available[#Declaration Attribute#]; name=available{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: objc[#Declaration Attribute#]; name=objc{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: dynamicCallable[#Declaration Attribute#]; name=dynamicCallable
// KEYWORD_LAST-NEXT: Keyword/None: dynamicMemberLookup[#Declaration Attribute#]; name=dynamicMemberLookup
// KEYWORD_LAST-NEXT: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: inline[#Declaration Attribute#]; name=inline{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: inlinable[#Declaration Attribute#]; name=inlinable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access
// KEYWORD_LAST-NEXT: Keyword/None: usableFromInline[#Declaration Attribute#]; name=usableFromInline{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult
// KEYWORD_LAST-NEXT: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: frozen[#Declaration Attribute#]; name=frozen
// KEYWORD_LAST-NEXT: Keyword/None: propertyWrapper[#Declaration Attribute#]; name=propertyWrapper
// KEYWORD_LAST-NEXT: Keyword/None: _functionBuilder[#Declaration Attribute#]; name=_functionBuilder{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: differentiable[#Declaration Attribute#]; name=differentiable
// KEYWORD_LAST-NEXT: Keyword/None: IBSegueAction[#Declaration Attribute#]; name=IBSegueAction{{$}}
// KEYWORD_LAST-NEXT: Keyword/None: derivative[#Declaration Attribute#]; name=derivative
// KEYWORD_LAST-NEXT: Keyword/None: transpose[#Declaration Attribute#]; name=transpose
// KEYWORD_LAST-NOT: Keyword
// KEYWORD_LAST: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD_LAST: End completions
| 82.487889 | 167 | 0.621796 |
c1418133cdfec8c57a2cd6e230a53691c07fa0c2 | 2,193 | //
// AppDelegate.swift
// HLMomentsModule
//
// Created by [email protected] on 07/10/2019.
// Copyright (c) 2019 [email protected]. 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:.
}
}
| 46.659574 | 285 | 0.75513 |
Subsets and Splits