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
|
---|---|---|---|---|---|
3ac17831b7a53eb902e6912f59b505516cd570df
| 163 |
public func zip<A, B>(_ a: A?, _ b: B?) -> (A, B)? {
guard let aData = a else { return nil }
guard let bData = b else { return nil }
return (aData, bData)
}
| 27.166667 | 52 | 0.570552 |
e859339e2801024e22bc679178e8d73fd1264ee0
| 548 |
//
// AppsGalleryMediumCollectionViewCell.swift
// AppStoreLayout
//
// Created by Juan Laube on 6/8/19.
// Copyright © 2019 Juan Laube. All rights reserved.
//
import UIKit
class AppsGalleryMediumCollectionViewCell: AppsCollectionViewCell {
static var nib = UINib(nibName: nibName, bundle: .main)
static var nibName = "AppsGalleryMediumCollectionViewCell"
static var reuseIdentifier = "AppsGalleryMediumCollectionViewCell"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 23.826087 | 70 | 0.729927 |
fc6d9349d9f03203761da22986fd0da7a56258c3
| 753 |
import XCTest
import IICModuleFactory
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.965517 | 111 | 0.60425 |
180ba7fa9bea2aca69b34a1c58df1a7b42191e9e
| 13,112 |
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
`SceneManager` is responsible for presenting scenes, requesting future scenes be downloaded, and loading assets in the background.
*/
import SpriteKit
protocol SceneManagerDelegate: class {
// Called whenever a scene manager has transitioned to a new scene.
func sceneManager(_ sceneManager: SceneManager, didTransitionTo scene: SKScene)
}
/**
A manager for presenting `BaseScene`s. This allows for the preloading of future
levels while the player is in game to minimize the time spent between levels.
*/
final class SceneManager {
// MARK: Types
enum SceneIdentifier {
case home, end
case currentLevel, nextLevel
case level(Int)
}
// MARK: Properties
/**
A mapping of `SceneMetadata` instances to the resource requests
responsible for accessing the necessary resources for those scenes.
*/
let sceneLoaderForMetadata: [SceneMetadata: SceneLoader]
/**
The games input via connected control input sources. Used to
provide control to scenes after presentation.
*/
let gameInput: GameInput
/// The view used to choreograph scene transitions.
let presentingView: SKView
/// The next scene, assuming linear level progression.
var nextSceneMetadata: SceneMetadata {
let homeScene = sceneConfigurationInfo.first!
// If there is no current scene, we can only transition back to the home scene.
guard let currentSceneMetadata = currentSceneMetadata else { return homeScene }
let index = sceneConfigurationInfo.firstIndex(of: currentSceneMetadata)!
if index + 1 < sceneConfigurationInfo.count {
// Return the metadata for the next scene in the array.
return sceneConfigurationInfo[index + 1]
}
// Otherwise, loop back to the home scene.
return homeScene
}
/// The `SceneManager`'s delegate.
weak var delegate: SceneManagerDelegate?
/// The scene that is currently being presented.
private (set) var currentSceneMetadata: SceneMetadata?
/// The scene used to indicate progress when additional content needs to be loaded.
private var progressScene: ProgressScene?
/// Cached array of scene structure loaded from "SceneConfiguration.plist".
private let sceneConfigurationInfo: [SceneMetadata]
/// An object to act as the observer for `SceneLoaderDidCompleteNotification`s.
private var loadingCompletedObserver: AnyObject?
// MARK: Initialization
init(presentingView: SKView, gameInput: GameInput) {
self.presentingView = presentingView
self.gameInput = gameInput
/*
Load the game's `SceneConfiguration` plist. This provides information
about every scene in the game, and the order in which they should be displayed.
*/
let url = Bundle.main.url(forResource: "SceneConfiguration", withExtension: "plist")!
let scenes = NSArray(contentsOf: url) as! [[String: AnyObject]]
/*
Extract the configuration info dictionary for each possible scene,
and create a `SceneMetadata` instance from the contents of that dictionary.
*/
sceneConfigurationInfo = scenes.map {
SceneMetadata(sceneConfiguration: $0)
}
// Map `SceneMetadata` to a `SceneLoader` for each possible scene.
var sceneLoaderForMetadata = [SceneMetadata: SceneLoader]()
for metadata in sceneConfigurationInfo {
let sceneLoader = SceneLoader(sceneMetadata: metadata)
sceneLoaderForMetadata[metadata] = sceneLoader
}
// Keep an immutable copy of the scene loader dictionary.
self.sceneLoaderForMetadata = sceneLoaderForMetadata
/*
Because `SceneManager` is marked as `final` and cannot be subclassed,
it is safe to register for notifications within the initializer.
*/
registerForNotifications()
}
deinit {
// Unregister for `SceneLoader` notifications if the observer is still around.
if let loadingCompletedObserver = loadingCompletedObserver {
NotificationCenter.default.removeObserver(loadingCompletedObserver, name: NSNotification.Name.SceneLoaderDidCompleteNotification, object: nil)
}
}
// MARK: Scene Transitioning
/**
Instructs the scene loader associated with the requested scene to begin
preparing the scene's resources.
This method should be called in preparation for the user needing to transition
to the scene in order to minimize the amount of load time.
*/
func prepareScene(identifier sceneIdentifier: SceneIdentifier) {
let loader = sceneLoader(forSceneIdentifier: sceneIdentifier)
_ = loader.asynchronouslyLoadSceneForPresentation()
}
/**
Loads and presents a scene if the all the resources for the scene are
currently in memory. Otherwise, presents a progress scene to monitor the progress
of the resources being downloaded, or display an error if one has occurred.
*/
func transitionToScene(identifier sceneIdentifier: SceneIdentifier) {
let loader = self.sceneLoader(forSceneIdentifier: sceneIdentifier)
if loader.stateMachine.currentState is SceneLoaderResourcesReadyState {
// The scene is ready to be displayed.
presentScene(for: loader)
}
else {
_ = loader.asynchronouslyLoadSceneForPresentation()
/*
Mark the `sceneLoader` as `requestedForPresentation` to automatically
present the scene when loading completes.
*/
loader.requestedForPresentation = true
// The scene requires a progress scene to be displayed while its resources are prepared.
if loader.requiresProgressSceneForPreparing {
presentProgressScene(for: loader)
}
}
}
// MARK: Scene Presentation
/// Configures and presents a scene.
func presentScene(for loader: SceneLoader) {
guard let scene = loader.scene else {
assertionFailure("Requested presentation for a `sceneLoader` without a valid `scene`.")
return
}
// Hold on to a reference to the currently requested scene's metadata.
currentSceneMetadata = loader.sceneMetadata
// Ensure we present the scene on the main queue.
DispatchQueue.main.async {
/*
Provide the scene with a reference to the `SceneLoadingManger`
so that it can coordinate the next scene that should be loaded.
*/
scene.sceneManager = self
// Present the scene with a transition.
let transition = SKTransition.fade(withDuration: GameplayConfiguration.SceneManager.transitionDuration)
self.presentingView.presentScene(scene, transition: transition)
/*
When moving to a new scene in the game, we also start downloading
on demand resources for any subsequent possible scenes.
*/
#if os(iOS) || os(tvOS)
self.beginDownloadingNextPossibleScenes()
#endif
// Clear any reference to a progress scene that may have been presented.
self.progressScene = nil
// Notify the delegate that the manager has presented a scene.
self.delegate?.sceneManager(self, didTransitionTo: scene)
// Restart the scene loading process.
loader.stateMachine.enter(SceneLoaderInitialState.self)
}
}
/// Configures the progress scene to show the progress of the `sceneLoader`.
func presentProgressScene(for loader: SceneLoader) {
// If the `progressScene` is already being displayed, there's nothing to do.
guard progressScene == nil else { return }
// Create a `ProgressScene` for the scene loader.
progressScene = ProgressScene.progressScene(withSceneLoader: loader)
progressScene!.sceneManager = self
let transition = SKTransition.doorsCloseHorizontal(withDuration: GameplayConfiguration.SceneManager.progressSceneTransitionDuration)
presentingView.presentScene(progressScene!, transition: transition)
}
#if os(iOS) || os(tvOS)
/**
Begins downloading on demand resources for all scenes that the user may reach next,
and purges resources for any unreachable scenes that are no longer accessible.
*/
private func beginDownloadingNextPossibleScenes() {
let possibleScenes = allPossibleNextScenes()
for sceneMetadata in possibleScenes {
let resourceRequest = sceneLoaderForMetadata[sceneMetadata]!
resourceRequest.downloadResourcesIfNecessary()
}
// Clean up scenes that are no longer accessible.
var unreachableScenes = Set(sceneLoaderForMetadata.keys)
unreachableScenes.subtract(possibleScenes)
for sceneMetadata in unreachableScenes {
let resourceRequest = sceneLoaderForMetadata[sceneMetadata]!
resourceRequest.purgeResources()
}
}
#endif
/// Determines all possible scenes that the player may reach after the current scene.
private func allPossibleNextScenes() -> Set<SceneMetadata> {
let homeScene = sceneConfigurationInfo.first!
// If there is no current scene, we can only go to the home scene.
guard let currentSceneMetadata = currentSceneMetadata else {
return [homeScene]
}
/*
In DemoBots, the user can always go home, replay the level, or progress linearly
to the next level.
This could be expanded to include the previous level, the furthest
level that has been unlocked, etc. depending on how the game progresses.
*/
return [homeScene, nextSceneMetadata, currentSceneMetadata]
}
// MARK: SceneLoader Notifications
/// Register for notifications of `SceneLoader` download completion.
func registerForNotifications() {
// Avoid reregistering for the notification.
guard loadingCompletedObserver == nil else { return }
loadingCompletedObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.SceneLoaderDidCompleteNotification, object: nil, queue: OperationQueue.main) { [unowned self] notification in
let sceneLoader = notification.object as! SceneLoader
// Ensure this is a `sceneLoader` managed by this `SceneManager`.
guard let managedSceneLoader = self.sceneLoaderForMetadata[sceneLoader.sceneMetadata], managedSceneLoader === sceneLoader else { return }
guard sceneLoader.stateMachine.currentState is SceneLoaderResourcesReadyState else {
fatalError("Received complete notification, but the `stateMachine`'s current state is not ready.")
}
/*
If the `sceneLoader` associated with this state has been requested
for presentation than we will present it here.
This is used to present the `HomeScene` without any possibility of
a progress scene.
*/
if sceneLoader.requestedForPresentation {
self.presentScene(for: sceneLoader)
}
// Reset the scene loader's presentation preference.
sceneLoader.requestedForPresentation = false
}
}
// MARK: Convenience
/// Returns the scene loader associated with the scene identifier.
func sceneLoader(forSceneIdentifier sceneIdentifier: SceneIdentifier) -> SceneLoader {
let sceneMetadata: SceneMetadata
switch sceneIdentifier {
case .home:
sceneMetadata = sceneConfigurationInfo.first!
case .currentLevel:
guard let currentSceneMetadata = currentSceneMetadata else {
fatalError("Current scene doesn't exist.")
}
sceneMetadata = currentSceneMetadata
case .level(let number):
sceneMetadata = sceneConfigurationInfo[number]
case .nextLevel:
sceneMetadata = nextSceneMetadata
case .end:
sceneMetadata = sceneConfigurationInfo.last!
}
return sceneLoaderForMetadata[sceneMetadata]!
}
}
| 40.344615 | 212 | 0.645744 |
691c29b6f8a81ec8de01f46650ae44e5654726ce
| 4,169 |
//
// ViewController.swift
// FKSecureStoreExample
//
// Created by Firoz Khan on 27/01/22.
//
import UIKit
let keychainDataKey = "userData"
class ViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var infoTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
clearFields()
}
@IBAction func saveTapped(_ sender: Any) {
guard let username = usernameTextField.text, username.count > 0 else { return }
guard let password = passwordTextField.text, password.count > 0 else { return }
let user = User(username: username, password: password)
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: user, requiringSecureCoding: false)
switch FKSecureStore.save(data: data, key: keychainDataKey) {
case .success:
showAlert(message: "Credentials saved to keychain successfully")
clearFields()
break
default:
showAlert(message: "Unable to store credentials in keychain")
break
}
}
catch {
let message = "Unable to archive user: \(error.localizedDescription)"
showAlert(title: "Error", message: message)
}
}
@IBAction func loadTapped(_ sender: Any) {
guard let data = FKSecureStore.load(dataForKey: keychainDataKey) else {
showAlert(title: "Oops", message: "No saved credentials present in keychain")
return
}
do {
// https://developer.apple.com/forums/thread/683077
guard let user = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [User.self, NSString.self], from: data) as? User else {
showAlert(title: "Error", message: "Unable to unarchive saved data into User")
return
}
let infoString = "Username: \(user.username)\nPassword: \(user.password)"
infoTextView.text = infoString
}
catch {
let message = "Unable to unarchive user: \(error.localizedDescription)"
showAlert(title: "Error", message: message)
}
}
@IBAction func deleteTapped(_ sender: Any) {
switch FKSecureStore.delete(key: keychainDataKey) {
case .success:
showAlert(message: "Data deleted from keychain successfully")
clearFields()
break
case .noData:
showAlert(message: "No data to delete in keychain")
break
case .other:
showAlert(title: "Error", message: "Unable to delete data in keychain")
break
}
}
@IBAction func clearTapped(_ sender: Any) {
switch FKSecureStore.clear() {
case .success:
showAlert(message: "Data cleared from keychain successfully")
clearFields()
break
case .noData:
showAlert(message: "No data to delete in keychain")
break
case .other:
showAlert(title: "Error", message: "Unable to clear data in keychain")
break
}
}
}
extension ViewController {
private func showAlert(title: String? = "Success", message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
private func clearFields() {
usernameTextField.text = nil
passwordTextField.text = nil
infoTextView.text = nil
}
}
| 31.824427 | 134 | 0.543536 |
08e7a759ae64c95aa3acda8daa877bafd56e3f8b
| 228 |
import CoreLocation // Fakery needs this, but it doesn't get autolinked…
import OHHTTPStubs
import XCTest
internal class TestCase: XCTestCase {
override internal func tearDown() {
HTTPStubs.removeAllStubs()
}
}
| 22.8 | 72 | 0.736842 |
18a834e4a680e969322cd4d3e92854edb50ee4c9
| 2,155 |
import Foundation
struct ImagePainter {
func drawOnImage(drawData: DrawOnImageData) -> UIImage? {
guard let image = UIImage(data: drawData.imageCanvas) else { return nil }
let textColor = UIColor.fromInt(argbValue: drawData.fontColor)
let textFont = buildFont(drawData: drawData)
let scale = UIScreen.main.scale
let rect = buildTextRect(drawData: drawData, imageSize: image.size)
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: textColor,
] as [NSAttributedString.Key : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
drawData.stringToWrite.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
fileprivate func buildFont(drawData: DrawOnImageData) -> UIFont {
let fontSize = drawData.fontSize == defaultFontSize
? UIFont.systemFontSize
: CGFloat(drawData.fontSize)
return UIFont.systemFont(ofSize: fontSize)
}
fileprivate func buildTextRect(drawData: DrawOnImageData, imageSize: CGSize) -> CGRect {
let xOrigin = drawData.leftPadding < Int(imageSize.width)
? drawData.leftPadding
: 0
let yOrigin = drawData.topPadding < Int(imageSize.height)
? drawData.topPadding
: 0
let horPadding = drawData.leftPadding + drawData.rightPadding
let vertPadding = drawData.topPadding + drawData.bottomPadding
let width = Int(imageSize.width) - horPadding > 0
? Int(imageSize.width) - horPadding
: Int(imageSize.width)
let height = Int(imageSize.height) - vertPadding > 0
? Int(imageSize.height) - vertPadding
: Int(imageSize.height)
return CGRect(x: xOrigin, y: yOrigin, width: width, height: height)
}
}
| 38.482143 | 92 | 0.641763 |
4637ab70d3efcbe2aa8ea878277bd7a552364756
| 2,014 |
//
// ChatRightTextURLCell.swift
// Yep
//
// Created by nixzhu on 16/1/18.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import Ruler
class ChatRightTextURLCell: ChatRightTextCell {
var openGraphURL: NSURL?
var tapOpenGraphURLAction: ((URL: NSURL) -> Void)?
lazy var feedURLContainerView: FeedURLContainerView = {
let view = FeedURLContainerView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.directionLeading = false
view.compressionMode = false
view.tapAction = { [weak self] in
guard let URL = self?.openGraphURL else {
return
}
self?.tapOpenGraphURLAction?(URL: URL)
}
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(feedURLContainerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configureWithMessage(message: Message, textContentLabelWidth: CGFloat, mediaTapAction: MediaTapAction?, collectionView: UICollectionView, indexPath: NSIndexPath) {
bottomGap = 100 + 10
super.configureWithMessage(message, textContentLabelWidth: textContentLabelWidth, mediaTapAction: mediaTapAction, collectionView: collectionView, indexPath: indexPath)
let minWidth: CGFloat = Ruler.iPhoneHorizontal(190, 220, 220).value
let fullWidth = UIScreen.mainScreen().bounds.width
let width = max(minWidth, textContainerView.frame.width + 12 * 2 - 1)
let feedURLContainerViewFrame = CGRect(x: fullWidth - 65 - width - 1, y: CGRectGetMaxY(textContainerView.frame) + 8, width: width, height: 100)
feedURLContainerView.frame = feedURLContainerViewFrame
if let openGraphInfo = message.openGraphInfo {
feedURLContainerView.configureWithOpenGraphInfoType(openGraphInfo)
openGraphURL = openGraphInfo.URL
}
}
}
| 32.483871 | 181 | 0.677756 |
bfd0dbd416908c5aae9ad713ef770f0d2256dc88
| 1,457 |
//
// SimpleViewController.swift
// UIAutomationDemo
//
// Created by ty0x2333 on 2018/12/18.
// Copyright © 2018 ty0x2333. All rights reserved.
//
import UIKit
class SimpleViewController: UIViewController {
private let label = UILabel()
private let button = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
title = "Simple"
view.backgroundColor = UIColor.white
label.text = "Hello World"
label.textAlignment = .center
view.addSubview(label)
button.setTitle("rotate", for: .normal)
button.addTarget(self, action: #selector(onClick), for: .touchUpInside)
view.addSubview(button)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let itemMaxSize = CGSize(width: view.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let labelSize = label.sizeThatFits(itemMaxSize)
label.frame = CGRect(x: 0, y: (view.bounds.height - labelSize.height) / 2.0, width: view.bounds.width, height: labelSize.height)
let buttonSize = button.sizeThatFits(itemMaxSize)
button.frame = CGRect(x: (view.bounds.width - buttonSize.width) / 2.0, y: label.frame.maxY + 20.0, width: buttonSize.width, height: buttonSize.height)
}
@objc private func onClick() {
label.transform = label.transform.rotated(by: CGFloat.pi)
}
}
| 33.113636 | 158 | 0.652025 |
f933505945e03f4c345281074f88f1c64dc17e56
| 269 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{ func a
{
enum b {
let d {
case
let a = [ {
for in ( ) {
{
}
for {
deinit {
class A {
class
case ,
| 14.157895 | 87 | 0.67658 |
c1ea1a7cfcec9b3003eb3ec36a91c010715cc31a
| 1,723 |
/*
* Copyright 2017 WalmartLabs
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
public class PersonEvents: PersonAPI.Events {
public override func addPersonAddedEventListenr(eventListener: @escaping ElectrodeBridgeEventListener) {
let listenerProcessor = EventListenerProcessor(eventName: PersonAPI.kEventPersonAdded, eventPayloadClass: Person.self, eventListener: eventListener)
listenerProcessor.execute()
}
public override func addPersonNameUpdatedEventListener(eventListener: @escaping ElectrodeBridgeEventListener) {
let listenerProcessor = EventListenerProcessor(eventName: PersonAPI.kEventPersonNameUpdated, eventPayloadClass: String.self, eventListener: eventListener)
listenerProcessor.execute()
}
public override func emitEventPersonAdded(person: Person) {
let eventProcessor = EventProcessor(eventName: PersonAPI.kEventPersonAdded, eventPayload: person)
eventProcessor.execute()
}
public override func emitEventPersonNameUpdated(updatedName: String) {
let eventProcessor = EventProcessor(eventName: PersonAPI.kEventPersonNameUpdated, eventPayload: updatedName)
eventProcessor.execute()
}
}
| 43.075 | 162 | 0.770749 |
fe56e2d1e285daea127167ab6d813e29dcbff491
| 1,354 |
//
// CacheKeyUtils.swift
// Malfurion
//
// Created by Shaw on 2020/3/16.
// Copyright © 2020 Dawa Inc. All rights reserved.
//
import Foundation
import Alamofire
extension ApiTemplate {
func cacheKey(with parameters: Parameters?) -> String {
let serverName = String(describing: type(of: self.service))
let path = self.path
guard let param = parameters else {
return "\(serverName)-\(path)"
}
let parametersArray = param.reduce(Array<String>()) { (result, arg1) -> Array<String> in
var tempResult = result
let (key, value) = arg1
var object: String
if (value is String) == false {
object = String(describing: value)
}else {
object = value as! String
}
if object.count > 0 {
tempResult.append("\(key)=\(value)")
}
tempResult.sort()
return tempResult
}
var parametersString = ""
for item in parametersArray {
if parametersString.count == 0 {
parametersString.append(item)
}else {
parametersString.append("&\(item)")
}
}
return "\(serverName)-\(path)-\(parametersString)"
}
}
| 26.54902 | 96 | 0.514032 |
e8e2372411346c89be1afd5c433b10cda5872aa9
| 2,734 |
// RUN: %target-swift-emit-silgen -parse-stdlib -module-name Swift %s | %FileCheck %s
class C {}
enum Optional<T> {
case none
case some(T)
}
precedencegroup AssignmentPrecedence {
assignment: true
associativity: right
}
struct Holder {
unowned(unsafe) var value: C
}
_ = Holder(value: C())
// CHECK-LABEL:sil hidden [ossa] @$ss6HolderV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned C, @thin Holder.Type) -> Holder
// CHECK: bb0([[T0:%.*]] : @owned $C,
// CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[T0]] : $C to $@sil_unmanaged C
// CHECK-NEXT: destroy_value [[T0]] : $C
// CHECK-NEXT: [[T2:%.*]] = struct $Holder ([[T1]] : $@sil_unmanaged C)
// CHECK-NEXT: return [[T2]] : $Holder
// CHECK-NEXT: } // end sil function '$ss6HolderV5valueABs1CC_tcfC'
func set(holder holder: inout Holder) {
holder.value = C()
}
// CHECK-LABEL: sil hidden [ossa] @$ss3set6holderys6HolderVz_tF : $@convention(thin) (@inout Holder) -> () {
// CHECK: bb0([[ADDR:%.*]] : $*Holder):
// CHECK: [[T0:%.*]] = function_ref @$ss1CC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[C:%.*]] = apply [[T0]](
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*Holder
// CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[WRITE]] : $*Holder, #Holder.value
// CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[C]]
// CHECK-NEXT: assign [[T1]] to [[T0]]
// CHECK-NEXT: destroy_value [[C]]
// CHECK-NEXT: end_access [[WRITE]] : $*Holder
// CHECK: } // end sil function '$ss3set6holderys6HolderVz_tF'
func get(holder holder: inout Holder) -> C {
return holder.value
}
// CHECK-LABEL: sil hidden [ossa] @$ss3get6holders1CCs6HolderVz_tF : $@convention(thin) (@inout Holder) -> @owned C {
// CHECK: bb0([[ADDR:%.*]] : $*Holder):
// CHECK-NEXT: debug_value %0 : $*Holder, var, name "holder", argno 1, expr op_deref
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*Holder
// CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[READ]] : $*Holder, #Holder.value
// CHECK-NEXT: [[T1:%.*]] = load [trivial] [[T0]] : $*@sil_unmanaged C
// CHECK-NEXT: [[T2:%.*]] = strong_copy_unmanaged_value [[T1]]
// CHECK-NEXT: end_access [[READ]] : $*Holder
// CHECK-NEXT: return [[T2]]
func project(fn fn: () -> Holder) -> C {
return fn().value
}
// CHECK-LABEL: sil hidden [ossa] @$ss7project2fns1CCs6HolderVyXE_tF : $@convention(thin) (@noescape @callee_guaranteed () -> Holder) -> @owned C {
// CHECK: bb0([[FN:%.*]] : $@noescape @callee_guaranteed () -> Holder):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[T0:%.*]] = apply [[FN]]()
// CHECK-NEXT: [[T1:%.*]] = struct_extract [[T0]] : $Holder, #Holder.value
// CHECK-NEXT: [[T2:%.*]] = strong_copy_unmanaged_value [[T1]]
// CHECK-NEXT: return [[T2]]
| 40.80597 | 147 | 0.61229 |
fba5fc49df8f37f9f48c3125750692e52c3a8496
| 185 |
//
// Parameter.swift
// TurtleCore
//
// Created by Andrew Fox on 7/31/20.
// Copyright © 2020 Andrew Fox. All rights reserved.
//
open class Parameter: AbstractSyntaxTreeNode {}
| 18.5 | 53 | 0.691892 |
75604451aee0868cae0c445636f9c1b47a50cb10
| 472 |
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Cache",
products: [
.library(
name: "Cache",
targets: ["Cache"]),
],
dependencies: [],
targets: [
.target(
name: "Cache",
path: "Source/Shared"), // relative to the target path
.testTarget(
name: "CacheTests",
dependencies: ["Cache"],
path: "Tests"),
]
)
| 20.521739 | 66 | 0.483051 |
d52c24c700c4232f3836d980f43ad832e589b0ce
| 5,616 |
///
/// RKJointTree.swift
/// BodyDetection
///
/// Created by Enzo Maruffa Moreira on 22/10/19.
/// Copyright © 2019 Apple. All rights reserved.
///
import RealityKit
/// A tree representing an skeleton's joints
class RKJointTree: Codable {
/// An optional RKJoint with the tree's root
var rootJoint: RKJoint?
/// An int that computes the tree size
/// - Returns: nil if it has no rootJoint, an Int if it has a rootJoint
var treeSize: Int? {
if let rootJoint = self.rootJoint {
return rootJoint.descendantCount + 1
}
return nil
}
/// A Bool describing if the tree is updateable. *true* by default
var canUpdate = true
/// Initializes an empty tree
init() { }
/// Initializes a tree with only the root joint.
/// - Parameter rootJoint: A tuple with the joint's name and translation
init(rootJoint: (String, Transform)) {
self.rootJoint = RKJoint(joint: rootJoint)
}
/// Initializes a tree based on a list of joints
// Every joint must have a unique name
init(from list: [(String, Transform)], usingAbsoluteTranslation: Bool) {
// Separates our joint name in a list with it`s original hierarchy
var hierachicalJoints = list.map( { ($0.0.components(separatedBy: "/"), $0.1)} )
hierachicalJoints.sort(by: { $0.0.count < $1.0.count } )
// Removes the root joint from the list
let rootJoint = hierachicalJoints.removeFirst()
// Checks that the root joint exists
guard let rootName = rootJoint.0.first else {
return
}
// Creates the root joint in the tree
self.rootJoint = RKJoint(joint: (rootName, rootJoint.1))
for joint in hierachicalJoints {
// If the joint has an ancestor, we get it's name
let ancestorName = joint.0.count >= 2 ? joint.0[joint.0.count - 2] : rootName
print(ancestorName)
if let ancestorJoint = self.rootJoint?.findSelfOrDescendantBy(name: ancestorName) {
let jointName = joint.0.last
// If somehow a joint is repeated, we just update it's position
if let existingJoint = ancestorJoint.childrenJoints.first(where: { $0.name == jointName} ) {
if usingAbsoluteTranslation {
existingJoint.relativeTranslations.append(joint.1.translation - ancestorJoint.absoluteTranslation)
} else {
existingJoint.relativeTranslations.append(joint.1.translation)
}
print("Repeated joint found with hierarchy \(joint.0)")
} else {
if usingAbsoluteTranslation {
let childJoint = RKJoint(jointName: jointName ?? "(nil)", rotation: joint.1.rotation, relativeTranslation: joint.1.translation - ancestorJoint.absoluteTranslation)
ancestorJoint.addChild(joint: childJoint)
} else {
let childJoint = RKJoint(jointName: jointName ?? "(nil)", rotation: joint.1.rotation, relativeTranslation: joint.1.translation)
ancestorJoint.addChild(joint: childJoint)
}
}
} else {
print("Error creating RKJointTree. Ancestor for joint with hierarchy \(joint.0) not found")
}
}
print("RKJointTree created successfully!")
}
///TODO: Optimize since we already know where each joint is in the tree
func updateJoints(from list: [(String, Transform)], usingAbsoluteTranslation: Bool) {
if canUpdate {
// Separates our joint name in a list with it`s original hierarchy
var hierachicalJoints = list.map( { ($0.0.components(separatedBy: "/"), $0.1)} )
hierachicalJoints.sort(by: { $0.0.count < $1.0.count } )
// Updates every joint
for joint in hierachicalJoints {
if let jointName = joint.0.last,
let existingJoint = rootJoint?.findSelfOrDescendantBy(name: jointName) {
existingJoint.update(newTransform: joint.1, usingAbsoluteTranslation: usingAbsoluteTranslation)
}
}
}
}
/// Prints the jointTree using a breadth-first search
func printJointsBFS() {
var jointQueue: [RKJoint] = []
if let root = rootJoint {
jointQueue.append(root)
}
while jointQueue.count > 0 {
let joint = jointQueue.removeFirst()
print(joint.description)
jointQueue.append(contentsOf: joint.childrenJoints)
}
}
func isEquivalent(to other: RKJointTree) -> Bool {
guard let rootJoint = self.rootJoint, let otherRootJoint = other.rootJoint else {
return false
}
if treeSize != other.treeSize {
return false
}
// Compare the structure between two trees
return rootJoint.isEquivalent(to: otherRootJoint)
}
func copy() -> RKJointTree {
let newTree = RKJointTree()
if let rootJoint = self.rootJoint {
newTree.rootJoint = rootJoint.copyJoint(withChildren: true)
}
return newTree
}
}
| 36.705882 | 187 | 0.565705 |
d784745b23269b50e5ea58befd0b260a5832adb0
| 1,809 |
//
// NavigationTitleView.swift
// PACECloudSDK
//
// Created by PACE Telematics GmbH.
//
import UIKit
class NavigationTitleView: UIView {
lazy var lockIconImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.tintColor = AppStyle.textColor1
return imageView
}()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = AppStyle.regularFont(ofSize: 16)
label.textAlignment = .center
label.numberOfLines = 1
label.textColor = AppStyle.textColor1
return label
}()
var shouldShowLockIcon: Bool = false {
didSet {
adjustTitleView()
}
}
init() {
super.init(frame: CGRect.zero)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func set(titleText: String?, showLockIcon: Bool) {
titleLabel.text = titleText
shouldShowLockIcon = showLockIcon
}
private func setup() {
addSubview(titleLabel)
addSubview(lockIconImageView)
lockIconImageView.anchor(leading: self.leadingAnchor,
trailing: titleLabel.leadingAnchor,
centerY: centerYAnchor,
padding: .init(top: 0, left: 0, bottom: 0, right: 5),
size: .init(width: 15, height: 15))
titleLabel.anchor(trailing: self.trailingAnchor, centerY: centerYAnchor)
}
private func adjustTitleView() {
lockIconImageView.image = shouldShowLockIcon ? AppStyle.lockIcon : nil
}
}
| 26.217391 | 86 | 0.589276 |
039a07cc72fca1ef31fa19964cbbb6d6b4a94a3c
| 8,493 |
//
// Copyright (c) topmind GmbH and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
//
import CoreData
import Foundation
public struct RequestConfig {
public let predicate: NSPredicate?
public let sortDescriptors: [NSSortDescriptor]
public let sectionNameKeyPath: String?
public let fetchLimit: Int?
public let includesPropertyValues: Bool
public init(predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor] = [], sectionNameKeyPath: String? = nil, fetchLimit: Int? = nil, includesPropertyValues: Bool = true) {
self.predicate = predicate
self.sortDescriptors = sortDescriptors
self.sectionNameKeyPath = sectionNameKeyPath
self.fetchLimit = fetchLimit
self.includesPropertyValues = includesPropertyValues
}
}
public struct CoreDataFetcher<T: NSManagedObject> {
public typealias Entity = T
public typealias BuilderCallback = (Entity) -> Void
public typealias CollectionResult = Result<[Entity], Error>
public typealias EntityResult = Result<Entity, Error>
public typealias CollectionCompletion = (CollectionResult) -> Void
public typealias EntityCompletion = (EntityResult) -> Void
// MARK: - PROPERTIES
public let context: NSManagedObjectContext
public let sortDescriptors: [NSSortDescriptor]?
// MARK: - Init
public init(context: NSManagedObjectContext, sortDescriptors: [NSSortDescriptor]? = nil) {
self.context = context
self.sortDescriptors = sortDescriptors
}
// MARK: - Single Entity
public func create(_ builder: BuilderCallback? = nil) -> EntityResult {
let entity = Entity(context: context)
builder?(entity)
return .success(entity)
}
public func find(identifier: NSManagedObjectID) -> EntityResult {
do {
guard let result = try context.existingObject(with: identifier) as? Entity else {
return .failure(CoreDataError.entityNotFound(entity: NSStringFromClass(Entity.self)))
}
return .success(result)
} catch {
return .failure(error)
}
}
// MARK: - All
public func all() -> CollectionResult {
all(configuration: configuration())
}
public func all(sortedBy sortDescriptors: [NSSortDescriptor]) -> CollectionResult {
all(configuration: configuration(predicate: nil, sortDescriptors: sortDescriptors))
}
public func all<U: Any>(keyPath: KeyPath<Entity, U>, value: AnyObject) -> CollectionResult {
all(attribute: NSExpression(forKeyPath: keyPath).keyPath, value: value)
}
public func all(attribute: String, value: AnyObject) -> CollectionResult {
let predicate = NSPredicate(attribute: attribute, value: value, operation: .equal)
return all(configuration: configuration(predicate: predicate))
}
public func all(configuration config: RequestConfig) -> CollectionResult {
execute(config)
}
// MARK: All async
public func all(_ completion: @escaping CollectionCompletion) {
all(configuration: configuration(), completion: completion)
}
public func all(sortedBy sortDescriptors: [NSSortDescriptor], completion: @escaping CollectionCompletion) {
all(configuration: configuration(predicate: nil, sortDescriptors: sortDescriptors), completion: completion)
}
public func all<U: Any>(keyPath: KeyPath<Entity, U>, value: AnyObject, completion: @escaping CollectionCompletion) {
all(attribute: NSExpression(forKeyPath: keyPath).keyPath, value: value, completion: completion)
}
public func all(attribute: String, value: AnyObject, completion: @escaping CollectionCompletion) {
let predicate = NSPredicate(attribute: attribute, value: value, operation: .equal)
let config = configuration(predicate: predicate)
all(configuration: config, completion: completion)
}
public func all(configuration config: RequestConfig, completion: @escaping CollectionCompletion) {
context.perform {
completion(self.execute(config))
}
}
// MARK: - First
public func first<U: Any>(keyPath: KeyPath<Entity, U>, value: AnyObject) -> EntityResult {
first(attribute: NSExpression(forKeyPath: keyPath).keyPath, value: value)
}
public func first(attribute: String, value: AnyObject) -> EntityResult {
extractFirst(all(attribute: attribute, value: value))
}
public func first(configuration config: RequestConfig) -> EntityResult {
extractFirst(all(configuration: config))
}
public func first<U: Any>(keyPath: KeyPath<Entity, U>, value: AnyObject, completion: @escaping EntityCompletion) {
first(attribute: NSExpression(forKeyPath: keyPath).keyPath, value: value, completion: completion)
}
public func first(attribute: String, value: AnyObject, completion: @escaping EntityCompletion) {
all(attribute: attribute, value: value) {
completion(self.extractFirst($0))
}
}
public func firstOrCreate<U: Any>(keyPath: KeyPath<Entity, U>, value: AnyObject, builder: BuilderCallback? = nil) -> EntityResult {
firstOrCreate(attribute: NSExpression(forKeyPath: keyPath).keyPath, value: value, builder: builder)
}
public func firstOrCreate(attribute: String, value: AnyObject, builder: BuilderCallback? = nil) -> EntityResult {
let predicate = NSPredicate(attribute: attribute, value: value, operation: .equal)
return firstOrCreate(configuration: configuration(predicate: predicate), builder: builder)
}
public func firstOrCreate(configuration config: RequestConfig, builder: BuilderCallback? = nil) -> EntityResult {
let result = extractFirst(all(configuration: config))
if case let .success(entity) = result {
builder?(entity)
return result
}
return create(builder)
}
// MARK: - Requests
public func fetchRequest(configuration config: RequestConfig) -> NSFetchRequest<Entity> {
let request = NSFetchRequest<Entity>()
request.entity = Entity.entity()
update(request: request, config: config)
return request
}
// FIXME: extension on NSFetchRequest<Entity> is not working anymore :-(
// due to generic NSFetchRequest
public func update(request: NSFetchRequest<Entity>, config: RequestConfig) {
request.predicate = config.predicate
request.sortDescriptors = config.sortDescriptors
if let limit = config.fetchLimit {
request.fetchLimit = limit
}
request.includesPropertyValues = config.includesPropertyValues
}
// MARK: Delete
public func delete(_ entity: Entity) throws {
try delete([entity])
}
public func delete(_ entities: [Entity]) throws {
let predicate = NSPredicate(format: "(SELF IN %@)", entities)
let configuration = RequestConfig(predicate: predicate, includesPropertyValues: false)
try delete(configuration: configuration)
}
public func deleteAll() throws {
let configuration = RequestConfig(predicate: nil, includesPropertyValues: false)
try delete(configuration: configuration)
}
public func delete(configuration config: RequestConfig) throws {
let request = fetchRequest(configuration: config)
let results = try context.fetch(request)
context.performAndWait {
for entity in results {
self.context.delete(entity)
}
}
}
// When using NSBatchDeleteRequest, changes are not refelected in the context. Calling this method in iOS 9 resets the context.
// Consumers need to fetch again after calling it. http://stackoverflow.com/a/33534668
public func batchDelete(configuration config: RequestConfig) throws {
try context.execute(deleteRequest(configuration: config))
context.reset()
}
// MARK: - Private
@available(iOS 9.0, OSX 10.11, *)
private func deleteRequest(configuration config: RequestConfig) -> NSBatchDeleteRequest {
// swiftlint:disable force_cast
NSBatchDeleteRequest(fetchRequest: fetchRequest(configuration: config) as! NSFetchRequest<NSFetchRequestResult>)
// swiftlint:enable force_cast
}
private func execute(_ config: RequestConfig) -> CollectionResult {
do {
let request = fetchRequest(configuration: config)
let result = try context.fetch(request)
return .success(result)
} catch {
return .failure(error)
}
}
private func configuration(predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil) -> RequestConfig {
let sort = (sortDescriptors ?? self.sortDescriptors) ?? []
return RequestConfig(predicate: predicate, sortDescriptors: sort)
}
private func extractFirst(_ result: CollectionResult) -> EntityResult {
switch result {
case let .success(entities):
guard let entity = entities.first else {
return .failure(CoreDataError.entityNotFound(entity: NSStringFromClass(Entity.self)))
}
return .success(entity)
case let .failure(error):
return .failure(error)
}
}
}
| 34.245968 | 177 | 0.753915 |
d73000bd91360b5085ba6536a70b96abd94ba4db
| 2,025 |
//
// LedgerExtryDataXDR.swift
// stellarsdk
//
// Created by Rogobete Christian on 13.02.18.
// Copyright © 2018 Soneso. All rights reserved.
//
import Foundation
public enum LedgerEntryDataXDR: XDRCodable {
case account (AccountEntryXDR)
case trustline (TrustlineEntryXDR)
case offer (OfferEntryXDR)
case data (DataEntryXDR)
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let type = try container.decode(Int32.self)
switch type {
case LedgerEntryType.account.rawValue:
self = .account(try container.decode(AccountEntryXDR.self))
case LedgerEntryType.trustline.rawValue:
self = .trustline(try container.decode(TrustlineEntryXDR.self))
case LedgerEntryType.offer.rawValue:
self = .offer(try container.decode(OfferEntryXDR.self))
case LedgerEntryType.data.rawValue:
self = .data(try container.decode(DataEntryXDR.self))
default:
self = .account(try container.decode(AccountEntryXDR.self))
}
}
public func type() -> Int32 {
switch self {
case .account: return LedgerEntryType.account.rawValue
case .trustline: return LedgerEntryType.trustline.rawValue
case .offer: return LedgerEntryType.offer.rawValue
case .data: return LedgerEntryType.data.rawValue
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(type())
switch self {
case .account (let op):
try container.encode(op)
case .trustline (let op):
try container.encode(op)
case .offer (let op):
try container.encode(op)
case .data (let op):
try container.encode(op)
}
}
}
| 30.681818 | 79 | 0.59358 |
f458fb3d8952ef062061c993cfcd7cb6cd898ebb
| 1,564 |
//
// StairsModel.swift
//
// Created by Zack Brown on 15/08/2021.
//
import Euclid
import Meadow
import SceneKit
class StairsModel: SCNNode, Responder, Shadable, Soilable {
public var ancestor: SoilableParent? { return parent as? SoilableParent }
public var isDirty: Bool = true
public var category: Int { SceneGraphCategory.stairChunk.rawValue }
public var program: SCNProgram? { scene?.map.stairs.program }
public var uniforms: [Uniform]? { nil }
public var textures: [Texture]? { nil }
let model: Stairs
init(model: Stairs) {
self.model = model
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult func clean() -> Bool {
guard isDirty else { return false }
let mesh = Mesh(model.build(position: .zero))
self.geometry = SCNGeometry(mesh)
self.geometry?.program = program
if let uniforms = uniforms {
self.geometry?.set(uniforms: uniforms)
}
if let textures = textures {
self.geometry?.set(textures: textures)
}
for child in childNodes {
child.removeFromParentNode()
}
let node = SCNNode(geometry: SCNGeometry(wireframe: mesh))
addChildNode(node)
isDirty = false
return true
}
}
| 22.666667 | 77 | 0.551151 |
2f37575b565e992d9cd519d457b027c27667bf51
| 1,001 |
//
// UserRequest.swift
// NetworkLayer
//
// Created by AHMET KAZIM GUNAY on 29/10/2017.
// Copyright © 2017 AHMET KAZIM GUNAY. All rights reserved.
//
import Foundation
final class UserRequest: Requestable {
typealias ResponseType = UserResponse
private var userName : String
init(userName:String) {
self.userName = userName
}
var baseUrl: URL {
return URL(string: "https://api.github.com/")!
}
var endpoint: String {
return "users/\(self.userName)"
}
var method: Network.Method {
return .get
}
var query: Network.QueryType {
return .path
}
var parameters: [String : Any]? {
return nil
}
var headers: [String : String]? {
return defaultJSONHeader
}
var timeout: TimeInterval {
return 30.0
}
var cachePolicy: NSURLRequest.CachePolicy {
return .reloadIgnoringLocalAndRemoteCacheData
}
}
| 18.886792 | 60 | 0.586414 |
48fccf5a46f071fc2b0d9c30954603dbcd83a3ae
| 794 |
import MediaFeature
import TestUtils
import XCTest
final class MediaFeatureTests: XCTestCase {
override func setUp() {
initSnapshotTesting()
}
func testMediaDetailScreen() {
assertPreviewScreenSnapshot(MediaDetailScreen_Previews.self)
}
func testMediaListView() {
assertPreviewScreenSnapshot(MediaListView_Previews.self)
}
func testMediaScreen() {
assertPreviewScreenSnapshot(MediaScreen_Previews.self)
}
func testMediaSection() {
assertPreviewSnapshot(MediaSectionView_Previews.self)
}
func testMediaSectionHeader() {
assertPreviewSnapshot(MediaSectionHeader_Previews.self)
}
func testSearchResultScreen() {
assertPreviewScreenSnapshot(SearchResultScreen_Previews.self)
}
}
| 23.352941 | 69 | 0.725441 |
20f5d35453c4782b425c5e46f26f8161417f9b92
| 15,803 |
import XCTest
import BigInt
import Quick
import Nimble
import Cuckoo
@testable import EthereumKit
class PeerGroupTests: QuickSpec {
override func spec() {
let mockStorage = MockISpvStorage()
let mockPeerProvider = MockIPeerProvider()
let mockValidator = MockBlockValidator()
let mockBlockHelper = MockIBlockHelper()
let mockState = MockPeerGroupState()
let mockDelegate = MockIPeerGroupDelegate()
let address = Data(repeating: 1, count: 20)
let limit = 2
let peerGroup = PeerGroup(storage: mockStorage, peerProvider: mockPeerProvider, validator: mockValidator, blockHelper: mockBlockHelper, state: mockState, address: address, headersLimit: limit)
peerGroup.delegate = mockDelegate
beforeEach {
}
afterEach {
reset(mockStorage, mockPeerProvider, mockValidator, mockBlockHelper, mockState, mockDelegate)
}
describe("#syncState") {
let syncState: EthereumKit.SyncState = .syncing
beforeEach {
stub(mockState) { mock in
when(mock.syncState.get).thenReturn(syncState)
}
}
it("returns sync state from state") {
expect(peerGroup.syncState).to(equal(syncState))
}
}
describe("#start") {
let mockPeer = MockIPeer()
beforeEach {
stub(mockPeerProvider) { mock in
when(mock.peer()).thenReturn(mockPeer)
}
stub(mockState) { mock in
when(mock.syncState.set(any())).thenDoNothing()
when(mock.syncPeer.set(any())).thenDoNothing()
}
stub(mockDelegate) { mock in
when(mock.onUpdate(syncState: any())).thenDoNothing()
}
stub(mockPeer) { mock in
when(mock.connect()).thenDoNothing()
when(mock.delegate.set(any())).thenDoNothing()
}
peerGroup.start()
}
afterEach {
reset(mockPeer)
}
it("sets `syncing` sync state to state") {
verify(mockState).syncState.set(equal(to: EthereumKit.SyncState.syncing))
}
it("notifies delegate that sync state changed to `syncing`") {
verify(mockDelegate).onUpdate(syncState: equal(to: EthereumKit.SyncState.syncing))
}
it("sets sync peer delegate to self") {
verify(mockPeer).delegate.set(equal(to: peerGroup, type: PeerGroup.self))
}
it("sets sync peer to state") {
verify(mockState).syncPeer.set(equal(to: mockPeer, type: MockIPeer.self))
}
it("connects sync peer") {
verify(mockPeer).connect()
}
}
describe("#sendTransaction") {
let mockPeer = MockIPeer()
let rawTransaction = RawTransaction()
let signature: (v: BigUInt, r: BigUInt, s: BigUInt) = (0, 0, 0)
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.get).thenReturn(mockPeer)
}
stub(mockPeer) { mock in
when(mock.send(rawTransaction: any(), signature: any())).thenDoNothing()
}
peerGroup.send(rawTransaction: rawTransaction, signature: signature)
}
afterEach {
reset(mockPeer)
}
it("sends transaction to sync peer") {
verify(mockPeer).send(rawTransaction: sameInstance(as: rawTransaction), signature: any())
}
}
describe("#didConnect") {
let mockPeer = MockIPeer()
let lastBlockHeader = BlockHeader()
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.get).thenReturn(mockPeer)
}
stub(mockBlockHelper) { mock in
when(mock.lastBlockHeader.get).thenReturn(lastBlockHeader)
}
stub(mockPeer) { mock in
when(mock.requestBlockHeaders(blockHeader: any(), limit: any(), reverse: any())).thenDoNothing()
}
peerGroup.didConnect()
}
afterEach {
reset(mockPeer)
}
it("requests block headers from peer using last block height") {
verify(mockPeer).requestBlockHeaders(blockHeader: equal(to: lastBlockHeader), limit: equal(to: limit), reverse: false)
}
}
describe("#didDisconnect") {
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.set(any())).thenDoNothing()
}
peerGroup.didDisconnect(error: nil)
}
it("sets sync peer to nil in state") {
// verify(mockState).syncPeer.set(nil)
}
}
describe("#didReceiveBlockHeaders") {
let lastBlockHeader = BlockHeader()
let firstHeader = BlockHeader()
let secondHeader = BlockHeader()
beforeEach {
stub(mockValidator) { mock in
when(mock.validate(blockHeaders: any(), from: any())).thenDoNothing()
}
}
context("when block headers are valid") {
let mockPeer = MockIPeer()
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.get).thenReturn(mockPeer)
}
stub(mockStorage) { mock in
when(mock.save(blockHeaders: any())).thenDoNothing()
}
stub(mockPeer) { mock in
when(mock.requestBlockHeaders(blockHeader: any(), limit: any(), reverse: any())).thenDoNothing()
}
}
afterEach {
reset(mockPeer)
}
it("saves all block headers except first one to storage") {
peerGroup.didReceive(blockHeaders: [firstHeader, secondHeader], blockHeader: lastBlockHeader, reverse: false)
verify(mockStorage).save(blockHeaders: equal(to: [firstHeader, secondHeader]))
}
context("when blocks count is the same as limit") {
beforeEach {
peerGroup.didReceive(blockHeaders: [firstHeader, secondHeader], blockHeader: lastBlockHeader, reverse: false)
}
it("requests more block headers starting from last received block header") {
verify(mockPeer).requestBlockHeaders(blockHeader: equal(to: secondHeader), limit: equal(to: limit), reverse: false)
}
}
context("when blocks count is less then limit") {
beforeEach {
stub(mockPeer) { mock in
when(mock.requestAccountState(address: any(), blockHeader: any())).thenDoNothing()
}
peerGroup.didReceive(blockHeaders: [firstHeader], blockHeader: lastBlockHeader, reverse: false)
}
it("does not request any more block headers") {
verify(mockPeer, never()).requestBlockHeaders(blockHeader: any(), limit: any(), reverse: any())
}
it("requests account state for last received block header") {
verify(mockPeer).requestAccountState(address: equal(to: address), blockHeader: equal(to: firstHeader))
}
}
}
context("when validator throws ForkDetected error") {
let mockPeer = MockIPeer()
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.get).thenReturn(mockPeer)
}
stub(mockValidator) { mock in
when(mock.validate(blockHeaders: equal(to: [firstHeader, secondHeader]), from: equal(to: lastBlockHeader))).thenThrow(BlockValidator.ValidationError.forkDetected)
}
stub(mockPeer) { mock in
when(mock.requestBlockHeaders(blockHeader: any(), limit: any(), reverse: any())).thenDoNothing()
}
peerGroup.didReceive(blockHeaders: [firstHeader, secondHeader], blockHeader: lastBlockHeader, reverse: false)
}
afterEach {
reset(mockPeer)
}
it("requests reversed block headers for block header") {
verify(mockPeer).requestBlockHeaders(blockHeader: equal(to: lastBlockHeader), limit: equal(to: limit), reverse: true)
}
}
context("when validator throws validation error") {
let error = TestError()
let mockPeer = MockIPeer()
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.get).thenReturn(mockPeer)
}
stub(mockValidator) { mock in
when(mock.validate(blockHeaders: equal(to: [firstHeader, secondHeader]), from: equal(to: lastBlockHeader))).thenThrow(error)
}
stub(mockPeer) { mock in
when(mock.disconnect(error: any())).thenDoNothing()
}
peerGroup.didReceive(blockHeaders: [firstHeader, secondHeader], blockHeader: lastBlockHeader, reverse: false)
}
afterEach {
reset(mockPeer)
}
it("disconnects peer") {
verify(mockPeer).disconnect(error: equal(to: error, type: TestError.self))
}
}
}
describe("#didReceiveReversedBlockHeaders") {
let mockPeer = MockIPeer()
let forkHeaderHash = Data(repeating: 1, count: 10)
let forkHeaderHeight = 99
let firstReceivedHeader = BlockHeader(hashHex: Data(repeating: 2, count: 10), height: 100)
let firstStoredHeader = BlockHeader(hashHex: Data(repeating: 3, count: 10), height: 100)
let secondStoredHeader = BlockHeader(hashHex: forkHeaderHash, height: forkHeaderHeight)
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.get).thenReturn(mockPeer)
}
stub(mockStorage) { mock in
when(mock.reversedLastBlockHeaders(from: equal(to: firstStoredHeader.height), limit: equal(to: 2))).thenReturn([firstStoredHeader, secondStoredHeader])
}
}
afterEach {
reset(mockPeer)
}
context("when fork block header exists") {
let validReceivedHeader = BlockHeader(hashHex: forkHeaderHash, height: forkHeaderHeight)
beforeEach {
stub(mockPeer) { mock in
when(mock.requestBlockHeaders(blockHeader: any(), limit: any(), reverse: any())).thenDoNothing()
}
peerGroup.didReceive(blockHeaders: [firstReceivedHeader, validReceivedHeader], blockHeader: firstStoredHeader, reverse: true)
}
it("requests blocks headers from fork block header") {
verify(mockPeer).requestBlockHeaders(blockHeader: equal(to: secondStoredHeader), limit: equal(to: limit), reverse: false)
}
}
context("when fork block header does not exist") {
let invalidReceivedHeader = BlockHeader(hashHex: Data(repeating: 5, count: 10), height: forkHeaderHeight)
beforeEach {
stub(mockPeer) { mock in
when(mock.disconnect(error: any())).thenDoNothing()
}
peerGroup.didReceive(blockHeaders: [firstReceivedHeader, invalidReceivedHeader], blockHeader: firstStoredHeader, reverse: true)
}
it("disconnects peer with invalidPeer error") {
verify(mockPeer).disconnect(error: equal(to: PeerGroup.PeerError.invalidForkedPeer, type: PeerGroup.PeerError.self))
}
}
}
describe("#didReceiveAccountState") {
let accountState = AccountState()
beforeEach {
stub(mockDelegate) { mock in
when(mock.onUpdate(accountState: any())).thenDoNothing()
when(mock.onUpdate(syncState: any())).thenDoNothing()
}
stub(mockState) { mock in
when(mock.syncState.set(any())).thenDoNothing()
}
peerGroup.didReceive(accountState: accountState, address: Data(), blockHeader: BlockHeader())
}
it("notifies delegate about account state update") {
verify(mockDelegate).onUpdate(accountState: equal(to: accountState))
}
it("sets `synced` sync state to state") {
verify(mockState).syncState.set(equal(to: EthereumKit.SyncState.synced))
}
it("notifies delegate that sync state changed to `synced`") {
verify(mockDelegate).onUpdate(syncState: equal(to: EthereumKit.SyncState.synced))
}
}
describe("#didAnnounce") {
let mockPeer = MockIPeer()
beforeEach {
stub(mockState) { mock in
when(mock.syncPeer.get).thenReturn(mockPeer)
}
}
afterEach {
reset(mockPeer)
}
context("when sync state is not `synced`") {
beforeEach {
stub(mockState) { mock in
when(mock.syncState.get).thenReturn(EthereumKit.SyncState.syncing)
}
peerGroup.didAnnounce(blockHash: Data(), blockHeight: 0)
}
it("should not request any block headers") {
verify(mockPeer, never()).requestBlockHeaders(blockHeader: any(), limit: any(), reverse: any())
}
}
context("when sync state is `synced`") {
let lastBlockHeader = BlockHeader()
beforeEach {
stub(mockState) { mock in
when(mock.syncState.get).thenReturn(EthereumKit.SyncState.synced)
}
stub(mockBlockHelper) { mock in
when(mock.lastBlockHeader.get).thenReturn(lastBlockHeader)
}
stub(mockPeer) { mock in
when(mock.requestBlockHeaders(blockHeader: any(), limit: any(), reverse: any())).thenDoNothing()
}
peerGroup.didAnnounce(blockHash: Data(), blockHeight: 0)
}
it("requests block headers from peer using last block height") {
verify(mockPeer).requestBlockHeaders(blockHeader: equal(to: lastBlockHeader), limit: equal(to: limit), reverse: false)
}
}
}
}
}
| 38.263923 | 200 | 0.520344 |
20a4f4474dbd3fe4d3e51b9b018a34ef7e8875b9
| 15,215 |
import UIKit
import MapboxDirections
protocol InstructionPresenterDataSource: class {
var availableBounds: (() -> CGRect)! { get }
var font: UIFont! { get }
var textColor: UIColor! { get }
var shieldHeight: CGFloat { get }
}
typealias DataSource = InstructionPresenterDataSource
class InstructionPresenter {
private let instruction: VisualInstruction
private weak var dataSource: DataSource?
required init(_ instruction: VisualInstruction, dataSource: DataSource, imageRepository: ImageRepository = .shared, downloadCompletion: ShieldDownloadCompletion?) {
self.instruction = instruction
self.dataSource = dataSource
self.imageRepository = imageRepository
self.onShieldDownload = downloadCompletion
}
typealias ImageDownloadCompletion = (UIImage?) -> Void
typealias ShieldDownloadCompletion = (NSAttributedString) -> ()
let onShieldDownload: ShieldDownloadCompletion?
private let imageRepository: ImageRepository
func attributedText() -> NSAttributedString {
let string = NSMutableAttributedString()
fittedAttributedComponents().forEach { string.append($0) }
return string
}
func fittedAttributedComponents() -> [NSAttributedString] {
guard let source = self.dataSource else { return [] }
var attributedPairs = self.attributedPairs(for: instruction, dataSource: source, imageRepository: imageRepository, onImageDownload: completeShieldDownload)
let availableBounds = source.availableBounds()
let totalWidth: CGFloat = attributedPairs.attributedStrings.map { $0.size() }.reduce(.zero, +).width
let stringFits = totalWidth <= availableBounds.width
guard !stringFits else { return attributedPairs.attributedStrings }
let indexedComponents: [IndexedVisualInstructionComponent] = attributedPairs.components.enumerated().map { IndexedVisualInstructionComponent(component: $1, index: $0) }
let filtered = indexedComponents.filter { $0.component.abbreviation != nil }
let sorted = filtered.sorted { $0.component.abbreviationPriority < $1.component.abbreviationPriority }
for component in sorted {
let isFirst = component.index == 0
let joinChar = isFirst ? "" : " "
guard component.component.type == .text else { continue }
guard let abbreviation = component.component.abbreviation else { continue }
attributedPairs.attributedStrings[component.index] = NSAttributedString(string: joinChar + abbreviation, attributes: attributes(for: source))
let newWidth: CGFloat = attributedPairs.attributedStrings.map { $0.size() }.reduce(.zero, +).width
if newWidth <= availableBounds.width {
break
}
}
return attributedPairs.attributedStrings
}
typealias AttributedInstructionComponents = (components: [VisualInstructionComponent], attributedStrings: [NSAttributedString])
func attributedPairs(for instruction: VisualInstruction, dataSource: DataSource, imageRepository: ImageRepository, onImageDownload: @escaping ImageDownloadCompletion) -> AttributedInstructionComponents {
let components = instruction.components.compactMap { $0 as? VisualInstructionComponent }
var strings: [NSAttributedString] = []
var processedComponents: [VisualInstructionComponent] = []
for (index, component) in components.enumerated() {
let isFirst = index == 0
let joinChar = isFirst ? "" : " "
let joinString = NSAttributedString(string: joinChar, attributes: attributes(for: dataSource))
let initial = NSAttributedString()
//This is the closure that builds the string.
let build: (_: VisualInstructionComponent, _: [NSAttributedString]) -> Void = { (component, attributedStrings) in
processedComponents.append(component)
strings.append(attributedStrings.reduce(initial, +))
}
let isShield: (_: VisualInstructionComponent?) -> Bool = { (component) in
guard let key = component?.cacheKey else { return false }
return imageRepository.cachedImageForKey(key) != nil
}
let componentBefore = components.component(before: component)
let componentAfter = components.component(after: component)
switch component.type {
//Throw away exit components. We know this is safe because we know that if there is an exit component,
// there is an exit code component, and the latter contains the information we care about.
case .exit:
continue
//If we have a exit, in the first two components, lets handle that.
case .exitCode where 0...1 ~= index:
guard let exitString = self.attributedString(forExitComponent: component, maneuverDirection: instruction.maneuverDirection, dataSource: dataSource) else { fallthrough }
build(component, [exitString])
//if it's a delimiter, skip it if it's between two shields.
case .delimiter where isShield(componentBefore) && isShield(componentAfter):
continue
//If we have an icon component, lets turn it into a shield.
case .image:
if let shieldString = attributedString(forShieldComponent: component, repository: imageRepository, dataSource: dataSource, onImageDownload: onImageDownload) {
build(component, [joinString, shieldString])
} else if let genericShieldString = attributedString(forGenericShield: component, dataSource: dataSource) {
build(component, [joinString, genericShieldString])
} else {
fallthrough
}
//Otherwise, process as text component.
default:
guard let componentString = attributedString(forTextComponent: component, dataSource: dataSource) else { continue }
build(component, [joinString, componentString])
}
}
assert(processedComponents.count == strings.count, "The number of processed components must match the number of attributed strings")
return (components: processedComponents, attributedStrings: strings)
}
func attributedString(forExitComponent component: VisualInstructionComponent, maneuverDirection: ManeuverDirection, dataSource: DataSource) -> NSAttributedString? {
guard component.type == .exitCode, let exitCode = component.text else { return nil }
let side: ExitSide = maneuverDirection == .left ? .left : .right
guard let exitString = exitShield(side: side, text: exitCode, component: component, dataSource: dataSource) else { return nil }
return exitString
}
func attributedString(forGenericShield component: VisualInstructionComponent, dataSource: DataSource) -> NSAttributedString? {
guard component.type == .image, let text = component.text else { return nil }
return genericShield(text: text, component: component, dataSource: dataSource)
}
func attributedString(forShieldComponent shield: VisualInstructionComponent, repository:ImageRepository, dataSource: DataSource, onImageDownload: @escaping ImageDownloadCompletion) -> NSAttributedString? {
guard shield.imageURL != nil, let shieldKey = shield.cacheKey else { return nil }
//If we have the shield already cached, use that.
if let cachedImage = repository.cachedImageForKey(shieldKey) {
return attributedString(withFont: dataSource.font, shieldImage: cachedImage)
}
// Let's download the shield
shieldImageForComponent(shield, in: repository, completion: onImageDownload)
//Return nothing in the meantime, triggering downstream behavior (generic shield or text)
return nil
}
func attributedString(forTextComponent component: VisualInstructionComponent, dataSource: DataSource) -> NSAttributedString? {
guard let text = component.text else { return nil }
return NSAttributedString(string: text, attributes: attributes(for: dataSource))
}
private func shieldImageForComponent(_ component: VisualInstructionComponent, in repository: ImageRepository, completion: @escaping ImageDownloadCompletion) {
guard let imageURL = component.imageURL, let shieldKey = component.cacheKey else {
return
}
repository.imageWithURL(imageURL, cacheKey: shieldKey, completion: completion )
}
private func attributes(for dataSource: InstructionPresenterDataSource) -> [NSAttributedString.Key: Any] {
return [.font: dataSource.font as Any, .foregroundColor: dataSource.textColor as Any]
}
private func attributedString(withFont font: UIFont, shieldImage: UIImage) -> NSAttributedString {
let attachment = ShieldAttachment()
attachment.font = font
attachment.image = shieldImage
return NSAttributedString(attachment: attachment)
}
private func genericShield(text: String, component: VisualInstructionComponent, dataSource: DataSource) -> NSAttributedString? {
guard let cacheKey = component.cacheKey else { return nil }
let additionalKey = GenericRouteShield.criticalHash(dataSource: dataSource)
let attachment = GenericShieldAttachment()
let key = [cacheKey, additionalKey].joined(separator: "-")
if let image = imageRepository.cachedImageForKey(key) {
attachment.image = image
} else {
let view = GenericRouteShield(pointSize: dataSource.font.pointSize, text: text)
guard let image = takeSnapshot(on: view) else { return nil }
imageRepository.storeImage(image, forKey: key, toDisk: false)
attachment.image = image
}
attachment.font = dataSource.font
return NSAttributedString(attachment: attachment)
}
private func exitShield(side: ExitSide = .right, text: String, component: VisualInstructionComponent, dataSource: DataSource) -> NSAttributedString? {
guard let cacheKey = component.cacheKey else { return nil }
let additionalKey = ExitView.criticalHash(side: side, dataSource: dataSource)
let attachment = ExitAttachment()
let key = [cacheKey, additionalKey].joined(separator: "-")
if let image = imageRepository.cachedImageForKey(key) {
attachment.image = image
} else {
let view = ExitView(pointSize: dataSource.font.pointSize, side: side, text: text)
guard let image = takeSnapshot(on: view) else { return nil }
imageRepository.storeImage(image, forKey: key, toDisk: false)
attachment.image = image
}
attachment.font = dataSource.font
return NSAttributedString(attachment: attachment)
}
private func completeShieldDownload(_ image: UIImage?) {
guard image != nil else { return }
//We *must* be on main thread here, because attributedText() looks at object properties only accessible on main thread.
DispatchQueue.main.async {
self.onShieldDownload?(self.attributedText()) //FIXME: Can we work with the image directly?
}
}
private func takeSnapshot(on view: UIView) -> UIImage? {
let window: UIWindow
if let hostView = dataSource as? UIView, let hostWindow = hostView.window {
window = hostWindow
} else {
window = UIApplication.shared.delegate!.window!!
}
// Temporarily add the view to the view hierarchy for UIAppearance to work its magic.
window.addSubview(view)
let image = view.imageRepresentation
view.removeFromSuperview()
return image
}
}
protocol ImagePresenter: TextPresenter {
var image: UIImage? { get }
}
protocol TextPresenter {
var text: String? { get }
var font: UIFont { get }
}
class ImageInstruction: NSTextAttachment, ImagePresenter {
var font: UIFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)
var text: String?
override func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
guard let image = image else {
return super.attachmentBounds(for: textContainer, proposedLineFragment: lineFrag, glyphPosition: position, characterIndex: charIndex)
}
let yOrigin = (font.capHeight - image.size.height).rounded() / 2
return CGRect(x: 0, y: yOrigin, width: image.size.width, height: image.size.height)
}
}
class TextInstruction: ImageInstruction {}
class ShieldAttachment: ImageInstruction {}
class GenericShieldAttachment: ShieldAttachment {}
class ExitAttachment: ImageInstruction {}
class RoadNameLabelAttachment: TextInstruction {
var scale: CGFloat?
var color: UIColor?
var compositeImage: UIImage? {
guard let image = image, let text = text, let color = color, let scale = scale else {
return nil
}
var currentImage: UIImage?
let textHeight = font.lineHeight
let pointY = (image.size.height - textHeight) / 2
currentImage = image.insert(text: text as NSString, color: color, font: font, atPoint: CGPoint(x: 0, y: pointY), scale: scale)
return currentImage
}
convenience init(image: UIImage, text: String, color: UIColor, font: UIFont, scale: CGFloat) {
self.init()
self.image = image
self.font = font
self.text = text
self.color = color
self.scale = scale
self.image = compositeImage ?? image
}
}
extension CGSize {
fileprivate static func +(lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height)
}
}
fileprivate struct IndexedVisualInstructionComponent {
let component: Array<VisualInstructionComponent>.Element
let index: Array<VisualInstructionComponent>.Index
}
extension Array where Element == VisualInstructionComponent {
fileprivate func component(before component: VisualInstructionComponent) -> VisualInstructionComponent? {
guard let index = self.firstIndex(of: component) else {
return nil
}
if index > 0 {
return self[index-1]
}
return nil
}
fileprivate func component(after component: VisualInstructionComponent) -> VisualInstructionComponent? {
guard let index = self.firstIndex(of: component) else {
return nil
}
if index+1 < self.endIndex {
return self[index+1]
}
return nil
}
}
| 45.41791 | 209 | 0.666645 |
1ef0bfe50d01b95b1282bc28683f3a10c4dd9792
| 1,007 |
//
// ASRRequest.swift
// NuguAgents
//
// Created by MinChul Lee on 13/05/2019.
// Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import NuguCore
struct ASRRequest {
let contextPayload: [ContextInfo]
let eventIdentifier: EventIdentifier
let initiator: ASRInitiator
let options: ASROptions
let referrerDialogRequestId: String?
let completion: ((StreamDataState) -> Void)?
}
| 30.515152 | 76 | 0.724926 |
9cd7e92ca09a3ab72f9c8415f0dc2e6ad2c4d10a
| 1,787 |
// Copyright 2017 The xi-editor Authors.
//
// 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
//
// https://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
/// A safe wrapper around a system lock, also suitable as a superclass
/// for objects that hold state protected by the lock.
class UnfairLock {
fileprivate var _lock = os_unfair_lock_s()
fileprivate var _fallback = pthread_mutex_t()
init() {
if #available(OSX 10.12, *) {
// noop
} else {
pthread_mutex_init(&_fallback, nil)
}
}
deinit {
if #available(OSX 10.12, *) {
// noop
} else {
pthread_mutex_destroy(&_fallback)
}
}
func lock() {
if #available(OSX 10.12, *) {
os_unfair_lock_lock(&_lock)
} else {
pthread_mutex_lock(&_fallback)
}
}
func unlock() {
if #available(OSX 10.12, *) {
os_unfair_lock_unlock(&_lock)
} else {
pthread_mutex_unlock(&_fallback)
}
}
/// Tries to take the lock. Returns `true` if successful.
func tryLock() -> Bool {
if #available(OSX 10.12, *) {
return os_unfair_lock_trylock(&_lock)
} else {
return pthread_mutex_trylock(&_fallback) == 0
}
}
}
| 27.921875 | 75 | 0.607163 |
f491bafe7bed7c5b7fa74b485fe25eed727df9ed
| 1,578 |
//
// UserActivity.swift
// Armore
//
// Created by Dario Talarico on 1/29/20.
// Copyright © 2020 Security Union. All rights reserved.
//
import Foundation
let OnVerificationCodeNotif = "Verification"
let OnInvitationNotif = "Invitation"
let notifications = [
OnVerificationCodeNotif
]
protocol UserActivity {
func notificationName() -> NSNotification.Name
}
struct Verification: UserActivity {
func notificationName() -> NSNotification.Name {
NSNotification.Name(rawValue: OnVerificationCodeNotif)
}
let code: String
}
struct InvitationIntent: UserActivity {
func notificationName() -> NSNotification.Name {
NSNotification.Name(rawValue: OnInvitationNotif)
}
let invitationId: String
}
class UserActivityParser {
static func parseUrl(url: URL?) -> UserActivity? {
url.flatMap { urlToParse in
switch urlToParse {
case _ where urlToParse.pathComponents.filter {
$0.contains("verify")
}.count > 0:
return Verification(code: urlToParse.lastPathComponent)
case _ where urlToParse.absoluteString.contains("invitations") && urlToParse.lastPathComponent.count > 3:
return InvitationIntent(invitationId: urlToParse.lastPathComponent)
default:
return nil
}
}
}
static func notificationFromUrl(url: URL?) -> Notification? {
parseUrl(url: url).flatMap {
Notification(name: $0.notificationName(), object: $0, userInfo: nil)
}
}
}
| 26.3 | 117 | 0.653359 |
89eac47037c6a9ec8ccb68a38244ba290de908ff
| 2,406 |
//
// UPnPActionInvoke.swift
//
import Foundation
/**
UPnP Action Invoke
*/
public class UPnPActionInvoke {
/**
action invoke completion handler
- Parameter upnp soap response
- Parameter error
*/
public typealias invokeCompletionHandler = ((UPnPSoapResponse?, Error?) -> Void)
/**
url to request
*/
public var url: URL
/**
soap request
*/
public var soapRequest: UPnPSoapRequest
/**
complete handler
*/
public var completionHandler: (invokeCompletionHandler)?
public init(url: URL, soapRequest: UPnPSoapRequest, completionHandler: (invokeCompletionHandler)?) {
self.url = url
self.soapRequest = soapRequest
self.completionHandler = completionHandler
}
/**
Invoke Action
*/
public func invoke() {
let data = soapRequest.xmlDocument.data(using: .utf8)
var fields = [KeyValuePair]()
fields.append(KeyValuePair(key: "SOAPACTION", value: "\"\(soapRequest.soapaction)\""))
HttpClient(url: url, method: "POST", data: data, contentType: "text/xml", fields: fields) {
(data, response, error) in
guard error == nil else {
self.completionHandler?(nil, UPnPError.custom(string: "error - \(error!)"))
return
}
guard getStatusCodeRange(response: response) == .success else {
self.completionHandler?(nil, HttpError.notSuccess(code: getStatusCode(response: response, defaultValue: 0)))
return
}
guard let data = data else {
self.completionHandler?(nil, UPnPError.custom(string: "no data"))
return
}
guard let text = String(data: data, encoding: .utf8) else {
self.completionHandler?(nil, UPnPError.custom(string: "not string"))
return
}
do {
guard let soapResponse = try UPnPSoapResponse.read(xmlString: text) else {
self.completionHandler?(nil, UPnPError.custom(string: "not soap response -- \(text)"))
return
}
self.completionHandler?(soapResponse, nil)
} catch {
self.completionHandler?(nil, UPnPError.custom(string: "\(error)"))
}
}.start()
}
}
| 30.846154 | 124 | 0.569825 |
019923b0153fe3ebe44d6f98689e13146a68d765
| 60,091 |
// 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
//
import CoreFoundation
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
#if os(macOS) || os(iOS)
internal let kCFURLPOSIXPathStyle = CFURLPathStyle.cfurlposixPathStyle
internal let kCFURLWindowsPathStyle = CFURLPathStyle.cfurlWindowsPathStyle
#endif
private func _standardizedPath(_ path: String) -> String {
if !path.absolutePath {
return path._nsObject.standardizingPath
}
return path
}
internal func _pathComponents(_ path: String?) -> [String]? {
guard let p = path else {
return nil
}
var result = [String]()
if p.length == 0 {
return result
} else {
let characterView = p
var curPos = characterView.startIndex
let endPos = characterView.endIndex
if characterView[curPos] == "/" {
result.append("/")
}
while curPos < endPos {
while curPos < endPos && characterView[curPos] == "/" {
curPos = characterView.index(after: curPos)
}
if curPos == endPos {
break
}
var curEnd = curPos
while curEnd < endPos && characterView[curEnd] != "/" {
curEnd = characterView.index(after: curEnd)
}
result.append(String(characterView[curPos ..< curEnd]))
curPos = curEnd
}
}
if p.length > 1 && p.hasSuffix("/") {
result.append("/")
}
return result
}
public struct URLResourceKey : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: URLResourceKey, rhs: URLResourceKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension URLResourceKey {
public static let keysOfUnsetValuesKey = URLResourceKey(rawValue: "NSURLKeysOfUnsetValuesKey")
public static let nameKey = URLResourceKey(rawValue: "NSURLNameKey")
public static let localizedNameKey = URLResourceKey(rawValue: "NSURLLocalizedNameKey")
public static let isRegularFileKey = URLResourceKey(rawValue: "NSURLIsRegularFileKey")
public static let isDirectoryKey = URLResourceKey(rawValue: "NSURLIsDirectoryKey")
public static let isSymbolicLinkKey = URLResourceKey(rawValue: "NSURLIsSymbolicLinkKey")
public static let isVolumeKey = URLResourceKey(rawValue: "NSURLIsVolumeKey")
public static let isPackageKey = URLResourceKey(rawValue: "NSURLIsPackageKey")
public static let isApplicationKey = URLResourceKey(rawValue: "NSURLIsApplicationKey")
public static let applicationIsScriptableKey = URLResourceKey(rawValue: "NSURLApplicationIsScriptableKey")
public static let isSystemImmutableKey = URLResourceKey(rawValue: "NSURLIsSystemImmutableKey")
public static let isUserImmutableKey = URLResourceKey(rawValue: "NSURLIsUserImmutableKey")
public static let isHiddenKey = URLResourceKey(rawValue: "NSURLIsHiddenKey")
public static let hasHiddenExtensionKey = URLResourceKey(rawValue: "NSURLHasHiddenExtensionKey")
public static let creationDateKey = URLResourceKey(rawValue: "NSURLCreationDateKey")
public static let contentAccessDateKey = URLResourceKey(rawValue: "NSURLContentAccessDateKey")
public static let contentModificationDateKey = URLResourceKey(rawValue: "NSURLContentModificationDateKey")
public static let attributeModificationDateKey = URLResourceKey(rawValue: "NSURLAttributeModificationDateKey")
public static let linkCountKey = URLResourceKey(rawValue: "NSURLLinkCountKey")
public static let parentDirectoryURLKey = URLResourceKey(rawValue: "NSURLParentDirectoryURLKey")
public static let volumeURLKey = URLResourceKey(rawValue: "NSURLVolumeURLKey")
public static let typeIdentifierKey = URLResourceKey(rawValue: "NSURLTypeIdentifierKey")
public static let localizedTypeDescriptionKey = URLResourceKey(rawValue: "NSURLLocalizedTypeDescriptionKey")
public static let labelNumberKey = URLResourceKey(rawValue: "NSURLLabelNumberKey")
public static let labelColorKey = URLResourceKey(rawValue: "NSURLLabelColorKey")
public static let localizedLabelKey = URLResourceKey(rawValue: "NSURLLocalizedLabelKey")
public static let effectiveIconKey = URLResourceKey(rawValue: "NSURLEffectiveIconKey")
public static let customIconKey = URLResourceKey(rawValue: "NSURLCustomIconKey")
public static let fileResourceIdentifierKey = URLResourceKey(rawValue: "NSURLFileResourceIdentifierKey")
public static let volumeIdentifierKey = URLResourceKey(rawValue: "NSURLVolumeIdentifierKey")
public static let preferredIOBlockSizeKey = URLResourceKey(rawValue: "NSURLPreferredIOBlockSizeKey")
public static let isReadableKey = URLResourceKey(rawValue: "NSURLIsReadableKey")
public static let isWritableKey = URLResourceKey(rawValue: "NSURLIsWritableKey")
public static let isExecutableKey = URLResourceKey(rawValue: "NSURLIsExecutableKey")
public static let fileSecurityKey = URLResourceKey(rawValue: "NSURLFileSecurityKey")
public static let isExcludedFromBackupKey = URLResourceKey(rawValue: "NSURLIsExcludedFromBackupKey")
public static let tagNamesKey = URLResourceKey(rawValue: "NSURLTagNamesKey")
public static let pathKey = URLResourceKey(rawValue: "NSURLPathKey")
public static let canonicalPathKey = URLResourceKey(rawValue: "NSURLCanonicalPathKey")
public static let isMountTriggerKey = URLResourceKey(rawValue: "NSURLIsMountTriggerKey")
public static let generationIdentifierKey = URLResourceKey(rawValue: "NSURLGenerationIdentifierKey")
public static let documentIdentifierKey = URLResourceKey(rawValue: "NSURLDocumentIdentifierKey")
public static let addedToDirectoryDateKey = URLResourceKey(rawValue: "NSURLAddedToDirectoryDateKey")
public static let quarantinePropertiesKey = URLResourceKey(rawValue: "NSURLQuarantinePropertiesKey")
public static let fileResourceTypeKey = URLResourceKey(rawValue: "NSURLFileResourceTypeKey")
public static let thumbnailDictionaryKey = URLResourceKey(rawValue: "NSURLThumbnailDictionaryKey")
public static let thumbnailKey = URLResourceKey(rawValue: "NSURLThumbnailKey")
public static let fileSizeKey = URLResourceKey(rawValue: "NSURLFileSizeKey")
public static let fileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLFileAllocatedSizeKey")
public static let totalFileSizeKey = URLResourceKey(rawValue: "NSURLTotalFileSizeKey")
public static let totalFileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLTotalFileAllocatedSizeKey")
public static let isAliasFileKey = URLResourceKey(rawValue: "NSURLIsAliasFileKey")
public static let volumeLocalizedFormatDescriptionKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedFormatDescriptionKey")
public static let volumeTotalCapacityKey = URLResourceKey(rawValue: "NSURLVolumeTotalCapacityKey")
public static let volumeAvailableCapacityKey = URLResourceKey(rawValue: "NSURLVolumeAvailableCapacityKey")
public static let volumeResourceCountKey = URLResourceKey(rawValue: "NSURLVolumeResourceCountKey")
public static let volumeSupportsPersistentIDsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsPersistentIDsKey")
public static let volumeSupportsSymbolicLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSymbolicLinksKey")
public static let volumeSupportsHardLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsHardLinksKey")
public static let volumeSupportsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsJournalingKey")
public static let volumeIsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeIsJournalingKey")
public static let volumeSupportsSparseFilesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSparseFilesKey")
public static let volumeSupportsZeroRunsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsZeroRunsKey")
public static let volumeSupportsCaseSensitiveNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCaseSensitiveNamesKey")
public static let volumeSupportsCasePreservedNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCasePreservedNamesKey")
public static let volumeSupportsRootDirectoryDatesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRootDirectoryDatesKey")
public static let volumeSupportsVolumeSizesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsVolumeSizesKey")
public static let volumeSupportsRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRenamingKey")
public static let volumeSupportsAdvisoryFileLockingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsAdvisoryFileLockingKey")
public static let volumeSupportsExtendedSecurityKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExtendedSecurityKey")
public static let volumeIsBrowsableKey = URLResourceKey(rawValue: "NSURLVolumeIsBrowsableKey")
public static let volumeMaximumFileSizeKey = URLResourceKey(rawValue: "NSURLVolumeMaximumFileSizeKey")
public static let volumeIsEjectableKey = URLResourceKey(rawValue: "NSURLVolumeIsEjectableKey")
public static let volumeIsRemovableKey = URLResourceKey(rawValue: "NSURLVolumeIsRemovableKey")
public static let volumeIsInternalKey = URLResourceKey(rawValue: "NSURLVolumeIsInternalKey")
public static let volumeIsAutomountedKey = URLResourceKey(rawValue: "NSURLVolumeIsAutomountedKey")
public static let volumeIsLocalKey = URLResourceKey(rawValue: "NSURLVolumeIsLocalKey")
public static let volumeIsReadOnlyKey = URLResourceKey(rawValue: "NSURLVolumeIsReadOnlyKey")
public static let volumeCreationDateKey = URLResourceKey(rawValue: "NSURLVolumeCreationDateKey")
public static let volumeURLForRemountingKey = URLResourceKey(rawValue: "NSURLVolumeURLForRemountingKey")
public static let volumeUUIDStringKey = URLResourceKey(rawValue: "NSURLVolumeUUIDStringKey")
public static let volumeNameKey = URLResourceKey(rawValue: "NSURLVolumeNameKey")
public static let volumeLocalizedNameKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedNameKey")
public static let volumeIsEncryptedKey = URLResourceKey(rawValue: "NSURLVolumeIsEncryptedKey")
public static let volumeIsRootFileSystemKey = URLResourceKey(rawValue: "NSURLVolumeIsRootFileSystemKey")
public static let volumeSupportsCompressionKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCompressionKey")
public static let volumeSupportsFileCloningKey = URLResourceKey(rawValue: "NSURLVolumeSupportsFileCloningKey")
public static let volumeSupportsSwapRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSwapRenamingKey")
public static let volumeSupportsExclusiveRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExclusiveRenamingKey")
public static let isUbiquitousItemKey = URLResourceKey(rawValue: "NSURLIsUbiquitousItemKey")
public static let ubiquitousItemHasUnresolvedConflictsKey = URLResourceKey(rawValue: "NSURLUbiquitousItemHasUnresolvedConflictsKey")
public static let ubiquitousItemIsDownloadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsDownloadingKey")
public static let ubiquitousItemIsUploadedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadedKey")
public static let ubiquitousItemIsUploadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadingKey")
public static let ubiquitousItemDownloadingStatusKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingStatusKey")
public static let ubiquitousItemDownloadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingErrorKey")
public static let ubiquitousItemUploadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemUploadingErrorKey")
public static let ubiquitousItemDownloadRequestedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadRequestedKey")
public static let ubiquitousItemContainerDisplayNameKey = URLResourceKey(rawValue: "NSURLUbiquitousItemContainerDisplayNameKey")
}
public struct URLFileResourceType : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(lhs: URLFileResourceType, rhs: URLFileResourceType) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension URLFileResourceType {
public static let namedPipe = URLFileResourceType(rawValue: "NSURLFileResourceTypeNamedPipe")
public static let characterSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeCharacterSpecial")
public static let directory = URLFileResourceType(rawValue: "NSURLFileResourceTypeDirectory")
public static let blockSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeBlockSpecial")
public static let regular = URLFileResourceType(rawValue: "NSURLFileResourceTypeRegular")
public static let symbolicLink = URLFileResourceType(rawValue: "NSURLFileResourceTypeSymbolicLink")
public static let socket = URLFileResourceType(rawValue: "NSURLFileResourceTypeSocket")
public static let unknown = URLFileResourceType(rawValue: "NSURLFileResourceTypeUnknown")
}
open class NSURL : NSObject, NSSecureCoding, NSCopying {
typealias CFType = CFURL
internal var _base = _CFInfo(typeID: CFURLGetTypeID())
internal var _flags : UInt32 = 0
internal var _encoding : CFStringEncoding = 0
internal var _string : UnsafeMutablePointer<CFString>? = nil
internal var _baseURL : UnsafeMutablePointer<CFURL>? = nil
internal var _extra : OpaquePointer? = nil
internal var _resourceInfo : OpaquePointer? = nil
internal var _range1 = NSRange(location: 0, length: 0)
internal var _range2 = NSRange(location: 0, length: 0)
internal var _range3 = NSRange(location: 0, length: 0)
internal var _range4 = NSRange(location: 0, length: 0)
internal var _range5 = NSRange(location: 0, length: 0)
internal var _range6 = NSRange(location: 0, length: 0)
internal var _range7 = NSRange(location: 0, length: 0)
internal var _range8 = NSRange(location: 0, length: 0)
internal var _range9 = NSRange(location: 0, length: 0)
internal var _cfObject : CFType {
if type(of: self) === NSURL.self {
return unsafeBitCast(self, to: CFType.self)
} else {
return CFURLCreateWithString(kCFAllocatorSystemDefault, relativeString._cfObject, self.baseURL?._cfObject)
}
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURL else { return false }
return CFEqual(_cfObject, other._cfObject)
}
open override var description: String {
if self.relativeString != self.absoluteString {
return "\(self.relativeString) -- \(self.baseURL!)"
} else {
return self.absoluteString
}
}
deinit {
_CFDeinit(self)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool { return true }
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let base = aDecoder.decodeObject(of: NSURL.self, forKey:"NS.base")?._swiftObject
let relative = aDecoder.decodeObject(of: NSString.self, forKey:"NS.relative")
if relative == nil {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(relative!), relativeTo: base)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.baseURL?._nsObject, forKey:"NS.base")
aCoder.encode(self.relativeString._bridgeToObjectiveC(), forKey:"NS.relative")
}
public init(fileURLWithPath path: String, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
super.init()
let thePath = _standardizedPath(path)
if thePath.length > 0 {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir, baseURL?._cfObject)
} else if let baseURL = baseURL {
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, baseURL.path._cfObject, kCFURLPOSIXPathStyle, baseURL.hasDirectoryPath, nil)
}
}
public convenience init(fileURLWithPath path: String, relativeTo baseURL: URL?) {
let thePath = _standardizedPath(path)
var isDir: ObjCBool = false
if thePath.hasSuffix("/") {
isDir = true
} else {
let absolutePath: String
if let absPath = baseURL?.appendingPathComponent(path).path {
absolutePath = absPath
} else {
absolutePath = path
}
let _ = FileManager.default.fileExists(atPath: absolutePath, isDirectory: &isDir)
}
self.init(fileURLWithPath: thePath, isDirectory: isDir.boolValue, relativeTo: baseURL)
}
public convenience init(fileURLWithPath path: String, isDirectory isDir: Bool) {
self.init(fileURLWithPath: path, isDirectory: isDir, relativeTo: nil)
}
public init(fileURLWithPath path: String) {
let thePath: String
let pathString = NSString(string: path)
if !pathString.isAbsolutePath {
thePath = pathString.standardizingPath
} else {
thePath = path
}
var isDir: ObjCBool = false
if thePath.hasSuffix("/") {
isDir = true
} else {
if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) {
isDir = false
}
}
super.init()
_CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir.boolValue, nil)
}
public convenience init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
let pathString = String(cString: path)
self.init(fileURLWithPath: pathString, isDirectory: isDir, relativeTo: baseURL)
}
public convenience init?(string URLString: String) {
self.init(string: URLString, relativeTo:nil)
}
public init?(string URLString: String, relativeTo baseURL: URL?) {
super.init()
if !_CFURLInitWithURLString(_cfObject, URLString._cfObject, true, baseURL?._cfObject) {
return nil
}
}
public init(dataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
// _CFURLInitWithURLString does not fail if checkForLegalCharacters == false
data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), false) {
_CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject)
} else {
fatalError()
}
}
}
public init(absoluteURLWithDataRepresentation data: Data, relativeTo baseURL: URL?) {
super.init()
data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), baseURL?._cfObject) {
return
}
if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), baseURL?._cfObject) {
return
}
fatalError()
}
}
/* Returns the data representation of the URL's relativeString. If the URL was initialized with -initWithData:relativeTo:, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the relativeString encoded with NSUTF8StringEncoding.
*/
open var dataRepresentation: Data {
let bytesNeeded = CFURLGetBytes(_cfObject, nil, 0)
assert(bytesNeeded > 0)
let buffer = malloc(bytesNeeded)!.bindMemory(to: UInt8.self, capacity: bytesNeeded)
let bytesFilled = CFURLGetBytes(_cfObject, buffer, bytesNeeded)
if bytesFilled == bytesNeeded {
return Data(bytesNoCopy: buffer, count: bytesNeeded, deallocator: .free)
} else {
fatalError()
}
}
open var absoluteString: String {
if let absURL = CFURLCopyAbsoluteURL(_cfObject) {
return CFURLGetString(absURL)._swiftObject
}
return CFURLGetString(_cfObject)._swiftObject
}
// The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString
open var relativeString: String {
return CFURLGetString(_cfObject)._swiftObject
}
open var baseURL: URL? {
return CFURLGetBaseURL(_cfObject)?._swiftObject
}
// if the receiver is itself absolute, this will return self.
open var absoluteURL: URL? {
return CFURLCopyAbsoluteURL(_cfObject)?._swiftObject
}
/* Any URL is composed of these two basic pieces. The full URL would be the concatenation of [myURL scheme], ':', [myURL resourceSpecifier]
*/
open var scheme: String? {
return CFURLCopyScheme(_cfObject)?._swiftObject
}
internal var _isAbsolute : Bool {
return self.baseURL == nil && self.scheme != nil
}
open var resourceSpecifier: String? {
// Note that this does NOT have the same meaning as CFURL's resource specifier, which, for decomposeable URLs is merely that portion of the URL which comes after the path. NSURL means everything after the scheme.
if !_isAbsolute {
return self.relativeString
} else {
let cf = _cfObject
guard CFURLCanBeDecomposed(cf) else {
return CFURLCopyResourceSpecifier(cf)?._swiftObject
}
guard baseURL == nil else {
return CFURLGetString(cf)?._swiftObject
}
let netLoc = CFURLCopyNetLocation(cf)?._swiftObject
let path = CFURLCopyPath(cf)?._swiftObject
let theRest = CFURLCopyResourceSpecifier(cf)?._swiftObject
if let netLoc = netLoc {
let p = path ?? ""
let rest = theRest ?? ""
return "//\(netLoc)\(p)\(rest)"
} else if let path = path {
let rest = theRest ?? ""
return "\(path)\(rest)"
} else {
return theRest
}
}
}
/* If the URL conforms to rfc 1808 (the most common form of URL), the following accessors will return the various components; otherwise they return nil. The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is @"//". In all cases, they return the component's value after resolving the receiver against its base URL.
*/
open var host: String? {
return CFURLCopyHostName(_cfObject)?._swiftObject
}
open var port: NSNumber? {
let port = CFURLGetPortNumber(_cfObject)
if port == -1 {
return nil
} else {
return NSNumber(value: port)
}
}
open var user: String? {
return CFURLCopyUserName(_cfObject)?._swiftObject
}
open var password: String? {
let absoluteURL = CFURLCopyAbsoluteURL(_cfObject)
#if os(Linux) || os(Android) || CYGWIN
let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, kCFURLComponentPassword, nil)
#else
let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, .password, nil)
#endif
guard passwordRange.location != kCFNotFound else {
return nil
}
// For historical reasons, the password string should _not_ have its percent escapes removed.
let bufSize = CFURLGetBytes(absoluteURL, nil, 0)
var buf = [UInt8](repeating: 0, count: bufSize)
guard CFURLGetBytes(absoluteURL, &buf, bufSize) >= 0 else {
return nil
}
let passwordBuf = buf[passwordRange.location ..< passwordRange.location+passwordRange.length]
return passwordBuf.withUnsafeBufferPointer { ptr in
NSString(bytes: ptr.baseAddress!, length: passwordBuf.count, encoding: String.Encoding.utf8.rawValue)?._swiftObject
}
}
open var path: String? {
let absURL = CFURLCopyAbsoluteURL(_cfObject)
return CFURLCopyFileSystemPath(absURL, kCFURLPOSIXPathStyle)?._swiftObject
}
open var fragment: String? {
return CFURLCopyFragment(_cfObject, nil)?._swiftObject
}
open var parameterString: String? {
return CFURLCopyParameterString(_cfObject, nil)?._swiftObject
}
open var query: String? {
return CFURLCopyQueryString(_cfObject, nil)?._swiftObject
}
// The same as path if baseURL is nil
open var relativePath: String? {
return CFURLCopyFileSystemPath(_cfObject, kCFURLPOSIXPathStyle)?._swiftObject
}
/* Determines if a given URL string's path represents a directory (i.e. the path component in the URL string ends with a '/' character). This does not check the resource the URL refers to.
*/
open var hasDirectoryPath: Bool {
return CFURLHasDirectoryPath(_cfObject)
}
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding.
*/
open func getFileSystemRepresentation(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferLength: Int) -> Bool {
return buffer.withMemoryRebound(to: UInt8.self, capacity: maxBufferLength) {
CFURLGetFileSystemRepresentation(_cfObject, true, $0, maxBufferLength)
}
}
/* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength: if it needs to store the representation outside of the autorelease context in which the representation is created.
*/
// Memory leak. See https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/Issues.md
open var fileSystemRepresentation: UnsafePointer<Int8> {
let bufSize = Int(PATH_MAX + 1)
let _fsrBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: bufSize)
for i in 0..<bufSize {
_fsrBuffer.advanced(by: i).initialize(to: 0)
}
if getFileSystemRepresentation(_fsrBuffer, maxLength: bufSize) {
return UnsafePointer(_fsrBuffer)
}
// FIXME: This used to return nil, but the corresponding Darwin
// implementation is marked as non-nullable.
fatalError("URL cannot be expressed in the filesystem representation;" +
"use getFileSystemRepresentation to handle this case")
}
// Whether the scheme is file:; if myURL.isFileURL is true, then myURL.path is suitable for input into FileManager or NSPathUtilities.
open var isFileURL: Bool {
return _CFURLIsFileURL(_cfObject)
}
/* A string constant for the "file" URL scheme. If you are using this to compare to a URL's scheme to see if it is a file URL, you should instead use the NSURL fileURL property -- the fileURL property is much faster. */
open var standardized: URL? {
guard (path != nil) else {
return nil
}
let URLComponents = NSURLComponents(string: relativeString)
guard ((URLComponents != nil) && (URLComponents!.path != nil)) else {
return nil
}
guard (URLComponents!.path!.contains("..") || URLComponents!.path!.contains(".")) else{
return URLComponents!.url(relativeTo: baseURL)
}
URLComponents!.path! = _pathByRemovingDots(pathComponents!)
return URLComponents!.url(relativeTo: baseURL)
}
/* Returns whether the URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. If this method returns NO, the optional error is populated. This method is currently applicable only to URLs for file system resources. For other URL types, NO is returned. Symbol is present in iOS 4, but performs no operation.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
// TODO: should be `checkResourceIsReachableAndReturnError` with autoreleased error parameter.
// Currently Autoreleased pointers is not supported on Linux.
open func checkResourceIsReachable() throws -> Bool {
guard isFileURL,
let path = path else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileNoSuchFile.rawValue)
//return false
}
guard FileManager.default.fileExists(atPath: path) else {
throw NSError(domain: NSCocoaErrorDomain,
code: CocoaError.Code.fileReadNoSuchFile.rawValue,
userInfo: [
"NSURL" : self,
"NSFilePath" : path])
//return false
}
return true
}
/* Returns a file path URL that refers to the same resource as a specified URL. File path URLs use a file system style path. An error will occur if the url parameter is not a file URL. A file reference URL's resource must exist and be reachable to be converted to a file path URL. Symbol is present in iOS 4, but performs no operation.
*/
open var filePathURL: URL? {
guard isFileURL else {
return nil
}
return URL(string: absoluteString)
}
override open var _cfTypeID: CFTypeID {
return CFURLGetTypeID()
}
open func removeAllCachedResourceValues() { NSUnimplemented() }
open func removeCachedResourceValue(forKey key: URLResourceKey) { NSUnimplemented() }
open func resourceValues(forKeys keys: [URLResourceKey]) throws -> [URLResourceKey : Any] { NSUnimplemented() }
open func setResourceValue(_ value: Any?, forKey key: URLResourceKey) throws { NSUnimplemented() }
open func setResourceValues(_ keyedValues: [URLResourceKey : Any]) throws { NSUnimplemented() }
open func setTemporaryResourceValue(_ value: Any?, forKey key: URLResourceKey) { NSUnimplemented() }
}
extension NSCharacterSet {
// Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.
// Returns a character set containing the characters allowed in an URL's user subcomponent.
open class var urlUserAllowed: CharacterSet {
return _CFURLComponentsGetURLUserAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's password subcomponent.
open class var urlPasswordAllowed: CharacterSet {
return _CFURLComponentsGetURLPasswordAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's host subcomponent.
open class var urlHostAllowed: CharacterSet {
return _CFURLComponentsGetURLHostAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's path component. ';' is a legal path character, but it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet).
open class var urlPathAllowed: CharacterSet {
return _CFURLComponentsGetURLPathAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's query component.
open class var urlQueryAllowed: CharacterSet {
return _CFURLComponentsGetURLQueryAllowedCharacterSet()._swiftObject
}
// Returns a character set containing the characters allowed in an URL's fragment component.
open class var urlFragmentAllowed: CharacterSet {
return _CFURLComponentsGetURLFragmentAllowedCharacterSet()._swiftObject
}
}
extension NSString {
// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
open func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String? {
return _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, self._cfObject, allowedCharacters._cfObject)._swiftObject
}
// Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters.
open var removingPercentEncoding: String? {
return _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, self._cfObject)?._swiftObject
}
}
extension NSURL {
/* The following methods work on the path portion of a URL in the same manner that the NSPathUtilities methods on NSString do.
*/
open class func fileURL(withPathComponents components: [String]) -> URL? {
let path = NSString.pathWithComponents(components)
if components.last == "/" {
return URL(fileURLWithPath: path, isDirectory: true)
} else {
return URL(fileURLWithPath: path)
}
}
internal func _pathByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String? {
guard let p = path else {
return nil
}
if p == "/" {
return p
}
var result = p
if compress {
let startPos = result.startIndex
var endPos = result.endIndex
var curPos = startPos
while curPos < endPos {
if result[curPos] == "/" {
var afterLastSlashPos = curPos
while afterLastSlashPos < endPos && result[afterLastSlashPos] == "/" {
afterLastSlashPos = result.index(after: afterLastSlashPos)
}
if afterLastSlashPos != result.index(after: curPos) {
result.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"])
endPos = result.endIndex
}
curPos = afterLastSlashPos
} else {
curPos = result.index(after: curPos)
}
}
}
if stripTrailing && result.hasSuffix("/") {
result.remove(at: result.index(before: result.endIndex))
}
return result
}
open var pathComponents: [String]? {
return _pathComponents(path)
}
open var lastPathComponent: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return fixedSelf
}
return String(fixedSelf.suffix(from: fixedSelf._startOfLastPathComponent))
}
open var pathExtension: String? {
guard let fixedSelf = _pathByFixingSlashes() else {
return nil
}
if fixedSelf.length <= 1 {
return ""
}
if let extensionPos = fixedSelf._startOfPathExtension {
return String(fixedSelf.suffix(from: extensionPos))
} else {
return ""
}
}
open func appendingPathComponent(_ pathComponent: String) -> URL? {
var result : URL? = appendingPathComponent(pathComponent, isDirectory: false)
if !pathComponent.hasSuffix("/") && isFileURL {
if let urlWithoutDirectory = result {
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: urlWithoutDirectory.path, isDirectory: &isDir) && isDir.boolValue {
result = self.appendingPathComponent(pathComponent, isDirectory: true)
}
}
}
return result
}
open func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL? {
return CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, _cfObject, pathComponent._cfObject, isDirectory)?._swiftObject
}
open var deletingLastPathComponent: URL? {
return CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
open func appendingPathExtension(_ pathExtension: String) -> URL? {
return CFURLCreateCopyAppendingPathExtension(kCFAllocatorSystemDefault, _cfObject, pathExtension._cfObject)?._swiftObject
}
open var deletingPathExtension: URL? {
return CFURLCreateCopyDeletingPathExtension(kCFAllocatorSystemDefault, _cfObject)?._swiftObject
}
/* The following methods work only on `file:` scheme URLs; for non-`file:` scheme URLs, these methods return the URL unchanged.
*/
open var standardizingPath: URL? {
// Documentation says it should expand initial tilde, but it does't do this on OS X.
// In remaining cases it works just like URLByResolvingSymlinksInPath.
return resolvingSymlinksInPath
}
open var resolvingSymlinksInPath: URL? {
return _resolveSymlinksInPath(excludeSystemDirs: true)
}
internal func _resolveSymlinksInPath(excludeSystemDirs: Bool) -> URL? {
guard isFileURL else {
return URL(string: absoluteString)
}
guard let selfPath = path else {
return URL(string: absoluteString)
}
let absolutePath: String
if selfPath.hasPrefix("/") {
absolutePath = selfPath
} else {
let workingDir = FileManager.default.currentDirectoryPath
absolutePath = workingDir._bridgeToObjectiveC().appendingPathComponent(selfPath)
}
var components = URL(fileURLWithPath: absolutePath).pathComponents
guard !components.isEmpty else {
return URL(string: absoluteString)
}
var resolvedPath = components.removeFirst()
for component in components {
switch component {
case "", ".":
break
case "..":
resolvedPath = resolvedPath._bridgeToObjectiveC().deletingLastPathComponent
default:
resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component)
if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) {
resolvedPath = destination
}
}
}
// It might be a responsibility of NSURL(fileURLWithPath:). Check it.
var isExistingDirectory: ObjCBool = false
let _ = FileManager.default.fileExists(atPath: resolvedPath, isDirectory: &isExistingDirectory)
if excludeSystemDirs {
resolvedPath = resolvedPath._tryToRemovePathPrefix("/private") ?? resolvedPath
}
if isExistingDirectory.boolValue && !resolvedPath.hasSuffix("/") {
resolvedPath += "/"
}
return URL(fileURLWithPath: resolvedPath)
}
fileprivate func _pathByRemovingDots(_ comps: [String]) -> String {
var components = comps
if(components.last == "/") {
components.removeLast()
}
guard !components.isEmpty else {
return self.path!
}
let isAbsolutePath = components.first == "/"
var result : String = components.removeFirst()
for component in components {
switch component {
case ".":
break
case ".." where isAbsolutePath:
result = result._bridgeToObjectiveC().deletingLastPathComponent
default:
result = result._bridgeToObjectiveC().appendingPathComponent(component)
}
}
if(self.path!.hasSuffix("/")) {
result += "/"
}
return result
}
}
// NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property.
open class NSURLQueryItem : NSObject, NSSecureCoding, NSCopying {
public init(name: String, value: String?) {
self.name = name
self.value = value
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
public static var supportsSecureCoding: Bool {
return true
}
required public init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let encodedName = aDecoder.decodeObject(forKey: "NS.name") as! NSString
self.name = encodedName._swiftObject
let encodedValue = aDecoder.decodeObject(forKey: "NS.value") as? NSString
self.value = encodedValue?._swiftObject
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.name._bridgeToObjectiveC(), forKey: "NS.name")
aCoder.encode(self.value?._bridgeToObjectiveC(), forKey: "NS.value")
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLQueryItem else { return false }
return other === self
|| (other.name == self.name
&& other.value == self.value)
}
open let name: String
open let value: String?
}
open class NSURLComponents: NSObject, NSCopying {
private let _components : CFURLComponentsRef!
deinit {
if let component = _components {
__CFURLComponentsDeallocate(component)
}
}
open override func copy() -> Any {
return copy(with: nil)
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSURLComponents else { return false }
return self === other
|| (scheme == other.scheme
&& user == other.user
&& password == other.password
&& host == other.host
&& port == other.port
&& path == other.path
&& query == other.query
&& fragment == other.fragment)
}
open func copy(with zone: NSZone? = nil) -> Any {
let copy = NSURLComponents()
copy.scheme = self.scheme
copy.user = self.user
copy.password = self.password
copy.host = self.host
copy.port = self.port
copy.path = self.path
copy.query = self.query
copy.fragment = self.fragment
return copy
}
// Initialize a NSURLComponents with the components of a URL. If resolvingAgainstBaseURL is YES and url is a relative URL, the components of [url absoluteURL] are used. If the url string from the NSURL is malformed, nil is returned.
public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) {
_components = _CFURLComponentsCreateWithURL(kCFAllocatorSystemDefault, url._cfObject, resolve)
super.init()
if _components == nil {
return nil
}
}
// Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned.
public init?(string URLString: String) {
_components = _CFURLComponentsCreateWithString(kCFAllocatorSystemDefault, URLString._cfObject)
super.init()
if _components == nil {
return nil
}
}
public override init() {
_components = _CFURLComponentsCreate(kCFAllocatorSystemDefault)
}
// Returns a URL created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var url: URL? {
guard let result = _CFURLComponentsCopyURL(_components) else { return nil }
return unsafeBitCast(result, to: URL.self)
}
// Returns a URL created from the NSURLComponents relative to a base URL. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open func url(relativeTo baseURL: URL?) -> URL? {
if let componentString = string {
return URL(string: componentString, relativeTo: baseURL)
}
return nil
}
// Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned.
open var string: String? {
return _CFURLComponentsCopyString(_components)?._swiftObject
}
// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided.
// Getting these properties removes any percent encoding these components may have (if the component allows percent encoding). Setting these properties assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding).
// Attempting to set the scheme with an invalid scheme string will cause an exception.
open var scheme: String? {
get {
return _CFURLComponentsCopyScheme(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetScheme(_components, new?._cfObject) {
fatalError()
}
}
}
open var user: String? {
get {
return _CFURLComponentsCopyUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var password: String? {
get {
return _CFURLComponentsCopyPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var host: String? {
get {
return _CFURLComponentsCopyHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetHost(_components, new?._cfObject) {
fatalError()
}
}
}
// Attempting to set a negative port number will cause an exception.
open var port: NSNumber? {
get {
if let result = _CFURLComponentsCopyPort(_components) {
return unsafeBitCast(result, to: NSNumber.self)
} else {
return nil
}
}
set(new) {
if !_CFURLComponentsSetPort(_components, new?._cfObject) {
fatalError()
}
}
}
open var path: String? {
get {
return _CFURLComponentsCopyPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var query: String? {
get {
return _CFURLComponentsCopyQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var fragment: String? {
get {
return _CFURLComponentsCopyFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetFragment(_components, new?._cfObject) {
fatalError()
}
}
}
// Getting these properties retains any percent encoding these components may have. Setting these properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause an exception. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the urlPathAllowed).
open var percentEncodedUser: String? {
get {
return _CFURLComponentsCopyPercentEncodedUser(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedUser(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPassword: String? {
get {
return _CFURLComponentsCopyPercentEncodedPassword(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPassword(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedHost: String? {
get {
return _CFURLComponentsCopyPercentEncodedHost(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedHost(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedPath: String? {
get {
return _CFURLComponentsCopyPercentEncodedPath(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedPath(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedQuery: String? {
get {
return _CFURLComponentsCopyPercentEncodedQuery(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedQuery(_components, new?._cfObject) {
fatalError()
}
}
}
open var percentEncodedFragment: String? {
get {
return _CFURLComponentsCopyPercentEncodedFragment(_components)?._swiftObject
}
set(new) {
if !_CFURLComponentsSetPercentEncodedFragment(_components, new?._cfObject) {
fatalError()
}
}
}
/* These properties return the character range of a component in the URL string returned by -[NSURLComponents string]. If the component does not exist in the NSURLComponents object, {NSNotFound, 0} is returned. Note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path.
*/
open var rangeOfScheme: NSRange {
return NSRange(_CFURLComponentsGetRangeOfScheme(_components))
}
open var rangeOfUser: NSRange {
return NSRange(_CFURLComponentsGetRangeOfUser(_components))
}
open var rangeOfPassword: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPassword(_components))
}
open var rangeOfHost: NSRange {
return NSRange(_CFURLComponentsGetRangeOfHost(_components))
}
open var rangeOfPort: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPort(_components))
}
open var rangeOfPath: NSRange {
return NSRange(_CFURLComponentsGetRangeOfPath(_components))
}
open var rangeOfQuery: NSRange {
return NSRange(_CFURLComponentsGetRangeOfQuery(_components))
}
open var rangeOfFragment: NSRange {
return NSRange(_CFURLComponentsGetRangeOfFragment(_components))
}
// The getter method that underlies the queryItems property parses the query string based on these delimiters and returns an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string. Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the NSURLComponents object has an empty query component, queryItems returns an empty NSArray. If the NSURLComponents object has no query component, queryItems returns nil.
// The setter method that underlies the queryItems property combines an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, into a query string and sets the NSURLComponents' query property. Passing an empty NSArray to setQueryItems sets the query component of the NSURLComponents object to an empty string. Passing nil to setQueryItems removes the query component of the NSURLComponents object.
// Note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a NSURLQueryItem with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value.
open var queryItems: [URLQueryItem]? {
get {
// This CFURL implementation returns a CFArray of CFDictionary; each CFDictionary has an entry for name and optionally an entry for value
guard let queryArray = _CFURLComponentsCopyQueryItems(_components) else {
return nil
}
let count = CFArrayGetCount(queryArray)
return (0..<count).map { idx in
let oneEntry = unsafeBitCast(CFArrayGetValueAtIndex(queryArray, idx), to: NSDictionary.self)
let swiftEntry = oneEntry._swiftObject
let entryName = swiftEntry["name"] as! String
let entryValue = swiftEntry["value"] as? String
return URLQueryItem(name: entryName, value: entryValue)
}
}
set(new) {
guard let new = new else {
self.percentEncodedQuery = nil
return
}
// The CFURL implementation requires two CFArrays, one for names and one for values
var names = [CFTypeRef]()
var values = [CFTypeRef]()
for entry in new {
names.append(entry.name._cfObject)
if let v = entry.value {
values.append(v._cfObject)
} else {
values.append(kCFNull)
}
}
_CFURLComponentsSetQueryItems(_components, names._cfObject, values._cfObject)
}
}
}
extension NSURL: _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = URL
internal var _swiftObject: SwiftType { return URL(reference: self) }
}
extension CFURL : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSURL
typealias SwiftType = URL
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
internal var _swiftObject: SwiftType { return _nsObject._swiftObject }
}
extension URL : _NSBridgeable, _CFBridgeable {
typealias NSType = NSURL
typealias CFType = CFURL
internal var _nsObject: NSType { return self.reference }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
extension NSURL : _StructTypeBridgeable {
public typealias _StructType = URL
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLComponents : _StructTypeBridgeable {
public typealias _StructType = URLComponents
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
extension NSURLQueryItem : _StructTypeBridgeable {
public typealias _StructType = URLQueryItem
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| 45.249247 | 740 | 0.680318 |
f4bac18e28301318bef8aeb30507e35a9099c794
| 1,620 |
//
// FeedsTableViewController.swift
// PlatinumBlue
//
// Created by 林涛 on 15/12/10.
// Copyright © 2015年 林涛. All rights reserved.
//
import UIKit
class FeedsTableViewController: UITableViewController {
var feedItems = [FeedItem]()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.feedItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let feedItem = self.feedItems[indexPath.row]
cell.textLabel?.text = feedItem.title
cell.detailTextLabel?.text = feedItem.pubDate
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showFeedContent", sender: self.feedItems[indexPath.row])
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.destinationViewController is FeedContentViewController {
let contentVc = segue.destinationViewController as! FeedContentViewController
let feedItem = sender as! FeedItem
contentVc.feedContent = feedItem.content
}
}
}
| 31.153846 | 118 | 0.698148 |
dd381676a4f8af2a5c50ab0b71906ea4bb21343e
| 30,113 |
///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import Foundation
import Alamofire
/// Constants used to make API requests. e.g. server addresses and default user agent to be used.
enum ApiClientConstants {
static let apiHost = "https://api.dropbox.com"
static let contentHost = "https://api-content.dropbox.com"
static let notifyHost = "https://notify.dropboxapi.com"
static let defaultUserAgent = "OfficialDropboxSwiftSDKv2/\(Constants.versionSDK)"
}
open class DropboxTransportClient {
struct SwiftyArgEncoding: ParameterEncoding {
fileprivate let rawJsonRequest: Data
init(rawJsonRequest: Data) {
self.rawJsonRequest = rawJsonRequest
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
urlRequest!.httpBody = rawJsonRequest
return urlRequest!
}
}
public let manager: Session
public let backgroundManager: Session
public let longpollManager: Session
let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
public var accessTokenProvider: AccessTokenProvider
open var selectUser: String?
open var pathRoot: Common.PathRoot?
var baseHosts: [String: String]
var userAgent: String
public convenience init(accessToken: String, selectUser: String? = nil, pathRoot: Common.PathRoot? = nil) {
self.init(accessToken: accessToken, baseHosts: nil, userAgent: nil, selectUser: selectUser, pathRoot: pathRoot)
}
public convenience init(
accessToken: String, baseHosts: [String: String]?, userAgent: String?, selectUser: String?,
sessionDelegate: SessionDelegate? = nil, backgroundSessionDelegate: SessionDelegate? = nil,
longpollSessionDelegate: SessionDelegate? = nil, serverTrustPolicyManager: ServerTrustManager? = nil,
sharedContainerIdentifier: String? = nil, pathRoot: Common.PathRoot? = nil
) {
self.init(
accessTokenProvider: LongLivedAccessTokenProvider(accessToken: accessToken),
baseHosts: baseHosts,
userAgent: userAgent,
selectUser: selectUser,
sessionDelegate: sessionDelegate,
backgroundSessionDelegate: backgroundSessionDelegate,
longpollSessionDelegate: longpollSessionDelegate,
serverTrustPolicyManager: serverTrustPolicyManager,
sharedContainerIdentifier: sharedContainerIdentifier,
pathRoot: pathRoot
)
}
public convenience init(
accessTokenProvider: AccessTokenProvider, selectUser: String? = nil, pathRoot: Common.PathRoot? = nil
) {
self.init(
accessTokenProvider: accessTokenProvider, baseHosts: nil,
userAgent: nil, selectUser: selectUser, pathRoot: pathRoot
)
}
public init(
accessTokenProvider: AccessTokenProvider, baseHosts: [String: String]?, userAgent: String?, selectUser: String?,
sessionDelegate: SessionDelegate? = nil, backgroundSessionDelegate: SessionDelegate? = nil,
longpollSessionDelegate: SessionDelegate? = nil, serverTrustPolicyManager: ServerTrustManager? = nil,
sharedContainerIdentifier: String? = nil, pathRoot: Common.PathRoot? = nil
) {
let config = URLSessionConfiguration.default
let delegate = sessionDelegate ?? SessionDelegate()
let serverTrustPolicyManager = serverTrustPolicyManager ?? nil
let manager = Session(configuration: config, delegate: delegate, rootQueue: queue, startRequestsImmediately: false, serverTrustManager: serverTrustPolicyManager)
let backgroundConfig = URLSessionConfiguration.background(withIdentifier: "com.dropbox.SwiftyDropbox." + UUID().uuidString)
if let sharedContainerIdentifier = sharedContainerIdentifier{
backgroundConfig.sharedContainerIdentifier = sharedContainerIdentifier
}
let backgroundManager = Session(configuration: backgroundConfig, delegate: backgroundSessionDelegate ?? SessionDelegate(), rootQueue: queue, startRequestsImmediately: false, serverTrustManager: serverTrustPolicyManager)
let longpollConfig = URLSessionConfiguration.default
longpollConfig.timeoutIntervalForRequest = 480.0
let longpollSessionDelegate = longpollSessionDelegate ?? SessionDelegate()
let longpollManager = Session(configuration: longpollConfig, delegate: longpollSessionDelegate, rootQueue: queue, startRequestsImmediately: false, serverTrustManager: serverTrustPolicyManager)
let defaultBaseHosts = [
"api": "\(ApiClientConstants.apiHost)/2",
"content": "\(ApiClientConstants.contentHost)/2",
"notify": "\(ApiClientConstants.notifyHost)/2",
]
let defaultUserAgent = ApiClientConstants.defaultUserAgent
self.manager = manager
self.backgroundManager = backgroundManager
self.longpollManager = longpollManager
self.accessTokenProvider = accessTokenProvider
self.selectUser = selectUser
self.pathRoot = pathRoot;
self.baseHosts = baseHosts ?? defaultBaseHosts
if let userAgent = userAgent {
let customUserAgent = "\(userAgent)/\(defaultUserAgent)"
self.userAgent = customUserAgent
} else {
self.userAgent = defaultUserAgent
}
}
open func request<ASerial, RSerial, ESerial>(
_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType? = nil
) -> RpcRequest<RSerial, ESerial> {
let requestCreation = { self.createRpcRequest(route: route, serverArgs: serverArgs) }
let request = RequestWithTokenRefresh(requestCreation: requestCreation, tokenProvider: accessTokenProvider)
return RpcRequest(
request: request,
responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
}
open func request<ASerial, RSerial, ESerial>(
_ route: Route<ASerial, RSerial, ESerial>, serverArgs: ASerial.ValueType, input: UploadBody
) -> UploadRequest<RSerial, ESerial> {
let requestCreation = { self.createUploadRequest(route: route, serverArgs: serverArgs, input: input) }
let request = RequestWithTokenRefresh(
requestCreation: requestCreation, tokenProvider: accessTokenProvider
)
return UploadRequest(
request: request,
responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
}
open func request<ASerial, RSerial, ESerial>(
_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType,
overwrite: Bool,
destination: @escaping (URL, HTTPURLResponse) -> URL
) -> DownloadRequestFile<RSerial, ESerial> {
weak var weakDownloadRequest: DownloadRequestFile<RSerial, ESerial>!
let destinationWrapper: DownloadRequest.Destination = { url, resp in
var finalUrl = destination(url, resp)
if 200 ... 299 ~= resp.statusCode {
if FileManager.default.fileExists(atPath: finalUrl.path) {
if overwrite {
do {
try FileManager.default.removeItem(at: finalUrl)
} catch let error as NSError {
print("Error: \(error)")
}
} else {
print("Error: File already exists at \(finalUrl.path)")
}
}
} else {
weakDownloadRequest.errorMessage = try! Data(contentsOf: url)
// Alamofire will "move" the file to the temporary location where it already resides,
// and where it will soon be automatically deleted
finalUrl = url
}
weakDownloadRequest.urlPath = finalUrl
return (finalUrl, [])
}
let requestCreation = {
self.createDownloadFileRequest(
route: route, serverArgs: serverArgs,
overwrite: overwrite, downloadFileDestination: destinationWrapper
)
}
let request = RequestWithTokenRefresh(requestCreation: requestCreation, tokenProvider: accessTokenProvider)
let downloadRequest = DownloadRequestFile(
request: request,
responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
weakDownloadRequest = downloadRequest
return downloadRequest
}
public func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType) -> DownloadRequestMemory<RSerial, ESerial> {
let requestCreation = {
self.createDownloadMemoryRequest(route: route, serverArgs: serverArgs)
}
let request = RequestWithTokenRefresh(requestCreation: requestCreation, tokenProvider: accessTokenProvider)
return DownloadRequestMemory(
request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer
)
}
private func getHeaders(_ routeStyle: RouteStyle, jsonRequest: Data?, host: String) -> HTTPHeaders {
var headers = ["User-Agent": userAgent]
let noauth = (host == "notify")
if (!noauth) {
headers["Authorization"] = "Bearer \(accessTokenProvider.accessToken)"
if let selectUser = selectUser {
headers["Dropbox-Api-Select-User"] = selectUser
}
if let pathRoot = pathRoot {
let obj = Common.PathRootSerializer().serialize(pathRoot)
headers["Dropbox-Api-Path-Root"] = utf8Decode(SerializeUtil.dumpJSON(obj)!)
}
}
if (routeStyle == RouteStyle.Rpc) {
headers["Content-Type"] = "application/json"
} else if (routeStyle == RouteStyle.Upload) {
headers["Content-Type"] = "application/octet-stream"
if let jsonRequest = jsonRequest {
let value = asciiEscape(utf8Decode(jsonRequest))
headers["Dropbox-Api-Arg"] = value
}
} else if (routeStyle == RouteStyle.Download) {
if let jsonRequest = jsonRequest {
let value = asciiEscape(utf8Decode(jsonRequest))
headers["Dropbox-Api-Arg"] = value
}
}
return HTTPHeaders(headers)
}
private func createRpcRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType? = nil
) -> Alamofire.DataRequest {
let host = route.attrs["host"]! ?? "api"
var routeName = route.name
if route.version > 1 {
routeName = String(format: "%@_v%d", route.name, route.version)
}
let url = "\(baseHosts[host]!)/\(route.namespace)/\(routeName)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
var rawJsonRequest: Data?
rawJsonRequest = nil
if let serverArgs = serverArgs {
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
} else {
let voidSerializer = route.argSerializer as! VoidSerializer
let jsonRequestObj = voidSerializer.serialize(())
rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
}
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
let customEncoding = SwiftyArgEncoding(rawJsonRequest: rawJsonRequest!)
let managerToUse = { () -> Session in
// longpoll requests have a much longer timeout period than other requests
if type(of: route) == type(of: Files.listFolderLongpoll) {
return self.longpollManager
}
return self.manager
}()
let request = managerToUse.request(
url, method: .post, parameters: ["jsonRequest": rawJsonRequest!],
encoding: customEncoding, headers: headers
)
request.task?.priority = URLSessionTask.highPriority
return request
}
private func createUploadRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType, input: UploadBody
) -> Alamofire.UploadRequest {
let host = route.attrs["host"]! ?? "api"
var routeName = route.name
if route.version > 1 {
routeName = String(format: "%@_v%d", route.name, route.version)
}
let url = "\(baseHosts[host]!)/\(route.namespace)/\(routeName)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
let request: Alamofire.UploadRequest
switch input {
case let .data(data):
request = manager.upload(data, to: url, method: .post, headers: headers)
case let .file(file):
request = backgroundManager.upload(file, to: url, method: .post, headers: headers)
case let .stream(stream):
request = manager.upload(stream, to: url, method: .post, headers: headers)
}
return request
}
private func createDownloadFileRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType,
overwrite: Bool,
downloadFileDestination: @escaping DownloadRequest.Destination
) -> DownloadRequest {
let host = route.attrs["host"]! ?? "api"
var routeName = route.name
if route.version > 1 {
routeName = String(format: "%@_v%d", route.name, route.version)
}
let url = "\(baseHosts[host]!)/\(route.namespace)/\(routeName)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
return backgroundManager.download(url, method: .post, headers: headers, to: downloadFileDestination)
}
private func createDownloadMemoryRequest<ASerial, RSerial, ESerial>(
route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType
) -> DataRequest {
let host = route.attrs["host"]! ?? "api"
let url = "\(baseHosts[host]!)/\(route.namespace)/\(route.name)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
return backgroundManager.request(url, method: .post, headers: headers)
}
}
open class Box<T> {
public let unboxed: T
init (_ v: T) { self.unboxed = v }
}
public enum DropboxTransportClientError: Error {
case objectAlreadyDeinit
}
public enum CallError<EType>: CustomStringConvertible {
case internalServerError(Int, String?, String?)
case badInputError(String?, String?)
case rateLimitError(Auth.RateLimitError, String?, String?, String?)
case httpError(Int?, String?, String?)
case authError(Auth.AuthError, String?, String?, String?)
case accessError(Auth.AccessError, String?, String?, String?)
case routeError(Box<EType>, String?, String?, String?)
case clientError(Error?)
public var description: String {
switch self {
case let .internalServerError(code, message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "Internal Server Error \(code)"
if let m = message {
ret += ": \(m)"
}
return ret
case let .badInputError(message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "Bad Input"
if let m = message {
ret += ": \(m)"
}
return ret
case let .authError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API auth error - \(error)"
return ret
case let .accessError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API access error - \(error)"
return ret
case let .httpError(code, message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "HTTP Error"
if let c = code {
ret += "\(c)"
}
if let m = message {
ret += ": \(m)"
}
return ret
case let .routeError(box, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API route error - \(box.unboxed)"
return ret
case let .rateLimitError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API rate limit error - \(error)"
return ret
case let .clientError(err):
if let e = err {
return "\(e)"
}
return "An unknown system error"
}
}
}
func utf8Decode(_ data: Data) -> String {
return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
}
func asciiEscape(_ s: String) -> String {
var out: String = ""
for char in s.unicodeScalars {
var esc = "\(char)"
if !char.isASCII {
esc = NSString(format:"\\u%04x", char.value) as String
} else {
esc = "\(char)"
}
out += esc
}
return out
}
public enum RouteStyle: String {
case Rpc = "rpc"
case Upload = "upload"
case Download = "download"
case Other
}
public enum UploadBody {
case data(Data)
case file(URL)
case stream(InputStream)
}
/// These objects are constructed by the SDK; users of the SDK do not need to create them manually.
///
/// Pass in a closure to the `response` method to handle a response or error.
open class Request<RSerial: JSONSerializer, ESerial: JSONSerializer> {
let responseSerializer: RSerial
let errorSerializer: ESerial
private var selfRetain: AnyObject?
init(responseSerializer: RSerial, errorSerializer: ESerial) {
self.errorSerializer = errorSerializer
self.responseSerializer = responseSerializer
self.selfRetain = self
}
func handleResponseError(_ response: HTTPURLResponse?, data: Data?, error: Error?) -> CallError<ESerial.ValueType> {
let requestId = response?.allHeaderFields["X-Dropbox-Request-Id"] as? String
if let code = response?.statusCode {
switch code {
case 500...599:
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .internalServerError(code, message, requestId)
case 400:
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .badInputError(message, requestId)
case 401:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .authError(Auth.AuthErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 403:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .accessError(Auth.AccessErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"),requestId)
default:
fatalError("Failed to parse error type")
}
case 409:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .routeError(Box(self.errorSerializer.deserialize(d["error"]!)), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 429:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .rateLimitError(Auth.RateLimitErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 200:
return .clientError(error)
default:
return .httpError(code, "An error occurred.", requestId)
}
} else if response == nil {
return .clientError(error)
} else {
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .httpError(nil, message, requestId)
}
}
func getStringFromJson(json: [String : JSON], key: String) -> String {
if let jsonStr = json[key] {
switch jsonStr {
case .str(let str):
return str;
default:
break;
}
}
return "";
}
func cleanupSelfRetain() {
self.selfRetain = nil
}
}
/// An "rpc-style" request
open class RpcRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
private let request: ApiRequest
init(request: ApiRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
public func cancel() {
request.cancel()
}
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .dataCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(nil, strongSelf.handleResponseError(response.response, data: response.data, error: error))
} else {
completionHandler(strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil)
}
strongSelf.cleanupSelfRetain()
}))
return self
}
}
/// An "upload-style" request
open class UploadRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
private let request: ApiRequest
init(request: ApiRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
@discardableResult
public func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
request.setProgressHandler(progressHandler)
return self
}
public func cancel() {
request.cancel()
}
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .dataCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(nil, strongSelf.handleResponseError(response.response, data: response.data, error: error))
} else {
completionHandler(strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil)
}
strongSelf.cleanupSelfRetain()
}))
return self
}
}
/// A "download-style" request to a file
open class DownloadRequestFile<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
private let request: ApiRequest
var urlPath: URL?
var errorMessage: Data
init(request: ApiRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
urlPath = nil
errorMessage = Data()
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
@discardableResult
public func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
request.setProgressHandler(progressHandler)
return self
}
public func cancel() {
self.request.cancel()
}
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping ((RSerial.ValueType, URL)?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .downloadFileCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(
nil, strongSelf.handleResponseError(response.response, data: strongSelf.errorMessage, error: error)
)
} else {
let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields
let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)!
let resultData = result.data(using: .utf8, allowLossyConversion: false)
let resultObject = strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!))
completionHandler((resultObject, strongSelf.urlPath!), nil)
}
strongSelf.cleanupSelfRetain()
}))
return self
}
}
/// A "download-style" request to memory
open class DownloadRequestMemory<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
private let request: ApiRequest
init(request: ApiRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
@discardableResult
public func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
request.setProgressHandler(progressHandler)
return self
}
public func cancel() {
request.cancel()
}
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping ((RSerial.ValueType, Data)?, CallError<ESerial.ValueType>?) -> Void
) -> Self {
request.setCompletionHandler(queue: queue, completionHandler: .dataCompletionHandler({ [weak self] response in
guard let strongSelf = self else {
completionHandler(nil, .clientError(DropboxTransportClientError.objectAlreadyDeinit))
return
}
if let error = response.error {
completionHandler(nil, strongSelf.handleResponseError(response.response, data: response.data, error: error))
} else {
let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields
let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)!
let resultData = result.data(using: .utf8, allowLossyConversion: false)
let resultObject = strongSelf.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!))
completionHandler((resultObject, response.data!), nil)
}
strongSelf.cleanupSelfRetain()
}))
return self
}
}
func caseInsensitiveLookup(_ lookupKey: String, dictionary: [AnyHashable : Any]) -> String? {
for key in dictionary.keys {
let keyString = key as! String
if (keyString.lowercased() == lookupKey.lowercased()) {
return dictionary[key] as? String
}
}
return nil
}
| 40.365952 | 227 | 0.618636 |
2602fd7afa524d3f527fd95bc6410143763667d4
| 20,017 |
//
// ImageSlideshow.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 30.07.15.
//
import UIKit
@objc
/// The delegate protocol informing about image slideshow state changes
public protocol ImageSlideshowDelegate: class {
/// Tells the delegate that the current page has changed
///
/// - Parameters:
/// - imageSlideshow: image slideshow instance
/// - page: new page
@objc optional func imageSlideshow(_ imageSlideshow: ImageSlideshow, didChangeCurrentPageTo page: Int)
/// Tells the delegate that the slideshow will begin dragging
///
/// - Parameter imageSlideshow: image slideshow instance
@objc optional func imageSlideshowWillBeginDragging(_ imageSlideshow: ImageSlideshow)
/// Tells the delegate that the slideshow did end decelerating
///
/// - Parameter imageSlideshow: image slideshow instance
@objc optional func imageSlideshowDidEndDecelerating(_ imageSlideshow: ImageSlideshow)
}
/**
Used to represent position of the Page Control
- hidden: Page Control is hidden
- insideScrollView: Page Control is inside image slideshow
- underScrollView: Page Control is under image slideshow
- custom: Custom vertical padding, relative to "insideScrollView" position
*/
public enum PageControlPosition {
case hidden
case insideScrollView
case underScrollView
case custom(padding: CGFloat)
}
/// Used to represent image preload strategy
///
/// - fixed: preload only fixed number of images before and after the current image
/// - all: preload all images in the slideshow
public enum ImagePreload {
case fixed(offset: Int)
case all
}
/// Main view containing the Image Slideshow
@objcMembers
open class ImageSlideshow: UIView {
/// Scroll View to wrap the slideshow
public let scrollView = UIScrollView()
/// Page Control shown in the slideshow
@available(*, deprecated, message: "Use pageIndicator.view instead")
open var pageControl: UIPageControl {
if let pageIndicator = pageIndicator as? UIPageControl {
return pageIndicator
}
fatalError("pageIndicator is not an instance of UIPageControl")
}
/// Activity indicator shown when loading image
open var activityIndicator: ActivityIndicatorFactory? {
didSet {
reloadScrollView()
}
}
open var pageIndicator: PageIndicatorView? = UIPageControl() {
didSet {
oldValue?.view.removeFromSuperview()
if let pageIndicator = pageIndicator {
addSubview(pageIndicator.view)
}
setNeedsLayout()
}
}
open var pageIndicatorPosition: PageIndicatorPosition = PageIndicatorPosition() {
didSet {
setNeedsLayout()
}
}
// MARK: - State properties
/// Page control position
@available(*, deprecated, message: "Use pageIndicatorPosition instead")
open var pageControlPosition = PageControlPosition.insideScrollView {
didSet {
pageIndicator = UIPageControl()
switch pageControlPosition {
case .hidden:
pageIndicator = nil
case .insideScrollView:
pageIndicatorPosition = PageIndicatorPosition(vertical: .bottom)
case .underScrollView:
pageIndicatorPosition = PageIndicatorPosition(vertical: .under)
case .custom(let padding):
pageIndicatorPosition = PageIndicatorPosition(vertical: .customUnder(padding: padding-30))
}
}
}
/// Current page
open fileprivate(set) var currentPage: Int = 0 {
didSet {
if oldValue != currentPage {
currentPageChanged?(currentPage)
delegate?.imageSlideshow?(self, didChangeCurrentPageTo: currentPage)
}
}
}
/// Delegate called on image slideshow state change
open weak var delegate: ImageSlideshowDelegate?
/// Called on each currentPage change
open var currentPageChanged: ((_ page: Int) -> ())?
/// Called on scrollViewWillBeginDragging
open var willBeginDragging: (() -> ())?
/// Called on scrollViewDidEndDecelerating
open var didEndDecelerating: (() -> ())?
/// Currenlty displayed slideshow item
open var currentSlideshowItem: ImageSlideshowItem? {
if slideshowItems.count > scrollViewPage {
return slideshowItems[scrollViewPage]
} else {
return nil
}
}
/// Current scroll view page. This may differ from `currentPage` as circular slider has two more dummy pages at indexes 0 and n-1 to provide fluent scrolling between first and last item.
open fileprivate(set) var scrollViewPage: Int = 0
/// Input Sources loaded to slideshow
open fileprivate(set) var images = [InputSource]()
/// Image Slideshow Items loaded to slideshow
open fileprivate(set) var slideshowItems = [ImageSlideshowItem]()
// MARK: - Preferences
/// Enables/disables infinite scrolling between images
open var circular = true {
didSet {
if images.count > 0 {
setImageInputs(images)
}
}
}
/// Enables/disables user interactions
open var draggingEnabled = true {
didSet {
scrollView.isUserInteractionEnabled = draggingEnabled
}
}
/// Enables/disables zoom
open var zoomEnabled = false {
didSet {
reloadScrollView()
}
}
/// Maximum zoom scale
open var maximumScale: CGFloat = 2.0 {
didSet {
reloadScrollView()
}
}
open var imageCornerRadius : CGFloat = 0 {
didSet {
reloadScrollView()
}
}
open var spaceBetweenImages : CGFloat = 0 {
didSet {
reloadScrollView()
}
}
/// Image change interval, zero stops the auto-scrolling
open var slideshowInterval = 0.0 {
didSet {
slideshowTimer?.invalidate()
slideshowTimer = nil
setTimerIfNeeded()
}
}
/// Image preload configuration, can be sed to .fixed to enable lazy load or .all
open var preload = ImagePreload.all
/// Content mode of each image in the slideshow
open var contentScaleMode: UIViewContentMode = UIViewContentMode.scaleAspectFit {
didSet {
for view in slideshowItems {
view.imageView.contentMode = contentScaleMode
}
}
}
fileprivate var slideshowTimer: Timer?
fileprivate var scrollViewImages = [InputSource]()
fileprivate var isAnimating: Bool = false
/// Transitioning delegate to manage the transition to full screen controller
open fileprivate(set) var slideshowTransitioningDelegate: ZoomAnimatedTransitioningDelegate?
var primaryVisiblePage: Int {
return scrollView.frame.size.width > 0 ? Int(scrollView.contentOffset.x + scrollView.frame.size.width / 2) / Int(scrollView.frame.size.width) : 0
}
// MARK: - Life cycle
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
autoresizesSubviews = true
clipsToBounds = true
// scroll view configuration
scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - 50.0)
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.bounces = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.autoresizingMask = autoresizingMask
if #available(iOS 11.0, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
addSubview(scrollView)
if let pageIndicator = pageIndicator {
addSubview(pageIndicator.view)
}
if let pageIndicator = pageIndicator as? UIControl {
pageIndicator.addTarget(self, action: #selector(pageControlValueChanged), for: .valueChanged)
}
setTimerIfNeeded()
layoutScrollView()
}
open override func removeFromSuperview() {
super.removeFromSuperview()
pauseTimer()
}
open override func layoutSubviews() {
super.layoutSubviews()
// fixes the case when automaticallyAdjustsScrollViewInsets on parenting view controller is set to true
scrollView.contentInset = UIEdgeInsets.zero
layoutPageControl()
layoutScrollView()
}
open func layoutPageControl() {
if let pageIndicatorView = pageIndicator?.view {
pageIndicatorView.isHidden = images.count < 2
var edgeInsets: UIEdgeInsets = UIEdgeInsets.zero
if #available(iOS 11.0, *) {
edgeInsets = safeAreaInsets
}
pageIndicatorView.sizeToFit()
pageIndicatorView.frame = pageIndicatorPosition.indicatorFrame(for: frame, indicatorSize: pageIndicatorView.frame.size, edgeInsets: edgeInsets)
}
}
/// updates frame of the scroll view and its inner items
func layoutScrollView() {
let pageIndicatorViewSize = pageIndicator?.view.frame.size
let scrollViewBottomPadding = pageIndicatorViewSize.flatMap { pageIndicatorPosition.underPadding(for: $0) } ?? 0
scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - scrollViewBottomPadding)
scrollView.contentSize = CGSize(width: scrollView.frame.size.width * CGFloat(scrollViewImages.count), height: scrollView.frame.size.height)
for (index, view) in slideshowItems.enumerated() {
if !view.zoomInInitially {
view.zoomOut()
}
view.frame = CGRect(x: scrollView.frame.size.width * CGFloat(index), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height)
}
setScrollViewPage(scrollViewPage, animated: false)
}
/// reloads scroll view with latest slideshow items
func reloadScrollView() {
// remove previous slideshow items
for view in slideshowItems {
view.removeFromSuperview()
}
slideshowItems = []
var i = 0
for image in scrollViewImages {
let item = ImageSlideshowItem(image: image, zoomEnabled: zoomEnabled, activityIndicator: activityIndicator?.create(), maximumScale: maximumScale, spaceBetweenImages: spaceBetweenImages, imageCornerRadius: imageCornerRadius)
item.imageView.contentMode = contentScaleMode
slideshowItems.append(item)
scrollView.addSubview(item)
i += 1
}
if circular && (scrollViewImages.count > 1) {
scrollViewPage = 1
scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: false)
} else {
scrollViewPage = 0
}
loadImages(for: scrollViewPage)
}
private func loadImages(for scrollViewPage: Int) {
let totalCount = slideshowItems.count
for i in 0..<totalCount {
let item = slideshowItems[i]
switch preload {
case .all:
item.loadImage()
case .fixed(let offset):
// if circular scrolling is enabled and image is on the edge, a helper ("dummy") image on the other side needs to be loaded too
let circularEdgeLoad = circular && ((scrollViewPage == 0 && i == totalCount-3) || (scrollViewPage == 0 && i == totalCount-2) || (scrollViewPage == totalCount-2 && i == 1))
// load image if page is in range of loadOffset, else release image
let shouldLoad = abs(scrollViewPage-i) <= offset || abs(scrollViewPage-i) > totalCount-offset || circularEdgeLoad
shouldLoad ? item.loadImage() : item.releaseImage()
}
}
}
// MARK: - Image setting
/**
Set image inputs into the image slideshow
- parameter inputs: Array of InputSource instances.
*/
open func setImageInputs(_ inputs: [InputSource]) {
images = inputs
pageIndicator?.numberOfPages = inputs.count
// in circular mode we add dummy first and last image to enable smooth scrolling
if circular && images.count > 1 {
var scImages = [InputSource]()
if let last = images.last {
scImages.append(last)
}
scImages += images
if let first = images.first {
scImages.append(first)
}
scrollViewImages = scImages
} else {
scrollViewImages = images
}
reloadScrollView()
layoutScrollView()
layoutPageControl()
setTimerIfNeeded()
}
// MARK: paging methods
/**
Change the current page
- parameter newPage: new page
- parameter animated: true if animate the change
*/
open func setCurrentPage(_ newPage: Int, animated: Bool) {
var pageOffset = newPage
if circular && (scrollViewImages.count > 1) {
pageOffset += 1
}
setScrollViewPage(pageOffset, animated: animated)
}
/**
Change the scroll view page. This may differ from `setCurrentPage` as circular slider has two more dummy pages at indexes 0 and n-1 to provide fluent scrolling between first and last item.
- parameter newScrollViewPage: new scroll view page
- parameter animated: true if animate the change
*/
open func setScrollViewPage(_ newScrollViewPage: Int, animated: Bool) {
if scrollViewPage < scrollViewImages.count {
scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width * CGFloat(newScrollViewPage), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: animated)
setCurrentPageForScrollViewPage(newScrollViewPage)
if animated {
isAnimating = true
}
}
}
fileprivate func setTimerIfNeeded() {
if slideshowInterval > 0 && scrollViewImages.count > 1 && slideshowTimer == nil {
slideshowTimer = Timer.scheduledTimer(timeInterval: slideshowInterval, target: self, selector: #selector(ImageSlideshow.slideshowTick(_:)), userInfo: nil, repeats: true)
}
}
@objc func slideshowTick(_ timer: Timer) {
let page = scrollView.frame.size.width > 0 ? Int(scrollView.contentOffset.x / scrollView.frame.size.width) : 0
var nextPage = page + 1
if !circular && page == scrollViewImages.count - 1 {
nextPage = 0
}
setScrollViewPage(nextPage, animated: true)
}
fileprivate func setCurrentPageForScrollViewPage(_ page: Int) {
if scrollViewPage != page {
// current page has changed, zoom out this image
if slideshowItems.count > scrollViewPage {
slideshowItems[scrollViewPage].zoomOut()
}
}
if page != scrollViewPage {
loadImages(for: page)
}
scrollViewPage = page
currentPage = currentPageForScrollViewPage(page)
}
fileprivate func currentPageForScrollViewPage(_ page: Int) -> Int {
if circular {
if page == 0 {
// first page contains the last image
return Int(images.count) - 1
} else if page == scrollViewImages.count - 1 {
// last page contains the first image
return 0
} else {
return page - 1
}
} else {
return page
}
}
fileprivate func restartTimer() {
if slideshowTimer?.isValid != nil {
slideshowTimer?.invalidate()
slideshowTimer = nil
}
setTimerIfNeeded()
}
/// Stops slideshow timer
open func pauseTimer() {
slideshowTimer?.invalidate()
slideshowTimer = nil
}
/// Restarts slideshow timer
open func unpauseTimer() {
setTimerIfNeeded()
}
@available(*, deprecated, message: "use pauseTimer instead")
open func pauseTimerIfNeeded() {
pauseTimer()
}
@available(*, deprecated, message: "use unpauseTimer instead")
open func unpauseTimerIfNeeded() {
unpauseTimer()
}
/**
Change the page to the next one
- Parameter animated: true if animate the change
*/
open func nextPage(animated: Bool) {
if !circular && currentPage == images.count - 1 {
return
}
if isAnimating {
return
}
setCurrentPage(currentPage + 1, animated: animated)
restartTimer()
}
/**
Change the page to the previous one
- Parameter animated: true if animate the change
*/
open func previousPage(animated: Bool) {
if !circular && currentPage == 0 {
return
}
if isAnimating {
return
}
let newPage = scrollViewPage > 0 ? scrollViewPage - 1 : scrollViewImages.count - 3
setScrollViewPage(newPage, animated: animated)
restartTimer()
}
/**
Open full screen slideshow
- parameter controller: Controller to present the full screen controller from
- returns: FullScreenSlideshowViewController instance
*/
@discardableResult
open func presentFullScreenController(from controller: UIViewController) -> FullScreenSlideshowViewController {
let fullscreen = FullScreenSlideshowViewController()
fullscreen.pageSelected = {[weak self] (page: Int) in
self?.setCurrentPage(page, animated: false)
}
fullscreen.initialPage = currentPage
fullscreen.inputs = images
slideshowTransitioningDelegate = ZoomAnimatedTransitioningDelegate(slideshowView: self, slideshowController: fullscreen)
fullscreen.transitioningDelegate = slideshowTransitioningDelegate
controller.present(fullscreen, animated: true, completion: nil)
return fullscreen
}
@objc private func pageControlValueChanged() {
if let currentPage = pageIndicator?.page {
setCurrentPage(currentPage, animated: true)
}
}
}
extension ImageSlideshow: UIScrollViewDelegate {
open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
restartTimer()
willBeginDragging?()
delegate?.imageSlideshowWillBeginDragging?(self)
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
setCurrentPageForScrollViewPage(primaryVisiblePage)
didEndDecelerating?()
delegate?.imageSlideshowDidEndDecelerating?(self)
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if circular && (scrollViewImages.count > 1) {
let regularContentOffset = scrollView.frame.size.width * CGFloat(images.count)
if scrollView.contentOffset.x >= scrollView.frame.size.width * CGFloat(images.count + 1) {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x - regularContentOffset, y: 0)
} else if scrollView.contentOffset.x <= 0 {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x + regularContentOffset, y: 0)
}
}
pageIndicator?.page = currentPageForScrollViewPage(primaryVisiblePage)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
isAnimating = false
}
}
| 33.250831 | 235 | 0.63471 |
1afae743adedeace1638862391f865cbb0723dc9
| 3,871 |
//=----------------------------------------------------------------------------=
// This source file is part of the DiffableTextViews open source project.
//
// Copyright (c) 2022 Oscar Byström Ericsson
// Licensed under Apache License, Version 2.0
//
// See http://www.apache.org/licenses/LICENSE-2.0 for license information.
//=----------------------------------------------------------------------------=
//*============================================================================*
// MARK: * Sequencer
//*============================================================================*
@usableFromInline struct Sequencer<Value: Collection> where Value.Element == Character {
@usableFromInline typealias Placeholders = [Character: Predicate]
//=------------------------------------------------------------------------=
// MARK: State
//=------------------------------------------------------------------------=
@usableFromInline let pattern: String
@usableFromInline let placeholders: Placeholders
@usableFromInline let value: Value
//=------------------------------------------------------------------------=
// MARK: Initializers
//=------------------------------------------------------------------------=
@inlinable init(_ pattern: String, _ placeholders: Placeholders, _ value: Value) {
self.pattern = pattern; self.placeholders = placeholders; self.value = value
}
//=------------------------------------------------------------------------=
// MARK: Utilities
//=------------------------------------------------------------------------=
@inlinable func reduce<Result>(into result: Result,
some: (inout Result, Substring, Character) -> Void,
none: (inout Result, Substring) -> Void,
done: (inout Result, Substring, Value.SubSequence) -> Void) -> Result {
//=--------------------------------------=
// State
//=--------------------------------------=
var result = result
var vIndex = value .startIndex
var pIndex = pattern.startIndex
var qIndex = pIndex // queue
//=--------------------------------------=
// Pattern
//=--------------------------------------=
body: while pIndex != pattern.endIndex {
let character = pattern[pIndex]
//=----------------------------------=
// Placeholder
//=----------------------------------=
if let predicate = placeholders[character] {
guard vIndex != value.endIndex else { break body }
let content = value[vIndex]
//=------------------------------=
// Predicate
//=------------------------------=
guard predicate.check(content) else { break body }
//=------------------------------=
// (!) Some
//=------------------------------=
some(&result, pattern[qIndex..<pIndex], content)
value .formIndex(after: &vIndex)
pattern.formIndex(after: &pIndex)
qIndex = pIndex
//=----------------------------------=
// Miscellaneous
//=----------------------------------=
} else {
pattern.formIndex(after: &pIndex)
}
}
//=--------------------------------------=
// (!) None
//=--------------------------------------=
if qIndex == pattern.startIndex {
none(&result, pattern[qIndex..<pIndex])
qIndex = pIndex
}
//=--------------------------------------=
// (!) Done
//=--------------------------------------=
done(&result, pattern[qIndex...], value[vIndex...]); return result
}
}
| 43.011111 | 88 | 0.34048 |
e89bfeb80d6471951ba7d971226f5aa6ee7bb109
| 2,704 |
//
// SceneDelegate.swift
// Kefilm
//
// Created by Oguz Demırhan on 25.01.2021.
//
import UIKit
import SwiftUI
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).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
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.25 | 147 | 0.705251 |
233bc592128f4845e9659db9fda8999b24f57c0b
| 941 |
import Foundation
import HelloDependency
import UIKitDependencyHelper
class StoryboardCounterConfigurator: NSObject {
@IBOutlet weak var vc: StoryboardCounterViewController? {
didSet {
guard let vc = vc else { return }
HelloDependency.register(CounterView.self, forIdentifier: storyboardExample, WeakBox(vc))
HelloDependency.register(CounterViewEventHandler.self, forIdentifier: storyboardExample,
{
let counterVc = HelloDependency.resolve(CounterView.self, forIdentifier: storyboardExample)
let incrementCountLabelView = HelloDependency.resolve(IncrementCountLabelView.self, forIdentifier: storyboardExample)
return CounterViewEventHandlerImpl(counterVc, incrementCountLabelView)
})
vc.eventHandler = HelloDependency.resolve(CounterViewEventHandler.self, forIdentifier: storyboardExample)
}
}
}
| 47.05 | 133 | 0.723698 |
db0b2ea0e5167808c6c972c898d93302ffd38eb5
| 1,806 |
//
// FrozenReferenceTime.swift
// TrueTime
//
// Created by Michael Sanders on 10/26/16.
// Copyright © 2016 Instacart. All rights reserved.
//
import Foundation
typealias FrozenTimeResult = Result<FrozenTime, NSError>
typealias FrozenTimeCallback = (FrozenTimeResult) -> Void
typealias FrozenNetworkTimeResult = Result<FrozenNetworkTime, NSError>
typealias FrozenNetworkTimeCallback = (FrozenNetworkTimeResult) -> Void
protocol FrozenTime {
var time: Date { get }
var uptime: timeval { get }
}
struct FrozenReferenceTime: FrozenTime {
let time: Date
let uptime: timeval
}
struct FrozenNetworkTime: FrozenTime {
let time: Date
let uptime: timeval
let serverResponse: NTPResponse
let startTime: NTP.Time64
let sampleSize: Int?
let host: String?
init(time: Date,
uptime: timeval,
serverResponse: NTPResponse,
startTime: NTP.Time64,
sampleSize: Int? = 0,
host: String? = nil) {
self.time = time
self.uptime = uptime
self.serverResponse = serverResponse
self.startTime = startTime
self.sampleSize = sampleSize
self.host = host
}
init(networkTime time: FrozenNetworkTime, sampleSize: Int, host: String) {
self.init(time: time.time,
uptime: time.uptime,
serverResponse: time.serverResponse,
startTime: time.startTime,
sampleSize: sampleSize,
host: host)
}
}
extension FrozenTime {
var uptimeInterval: TimeInterval {
let currentUptime = timeval.uptime()
return TimeInterval(milliseconds: currentUptime.milliseconds - uptime.milliseconds)
}
func now() -> Date {
return time.addingTimeInterval(uptimeInterval)
}
}
| 26.558824 | 91 | 0.653378 |
5652d372c1c5bb82f506de79a34a94f668ad9bb5
| 449,296 |
//// Automatically Generated From SyntaxNodes.swift.gyb.
//// Do Not Edit Directly!
//===------------ SyntaxNodes.swift - Syntax Node definitions -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// MARK: - CodeBlockItemSyntax
///
/// A CodeBlockItem is any Syntax node that appears on its own line inside
/// a CodeBlock.
///
public struct CodeBlockItemSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case item
case semicolon
case errorTokens
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `CodeBlockItemSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .codeBlockItem else { return nil }
self._syntaxNode = syntax
}
/// Creates a `CodeBlockItemSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .codeBlockItem)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The underlying node inside the code block.
public var item: Syntax {
get {
let childData = data.child(at: Cursor.item,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withItem(value)
}
}
/// Returns a copy of the receiver with its `item` replaced.
/// - param newChild: The new `item` to replace the node's
/// current `item`, if present.
public func withItem(
_ newChild: Syntax?) -> CodeBlockItemSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.item)
return CodeBlockItemSyntax(newData)
}
///
/// If present, the trailing semicolon at the end of the item.
///
public var semicolon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.semicolon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withSemicolon(value)
}
}
/// Returns a copy of the receiver with its `semicolon` replaced.
/// - param newChild: The new `semicolon` to replace the node's
/// current `semicolon`, if present.
public func withSemicolon(
_ newChild: TokenSyntax?) -> CodeBlockItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.semicolon)
return CodeBlockItemSyntax(newData)
}
public var errorTokens: Syntax? {
get {
let childData = data.child(at: Cursor.errorTokens,
parent: Syntax(self))
if childData == nil { return nil }
return Syntax(childData!)
}
set(value) {
self = withErrorTokens(value)
}
}
/// Returns a copy of the receiver with its `errorTokens` replaced.
/// - param newChild: The new `errorTokens` to replace the node's
/// current `errorTokens`, if present.
public func withErrorTokens(
_ newChild: Syntax?) -> CodeBlockItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.errorTokens)
return CodeBlockItemSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is Syntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
}
}
extension CodeBlockItemSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"item": Syntax(item).asProtocol(SyntaxProtocol.self),
"semicolon": semicolon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"errorTokens": errorTokens.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - CodeBlockSyntax
public struct CodeBlockSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftBrace
case statements
case rightBrace
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `CodeBlockSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .codeBlock else { return nil }
self._syntaxNode = syntax
}
/// Creates a `CodeBlockSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .codeBlock)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftBrace: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftBrace,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftBrace(value)
}
}
/// Returns a copy of the receiver with its `leftBrace` replaced.
/// - param newChild: The new `leftBrace` to replace the node's
/// current `leftBrace`, if present.
public func withLeftBrace(
_ newChild: TokenSyntax?) -> CodeBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftBrace)
let newData = data.replacingChild(raw, at: Cursor.leftBrace)
return CodeBlockSyntax(newData)
}
public var statements: CodeBlockItemListSyntax {
get {
let childData = data.child(at: Cursor.statements,
parent: Syntax(self))
return CodeBlockItemListSyntax(childData!)
}
set(value) {
self = withStatements(value)
}
}
/// Adds the provided `Statement` to the node's `statements`
/// collection.
/// - param element: The new `Statement` to add to the node's
/// `statements` collection.
/// - returns: A copy of the receiver with the provided `Statement`
/// appended to its `statements` collection.
public func addStatement(_ element: CodeBlockItemSyntax) -> CodeBlockSyntax {
var collection: RawSyntax
if let col = raw[Cursor.statements] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.codeBlockItemList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.statements)
return CodeBlockSyntax(newData)
}
/// Returns a copy of the receiver with its `statements` replaced.
/// - param newChild: The new `statements` to replace the node's
/// current `statements`, if present.
public func withStatements(
_ newChild: CodeBlockItemListSyntax?) -> CodeBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.codeBlockItemList)
let newData = data.replacingChild(raw, at: Cursor.statements)
return CodeBlockSyntax(newData)
}
public var rightBrace: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightBrace,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightBrace(value)
}
}
/// Returns a copy of the receiver with its `rightBrace` replaced.
/// - param newChild: The new `rightBrace` to replace the node's
/// current `rightBrace`, if present.
public func withRightBrace(
_ newChild: TokenSyntax?) -> CodeBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightBrace)
let newData = data.replacingChild(raw, at: Cursor.rightBrace)
return CodeBlockSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is CodeBlockItemListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(CodeBlockItemListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension CodeBlockSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftBrace": Syntax(leftBrace).asProtocol(SyntaxProtocol.self),
"statements": Syntax(statements).asProtocol(SyntaxProtocol.self),
"rightBrace": Syntax(rightBrace).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - DeclNameArgumentSyntax
public struct DeclNameArgumentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case colon
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DeclNameArgumentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .declNameArgument else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DeclNameArgumentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .declNameArgument)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> DeclNameArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.unknown(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return DeclNameArgumentSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> DeclNameArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return DeclNameArgumentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension DeclNameArgumentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - DeclNameArgumentsSyntax
public struct DeclNameArgumentsSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftParen
case arguments
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DeclNameArgumentsSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .declNameArguments else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DeclNameArgumentsSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .declNameArguments)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> DeclNameArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftParen)
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return DeclNameArgumentsSyntax(newData)
}
public var arguments: DeclNameArgumentListSyntax {
get {
let childData = data.child(at: Cursor.arguments,
parent: Syntax(self))
return DeclNameArgumentListSyntax(childData!)
}
set(value) {
self = withArguments(value)
}
}
/// Adds the provided `Argument` to the node's `arguments`
/// collection.
/// - param element: The new `Argument` to add to the node's
/// `arguments` collection.
/// - returns: A copy of the receiver with the provided `Argument`
/// appended to its `arguments` collection.
public func addArgument(_ element: DeclNameArgumentSyntax) -> DeclNameArgumentsSyntax {
var collection: RawSyntax
if let col = raw[Cursor.arguments] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.declNameArgumentList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.arguments)
return DeclNameArgumentsSyntax(newData)
}
/// Returns a copy of the receiver with its `arguments` replaced.
/// - param newChild: The new `arguments` to replace the node's
/// current `arguments`, if present.
public func withArguments(
_ newChild: DeclNameArgumentListSyntax?) -> DeclNameArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.declNameArgumentList)
let newData = data.replacingChild(raw, at: Cursor.arguments)
return DeclNameArgumentsSyntax(newData)
}
public var rightParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> DeclNameArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightParen)
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return DeclNameArgumentsSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is DeclNameArgumentListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DeclNameArgumentListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension DeclNameArgumentsSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftParen": Syntax(leftParen).asProtocol(SyntaxProtocol.self),
"arguments": Syntax(arguments).asProtocol(SyntaxProtocol.self),
"rightParen": Syntax(rightParen).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - TupleExprElementSyntax
public struct TupleExprElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case label
case colon
case expression
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `TupleExprElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .tupleExprElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `TupleExprElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .tupleExprElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var label: TokenSyntax? {
get {
let childData = data.child(at: Cursor.label,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withLabel(value)
}
}
/// Returns a copy of the receiver with its `label` replaced.
/// - param newChild: The new `label` to replace the node's
/// current `label`, if present.
public func withLabel(
_ newChild: TokenSyntax?) -> TupleExprElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.label)
return TupleExprElementSyntax(newData)
}
public var colon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> TupleExprElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.colon)
return TupleExprElementSyntax(newData)
}
public var expression: ExprSyntax {
get {
let childData = data.child(at: Cursor.expression,
parent: Syntax(self))
return ExprSyntax(childData!)
}
set(value) {
self = withExpression(value)
}
}
/// Returns a copy of the receiver with its `expression` replaced.
/// - param newChild: The new `expression` to replace the node's
/// current `expression`, if present.
public func withExpression(
_ newChild: ExprSyntax?) -> TupleExprElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.expr)
let newData = data.replacingChild(raw, at: Cursor.expression)
return TupleExprElementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> TupleExprElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return TupleExprElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is ExprSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension TupleExprElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"label": label.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"colon": colon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"expression": Syntax(expression).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - ArrayElementSyntax
public struct ArrayElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case expression
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ArrayElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .arrayElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ArrayElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .arrayElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var expression: ExprSyntax {
get {
let childData = data.child(at: Cursor.expression,
parent: Syntax(self))
return ExprSyntax(childData!)
}
set(value) {
self = withExpression(value)
}
}
/// Returns a copy of the receiver with its `expression` replaced.
/// - param newChild: The new `expression` to replace the node's
/// current `expression`, if present.
public func withExpression(
_ newChild: ExprSyntax?) -> ArrayElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.expr)
let newData = data.replacingChild(raw, at: Cursor.expression)
return ArrayElementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> ArrayElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return ArrayElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is ExprSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ArrayElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"expression": Syntax(expression).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - DictionaryElementSyntax
public struct DictionaryElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case keyExpression
case colon
case valueExpression
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DictionaryElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .dictionaryElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DictionaryElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .dictionaryElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var keyExpression: ExprSyntax {
get {
let childData = data.child(at: Cursor.keyExpression,
parent: Syntax(self))
return ExprSyntax(childData!)
}
set(value) {
self = withKeyExpression(value)
}
}
/// Returns a copy of the receiver with its `keyExpression` replaced.
/// - param newChild: The new `keyExpression` to replace the node's
/// current `keyExpression`, if present.
public func withKeyExpression(
_ newChild: ExprSyntax?) -> DictionaryElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.expr)
let newData = data.replacingChild(raw, at: Cursor.keyExpression)
return DictionaryElementSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> DictionaryElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return DictionaryElementSyntax(newData)
}
public var valueExpression: ExprSyntax {
get {
let childData = data.child(at: Cursor.valueExpression,
parent: Syntax(self))
return ExprSyntax(childData!)
}
set(value) {
self = withValueExpression(value)
}
}
/// Returns a copy of the receiver with its `valueExpression` replaced.
/// - param newChild: The new `valueExpression` to replace the node's
/// current `valueExpression`, if present.
public func withValueExpression(
_ newChild: ExprSyntax?) -> DictionaryElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.expr)
let newData = data.replacingChild(raw, at: Cursor.valueExpression)
return DictionaryElementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> DictionaryElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return DictionaryElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is ExprSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is ExprSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension DictionaryElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"keyExpression": Syntax(keyExpression).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"valueExpression": Syntax(valueExpression).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - ClosureCaptureItemSyntax
public struct ClosureCaptureItemSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case specifier
case name
case assignToken
case expression
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ClosureCaptureItemSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .closureCaptureItem else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ClosureCaptureItemSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .closureCaptureItem)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var specifier: TokenListSyntax? {
get {
let childData = data.child(at: Cursor.specifier,
parent: Syntax(self))
if childData == nil { return nil }
return TokenListSyntax(childData!)
}
set(value) {
self = withSpecifier(value)
}
}
/// Adds the provided `SpecifierToken` to the node's `specifier`
/// collection.
/// - param element: The new `SpecifierToken` to add to the node's
/// `specifier` collection.
/// - returns: A copy of the receiver with the provided `SpecifierToken`
/// appended to its `specifier` collection.
public func addSpecifierToken(_ element: TokenSyntax) -> ClosureCaptureItemSyntax {
var collection: RawSyntax
if let col = raw[Cursor.specifier] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.tokenList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.specifier)
return ClosureCaptureItemSyntax(newData)
}
/// Returns a copy of the receiver with its `specifier` replaced.
/// - param newChild: The new `specifier` to replace the node's
/// current `specifier`, if present.
public func withSpecifier(
_ newChild: TokenListSyntax?) -> ClosureCaptureItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.specifier)
return ClosureCaptureItemSyntax(newData)
}
public var name: TokenSyntax? {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> ClosureCaptureItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.name)
return ClosureCaptureItemSyntax(newData)
}
public var assignToken: TokenSyntax? {
get {
let childData = data.child(at: Cursor.assignToken,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withAssignToken(value)
}
}
/// Returns a copy of the receiver with its `assignToken` replaced.
/// - param newChild: The new `assignToken` to replace the node's
/// current `assignToken`, if present.
public func withAssignToken(
_ newChild: TokenSyntax?) -> ClosureCaptureItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.assignToken)
return ClosureCaptureItemSyntax(newData)
}
public var expression: ExprSyntax {
get {
let childData = data.child(at: Cursor.expression,
parent: Syntax(self))
return ExprSyntax(childData!)
}
set(value) {
self = withExpression(value)
}
}
/// Returns a copy of the receiver with its `expression` replaced.
/// - param newChild: The new `expression` to replace the node's
/// current `expression`, if present.
public func withExpression(
_ newChild: ExprSyntax?) -> ClosureCaptureItemSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.expr)
let newData = data.replacingChild(raw, at: Cursor.expression)
return ClosureCaptureItemSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> ClosureCaptureItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return ClosureCaptureItemSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 5)
// Check child #0 child is TokenListSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenListSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is ExprSyntax
assert(rawChildren[3].raw != nil)
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
// Check child #4 child is TokenSyntax or missing
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ClosureCaptureItemSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"specifier": specifier.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"name": name.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"assignToken": assignToken.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"expression": Syntax(expression).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - ClosureCaptureSignatureSyntax
public struct ClosureCaptureSignatureSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftSquare
case items
case rightSquare
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ClosureCaptureSignatureSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .closureCaptureSignature else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ClosureCaptureSignatureSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .closureCaptureSignature)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftSquare: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftSquare,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftSquare(value)
}
}
/// Returns a copy of the receiver with its `leftSquare` replaced.
/// - param newChild: The new `leftSquare` to replace the node's
/// current `leftSquare`, if present.
public func withLeftSquare(
_ newChild: TokenSyntax?) -> ClosureCaptureSignatureSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftSquareBracket)
let newData = data.replacingChild(raw, at: Cursor.leftSquare)
return ClosureCaptureSignatureSyntax(newData)
}
public var items: ClosureCaptureItemListSyntax? {
get {
let childData = data.child(at: Cursor.items,
parent: Syntax(self))
if childData == nil { return nil }
return ClosureCaptureItemListSyntax(childData!)
}
set(value) {
self = withItems(value)
}
}
/// Adds the provided `Item` to the node's `items`
/// collection.
/// - param element: The new `Item` to add to the node's
/// `items` collection.
/// - returns: A copy of the receiver with the provided `Item`
/// appended to its `items` collection.
public func addItem(_ element: ClosureCaptureItemSyntax) -> ClosureCaptureSignatureSyntax {
var collection: RawSyntax
if let col = raw[Cursor.items] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.closureCaptureItemList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.items)
return ClosureCaptureSignatureSyntax(newData)
}
/// Returns a copy of the receiver with its `items` replaced.
/// - param newChild: The new `items` to replace the node's
/// current `items`, if present.
public func withItems(
_ newChild: ClosureCaptureItemListSyntax?) -> ClosureCaptureSignatureSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.items)
return ClosureCaptureSignatureSyntax(newData)
}
public var rightSquare: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightSquare,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightSquare(value)
}
}
/// Returns a copy of the receiver with its `rightSquare` replaced.
/// - param newChild: The new `rightSquare` to replace the node's
/// current `rightSquare`, if present.
public func withRightSquare(
_ newChild: TokenSyntax?) -> ClosureCaptureSignatureSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightSquareBracket)
let newData = data.replacingChild(raw, at: Cursor.rightSquare)
return ClosureCaptureSignatureSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is ClosureCaptureItemListSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ClosureCaptureItemListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ClosureCaptureSignatureSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftSquare": Syntax(leftSquare).asProtocol(SyntaxProtocol.self),
"items": items.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"rightSquare": Syntax(rightSquare).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ClosureParamSyntax
public struct ClosureParamSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ClosureParamSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .closureParam else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ClosureParamSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .closureParam)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> ClosureParamSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return ClosureParamSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> ClosureParamSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return ClosureParamSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ClosureParamSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - ClosureSignatureSyntax
public struct ClosureSignatureSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case capture
case input
case throwsTok
case output
case inTok
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ClosureSignatureSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .closureSignature else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ClosureSignatureSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .closureSignature)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var capture: ClosureCaptureSignatureSyntax? {
get {
let childData = data.child(at: Cursor.capture,
parent: Syntax(self))
if childData == nil { return nil }
return ClosureCaptureSignatureSyntax(childData!)
}
set(value) {
self = withCapture(value)
}
}
/// Returns a copy of the receiver with its `capture` replaced.
/// - param newChild: The new `capture` to replace the node's
/// current `capture`, if present.
public func withCapture(
_ newChild: ClosureCaptureSignatureSyntax?) -> ClosureSignatureSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.capture)
return ClosureSignatureSyntax(newData)
}
public var input: Syntax? {
get {
let childData = data.child(at: Cursor.input,
parent: Syntax(self))
if childData == nil { return nil }
return Syntax(childData!)
}
set(value) {
self = withInput(value)
}
}
/// Returns a copy of the receiver with its `input` replaced.
/// - param newChild: The new `input` to replace the node's
/// current `input`, if present.
public func withInput(
_ newChild: Syntax?) -> ClosureSignatureSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.input)
return ClosureSignatureSyntax(newData)
}
public var throwsTok: TokenSyntax? {
get {
let childData = data.child(at: Cursor.throwsTok,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withThrowsTok(value)
}
}
/// Returns a copy of the receiver with its `throwsTok` replaced.
/// - param newChild: The new `throwsTok` to replace the node's
/// current `throwsTok`, if present.
public func withThrowsTok(
_ newChild: TokenSyntax?) -> ClosureSignatureSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.throwsTok)
return ClosureSignatureSyntax(newData)
}
public var output: ReturnClauseSyntax? {
get {
let childData = data.child(at: Cursor.output,
parent: Syntax(self))
if childData == nil { return nil }
return ReturnClauseSyntax(childData!)
}
set(value) {
self = withOutput(value)
}
}
/// Returns a copy of the receiver with its `output` replaced.
/// - param newChild: The new `output` to replace the node's
/// current `output`, if present.
public func withOutput(
_ newChild: ReturnClauseSyntax?) -> ClosureSignatureSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.output)
return ClosureSignatureSyntax(newData)
}
public var inTok: TokenSyntax {
get {
let childData = data.child(at: Cursor.inTok,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withInTok(value)
}
}
/// Returns a copy of the receiver with its `inTok` replaced.
/// - param newChild: The new `inTok` to replace the node's
/// current `inTok`, if present.
public func withInTok(
_ newChild: TokenSyntax?) -> ClosureSignatureSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.inKeyword)
let newData = data.replacingChild(raw, at: Cursor.inTok)
return ClosureSignatureSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 5)
// Check child #0 child is ClosureCaptureSignatureSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ClosureCaptureSignatureSyntax.self))
}
// Check child #1 child is Syntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is ReturnClauseSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ReturnClauseSyntax.self))
}
// Check child #4 child is TokenSyntax
assert(rawChildren[4].raw != nil)
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ClosureSignatureSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"capture": capture.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"input": input.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"throwsTok": throwsTok.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"output": output.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"inTok": Syntax(inTok).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - MultipleTrailingClosureElementSyntax
public struct MultipleTrailingClosureElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case label
case colon
case closure
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `MultipleTrailingClosureElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .multipleTrailingClosureElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `MultipleTrailingClosureElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .multipleTrailingClosureElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var label: TokenSyntax {
get {
let childData = data.child(at: Cursor.label,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLabel(value)
}
}
/// Returns a copy of the receiver with its `label` replaced.
/// - param newChild: The new `label` to replace the node's
/// current `label`, if present.
public func withLabel(
_ newChild: TokenSyntax?) -> MultipleTrailingClosureElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.label)
return MultipleTrailingClosureElementSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> MultipleTrailingClosureElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return MultipleTrailingClosureElementSyntax(newData)
}
public var closure: ClosureExprSyntax {
get {
let childData = data.child(at: Cursor.closure,
parent: Syntax(self))
return ClosureExprSyntax(childData!)
}
set(value) {
self = withClosure(value)
}
}
/// Returns a copy of the receiver with its `closure` replaced.
/// - param newChild: The new `closure` to replace the node's
/// current `closure`, if present.
public func withClosure(
_ newChild: ClosureExprSyntax?) -> MultipleTrailingClosureElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.closureExpr)
let newData = data.replacingChild(raw, at: Cursor.closure)
return MultipleTrailingClosureElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is ClosureExprSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ClosureExprSyntax.self))
}
}
}
extension MultipleTrailingClosureElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"label": Syntax(label).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"closure": Syntax(closure).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - StringSegmentSyntax
public struct StringSegmentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case content
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `StringSegmentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .stringSegment else { return nil }
self._syntaxNode = syntax
}
/// Creates a `StringSegmentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .stringSegment)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var content: TokenSyntax {
get {
let childData = data.child(at: Cursor.content,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withContent(value)
}
}
/// Returns a copy of the receiver with its `content` replaced.
/// - param newChild: The new `content` to replace the node's
/// current `content`, if present.
public func withContent(
_ newChild: TokenSyntax?) -> StringSegmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.stringSegment(""))
let newData = data.replacingChild(raw, at: Cursor.content)
return StringSegmentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 1)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension StringSegmentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"content": Syntax(content).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ExpressionSegmentSyntax
public struct ExpressionSegmentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case backslash
case delimiter
case leftParen
case expressions
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ExpressionSegmentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .expressionSegment else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ExpressionSegmentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .expressionSegment)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var backslash: TokenSyntax {
get {
let childData = data.child(at: Cursor.backslash,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withBackslash(value)
}
}
/// Returns a copy of the receiver with its `backslash` replaced.
/// - param newChild: The new `backslash` to replace the node's
/// current `backslash`, if present.
public func withBackslash(
_ newChild: TokenSyntax?) -> ExpressionSegmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.backslash)
let newData = data.replacingChild(raw, at: Cursor.backslash)
return ExpressionSegmentSyntax(newData)
}
public var delimiter: TokenSyntax? {
get {
let childData = data.child(at: Cursor.delimiter,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withDelimiter(value)
}
}
/// Returns a copy of the receiver with its `delimiter` replaced.
/// - param newChild: The new `delimiter` to replace the node's
/// current `delimiter`, if present.
public func withDelimiter(
_ newChild: TokenSyntax?) -> ExpressionSegmentSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.delimiter)
return ExpressionSegmentSyntax(newData)
}
public var leftParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> ExpressionSegmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftParen)
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return ExpressionSegmentSyntax(newData)
}
public var expressions: TupleExprElementListSyntax {
get {
let childData = data.child(at: Cursor.expressions,
parent: Syntax(self))
return TupleExprElementListSyntax(childData!)
}
set(value) {
self = withExpressions(value)
}
}
/// Adds the provided `Expression` to the node's `expressions`
/// collection.
/// - param element: The new `Expression` to add to the node's
/// `expressions` collection.
/// - returns: A copy of the receiver with the provided `Expression`
/// appended to its `expressions` collection.
public func addExpression(_ element: TupleExprElementSyntax) -> ExpressionSegmentSyntax {
var collection: RawSyntax
if let col = raw[Cursor.expressions] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.tupleExprElementList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.expressions)
return ExpressionSegmentSyntax(newData)
}
/// Returns a copy of the receiver with its `expressions` replaced.
/// - param newChild: The new `expressions` to replace the node's
/// current `expressions`, if present.
public func withExpressions(
_ newChild: TupleExprElementListSyntax?) -> ExpressionSegmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.tupleExprElementList)
let newData = data.replacingChild(raw, at: Cursor.expressions)
return ExpressionSegmentSyntax(newData)
}
public var rightParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> ExpressionSegmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.stringInterpolationAnchor)
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return ExpressionSegmentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 5)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TupleExprElementListSyntax
assert(rawChildren[3].raw != nil)
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TupleExprElementListSyntax.self))
}
// Check child #4 child is TokenSyntax
assert(rawChildren[4].raw != nil)
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ExpressionSegmentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"backslash": Syntax(backslash).asProtocol(SyntaxProtocol.self),
"delimiter": delimiter.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"leftParen": Syntax(leftParen).asProtocol(SyntaxProtocol.self),
"expressions": Syntax(expressions).asProtocol(SyntaxProtocol.self),
"rightParen": Syntax(rightParen).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ObjcNamePieceSyntax
public struct ObjcNamePieceSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case dot
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ObjcNamePieceSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .objcNamePiece else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ObjcNamePieceSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .objcNamePiece)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> ObjcNamePieceSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return ObjcNamePieceSyntax(newData)
}
public var dot: TokenSyntax? {
get {
let childData = data.child(at: Cursor.dot,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withDot(value)
}
}
/// Returns a copy of the receiver with its `dot` replaced.
/// - param newChild: The new `dot` to replace the node's
/// current `dot`, if present.
public func withDot(
_ newChild: TokenSyntax?) -> ObjcNamePieceSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.dot)
return ObjcNamePieceSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ObjcNamePieceSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"dot": dot.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - TypeInitializerClauseSyntax
public struct TypeInitializerClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case equal
case value
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `TypeInitializerClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .typeInitializerClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `TypeInitializerClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .typeInitializerClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var equal: TokenSyntax {
get {
let childData = data.child(at: Cursor.equal,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withEqual(value)
}
}
/// Returns a copy of the receiver with its `equal` replaced.
/// - param newChild: The new `equal` to replace the node's
/// current `equal`, if present.
public func withEqual(
_ newChild: TokenSyntax?) -> TypeInitializerClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.equal)
let newData = data.replacingChild(raw, at: Cursor.equal)
return TypeInitializerClauseSyntax(newData)
}
public var value: TypeSyntax {
get {
let childData = data.child(at: Cursor.value,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withValue(value)
}
}
/// Returns a copy of the receiver with its `value` replaced.
/// - param newChild: The new `value` to replace the node's
/// current `value`, if present.
public func withValue(
_ newChild: TypeSyntax?) -> TypeInitializerClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.value)
return TypeInitializerClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TypeSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
}
}
extension TypeInitializerClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"equal": Syntax(equal).asProtocol(SyntaxProtocol.self),
"value": Syntax(value).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ParameterClauseSyntax
public struct ParameterClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftParen
case parameterList
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ParameterClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .parameterClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ParameterClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .parameterClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> ParameterClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftParen)
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return ParameterClauseSyntax(newData)
}
public var parameterList: FunctionParameterListSyntax {
get {
let childData = data.child(at: Cursor.parameterList,
parent: Syntax(self))
return FunctionParameterListSyntax(childData!)
}
set(value) {
self = withParameterList(value)
}
}
/// Adds the provided `Parameter` to the node's `parameterList`
/// collection.
/// - param element: The new `Parameter` to add to the node's
/// `parameterList` collection.
/// - returns: A copy of the receiver with the provided `Parameter`
/// appended to its `parameterList` collection.
public func addParameter(_ element: FunctionParameterSyntax) -> ParameterClauseSyntax {
var collection: RawSyntax
if let col = raw[Cursor.parameterList] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.functionParameterList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.parameterList)
return ParameterClauseSyntax(newData)
}
/// Returns a copy of the receiver with its `parameterList` replaced.
/// - param newChild: The new `parameterList` to replace the node's
/// current `parameterList`, if present.
public func withParameterList(
_ newChild: FunctionParameterListSyntax?) -> ParameterClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.functionParameterList)
let newData = data.replacingChild(raw, at: Cursor.parameterList)
return ParameterClauseSyntax(newData)
}
public var rightParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> ParameterClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightParen)
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return ParameterClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is FunctionParameterListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(FunctionParameterListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ParameterClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftParen": Syntax(leftParen).asProtocol(SyntaxProtocol.self),
"parameterList": Syntax(parameterList).asProtocol(SyntaxProtocol.self),
"rightParen": Syntax(rightParen).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ReturnClauseSyntax
public struct ReturnClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case arrow
case returnType
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ReturnClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .returnClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ReturnClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .returnClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var arrow: TokenSyntax {
get {
let childData = data.child(at: Cursor.arrow,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withArrow(value)
}
}
/// Returns a copy of the receiver with its `arrow` replaced.
/// - param newChild: The new `arrow` to replace the node's
/// current `arrow`, if present.
public func withArrow(
_ newChild: TokenSyntax?) -> ReturnClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.arrow)
let newData = data.replacingChild(raw, at: Cursor.arrow)
return ReturnClauseSyntax(newData)
}
public var returnType: TypeSyntax {
get {
let childData = data.child(at: Cursor.returnType,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withReturnType(value)
}
}
/// Returns a copy of the receiver with its `returnType` replaced.
/// - param newChild: The new `returnType` to replace the node's
/// current `returnType`, if present.
public func withReturnType(
_ newChild: TypeSyntax?) -> ReturnClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.returnType)
return ReturnClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TypeSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
}
}
extension ReturnClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"arrow": Syntax(arrow).asProtocol(SyntaxProtocol.self),
"returnType": Syntax(returnType).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - FunctionSignatureSyntax
public struct FunctionSignatureSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case input
case throwsOrRethrowsKeyword
case output
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `FunctionSignatureSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .functionSignature else { return nil }
self._syntaxNode = syntax
}
/// Creates a `FunctionSignatureSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .functionSignature)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var input: ParameterClauseSyntax {
get {
let childData = data.child(at: Cursor.input,
parent: Syntax(self))
return ParameterClauseSyntax(childData!)
}
set(value) {
self = withInput(value)
}
}
/// Returns a copy of the receiver with its `input` replaced.
/// - param newChild: The new `input` to replace the node's
/// current `input`, if present.
public func withInput(
_ newChild: ParameterClauseSyntax?) -> FunctionSignatureSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.parameterClause)
let newData = data.replacingChild(raw, at: Cursor.input)
return FunctionSignatureSyntax(newData)
}
public var throwsOrRethrowsKeyword: TokenSyntax? {
get {
let childData = data.child(at: Cursor.throwsOrRethrowsKeyword,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withThrowsOrRethrowsKeyword(value)
}
}
/// Returns a copy of the receiver with its `throwsOrRethrowsKeyword` replaced.
/// - param newChild: The new `throwsOrRethrowsKeyword` to replace the node's
/// current `throwsOrRethrowsKeyword`, if present.
public func withThrowsOrRethrowsKeyword(
_ newChild: TokenSyntax?) -> FunctionSignatureSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.throwsOrRethrowsKeyword)
return FunctionSignatureSyntax(newData)
}
public var output: ReturnClauseSyntax? {
get {
let childData = data.child(at: Cursor.output,
parent: Syntax(self))
if childData == nil { return nil }
return ReturnClauseSyntax(childData!)
}
set(value) {
self = withOutput(value)
}
}
/// Returns a copy of the receiver with its `output` replaced.
/// - param newChild: The new `output` to replace the node's
/// current `output`, if present.
public func withOutput(
_ newChild: ReturnClauseSyntax?) -> FunctionSignatureSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.output)
return FunctionSignatureSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is ParameterClauseSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ParameterClauseSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is ReturnClauseSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ReturnClauseSyntax.self))
}
}
}
extension FunctionSignatureSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"input": Syntax(input).asProtocol(SyntaxProtocol.self),
"throwsOrRethrowsKeyword": throwsOrRethrowsKeyword.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"output": output.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - IfConfigClauseSyntax
public struct IfConfigClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case poundKeyword
case condition
case elements
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `IfConfigClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .ifConfigClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `IfConfigClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .ifConfigClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var poundKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.poundKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withPoundKeyword(value)
}
}
/// Returns a copy of the receiver with its `poundKeyword` replaced.
/// - param newChild: The new `poundKeyword` to replace the node's
/// current `poundKeyword`, if present.
public func withPoundKeyword(
_ newChild: TokenSyntax?) -> IfConfigClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.poundIfKeyword)
let newData = data.replacingChild(raw, at: Cursor.poundKeyword)
return IfConfigClauseSyntax(newData)
}
public var condition: ExprSyntax? {
get {
let childData = data.child(at: Cursor.condition,
parent: Syntax(self))
if childData == nil { return nil }
return ExprSyntax(childData!)
}
set(value) {
self = withCondition(value)
}
}
/// Returns a copy of the receiver with its `condition` replaced.
/// - param newChild: The new `condition` to replace the node's
/// current `condition`, if present.
public func withCondition(
_ newChild: ExprSyntax?) -> IfConfigClauseSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.condition)
return IfConfigClauseSyntax(newData)
}
public var elements: Syntax {
get {
let childData = data.child(at: Cursor.elements,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withElements(value)
}
}
/// Returns a copy of the receiver with its `elements` replaced.
/// - param newChild: The new `elements` to replace the node's
/// current `elements`, if present.
public func withElements(
_ newChild: Syntax?) -> IfConfigClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.elements)
return IfConfigClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is ExprSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
// Check child #2 child is Syntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
}
}
extension IfConfigClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"poundKeyword": Syntax(poundKeyword).asProtocol(SyntaxProtocol.self),
"condition": condition.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"elements": Syntax(elements).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - PoundSourceLocationArgsSyntax
public struct PoundSourceLocationArgsSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case fileArgLabel
case fileArgColon
case fileName
case comma
case lineArgLabel
case lineArgColon
case lineNumber
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `PoundSourceLocationArgsSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .poundSourceLocationArgs else { return nil }
self._syntaxNode = syntax
}
/// Creates a `PoundSourceLocationArgsSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .poundSourceLocationArgs)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var fileArgLabel: TokenSyntax {
get {
let childData = data.child(at: Cursor.fileArgLabel,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withFileArgLabel(value)
}
}
/// Returns a copy of the receiver with its `fileArgLabel` replaced.
/// - param newChild: The new `fileArgLabel` to replace the node's
/// current `fileArgLabel`, if present.
public func withFileArgLabel(
_ newChild: TokenSyntax?) -> PoundSourceLocationArgsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.fileArgLabel)
return PoundSourceLocationArgsSyntax(newData)
}
public var fileArgColon: TokenSyntax {
get {
let childData = data.child(at: Cursor.fileArgColon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withFileArgColon(value)
}
}
/// Returns a copy of the receiver with its `fileArgColon` replaced.
/// - param newChild: The new `fileArgColon` to replace the node's
/// current `fileArgColon`, if present.
public func withFileArgColon(
_ newChild: TokenSyntax?) -> PoundSourceLocationArgsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.fileArgColon)
return PoundSourceLocationArgsSyntax(newData)
}
public var fileName: TokenSyntax {
get {
let childData = data.child(at: Cursor.fileName,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withFileName(value)
}
}
/// Returns a copy of the receiver with its `fileName` replaced.
/// - param newChild: The new `fileName` to replace the node's
/// current `fileName`, if present.
public func withFileName(
_ newChild: TokenSyntax?) -> PoundSourceLocationArgsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.stringLiteral(""))
let newData = data.replacingChild(raw, at: Cursor.fileName)
return PoundSourceLocationArgsSyntax(newData)
}
public var comma: TokenSyntax {
get {
let childData = data.child(at: Cursor.comma,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withComma(value)
}
}
/// Returns a copy of the receiver with its `comma` replaced.
/// - param newChild: The new `comma` to replace the node's
/// current `comma`, if present.
public func withComma(
_ newChild: TokenSyntax?) -> PoundSourceLocationArgsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.comma)
let newData = data.replacingChild(raw, at: Cursor.comma)
return PoundSourceLocationArgsSyntax(newData)
}
public var lineArgLabel: TokenSyntax {
get {
let childData = data.child(at: Cursor.lineArgLabel,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLineArgLabel(value)
}
}
/// Returns a copy of the receiver with its `lineArgLabel` replaced.
/// - param newChild: The new `lineArgLabel` to replace the node's
/// current `lineArgLabel`, if present.
public func withLineArgLabel(
_ newChild: TokenSyntax?) -> PoundSourceLocationArgsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.lineArgLabel)
return PoundSourceLocationArgsSyntax(newData)
}
public var lineArgColon: TokenSyntax {
get {
let childData = data.child(at: Cursor.lineArgColon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLineArgColon(value)
}
}
/// Returns a copy of the receiver with its `lineArgColon` replaced.
/// - param newChild: The new `lineArgColon` to replace the node's
/// current `lineArgColon`, if present.
public func withLineArgColon(
_ newChild: TokenSyntax?) -> PoundSourceLocationArgsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.lineArgColon)
return PoundSourceLocationArgsSyntax(newData)
}
public var lineNumber: TokenSyntax {
get {
let childData = data.child(at: Cursor.lineNumber,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLineNumber(value)
}
}
/// Returns a copy of the receiver with its `lineNumber` replaced.
/// - param newChild: The new `lineNumber` to replace the node's
/// current `lineNumber`, if present.
public func withLineNumber(
_ newChild: TokenSyntax?) -> PoundSourceLocationArgsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.integerLiteral(""))
let newData = data.replacingChild(raw, at: Cursor.lineNumber)
return PoundSourceLocationArgsSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 7)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TokenSyntax
assert(rawChildren[3].raw != nil)
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #4 child is TokenSyntax
assert(rawChildren[4].raw != nil)
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #5 child is TokenSyntax
assert(rawChildren[5].raw != nil)
if let raw = rawChildren[5].raw {
let info = rawChildren[5].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #6 child is TokenSyntax
assert(rawChildren[6].raw != nil)
if let raw = rawChildren[6].raw {
let info = rawChildren[6].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension PoundSourceLocationArgsSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"fileArgLabel": Syntax(fileArgLabel).asProtocol(SyntaxProtocol.self),
"fileArgColon": Syntax(fileArgColon).asProtocol(SyntaxProtocol.self),
"fileName": Syntax(fileName).asProtocol(SyntaxProtocol.self),
"comma": Syntax(comma).asProtocol(SyntaxProtocol.self),
"lineArgLabel": Syntax(lineArgLabel).asProtocol(SyntaxProtocol.self),
"lineArgColon": Syntax(lineArgColon).asProtocol(SyntaxProtocol.self),
"lineNumber": Syntax(lineNumber).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - DeclModifierSyntax
public struct DeclModifierSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case detailLeftParen
case detail
case detailRightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DeclModifierSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .declModifier else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DeclModifierSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .declModifier)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> DeclModifierSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.unknown(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return DeclModifierSyntax(newData)
}
public var detailLeftParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.detailLeftParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withDetailLeftParen(value)
}
}
/// Returns a copy of the receiver with its `detailLeftParen` replaced.
/// - param newChild: The new `detailLeftParen` to replace the node's
/// current `detailLeftParen`, if present.
public func withDetailLeftParen(
_ newChild: TokenSyntax?) -> DeclModifierSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.detailLeftParen)
return DeclModifierSyntax(newData)
}
public var detail: TokenSyntax? {
get {
let childData = data.child(at: Cursor.detail,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withDetail(value)
}
}
/// Returns a copy of the receiver with its `detail` replaced.
/// - param newChild: The new `detail` to replace the node's
/// current `detail`, if present.
public func withDetail(
_ newChild: TokenSyntax?) -> DeclModifierSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.detail)
return DeclModifierSyntax(newData)
}
public var detailRightParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.detailRightParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withDetailRightParen(value)
}
}
/// Returns a copy of the receiver with its `detailRightParen` replaced.
/// - param newChild: The new `detailRightParen` to replace the node's
/// current `detailRightParen`, if present.
public func withDetailRightParen(
_ newChild: TokenSyntax?) -> DeclModifierSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.detailRightParen)
return DeclModifierSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension DeclModifierSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"detailLeftParen": detailLeftParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"detail": detail.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"detailRightParen": detailRightParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - InheritedTypeSyntax
public struct InheritedTypeSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case typeName
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `InheritedTypeSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .inheritedType else { return nil }
self._syntaxNode = syntax
}
/// Creates a `InheritedTypeSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .inheritedType)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var typeName: TypeSyntax {
get {
let childData = data.child(at: Cursor.typeName,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withTypeName(value)
}
}
/// Returns a copy of the receiver with its `typeName` replaced.
/// - param newChild: The new `typeName` to replace the node's
/// current `typeName`, if present.
public func withTypeName(
_ newChild: TypeSyntax?) -> InheritedTypeSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.typeName)
return InheritedTypeSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> InheritedTypeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return InheritedTypeSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TypeSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension InheritedTypeSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"typeName": Syntax(typeName).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - TypeInheritanceClauseSyntax
public struct TypeInheritanceClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case colon
case inheritedTypeCollection
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `TypeInheritanceClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .typeInheritanceClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `TypeInheritanceClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .typeInheritanceClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> TypeInheritanceClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return TypeInheritanceClauseSyntax(newData)
}
public var inheritedTypeCollection: InheritedTypeListSyntax {
get {
let childData = data.child(at: Cursor.inheritedTypeCollection,
parent: Syntax(self))
return InheritedTypeListSyntax(childData!)
}
set(value) {
self = withInheritedTypeCollection(value)
}
}
/// Adds the provided `InheritedType` to the node's `inheritedTypeCollection`
/// collection.
/// - param element: The new `InheritedType` to add to the node's
/// `inheritedTypeCollection` collection.
/// - returns: A copy of the receiver with the provided `InheritedType`
/// appended to its `inheritedTypeCollection` collection.
public func addInheritedType(_ element: InheritedTypeSyntax) -> TypeInheritanceClauseSyntax {
var collection: RawSyntax
if let col = raw[Cursor.inheritedTypeCollection] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.inheritedTypeList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.inheritedTypeCollection)
return TypeInheritanceClauseSyntax(newData)
}
/// Returns a copy of the receiver with its `inheritedTypeCollection` replaced.
/// - param newChild: The new `inheritedTypeCollection` to replace the node's
/// current `inheritedTypeCollection`, if present.
public func withInheritedTypeCollection(
_ newChild: InheritedTypeListSyntax?) -> TypeInheritanceClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.inheritedTypeList)
let newData = data.replacingChild(raw, at: Cursor.inheritedTypeCollection)
return TypeInheritanceClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is InheritedTypeListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(InheritedTypeListSyntax.self))
}
}
}
extension TypeInheritanceClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"inheritedTypeCollection": Syntax(inheritedTypeCollection).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - MemberDeclBlockSyntax
public struct MemberDeclBlockSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftBrace
case members
case rightBrace
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `MemberDeclBlockSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .memberDeclBlock else { return nil }
self._syntaxNode = syntax
}
/// Creates a `MemberDeclBlockSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .memberDeclBlock)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftBrace: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftBrace,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftBrace(value)
}
}
/// Returns a copy of the receiver with its `leftBrace` replaced.
/// - param newChild: The new `leftBrace` to replace the node's
/// current `leftBrace`, if present.
public func withLeftBrace(
_ newChild: TokenSyntax?) -> MemberDeclBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftBrace)
let newData = data.replacingChild(raw, at: Cursor.leftBrace)
return MemberDeclBlockSyntax(newData)
}
public var members: MemberDeclListSyntax {
get {
let childData = data.child(at: Cursor.members,
parent: Syntax(self))
return MemberDeclListSyntax(childData!)
}
set(value) {
self = withMembers(value)
}
}
/// Adds the provided `Member` to the node's `members`
/// collection.
/// - param element: The new `Member` to add to the node's
/// `members` collection.
/// - returns: A copy of the receiver with the provided `Member`
/// appended to its `members` collection.
public func addMember(_ element: MemberDeclListItemSyntax) -> MemberDeclBlockSyntax {
var collection: RawSyntax
if let col = raw[Cursor.members] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.memberDeclList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.members)
return MemberDeclBlockSyntax(newData)
}
/// Returns a copy of the receiver with its `members` replaced.
/// - param newChild: The new `members` to replace the node's
/// current `members`, if present.
public func withMembers(
_ newChild: MemberDeclListSyntax?) -> MemberDeclBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.memberDeclList)
let newData = data.replacingChild(raw, at: Cursor.members)
return MemberDeclBlockSyntax(newData)
}
public var rightBrace: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightBrace,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightBrace(value)
}
}
/// Returns a copy of the receiver with its `rightBrace` replaced.
/// - param newChild: The new `rightBrace` to replace the node's
/// current `rightBrace`, if present.
public func withRightBrace(
_ newChild: TokenSyntax?) -> MemberDeclBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightBrace)
let newData = data.replacingChild(raw, at: Cursor.rightBrace)
return MemberDeclBlockSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is MemberDeclListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(MemberDeclListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension MemberDeclBlockSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftBrace": Syntax(leftBrace).asProtocol(SyntaxProtocol.self),
"members": Syntax(members).asProtocol(SyntaxProtocol.self),
"rightBrace": Syntax(rightBrace).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - MemberDeclListItemSyntax
///
/// A member declaration of a type consisting of a declaration and an
/// optional semicolon;
///
public struct MemberDeclListItemSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case decl
case semicolon
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `MemberDeclListItemSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .memberDeclListItem else { return nil }
self._syntaxNode = syntax
}
/// Creates a `MemberDeclListItemSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .memberDeclListItem)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The declaration of the type member.
public var decl: DeclSyntax {
get {
let childData = data.child(at: Cursor.decl,
parent: Syntax(self))
return DeclSyntax(childData!)
}
set(value) {
self = withDecl(value)
}
}
/// Returns a copy of the receiver with its `decl` replaced.
/// - param newChild: The new `decl` to replace the node's
/// current `decl`, if present.
public func withDecl(
_ newChild: DeclSyntax?) -> MemberDeclListItemSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.decl)
let newData = data.replacingChild(raw, at: Cursor.decl)
return MemberDeclListItemSyntax(newData)
}
/// An optional trailing semicolon.
public var semicolon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.semicolon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withSemicolon(value)
}
}
/// Returns a copy of the receiver with its `semicolon` replaced.
/// - param newChild: The new `semicolon` to replace the node's
/// current `semicolon`, if present.
public func withSemicolon(
_ newChild: TokenSyntax?) -> MemberDeclListItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.semicolon)
return MemberDeclListItemSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is DeclSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DeclSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension MemberDeclListItemSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"decl": Syntax(decl).asProtocol(SyntaxProtocol.self),
"semicolon": semicolon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - SourceFileSyntax
public struct SourceFileSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case statements
case eofToken
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `SourceFileSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .sourceFile else { return nil }
self._syntaxNode = syntax
}
/// Creates a `SourceFileSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .sourceFile)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var statements: CodeBlockItemListSyntax {
get {
let childData = data.child(at: Cursor.statements,
parent: Syntax(self))
return CodeBlockItemListSyntax(childData!)
}
set(value) {
self = withStatements(value)
}
}
/// Adds the provided `Statement` to the node's `statements`
/// collection.
/// - param element: The new `Statement` to add to the node's
/// `statements` collection.
/// - returns: A copy of the receiver with the provided `Statement`
/// appended to its `statements` collection.
public func addStatement(_ element: CodeBlockItemSyntax) -> SourceFileSyntax {
var collection: RawSyntax
if let col = raw[Cursor.statements] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.codeBlockItemList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.statements)
return SourceFileSyntax(newData)
}
/// Returns a copy of the receiver with its `statements` replaced.
/// - param newChild: The new `statements` to replace the node's
/// current `statements`, if present.
public func withStatements(
_ newChild: CodeBlockItemListSyntax?) -> SourceFileSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.codeBlockItemList)
let newData = data.replacingChild(raw, at: Cursor.statements)
return SourceFileSyntax(newData)
}
public var eofToken: TokenSyntax {
get {
let childData = data.child(at: Cursor.eofToken,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withEOFToken(value)
}
}
/// Returns a copy of the receiver with its `eofToken` replaced.
/// - param newChild: The new `eofToken` to replace the node's
/// current `eofToken`, if present.
public func withEOFToken(
_ newChild: TokenSyntax?) -> SourceFileSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.unknown(""))
let newData = data.replacingChild(raw, at: Cursor.eofToken)
return SourceFileSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is CodeBlockItemListSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(CodeBlockItemListSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension SourceFileSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"statements": Syntax(statements).asProtocol(SyntaxProtocol.self),
"eofToken": Syntax(eofToken).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - InitializerClauseSyntax
public struct InitializerClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case equal
case value
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `InitializerClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .initializerClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `InitializerClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .initializerClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var equal: TokenSyntax {
get {
let childData = data.child(at: Cursor.equal,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withEqual(value)
}
}
/// Returns a copy of the receiver with its `equal` replaced.
/// - param newChild: The new `equal` to replace the node's
/// current `equal`, if present.
public func withEqual(
_ newChild: TokenSyntax?) -> InitializerClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.equal)
let newData = data.replacingChild(raw, at: Cursor.equal)
return InitializerClauseSyntax(newData)
}
public var value: ExprSyntax {
get {
let childData = data.child(at: Cursor.value,
parent: Syntax(self))
return ExprSyntax(childData!)
}
set(value) {
self = withValue(value)
}
}
/// Returns a copy of the receiver with its `value` replaced.
/// - param newChild: The new `value` to replace the node's
/// current `value`, if present.
public func withValue(
_ newChild: ExprSyntax?) -> InitializerClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.expr)
let newData = data.replacingChild(raw, at: Cursor.value)
return InitializerClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is ExprSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
}
}
extension InitializerClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"equal": Syntax(equal).asProtocol(SyntaxProtocol.self),
"value": Syntax(value).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - FunctionParameterSyntax
public struct FunctionParameterSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case attributes
case firstName
case secondName
case colon
case type
case ellipsis
case defaultArgument
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `FunctionParameterSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .functionParameter else { return nil }
self._syntaxNode = syntax
}
/// Creates a `FunctionParameterSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .functionParameter)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var attributes: AttributeListSyntax? {
get {
let childData = data.child(at: Cursor.attributes,
parent: Syntax(self))
if childData == nil { return nil }
return AttributeListSyntax(childData!)
}
set(value) {
self = withAttributes(value)
}
}
/// Adds the provided `Attribute` to the node's `attributes`
/// collection.
/// - param element: The new `Attribute` to add to the node's
/// `attributes` collection.
/// - returns: A copy of the receiver with the provided `Attribute`
/// appended to its `attributes` collection.
public func addAttribute(_ element: Syntax) -> FunctionParameterSyntax {
var collection: RawSyntax
if let col = raw[Cursor.attributes] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.attributeList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.attributes)
return FunctionParameterSyntax(newData)
}
/// Returns a copy of the receiver with its `attributes` replaced.
/// - param newChild: The new `attributes` to replace the node's
/// current `attributes`, if present.
public func withAttributes(
_ newChild: AttributeListSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.attributes)
return FunctionParameterSyntax(newData)
}
public var firstName: TokenSyntax? {
get {
let childData = data.child(at: Cursor.firstName,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withFirstName(value)
}
}
/// Returns a copy of the receiver with its `firstName` replaced.
/// - param newChild: The new `firstName` to replace the node's
/// current `firstName`, if present.
public func withFirstName(
_ newChild: TokenSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.firstName)
return FunctionParameterSyntax(newData)
}
public var secondName: TokenSyntax? {
get {
let childData = data.child(at: Cursor.secondName,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withSecondName(value)
}
}
/// Returns a copy of the receiver with its `secondName` replaced.
/// - param newChild: The new `secondName` to replace the node's
/// current `secondName`, if present.
public func withSecondName(
_ newChild: TokenSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.secondName)
return FunctionParameterSyntax(newData)
}
public var colon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.colon)
return FunctionParameterSyntax(newData)
}
public var type: TypeSyntax? {
get {
let childData = data.child(at: Cursor.type,
parent: Syntax(self))
if childData == nil { return nil }
return TypeSyntax(childData!)
}
set(value) {
self = withType(value)
}
}
/// Returns a copy of the receiver with its `type` replaced.
/// - param newChild: The new `type` to replace the node's
/// current `type`, if present.
public func withType(
_ newChild: TypeSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.type)
return FunctionParameterSyntax(newData)
}
public var ellipsis: TokenSyntax? {
get {
let childData = data.child(at: Cursor.ellipsis,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withEllipsis(value)
}
}
/// Returns a copy of the receiver with its `ellipsis` replaced.
/// - param newChild: The new `ellipsis` to replace the node's
/// current `ellipsis`, if present.
public func withEllipsis(
_ newChild: TokenSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.ellipsis)
return FunctionParameterSyntax(newData)
}
public var defaultArgument: InitializerClauseSyntax? {
get {
let childData = data.child(at: Cursor.defaultArgument,
parent: Syntax(self))
if childData == nil { return nil }
return InitializerClauseSyntax(childData!)
}
set(value) {
self = withDefaultArgument(value)
}
}
/// Returns a copy of the receiver with its `defaultArgument` replaced.
/// - param newChild: The new `defaultArgument` to replace the node's
/// current `defaultArgument`, if present.
public func withDefaultArgument(
_ newChild: InitializerClauseSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.defaultArgument)
return FunctionParameterSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> FunctionParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return FunctionParameterSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 8)
// Check child #0 child is AttributeListSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(AttributeListSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #4 child is TypeSyntax or missing
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #5 child is TokenSyntax or missing
if let raw = rawChildren[5].raw {
let info = rawChildren[5].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #6 child is InitializerClauseSyntax or missing
if let raw = rawChildren[6].raw {
let info = rawChildren[6].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(InitializerClauseSyntax.self))
}
// Check child #7 child is TokenSyntax or missing
if let raw = rawChildren[7].raw {
let info = rawChildren[7].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension FunctionParameterSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"attributes": attributes.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"firstName": firstName.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"secondName": secondName.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"colon": colon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"type": type.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"ellipsis": ellipsis.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"defaultArgument": defaultArgument.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - AccessLevelModifierSyntax
public struct AccessLevelModifierSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case leftParen
case modifier
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AccessLevelModifierSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .accessLevelModifier else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AccessLevelModifierSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .accessLevelModifier)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> AccessLevelModifierSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return AccessLevelModifierSyntax(newData)
}
public var leftParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> AccessLevelModifierSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return AccessLevelModifierSyntax(newData)
}
public var modifier: TokenSyntax? {
get {
let childData = data.child(at: Cursor.modifier,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withModifier(value)
}
}
/// Returns a copy of the receiver with its `modifier` replaced.
/// - param newChild: The new `modifier` to replace the node's
/// current `modifier`, if present.
public func withModifier(
_ newChild: TokenSyntax?) -> AccessLevelModifierSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.modifier)
return AccessLevelModifierSyntax(newData)
}
public var rightParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> AccessLevelModifierSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return AccessLevelModifierSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension AccessLevelModifierSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"leftParen": leftParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"modifier": modifier.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"rightParen": rightParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - AccessPathComponentSyntax
public struct AccessPathComponentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case trailingDot
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AccessPathComponentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .accessPathComponent else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AccessPathComponentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .accessPathComponent)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> AccessPathComponentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return AccessPathComponentSyntax(newData)
}
public var trailingDot: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingDot,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingDot(value)
}
}
/// Returns a copy of the receiver with its `trailingDot` replaced.
/// - param newChild: The new `trailingDot` to replace the node's
/// current `trailingDot`, if present.
public func withTrailingDot(
_ newChild: TokenSyntax?) -> AccessPathComponentSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingDot)
return AccessPathComponentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension AccessPathComponentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"trailingDot": trailingDot.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - AccessorParameterSyntax
public struct AccessorParameterSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftParen
case name
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AccessorParameterSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .accessorParameter else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AccessorParameterSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .accessorParameter)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> AccessorParameterSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftParen)
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return AccessorParameterSyntax(newData)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> AccessorParameterSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return AccessorParameterSyntax(newData)
}
public var rightParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> AccessorParameterSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightParen)
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return AccessorParameterSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension AccessorParameterSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftParen": Syntax(leftParen).asProtocol(SyntaxProtocol.self),
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"rightParen": Syntax(rightParen).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - AccessorBlockSyntax
public struct AccessorBlockSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftBrace
case accessors
case rightBrace
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AccessorBlockSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .accessorBlock else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AccessorBlockSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .accessorBlock)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftBrace: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftBrace,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftBrace(value)
}
}
/// Returns a copy of the receiver with its `leftBrace` replaced.
/// - param newChild: The new `leftBrace` to replace the node's
/// current `leftBrace`, if present.
public func withLeftBrace(
_ newChild: TokenSyntax?) -> AccessorBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftBrace)
let newData = data.replacingChild(raw, at: Cursor.leftBrace)
return AccessorBlockSyntax(newData)
}
public var accessors: AccessorListSyntax {
get {
let childData = data.child(at: Cursor.accessors,
parent: Syntax(self))
return AccessorListSyntax(childData!)
}
set(value) {
self = withAccessors(value)
}
}
/// Adds the provided `Accessor` to the node's `accessors`
/// collection.
/// - param element: The new `Accessor` to add to the node's
/// `accessors` collection.
/// - returns: A copy of the receiver with the provided `Accessor`
/// appended to its `accessors` collection.
public func addAccessor(_ element: AccessorDeclSyntax) -> AccessorBlockSyntax {
var collection: RawSyntax
if let col = raw[Cursor.accessors] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.accessorList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.accessors)
return AccessorBlockSyntax(newData)
}
/// Returns a copy of the receiver with its `accessors` replaced.
/// - param newChild: The new `accessors` to replace the node's
/// current `accessors`, if present.
public func withAccessors(
_ newChild: AccessorListSyntax?) -> AccessorBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.accessorList)
let newData = data.replacingChild(raw, at: Cursor.accessors)
return AccessorBlockSyntax(newData)
}
public var rightBrace: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightBrace,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightBrace(value)
}
}
/// Returns a copy of the receiver with its `rightBrace` replaced.
/// - param newChild: The new `rightBrace` to replace the node's
/// current `rightBrace`, if present.
public func withRightBrace(
_ newChild: TokenSyntax?) -> AccessorBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightBrace)
let newData = data.replacingChild(raw, at: Cursor.rightBrace)
return AccessorBlockSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is AccessorListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(AccessorListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension AccessorBlockSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftBrace": Syntax(leftBrace).asProtocol(SyntaxProtocol.self),
"accessors": Syntax(accessors).asProtocol(SyntaxProtocol.self),
"rightBrace": Syntax(rightBrace).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - PatternBindingSyntax
public struct PatternBindingSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case pattern
case typeAnnotation
case initializer
case accessor
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `PatternBindingSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .patternBinding else { return nil }
self._syntaxNode = syntax
}
/// Creates a `PatternBindingSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .patternBinding)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var pattern: PatternSyntax {
get {
let childData = data.child(at: Cursor.pattern,
parent: Syntax(self))
return PatternSyntax(childData!)
}
set(value) {
self = withPattern(value)
}
}
/// Returns a copy of the receiver with its `pattern` replaced.
/// - param newChild: The new `pattern` to replace the node's
/// current `pattern`, if present.
public func withPattern(
_ newChild: PatternSyntax?) -> PatternBindingSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.pattern)
let newData = data.replacingChild(raw, at: Cursor.pattern)
return PatternBindingSyntax(newData)
}
public var typeAnnotation: TypeAnnotationSyntax? {
get {
let childData = data.child(at: Cursor.typeAnnotation,
parent: Syntax(self))
if childData == nil { return nil }
return TypeAnnotationSyntax(childData!)
}
set(value) {
self = withTypeAnnotation(value)
}
}
/// Returns a copy of the receiver with its `typeAnnotation` replaced.
/// - param newChild: The new `typeAnnotation` to replace the node's
/// current `typeAnnotation`, if present.
public func withTypeAnnotation(
_ newChild: TypeAnnotationSyntax?) -> PatternBindingSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.typeAnnotation)
return PatternBindingSyntax(newData)
}
public var initializer: InitializerClauseSyntax? {
get {
let childData = data.child(at: Cursor.initializer,
parent: Syntax(self))
if childData == nil { return nil }
return InitializerClauseSyntax(childData!)
}
set(value) {
self = withInitializer(value)
}
}
/// Returns a copy of the receiver with its `initializer` replaced.
/// - param newChild: The new `initializer` to replace the node's
/// current `initializer`, if present.
public func withInitializer(
_ newChild: InitializerClauseSyntax?) -> PatternBindingSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.initializer)
return PatternBindingSyntax(newData)
}
public var accessor: Syntax? {
get {
let childData = data.child(at: Cursor.accessor,
parent: Syntax(self))
if childData == nil { return nil }
return Syntax(childData!)
}
set(value) {
self = withAccessor(value)
}
}
/// Returns a copy of the receiver with its `accessor` replaced.
/// - param newChild: The new `accessor` to replace the node's
/// current `accessor`, if present.
public func withAccessor(
_ newChild: Syntax?) -> PatternBindingSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.accessor)
return PatternBindingSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> PatternBindingSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return PatternBindingSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 5)
// Check child #0 child is PatternSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(PatternSyntax.self))
}
// Check child #1 child is TypeAnnotationSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeAnnotationSyntax.self))
}
// Check child #2 child is InitializerClauseSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(InitializerClauseSyntax.self))
}
// Check child #3 child is Syntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #4 child is TokenSyntax or missing
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension PatternBindingSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"pattern": Syntax(pattern).asProtocol(SyntaxProtocol.self),
"typeAnnotation": typeAnnotation.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"initializer": initializer.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"accessor": accessor.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - EnumCaseElementSyntax
///
/// An element of an enum case, containing the name of the case and,
/// optionally, either associated values or an assignment to a raw value.
///
public struct EnumCaseElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case identifier
case associatedValue
case rawValue
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `EnumCaseElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .enumCaseElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `EnumCaseElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .enumCaseElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The name of this case.
public var identifier: TokenSyntax {
get {
let childData = data.child(at: Cursor.identifier,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withIdentifier(value)
}
}
/// Returns a copy of the receiver with its `identifier` replaced.
/// - param newChild: The new `identifier` to replace the node's
/// current `identifier`, if present.
public func withIdentifier(
_ newChild: TokenSyntax?) -> EnumCaseElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.identifier)
return EnumCaseElementSyntax(newData)
}
/// The set of associated values of the case.
public var associatedValue: ParameterClauseSyntax? {
get {
let childData = data.child(at: Cursor.associatedValue,
parent: Syntax(self))
if childData == nil { return nil }
return ParameterClauseSyntax(childData!)
}
set(value) {
self = withAssociatedValue(value)
}
}
/// Returns a copy of the receiver with its `associatedValue` replaced.
/// - param newChild: The new `associatedValue` to replace the node's
/// current `associatedValue`, if present.
public func withAssociatedValue(
_ newChild: ParameterClauseSyntax?) -> EnumCaseElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.associatedValue)
return EnumCaseElementSyntax(newData)
}
///
/// The raw value of this enum element, if present.
///
public var rawValue: InitializerClauseSyntax? {
get {
let childData = data.child(at: Cursor.rawValue,
parent: Syntax(self))
if childData == nil { return nil }
return InitializerClauseSyntax(childData!)
}
set(value) {
self = withRawValue(value)
}
}
/// Returns a copy of the receiver with its `rawValue` replaced.
/// - param newChild: The new `rawValue` to replace the node's
/// current `rawValue`, if present.
public func withRawValue(
_ newChild: InitializerClauseSyntax?) -> EnumCaseElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.rawValue)
return EnumCaseElementSyntax(newData)
}
///
/// The trailing comma of this element, if the case has
/// multiple elements.
///
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> EnumCaseElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return EnumCaseElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is ParameterClauseSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ParameterClauseSyntax.self))
}
// Check child #2 child is InitializerClauseSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(InitializerClauseSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension EnumCaseElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"identifier": Syntax(identifier).asProtocol(SyntaxProtocol.self),
"associatedValue": associatedValue.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"rawValue": rawValue.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - OperatorPrecedenceAndTypesSyntax
///
/// A clause to specify precedence group in infix operator declarations, and designated types in any operator declaration.
///
public struct OperatorPrecedenceAndTypesSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case colon
case precedenceGroupAndDesignatedTypes
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `OperatorPrecedenceAndTypesSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .operatorPrecedenceAndTypes else { return nil }
self._syntaxNode = syntax
}
/// Creates a `OperatorPrecedenceAndTypesSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .operatorPrecedenceAndTypes)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> OperatorPrecedenceAndTypesSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return OperatorPrecedenceAndTypesSyntax(newData)
}
///
/// The precedence group and designated types for this operator
///
public var precedenceGroupAndDesignatedTypes: IdentifierListSyntax {
get {
let childData = data.child(at: Cursor.precedenceGroupAndDesignatedTypes,
parent: Syntax(self))
return IdentifierListSyntax(childData!)
}
set(value) {
self = withPrecedenceGroupAndDesignatedTypes(value)
}
}
/// Adds the provided `PrecedenceGroupAndDesignatedType` to the node's `precedenceGroupAndDesignatedTypes`
/// collection.
/// - param element: The new `PrecedenceGroupAndDesignatedType` to add to the node's
/// `precedenceGroupAndDesignatedTypes` collection.
/// - returns: A copy of the receiver with the provided `PrecedenceGroupAndDesignatedType`
/// appended to its `precedenceGroupAndDesignatedTypes` collection.
public func addPrecedenceGroupAndDesignatedType(_ element: TokenSyntax) -> OperatorPrecedenceAndTypesSyntax {
var collection: RawSyntax
if let col = raw[Cursor.precedenceGroupAndDesignatedTypes] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.identifierList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.precedenceGroupAndDesignatedTypes)
return OperatorPrecedenceAndTypesSyntax(newData)
}
/// Returns a copy of the receiver with its `precedenceGroupAndDesignatedTypes` replaced.
/// - param newChild: The new `precedenceGroupAndDesignatedTypes` to replace the node's
/// current `precedenceGroupAndDesignatedTypes`, if present.
public func withPrecedenceGroupAndDesignatedTypes(
_ newChild: IdentifierListSyntax?) -> OperatorPrecedenceAndTypesSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.identifierList)
let newData = data.replacingChild(raw, at: Cursor.precedenceGroupAndDesignatedTypes)
return OperatorPrecedenceAndTypesSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is IdentifierListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(IdentifierListSyntax.self))
}
}
}
extension OperatorPrecedenceAndTypesSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"precedenceGroupAndDesignatedTypes": Syntax(precedenceGroupAndDesignatedTypes).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - PrecedenceGroupRelationSyntax
///
/// Specify the new precedence group's relation to existing precedence
/// groups.
///
public struct PrecedenceGroupRelationSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case higherThanOrLowerThan
case colon
case otherNames
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `PrecedenceGroupRelationSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .precedenceGroupRelation else { return nil }
self._syntaxNode = syntax
}
/// Creates a `PrecedenceGroupRelationSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .precedenceGroupRelation)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
///
/// The relation to specified other precedence groups.
///
public var higherThanOrLowerThan: TokenSyntax {
get {
let childData = data.child(at: Cursor.higherThanOrLowerThan,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withHigherThanOrLowerThan(value)
}
}
/// Returns a copy of the receiver with its `higherThanOrLowerThan` replaced.
/// - param newChild: The new `higherThanOrLowerThan` to replace the node's
/// current `higherThanOrLowerThan`, if present.
public func withHigherThanOrLowerThan(
_ newChild: TokenSyntax?) -> PrecedenceGroupRelationSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.higherThanOrLowerThan)
return PrecedenceGroupRelationSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> PrecedenceGroupRelationSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return PrecedenceGroupRelationSyntax(newData)
}
///
/// The name of other precedence group to which this precedence
/// group relates.
///
public var otherNames: PrecedenceGroupNameListSyntax {
get {
let childData = data.child(at: Cursor.otherNames,
parent: Syntax(self))
return PrecedenceGroupNameListSyntax(childData!)
}
set(value) {
self = withOtherNames(value)
}
}
/// Adds the provided `OtherName` to the node's `otherNames`
/// collection.
/// - param element: The new `OtherName` to add to the node's
/// `otherNames` collection.
/// - returns: A copy of the receiver with the provided `OtherName`
/// appended to its `otherNames` collection.
public func addOtherName(_ element: PrecedenceGroupNameElementSyntax) -> PrecedenceGroupRelationSyntax {
var collection: RawSyntax
if let col = raw[Cursor.otherNames] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.precedenceGroupNameList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.otherNames)
return PrecedenceGroupRelationSyntax(newData)
}
/// Returns a copy of the receiver with its `otherNames` replaced.
/// - param newChild: The new `otherNames` to replace the node's
/// current `otherNames`, if present.
public func withOtherNames(
_ newChild: PrecedenceGroupNameListSyntax?) -> PrecedenceGroupRelationSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.precedenceGroupNameList)
let newData = data.replacingChild(raw, at: Cursor.otherNames)
return PrecedenceGroupRelationSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is PrecedenceGroupNameListSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(PrecedenceGroupNameListSyntax.self))
}
}
}
extension PrecedenceGroupRelationSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"higherThanOrLowerThan": Syntax(higherThanOrLowerThan).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"otherNames": Syntax(otherNames).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - PrecedenceGroupNameElementSyntax
public struct PrecedenceGroupNameElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `PrecedenceGroupNameElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .precedenceGroupNameElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `PrecedenceGroupNameElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .precedenceGroupNameElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> PrecedenceGroupNameElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return PrecedenceGroupNameElementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> PrecedenceGroupNameElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return PrecedenceGroupNameElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension PrecedenceGroupNameElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - PrecedenceGroupAssignmentSyntax
///
/// Specifies the precedence of an operator when used in an operation
/// that includes optional chaining.
///
public struct PrecedenceGroupAssignmentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case assignmentKeyword
case colon
case flag
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `PrecedenceGroupAssignmentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .precedenceGroupAssignment else { return nil }
self._syntaxNode = syntax
}
/// Creates a `PrecedenceGroupAssignmentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .precedenceGroupAssignment)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var assignmentKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.assignmentKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withAssignmentKeyword(value)
}
}
/// Returns a copy of the receiver with its `assignmentKeyword` replaced.
/// - param newChild: The new `assignmentKeyword` to replace the node's
/// current `assignmentKeyword`, if present.
public func withAssignmentKeyword(
_ newChild: TokenSyntax?) -> PrecedenceGroupAssignmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.assignmentKeyword)
return PrecedenceGroupAssignmentSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> PrecedenceGroupAssignmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return PrecedenceGroupAssignmentSyntax(newData)
}
///
/// When true, an operator in the corresponding precedence group
/// uses the same grouping rules during optional chaining as the
/// assignment operators from the standard library. Otherwise,
/// operators in the precedence group follows the same optional
/// chaining rules as operators that don't perform assignment.
///
public var flag: TokenSyntax {
get {
let childData = data.child(at: Cursor.flag,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withFlag(value)
}
}
/// Returns a copy of the receiver with its `flag` replaced.
/// - param newChild: The new `flag` to replace the node's
/// current `flag`, if present.
public func withFlag(
_ newChild: TokenSyntax?) -> PrecedenceGroupAssignmentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.trueKeyword)
let newData = data.replacingChild(raw, at: Cursor.flag)
return PrecedenceGroupAssignmentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension PrecedenceGroupAssignmentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"assignmentKeyword": Syntax(assignmentKeyword).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"flag": Syntax(flag).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - PrecedenceGroupAssociativitySyntax
///
/// Specifies how a sequence of operators with the same precedence level
/// are grouped together in the absence of grouping parentheses.
///
public struct PrecedenceGroupAssociativitySyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case associativityKeyword
case colon
case value
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `PrecedenceGroupAssociativitySyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .precedenceGroupAssociativity else { return nil }
self._syntaxNode = syntax
}
/// Creates a `PrecedenceGroupAssociativitySyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .precedenceGroupAssociativity)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var associativityKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.associativityKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withAssociativityKeyword(value)
}
}
/// Returns a copy of the receiver with its `associativityKeyword` replaced.
/// - param newChild: The new `associativityKeyword` to replace the node's
/// current `associativityKeyword`, if present.
public func withAssociativityKeyword(
_ newChild: TokenSyntax?) -> PrecedenceGroupAssociativitySyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.associativityKeyword)
return PrecedenceGroupAssociativitySyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> PrecedenceGroupAssociativitySyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return PrecedenceGroupAssociativitySyntax(newData)
}
///
/// Operators that are `left`-associative group left-to-right.
/// Operators that are `right`-associative group right-to-left.
/// Operators that are specified with an associativity of `none`
/// don't associate at all
///
public var value: TokenSyntax {
get {
let childData = data.child(at: Cursor.value,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withValue(value)
}
}
/// Returns a copy of the receiver with its `value` replaced.
/// - param newChild: The new `value` to replace the node's
/// current `value`, if present.
public func withValue(
_ newChild: TokenSyntax?) -> PrecedenceGroupAssociativitySyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.value)
return PrecedenceGroupAssociativitySyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension PrecedenceGroupAssociativitySyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"associativityKeyword": Syntax(associativityKeyword).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"value": Syntax(value).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - CustomAttributeSyntax
///
/// A custom `@` attribute.
///
public struct CustomAttributeSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case atSignToken
case attributeName
case leftParen
case argumentList
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `CustomAttributeSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .customAttribute else { return nil }
self._syntaxNode = syntax
}
/// Creates a `CustomAttributeSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .customAttribute)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The `@` sign.
public var atSignToken: TokenSyntax {
get {
let childData = data.child(at: Cursor.atSignToken,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withAtSignToken(value)
}
}
/// Returns a copy of the receiver with its `atSignToken` replaced.
/// - param newChild: The new `atSignToken` to replace the node's
/// current `atSignToken`, if present.
public func withAtSignToken(
_ newChild: TokenSyntax?) -> CustomAttributeSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.atSign)
let newData = data.replacingChild(raw, at: Cursor.atSignToken)
return CustomAttributeSyntax(newData)
}
/// The name of the attribute.
public var attributeName: TypeSyntax {
get {
let childData = data.child(at: Cursor.attributeName,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withAttributeName(value)
}
}
/// Returns a copy of the receiver with its `attributeName` replaced.
/// - param newChild: The new `attributeName` to replace the node's
/// current `attributeName`, if present.
public func withAttributeName(
_ newChild: TypeSyntax?) -> CustomAttributeSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.attributeName)
return CustomAttributeSyntax(newData)
}
public var leftParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> CustomAttributeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return CustomAttributeSyntax(newData)
}
public var argumentList: TupleExprElementListSyntax? {
get {
let childData = data.child(at: Cursor.argumentList,
parent: Syntax(self))
if childData == nil { return nil }
return TupleExprElementListSyntax(childData!)
}
set(value) {
self = withArgumentList(value)
}
}
/// Adds the provided `Argument` to the node's `argumentList`
/// collection.
/// - param element: The new `Argument` to add to the node's
/// `argumentList` collection.
/// - returns: A copy of the receiver with the provided `Argument`
/// appended to its `argumentList` collection.
public func addArgument(_ element: TupleExprElementSyntax) -> CustomAttributeSyntax {
var collection: RawSyntax
if let col = raw[Cursor.argumentList] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.tupleExprElementList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.argumentList)
return CustomAttributeSyntax(newData)
}
/// Returns a copy of the receiver with its `argumentList` replaced.
/// - param newChild: The new `argumentList` to replace the node's
/// current `argumentList`, if present.
public func withArgumentList(
_ newChild: TupleExprElementListSyntax?) -> CustomAttributeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.argumentList)
return CustomAttributeSyntax(newData)
}
public var rightParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> CustomAttributeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return CustomAttributeSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 5)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TypeSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TupleExprElementListSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TupleExprElementListSyntax.self))
}
// Check child #4 child is TokenSyntax or missing
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension CustomAttributeSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"atSignToken": Syntax(atSignToken).asProtocol(SyntaxProtocol.self),
"attributeName": Syntax(attributeName).asProtocol(SyntaxProtocol.self),
"leftParen": leftParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"argumentList": argumentList.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"rightParen": rightParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - AttributeSyntax
///
/// An `@` attribute.
///
public struct AttributeSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case atSignToken
case attributeName
case leftParen
case argument
case rightParen
case tokenList
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AttributeSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .attribute else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AttributeSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .attribute)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The `@` sign.
public var atSignToken: TokenSyntax {
get {
let childData = data.child(at: Cursor.atSignToken,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withAtSignToken(value)
}
}
/// Returns a copy of the receiver with its `atSignToken` replaced.
/// - param newChild: The new `atSignToken` to replace the node's
/// current `atSignToken`, if present.
public func withAtSignToken(
_ newChild: TokenSyntax?) -> AttributeSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.atSign)
let newData = data.replacingChild(raw, at: Cursor.atSignToken)
return AttributeSyntax(newData)
}
/// The name of the attribute.
public var attributeName: TokenSyntax {
get {
let childData = data.child(at: Cursor.attributeName,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withAttributeName(value)
}
}
/// Returns a copy of the receiver with its `attributeName` replaced.
/// - param newChild: The new `attributeName` to replace the node's
/// current `attributeName`, if present.
public func withAttributeName(
_ newChild: TokenSyntax?) -> AttributeSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.unknown(""))
let newData = data.replacingChild(raw, at: Cursor.attributeName)
return AttributeSyntax(newData)
}
///
/// If the attribute takes arguments, the opening parenthesis.
///
public var leftParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> AttributeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return AttributeSyntax(newData)
}
///
/// The arguments of the attribute. In case the attribute
/// takes multiple arguments, they are gather in the
/// appropriate takes first.
///
public var argument: Syntax? {
get {
let childData = data.child(at: Cursor.argument,
parent: Syntax(self))
if childData == nil { return nil }
return Syntax(childData!)
}
set(value) {
self = withArgument(value)
}
}
/// Returns a copy of the receiver with its `argument` replaced.
/// - param newChild: The new `argument` to replace the node's
/// current `argument`, if present.
public func withArgument(
_ newChild: Syntax?) -> AttributeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.argument)
return AttributeSyntax(newData)
}
///
/// If the attribute takes arguments, the closing parenthesis.
///
public var rightParen: TokenSyntax? {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> AttributeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return AttributeSyntax(newData)
}
public var tokenList: TokenListSyntax? {
get {
let childData = data.child(at: Cursor.tokenList,
parent: Syntax(self))
if childData == nil { return nil }
return TokenListSyntax(childData!)
}
set(value) {
self = withTokenList(value)
}
}
/// Adds the provided `Token` to the node's `tokenList`
/// collection.
/// - param element: The new `Token` to add to the node's
/// `tokenList` collection.
/// - returns: A copy of the receiver with the provided `Token`
/// appended to its `tokenList` collection.
public func addToken(_ element: TokenSyntax) -> AttributeSyntax {
var collection: RawSyntax
if let col = raw[Cursor.tokenList] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.tokenList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.tokenList)
return AttributeSyntax(newData)
}
/// Returns a copy of the receiver with its `tokenList` replaced.
/// - param newChild: The new `tokenList` to replace the node's
/// current `tokenList`, if present.
public func withTokenList(
_ newChild: TokenListSyntax?) -> AttributeSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.tokenList)
return AttributeSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 6)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is Syntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #4 child is TokenSyntax or missing
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #5 child is TokenListSyntax or missing
if let raw = rawChildren[5].raw {
let info = rawChildren[5].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenListSyntax.self))
}
}
}
extension AttributeSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"atSignToken": Syntax(atSignToken).asProtocol(SyntaxProtocol.self),
"attributeName": Syntax(attributeName).asProtocol(SyntaxProtocol.self),
"leftParen": leftParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"argument": argument.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"rightParen": rightParen.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"tokenList": tokenList.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - LabeledSpecializeEntrySyntax
///
/// A labeled argument for the `@_specialize` attribute like
/// `exported: true`
///
public struct LabeledSpecializeEntrySyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case label
case colon
case value
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `LabeledSpecializeEntrySyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .labeledSpecializeEntry else { return nil }
self._syntaxNode = syntax
}
/// Creates a `LabeledSpecializeEntrySyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .labeledSpecializeEntry)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The label of the argument
public var label: TokenSyntax {
get {
let childData = data.child(at: Cursor.label,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLabel(value)
}
}
/// Returns a copy of the receiver with its `label` replaced.
/// - param newChild: The new `label` to replace the node's
/// current `label`, if present.
public func withLabel(
_ newChild: TokenSyntax?) -> LabeledSpecializeEntrySyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.label)
return LabeledSpecializeEntrySyntax(newData)
}
/// The colon separating the label and the value
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> LabeledSpecializeEntrySyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return LabeledSpecializeEntrySyntax(newData)
}
/// The value for this argument
public var value: TokenSyntax {
get {
let childData = data.child(at: Cursor.value,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withValue(value)
}
}
/// Returns a copy of the receiver with its `value` replaced.
/// - param newChild: The new `value` to replace the node's
/// current `value`, if present.
public func withValue(
_ newChild: TokenSyntax?) -> LabeledSpecializeEntrySyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.unknown(""))
let newData = data.replacingChild(raw, at: Cursor.value)
return LabeledSpecializeEntrySyntax(newData)
}
///
/// A trailing comma if this argument is followed by another one
///
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> LabeledSpecializeEntrySyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return LabeledSpecializeEntrySyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension LabeledSpecializeEntrySyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"label": Syntax(label).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"value": Syntax(value).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - NamedAttributeStringArgumentSyntax
///
/// The argument for the `@_dynamic_replacement` or `@_private`
/// attribute of the form `for: "function()"` or `sourceFile:
/// "Src.swift"`
///
public struct NamedAttributeStringArgumentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case nameTok
case colon
case stringOrDeclname
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `NamedAttributeStringArgumentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .namedAttributeStringArgument else { return nil }
self._syntaxNode = syntax
}
/// Creates a `NamedAttributeStringArgumentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .namedAttributeStringArgument)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The label of the argument
public var nameTok: TokenSyntax {
get {
let childData = data.child(at: Cursor.nameTok,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withNameTok(value)
}
}
/// Returns a copy of the receiver with its `nameTok` replaced.
/// - param newChild: The new `nameTok` to replace the node's
/// current `nameTok`, if present.
public func withNameTok(
_ newChild: TokenSyntax?) -> NamedAttributeStringArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.unknown(""))
let newData = data.replacingChild(raw, at: Cursor.nameTok)
return NamedAttributeStringArgumentSyntax(newData)
}
/// The colon separating the label and the value
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> NamedAttributeStringArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return NamedAttributeStringArgumentSyntax(newData)
}
public var stringOrDeclname: Syntax {
get {
let childData = data.child(at: Cursor.stringOrDeclname,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withStringOrDeclname(value)
}
}
/// Returns a copy of the receiver with its `stringOrDeclname` replaced.
/// - param newChild: The new `stringOrDeclname` to replace the node's
/// current `stringOrDeclname`, if present.
public func withStringOrDeclname(
_ newChild: Syntax?) -> NamedAttributeStringArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.stringOrDeclname)
return NamedAttributeStringArgumentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is Syntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
}
}
extension NamedAttributeStringArgumentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"nameTok": Syntax(nameTok).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"stringOrDeclname": Syntax(stringOrDeclname).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - DeclNameSyntax
public struct DeclNameSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case declBaseName
case declNameArguments
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DeclNameSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .declName else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DeclNameSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .declName)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
///
/// The base name of the protocol's requirement.
///
public var declBaseName: Syntax {
get {
let childData = data.child(at: Cursor.declBaseName,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withDeclBaseName(value)
}
}
/// Returns a copy of the receiver with its `declBaseName` replaced.
/// - param newChild: The new `declBaseName` to replace the node's
/// current `declBaseName`, if present.
public func withDeclBaseName(
_ newChild: Syntax?) -> DeclNameSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.declBaseName)
return DeclNameSyntax(newData)
}
///
/// The argument labels of the protocol's requirement if it
/// is a function requirement.
///
public var declNameArguments: DeclNameArgumentsSyntax? {
get {
let childData = data.child(at: Cursor.declNameArguments,
parent: Syntax(self))
if childData == nil { return nil }
return DeclNameArgumentsSyntax(childData!)
}
set(value) {
self = withDeclNameArguments(value)
}
}
/// Returns a copy of the receiver with its `declNameArguments` replaced.
/// - param newChild: The new `declNameArguments` to replace the node's
/// current `declNameArguments`, if present.
public func withDeclNameArguments(
_ newChild: DeclNameArgumentsSyntax?) -> DeclNameSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.declNameArguments)
return DeclNameSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is DeclNameArgumentsSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DeclNameArgumentsSyntax.self))
}
}
}
extension DeclNameSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"declBaseName": Syntax(declBaseName).asProtocol(SyntaxProtocol.self),
"declNameArguments": declNameArguments.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - ImplementsAttributeArgumentsSyntax
///
/// The arguments for the `@_implements` attribute of the form
/// `Type, methodName(arg1Label:arg2Label:)`
///
public struct ImplementsAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case type
case comma
case declBaseName
case declNameArguments
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ImplementsAttributeArgumentsSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .implementsAttributeArguments else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ImplementsAttributeArgumentsSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .implementsAttributeArguments)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
///
/// The type for which the method with this attribute
/// implements a requirement.
///
public var type: SimpleTypeIdentifierSyntax {
get {
let childData = data.child(at: Cursor.type,
parent: Syntax(self))
return SimpleTypeIdentifierSyntax(childData!)
}
set(value) {
self = withType(value)
}
}
/// Returns a copy of the receiver with its `type` replaced.
/// - param newChild: The new `type` to replace the node's
/// current `type`, if present.
public func withType(
_ newChild: SimpleTypeIdentifierSyntax?) -> ImplementsAttributeArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.simpleTypeIdentifier)
let newData = data.replacingChild(raw, at: Cursor.type)
return ImplementsAttributeArgumentsSyntax(newData)
}
///
/// The comma separating the type and method name
///
public var comma: TokenSyntax {
get {
let childData = data.child(at: Cursor.comma,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withComma(value)
}
}
/// Returns a copy of the receiver with its `comma` replaced.
/// - param newChild: The new `comma` to replace the node's
/// current `comma`, if present.
public func withComma(
_ newChild: TokenSyntax?) -> ImplementsAttributeArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.comma)
let newData = data.replacingChild(raw, at: Cursor.comma)
return ImplementsAttributeArgumentsSyntax(newData)
}
///
/// The base name of the protocol's requirement.
///
public var declBaseName: Syntax {
get {
let childData = data.child(at: Cursor.declBaseName,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withDeclBaseName(value)
}
}
/// Returns a copy of the receiver with its `declBaseName` replaced.
/// - param newChild: The new `declBaseName` to replace the node's
/// current `declBaseName`, if present.
public func withDeclBaseName(
_ newChild: Syntax?) -> ImplementsAttributeArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.declBaseName)
return ImplementsAttributeArgumentsSyntax(newData)
}
///
/// The argument labels of the protocol's requirement if it
/// is a function requirement.
///
public var declNameArguments: DeclNameArgumentsSyntax? {
get {
let childData = data.child(at: Cursor.declNameArguments,
parent: Syntax(self))
if childData == nil { return nil }
return DeclNameArgumentsSyntax(childData!)
}
set(value) {
self = withDeclNameArguments(value)
}
}
/// Returns a copy of the receiver with its `declNameArguments` replaced.
/// - param newChild: The new `declNameArguments` to replace the node's
/// current `declNameArguments`, if present.
public func withDeclNameArguments(
_ newChild: DeclNameArgumentsSyntax?) -> ImplementsAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.declNameArguments)
return ImplementsAttributeArgumentsSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is SimpleTypeIdentifierSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(SimpleTypeIdentifierSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is Syntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #3 child is DeclNameArgumentsSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DeclNameArgumentsSyntax.self))
}
}
}
extension ImplementsAttributeArgumentsSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"type": Syntax(type).asProtocol(SyntaxProtocol.self),
"comma": Syntax(comma).asProtocol(SyntaxProtocol.self),
"declBaseName": Syntax(declBaseName).asProtocol(SyntaxProtocol.self),
"declNameArguments": declNameArguments.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - ObjCSelectorPieceSyntax
///
/// A piece of an Objective-C selector. Either consisiting of just an
/// identifier for a nullary selector, an identifier and a colon for a
/// labeled argument or just a colon for an unlabeled argument
///
public struct ObjCSelectorPieceSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case colon
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ObjCSelectorPieceSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .objCSelectorPiece else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ObjCSelectorPieceSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .objCSelectorPiece)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var name: TokenSyntax? {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> ObjCSelectorPieceSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.name)
return ObjCSelectorPieceSyntax(newData)
}
public var colon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> ObjCSelectorPieceSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.colon)
return ObjCSelectorPieceSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ObjCSelectorPieceSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": name.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"colon": colon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - DifferentiableAttributeArgumentsSyntax
///
/// The arguments for the `@differentiable` attribute: an optional
/// differentiability parameter clause and an optional 'where' clause.
///
public struct DifferentiableAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case diffParams
case diffParamsComma
case whereClause
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DifferentiableAttributeArgumentsSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .differentiableAttributeArguments else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DifferentiableAttributeArgumentsSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .differentiableAttributeArguments)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var diffParams: DifferentiabilityParamsClauseSyntax? {
get {
let childData = data.child(at: Cursor.diffParams,
parent: Syntax(self))
if childData == nil { return nil }
return DifferentiabilityParamsClauseSyntax(childData!)
}
set(value) {
self = withDiffParams(value)
}
}
/// Returns a copy of the receiver with its `diffParams` replaced.
/// - param newChild: The new `diffParams` to replace the node's
/// current `diffParams`, if present.
public func withDiffParams(
_ newChild: DifferentiabilityParamsClauseSyntax?) -> DifferentiableAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.diffParams)
return DifferentiableAttributeArgumentsSyntax(newData)
}
///
/// The comma following the differentiability parameters clause,
/// if it exists.
///
public var diffParamsComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.diffParamsComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withDiffParamsComma(value)
}
}
/// Returns a copy of the receiver with its `diffParamsComma` replaced.
/// - param newChild: The new `diffParamsComma` to replace the node's
/// current `diffParamsComma`, if present.
public func withDiffParamsComma(
_ newChild: TokenSyntax?) -> DifferentiableAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.diffParamsComma)
return DifferentiableAttributeArgumentsSyntax(newData)
}
public var whereClause: GenericWhereClauseSyntax? {
get {
let childData = data.child(at: Cursor.whereClause,
parent: Syntax(self))
if childData == nil { return nil }
return GenericWhereClauseSyntax(childData!)
}
set(value) {
self = withWhereClause(value)
}
}
/// Returns a copy of the receiver with its `whereClause` replaced.
/// - param newChild: The new `whereClause` to replace the node's
/// current `whereClause`, if present.
public func withWhereClause(
_ newChild: GenericWhereClauseSyntax?) -> DifferentiableAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.whereClause)
return DifferentiableAttributeArgumentsSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is DifferentiabilityParamsClauseSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DifferentiabilityParamsClauseSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is GenericWhereClauseSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(GenericWhereClauseSyntax.self))
}
}
}
extension DifferentiableAttributeArgumentsSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"diffParams": diffParams.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"diffParamsComma": diffParamsComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"whereClause": whereClause.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - DifferentiabilityParamsClauseSyntax
/// A clause containing differentiability parameters.
public struct DifferentiabilityParamsClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case wrtLabel
case colon
case parameters
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DifferentiabilityParamsClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .differentiabilityParamsClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DifferentiabilityParamsClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .differentiabilityParamsClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The "wrt" label.
public var wrtLabel: TokenSyntax {
get {
let childData = data.child(at: Cursor.wrtLabel,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withWrtLabel(value)
}
}
/// Returns a copy of the receiver with its `wrtLabel` replaced.
/// - param newChild: The new `wrtLabel` to replace the node's
/// current `wrtLabel`, if present.
public func withWrtLabel(
_ newChild: TokenSyntax?) -> DifferentiabilityParamsClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.wrtLabel)
return DifferentiabilityParamsClauseSyntax(newData)
}
///
/// The colon separating "wrt" and the parameter list.
///
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> DifferentiabilityParamsClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return DifferentiabilityParamsClauseSyntax(newData)
}
public var parameters: Syntax {
get {
let childData = data.child(at: Cursor.parameters,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withParameters(value)
}
}
/// Returns a copy of the receiver with its `parameters` replaced.
/// - param newChild: The new `parameters` to replace the node's
/// current `parameters`, if present.
public func withParameters(
_ newChild: Syntax?) -> DifferentiabilityParamsClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.parameters)
return DifferentiabilityParamsClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is Syntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
}
}
extension DifferentiabilityParamsClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"wrtLabel": Syntax(wrtLabel).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"parameters": Syntax(parameters).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - DifferentiabilityParamsSyntax
/// The differentiability parameters.
public struct DifferentiabilityParamsSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftParen
case diffParams
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DifferentiabilityParamsSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .differentiabilityParams else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DifferentiabilityParamsSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .differentiabilityParams)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> DifferentiabilityParamsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftParen)
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return DifferentiabilityParamsSyntax(newData)
}
/// The parameters for differentiation.
public var diffParams: DifferentiabilityParamListSyntax {
get {
let childData = data.child(at: Cursor.diffParams,
parent: Syntax(self))
return DifferentiabilityParamListSyntax(childData!)
}
set(value) {
self = withDiffParams(value)
}
}
/// Adds the provided `DifferentiabilityParam` to the node's `diffParams`
/// collection.
/// - param element: The new `DifferentiabilityParam` to add to the node's
/// `diffParams` collection.
/// - returns: A copy of the receiver with the provided `DifferentiabilityParam`
/// appended to its `diffParams` collection.
public func addDifferentiabilityParam(_ element: DifferentiabilityParamSyntax) -> DifferentiabilityParamsSyntax {
var collection: RawSyntax
if let col = raw[Cursor.diffParams] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.differentiabilityParamList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.diffParams)
return DifferentiabilityParamsSyntax(newData)
}
/// Returns a copy of the receiver with its `diffParams` replaced.
/// - param newChild: The new `diffParams` to replace the node's
/// current `diffParams`, if present.
public func withDiffParams(
_ newChild: DifferentiabilityParamListSyntax?) -> DifferentiabilityParamsSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.differentiabilityParamList)
let newData = data.replacingChild(raw, at: Cursor.diffParams)
return DifferentiabilityParamsSyntax(newData)
}
public var rightParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> DifferentiabilityParamsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightParen)
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return DifferentiabilityParamsSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is DifferentiabilityParamListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DifferentiabilityParamListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension DifferentiabilityParamsSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftParen": Syntax(leftParen).asProtocol(SyntaxProtocol.self),
"diffParams": Syntax(diffParams).asProtocol(SyntaxProtocol.self),
"rightParen": Syntax(rightParen).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - DifferentiabilityParamSyntax
///
/// A differentiability parameter: either the "self" identifier, a function
/// parameter name, or a function parameter index.
///
public struct DifferentiabilityParamSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case parameter
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DifferentiabilityParamSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .differentiabilityParam else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DifferentiabilityParamSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .differentiabilityParam)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var parameter: Syntax {
get {
let childData = data.child(at: Cursor.parameter,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withParameter(value)
}
}
/// Returns a copy of the receiver with its `parameter` replaced.
/// - param newChild: The new `parameter` to replace the node's
/// current `parameter`, if present.
public func withParameter(
_ newChild: Syntax?) -> DifferentiabilityParamSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.parameter)
return DifferentiabilityParamSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> DifferentiabilityParamSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return DifferentiabilityParamSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension DifferentiabilityParamSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"parameter": Syntax(parameter).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - DerivativeRegistrationAttributeArgumentsSyntax
///
/// The arguments for the '@derivative(of:)' and '@transpose(of:)'
/// attributes: the 'of:' label, the original declaration name, and an
/// optional differentiability parameter list.
///
public struct DerivativeRegistrationAttributeArgumentsSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case ofLabel
case colon
case originalDeclName
case period
case accessorKind
case comma
case diffParams
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `DerivativeRegistrationAttributeArgumentsSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .derivativeRegistrationAttributeArguments else { return nil }
self._syntaxNode = syntax
}
/// Creates a `DerivativeRegistrationAttributeArgumentsSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .derivativeRegistrationAttributeArguments)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The "of" label.
public var ofLabel: TokenSyntax {
get {
let childData = data.child(at: Cursor.ofLabel,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withOfLabel(value)
}
}
/// Returns a copy of the receiver with its `ofLabel` replaced.
/// - param newChild: The new `ofLabel` to replace the node's
/// current `ofLabel`, if present.
public func withOfLabel(
_ newChild: TokenSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.ofLabel)
return DerivativeRegistrationAttributeArgumentsSyntax(newData)
}
///
/// The colon separating the "of" label and the original
/// declaration name.
///
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return DerivativeRegistrationAttributeArgumentsSyntax(newData)
}
/// The referenced original declaration name.
public var originalDeclName: QualifiedDeclNameSyntax {
get {
let childData = data.child(at: Cursor.originalDeclName,
parent: Syntax(self))
return QualifiedDeclNameSyntax(childData!)
}
set(value) {
self = withOriginalDeclName(value)
}
}
/// Returns a copy of the receiver with its `originalDeclName` replaced.
/// - param newChild: The new `originalDeclName` to replace the node's
/// current `originalDeclName`, if present.
public func withOriginalDeclName(
_ newChild: QualifiedDeclNameSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.qualifiedDeclName)
let newData = data.replacingChild(raw, at: Cursor.originalDeclName)
return DerivativeRegistrationAttributeArgumentsSyntax(newData)
}
///
/// The period separating the original declaration name and the
/// accessor name.
///
public var period: TokenSyntax? {
get {
let childData = data.child(at: Cursor.period,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withPeriod(value)
}
}
/// Returns a copy of the receiver with its `period` replaced.
/// - param newChild: The new `period` to replace the node's
/// current `period`, if present.
public func withPeriod(
_ newChild: TokenSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.period)
return DerivativeRegistrationAttributeArgumentsSyntax(newData)
}
/// The accessor name.
public var accessorKind: TokenSyntax? {
get {
let childData = data.child(at: Cursor.accessorKind,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withAccessorKind(value)
}
}
/// Returns a copy of the receiver with its `accessorKind` replaced.
/// - param newChild: The new `accessorKind` to replace the node's
/// current `accessorKind`, if present.
public func withAccessorKind(
_ newChild: TokenSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.accessorKind)
return DerivativeRegistrationAttributeArgumentsSyntax(newData)
}
public var comma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.comma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withComma(value)
}
}
/// Returns a copy of the receiver with its `comma` replaced.
/// - param newChild: The new `comma` to replace the node's
/// current `comma`, if present.
public func withComma(
_ newChild: TokenSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.comma)
return DerivativeRegistrationAttributeArgumentsSyntax(newData)
}
public var diffParams: DifferentiabilityParamsClauseSyntax? {
get {
let childData = data.child(at: Cursor.diffParams,
parent: Syntax(self))
if childData == nil { return nil }
return DifferentiabilityParamsClauseSyntax(childData!)
}
set(value) {
self = withDiffParams(value)
}
}
/// Returns a copy of the receiver with its `diffParams` replaced.
/// - param newChild: The new `diffParams` to replace the node's
/// current `diffParams`, if present.
public func withDiffParams(
_ newChild: DifferentiabilityParamsClauseSyntax?) -> DerivativeRegistrationAttributeArgumentsSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.diffParams)
return DerivativeRegistrationAttributeArgumentsSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 7)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is QualifiedDeclNameSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(QualifiedDeclNameSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #4 child is TokenSyntax or missing
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #5 child is TokenSyntax or missing
if let raw = rawChildren[5].raw {
let info = rawChildren[5].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #6 child is DifferentiabilityParamsClauseSyntax or missing
if let raw = rawChildren[6].raw {
let info = rawChildren[6].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DifferentiabilityParamsClauseSyntax.self))
}
}
}
extension DerivativeRegistrationAttributeArgumentsSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"ofLabel": Syntax(ofLabel).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"originalDeclName": Syntax(originalDeclName).asProtocol(SyntaxProtocol.self),
"period": period.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"accessorKind": accessorKind.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"comma": comma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"diffParams": diffParams.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - QualifiedDeclNameSyntax
///
/// An optionally qualified function declaration name (e.g. `+(_:_:)`,
/// `A.B.C.foo(_:_:)`).
///
public struct QualifiedDeclNameSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case baseType
case dot
case name
case arguments
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `QualifiedDeclNameSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .qualifiedDeclName else { return nil }
self._syntaxNode = syntax
}
/// Creates a `QualifiedDeclNameSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .qualifiedDeclName)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
///
/// The base type of the qualified name, optionally specified.
///
public var baseType: TypeSyntax? {
get {
let childData = data.child(at: Cursor.baseType,
parent: Syntax(self))
if childData == nil { return nil }
return TypeSyntax(childData!)
}
set(value) {
self = withBaseType(value)
}
}
/// Returns a copy of the receiver with its `baseType` replaced.
/// - param newChild: The new `baseType` to replace the node's
/// current `baseType`, if present.
public func withBaseType(
_ newChild: TypeSyntax?) -> QualifiedDeclNameSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.baseType)
return QualifiedDeclNameSyntax(newData)
}
public var dot: TokenSyntax? {
get {
let childData = data.child(at: Cursor.dot,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withDot(value)
}
}
/// Returns a copy of the receiver with its `dot` replaced.
/// - param newChild: The new `dot` to replace the node's
/// current `dot`, if present.
public func withDot(
_ newChild: TokenSyntax?) -> QualifiedDeclNameSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.dot)
return QualifiedDeclNameSyntax(newData)
}
///
/// The base name of the referenced function.
///
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> QualifiedDeclNameSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return QualifiedDeclNameSyntax(newData)
}
///
/// The argument labels of the referenced function, optionally
/// specified.
///
public var arguments: DeclNameArgumentsSyntax? {
get {
let childData = data.child(at: Cursor.arguments,
parent: Syntax(self))
if childData == nil { return nil }
return DeclNameArgumentsSyntax(childData!)
}
set(value) {
self = withArguments(value)
}
}
/// Returns a copy of the receiver with its `arguments` replaced.
/// - param newChild: The new `arguments` to replace the node's
/// current `arguments`, if present.
public func withArguments(
_ newChild: DeclNameArgumentsSyntax?) -> QualifiedDeclNameSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.arguments)
return QualifiedDeclNameSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TypeSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is DeclNameArgumentsSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DeclNameArgumentsSyntax.self))
}
}
}
extension QualifiedDeclNameSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"baseType": baseType.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"dot": dot.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"arguments": arguments.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - FunctionDeclNameSyntax
/// A function declaration name (e.g. `foo(_:_:)`).
public struct FunctionDeclNameSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case name
case arguments
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `FunctionDeclNameSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .functionDeclName else { return nil }
self._syntaxNode = syntax
}
/// Creates a `FunctionDeclNameSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .functionDeclName)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
///
/// The base name of the referenced function.
///
public var name: Syntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: Syntax?) -> FunctionDeclNameSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.name)
return FunctionDeclNameSyntax(newData)
}
///
/// The argument labels of the referenced function, optionally
/// specified.
///
public var arguments: DeclNameArgumentsSyntax? {
get {
let childData = data.child(at: Cursor.arguments,
parent: Syntax(self))
if childData == nil { return nil }
return DeclNameArgumentsSyntax(childData!)
}
set(value) {
self = withArguments(value)
}
}
/// Returns a copy of the receiver with its `arguments` replaced.
/// - param newChild: The new `arguments` to replace the node's
/// current `arguments`, if present.
public func withArguments(
_ newChild: DeclNameArgumentsSyntax?) -> FunctionDeclNameSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.arguments)
return FunctionDeclNameSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is DeclNameArgumentsSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(DeclNameArgumentsSyntax.self))
}
}
}
extension FunctionDeclNameSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"arguments": arguments.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - WhereClauseSyntax
public struct WhereClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case whereKeyword
case guardResult
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `WhereClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .whereClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `WhereClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .whereClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var whereKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.whereKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withWhereKeyword(value)
}
}
/// Returns a copy of the receiver with its `whereKeyword` replaced.
/// - param newChild: The new `whereKeyword` to replace the node's
/// current `whereKeyword`, if present.
public func withWhereKeyword(
_ newChild: TokenSyntax?) -> WhereClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.whereKeyword)
let newData = data.replacingChild(raw, at: Cursor.whereKeyword)
return WhereClauseSyntax(newData)
}
public var guardResult: ExprSyntax {
get {
let childData = data.child(at: Cursor.guardResult,
parent: Syntax(self))
return ExprSyntax(childData!)
}
set(value) {
self = withGuardResult(value)
}
}
/// Returns a copy of the receiver with its `guardResult` replaced.
/// - param newChild: The new `guardResult` to replace the node's
/// current `guardResult`, if present.
public func withGuardResult(
_ newChild: ExprSyntax?) -> WhereClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.expr)
let newData = data.replacingChild(raw, at: Cursor.guardResult)
return WhereClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is ExprSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprSyntax.self))
}
}
}
extension WhereClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"whereKeyword": Syntax(whereKeyword).asProtocol(SyntaxProtocol.self),
"guardResult": Syntax(guardResult).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - YieldListSyntax
public struct YieldListSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftParen
case elementList
case trailingComma
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `YieldListSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .yieldList else { return nil }
self._syntaxNode = syntax
}
/// Creates a `YieldListSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .yieldList)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> YieldListSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftParen)
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return YieldListSyntax(newData)
}
public var elementList: ExprListSyntax {
get {
let childData = data.child(at: Cursor.elementList,
parent: Syntax(self))
return ExprListSyntax(childData!)
}
set(value) {
self = withElementList(value)
}
}
/// Adds the provided `Element` to the node's `elementList`
/// collection.
/// - param element: The new `Element` to add to the node's
/// `elementList` collection.
/// - returns: A copy of the receiver with the provided `Element`
/// appended to its `elementList` collection.
public func addElement(_ element: ExprSyntax) -> YieldListSyntax {
var collection: RawSyntax
if let col = raw[Cursor.elementList] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.exprList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.elementList)
return YieldListSyntax(newData)
}
/// Returns a copy of the receiver with its `elementList` replaced.
/// - param newChild: The new `elementList` to replace the node's
/// current `elementList`, if present.
public func withElementList(
_ newChild: ExprListSyntax?) -> YieldListSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.exprList)
let newData = data.replacingChild(raw, at: Cursor.elementList)
return YieldListSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> YieldListSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return YieldListSyntax(newData)
}
public var rightParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> YieldListSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightParen)
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return YieldListSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is ExprListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(ExprListSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TokenSyntax
assert(rawChildren[3].raw != nil)
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension YieldListSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftParen": Syntax(leftParen).asProtocol(SyntaxProtocol.self),
"elementList": Syntax(elementList).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"rightParen": Syntax(rightParen).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ConditionElementSyntax
public struct ConditionElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case condition
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ConditionElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .conditionElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ConditionElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .conditionElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var condition: Syntax {
get {
let childData = data.child(at: Cursor.condition,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withCondition(value)
}
}
/// Returns a copy of the receiver with its `condition` replaced.
/// - param newChild: The new `condition` to replace the node's
/// current `condition`, if present.
public func withCondition(
_ newChild: Syntax?) -> ConditionElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.condition)
return ConditionElementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> ConditionElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return ConditionElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension ConditionElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"condition": Syntax(condition).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - AvailabilityConditionSyntax
public struct AvailabilityConditionSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case poundAvailableKeyword
case leftParen
case availabilitySpec
case rightParen
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AvailabilityConditionSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .availabilityCondition else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AvailabilityConditionSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .availabilityCondition)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var poundAvailableKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.poundAvailableKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withPoundAvailableKeyword(value)
}
}
/// Returns a copy of the receiver with its `poundAvailableKeyword` replaced.
/// - param newChild: The new `poundAvailableKeyword` to replace the node's
/// current `poundAvailableKeyword`, if present.
public func withPoundAvailableKeyword(
_ newChild: TokenSyntax?) -> AvailabilityConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.poundAvailableKeyword)
let newData = data.replacingChild(raw, at: Cursor.poundAvailableKeyword)
return AvailabilityConditionSyntax(newData)
}
public var leftParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftParen(value)
}
}
/// Returns a copy of the receiver with its `leftParen` replaced.
/// - param newChild: The new `leftParen` to replace the node's
/// current `leftParen`, if present.
public func withLeftParen(
_ newChild: TokenSyntax?) -> AvailabilityConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftParen)
let newData = data.replacingChild(raw, at: Cursor.leftParen)
return AvailabilityConditionSyntax(newData)
}
public var availabilitySpec: AvailabilitySpecListSyntax {
get {
let childData = data.child(at: Cursor.availabilitySpec,
parent: Syntax(self))
return AvailabilitySpecListSyntax(childData!)
}
set(value) {
self = withAvailabilitySpec(value)
}
}
/// Adds the provided `AvailabilityArgument` to the node's `availabilitySpec`
/// collection.
/// - param element: The new `AvailabilityArgument` to add to the node's
/// `availabilitySpec` collection.
/// - returns: A copy of the receiver with the provided `AvailabilityArgument`
/// appended to its `availabilitySpec` collection.
public func addAvailabilityArgument(_ element: AvailabilityArgumentSyntax) -> AvailabilityConditionSyntax {
var collection: RawSyntax
if let col = raw[Cursor.availabilitySpec] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.availabilitySpecList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.availabilitySpec)
return AvailabilityConditionSyntax(newData)
}
/// Returns a copy of the receiver with its `availabilitySpec` replaced.
/// - param newChild: The new `availabilitySpec` to replace the node's
/// current `availabilitySpec`, if present.
public func withAvailabilitySpec(
_ newChild: AvailabilitySpecListSyntax?) -> AvailabilityConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.availabilitySpecList)
let newData = data.replacingChild(raw, at: Cursor.availabilitySpec)
return AvailabilityConditionSyntax(newData)
}
public var rightParen: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightParen,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightParen(value)
}
}
/// Returns a copy of the receiver with its `rightParen` replaced.
/// - param newChild: The new `rightParen` to replace the node's
/// current `rightParen`, if present.
public func withRightParen(
_ newChild: TokenSyntax?) -> AvailabilityConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightParen)
let newData = data.replacingChild(raw, at: Cursor.rightParen)
return AvailabilityConditionSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is AvailabilitySpecListSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(AvailabilitySpecListSyntax.self))
}
// Check child #3 child is TokenSyntax
assert(rawChildren[3].raw != nil)
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension AvailabilityConditionSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"poundAvailableKeyword": Syntax(poundAvailableKeyword).asProtocol(SyntaxProtocol.self),
"leftParen": Syntax(leftParen).asProtocol(SyntaxProtocol.self),
"availabilitySpec": Syntax(availabilitySpec).asProtocol(SyntaxProtocol.self),
"rightParen": Syntax(rightParen).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - MatchingPatternConditionSyntax
public struct MatchingPatternConditionSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case caseKeyword
case pattern
case typeAnnotation
case initializer
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `MatchingPatternConditionSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .matchingPatternCondition else { return nil }
self._syntaxNode = syntax
}
/// Creates a `MatchingPatternConditionSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .matchingPatternCondition)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var caseKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.caseKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withCaseKeyword(value)
}
}
/// Returns a copy of the receiver with its `caseKeyword` replaced.
/// - param newChild: The new `caseKeyword` to replace the node's
/// current `caseKeyword`, if present.
public func withCaseKeyword(
_ newChild: TokenSyntax?) -> MatchingPatternConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.caseKeyword)
let newData = data.replacingChild(raw, at: Cursor.caseKeyword)
return MatchingPatternConditionSyntax(newData)
}
public var pattern: PatternSyntax {
get {
let childData = data.child(at: Cursor.pattern,
parent: Syntax(self))
return PatternSyntax(childData!)
}
set(value) {
self = withPattern(value)
}
}
/// Returns a copy of the receiver with its `pattern` replaced.
/// - param newChild: The new `pattern` to replace the node's
/// current `pattern`, if present.
public func withPattern(
_ newChild: PatternSyntax?) -> MatchingPatternConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.pattern)
let newData = data.replacingChild(raw, at: Cursor.pattern)
return MatchingPatternConditionSyntax(newData)
}
public var typeAnnotation: TypeAnnotationSyntax? {
get {
let childData = data.child(at: Cursor.typeAnnotation,
parent: Syntax(self))
if childData == nil { return nil }
return TypeAnnotationSyntax(childData!)
}
set(value) {
self = withTypeAnnotation(value)
}
}
/// Returns a copy of the receiver with its `typeAnnotation` replaced.
/// - param newChild: The new `typeAnnotation` to replace the node's
/// current `typeAnnotation`, if present.
public func withTypeAnnotation(
_ newChild: TypeAnnotationSyntax?) -> MatchingPatternConditionSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.typeAnnotation)
return MatchingPatternConditionSyntax(newData)
}
public var initializer: InitializerClauseSyntax {
get {
let childData = data.child(at: Cursor.initializer,
parent: Syntax(self))
return InitializerClauseSyntax(childData!)
}
set(value) {
self = withInitializer(value)
}
}
/// Returns a copy of the receiver with its `initializer` replaced.
/// - param newChild: The new `initializer` to replace the node's
/// current `initializer`, if present.
public func withInitializer(
_ newChild: InitializerClauseSyntax?) -> MatchingPatternConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.initializerClause)
let newData = data.replacingChild(raw, at: Cursor.initializer)
return MatchingPatternConditionSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is PatternSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(PatternSyntax.self))
}
// Check child #2 child is TypeAnnotationSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeAnnotationSyntax.self))
}
// Check child #3 child is InitializerClauseSyntax
assert(rawChildren[3].raw != nil)
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(InitializerClauseSyntax.self))
}
}
}
extension MatchingPatternConditionSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"caseKeyword": Syntax(caseKeyword).asProtocol(SyntaxProtocol.self),
"pattern": Syntax(pattern).asProtocol(SyntaxProtocol.self),
"typeAnnotation": typeAnnotation.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"initializer": Syntax(initializer).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - OptionalBindingConditionSyntax
public struct OptionalBindingConditionSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case letOrVarKeyword
case pattern
case typeAnnotation
case initializer
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `OptionalBindingConditionSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .optionalBindingCondition else { return nil }
self._syntaxNode = syntax
}
/// Creates a `OptionalBindingConditionSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .optionalBindingCondition)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var letOrVarKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.letOrVarKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLetOrVarKeyword(value)
}
}
/// Returns a copy of the receiver with its `letOrVarKeyword` replaced.
/// - param newChild: The new `letOrVarKeyword` to replace the node's
/// current `letOrVarKeyword`, if present.
public func withLetOrVarKeyword(
_ newChild: TokenSyntax?) -> OptionalBindingConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.letKeyword)
let newData = data.replacingChild(raw, at: Cursor.letOrVarKeyword)
return OptionalBindingConditionSyntax(newData)
}
public var pattern: PatternSyntax {
get {
let childData = data.child(at: Cursor.pattern,
parent: Syntax(self))
return PatternSyntax(childData!)
}
set(value) {
self = withPattern(value)
}
}
/// Returns a copy of the receiver with its `pattern` replaced.
/// - param newChild: The new `pattern` to replace the node's
/// current `pattern`, if present.
public func withPattern(
_ newChild: PatternSyntax?) -> OptionalBindingConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.pattern)
let newData = data.replacingChild(raw, at: Cursor.pattern)
return OptionalBindingConditionSyntax(newData)
}
public var typeAnnotation: TypeAnnotationSyntax? {
get {
let childData = data.child(at: Cursor.typeAnnotation,
parent: Syntax(self))
if childData == nil { return nil }
return TypeAnnotationSyntax(childData!)
}
set(value) {
self = withTypeAnnotation(value)
}
}
/// Returns a copy of the receiver with its `typeAnnotation` replaced.
/// - param newChild: The new `typeAnnotation` to replace the node's
/// current `typeAnnotation`, if present.
public func withTypeAnnotation(
_ newChild: TypeAnnotationSyntax?) -> OptionalBindingConditionSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.typeAnnotation)
return OptionalBindingConditionSyntax(newData)
}
public var initializer: InitializerClauseSyntax {
get {
let childData = data.child(at: Cursor.initializer,
parent: Syntax(self))
return InitializerClauseSyntax(childData!)
}
set(value) {
self = withInitializer(value)
}
}
/// Returns a copy of the receiver with its `initializer` replaced.
/// - param newChild: The new `initializer` to replace the node's
/// current `initializer`, if present.
public func withInitializer(
_ newChild: InitializerClauseSyntax?) -> OptionalBindingConditionSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.initializerClause)
let newData = data.replacingChild(raw, at: Cursor.initializer)
return OptionalBindingConditionSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is PatternSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(PatternSyntax.self))
}
// Check child #2 child is TypeAnnotationSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeAnnotationSyntax.self))
}
// Check child #3 child is InitializerClauseSyntax
assert(rawChildren[3].raw != nil)
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(InitializerClauseSyntax.self))
}
}
}
extension OptionalBindingConditionSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"letOrVarKeyword": Syntax(letOrVarKeyword).asProtocol(SyntaxProtocol.self),
"pattern": Syntax(pattern).asProtocol(SyntaxProtocol.self),
"typeAnnotation": typeAnnotation.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"initializer": Syntax(initializer).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ElseIfContinuationSyntax
public struct ElseIfContinuationSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case ifStatement
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ElseIfContinuationSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .elseIfContinuation else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ElseIfContinuationSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .elseIfContinuation)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var ifStatement: IfStmtSyntax {
get {
let childData = data.child(at: Cursor.ifStatement,
parent: Syntax(self))
return IfStmtSyntax(childData!)
}
set(value) {
self = withIfStatement(value)
}
}
/// Returns a copy of the receiver with its `ifStatement` replaced.
/// - param newChild: The new `ifStatement` to replace the node's
/// current `ifStatement`, if present.
public func withIfStatement(
_ newChild: IfStmtSyntax?) -> ElseIfContinuationSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.ifStmt)
let newData = data.replacingChild(raw, at: Cursor.ifStatement)
return ElseIfContinuationSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 1)
// Check child #0 child is IfStmtSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(IfStmtSyntax.self))
}
}
}
extension ElseIfContinuationSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"ifStatement": Syntax(ifStatement).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ElseBlockSyntax
public struct ElseBlockSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case elseKeyword
case body
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ElseBlockSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .elseBlock else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ElseBlockSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .elseBlock)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var elseKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.elseKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withElseKeyword(value)
}
}
/// Returns a copy of the receiver with its `elseKeyword` replaced.
/// - param newChild: The new `elseKeyword` to replace the node's
/// current `elseKeyword`, if present.
public func withElseKeyword(
_ newChild: TokenSyntax?) -> ElseBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.elseKeyword)
let newData = data.replacingChild(raw, at: Cursor.elseKeyword)
return ElseBlockSyntax(newData)
}
public var body: CodeBlockSyntax {
get {
let childData = data.child(at: Cursor.body,
parent: Syntax(self))
return CodeBlockSyntax(childData!)
}
set(value) {
self = withBody(value)
}
}
/// Returns a copy of the receiver with its `body` replaced.
/// - param newChild: The new `body` to replace the node's
/// current `body`, if present.
public func withBody(
_ newChild: CodeBlockSyntax?) -> ElseBlockSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.codeBlock)
let newData = data.replacingChild(raw, at: Cursor.body)
return ElseBlockSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is CodeBlockSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(CodeBlockSyntax.self))
}
}
}
extension ElseBlockSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"elseKeyword": Syntax(elseKeyword).asProtocol(SyntaxProtocol.self),
"body": Syntax(body).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - SwitchCaseSyntax
public struct SwitchCaseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case unknownAttr
case label
case statements
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `SwitchCaseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .switchCase else { return nil }
self._syntaxNode = syntax
}
/// Creates a `SwitchCaseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .switchCase)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var unknownAttr: AttributeSyntax? {
get {
let childData = data.child(at: Cursor.unknownAttr,
parent: Syntax(self))
if childData == nil { return nil }
return AttributeSyntax(childData!)
}
set(value) {
self = withUnknownAttr(value)
}
}
/// Returns a copy of the receiver with its `unknownAttr` replaced.
/// - param newChild: The new `unknownAttr` to replace the node's
/// current `unknownAttr`, if present.
public func withUnknownAttr(
_ newChild: AttributeSyntax?) -> SwitchCaseSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.unknownAttr)
return SwitchCaseSyntax(newData)
}
public var label: Syntax {
get {
let childData = data.child(at: Cursor.label,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withLabel(value)
}
}
/// Returns a copy of the receiver with its `label` replaced.
/// - param newChild: The new `label` to replace the node's
/// current `label`, if present.
public func withLabel(
_ newChild: Syntax?) -> SwitchCaseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.label)
return SwitchCaseSyntax(newData)
}
public var statements: CodeBlockItemListSyntax {
get {
let childData = data.child(at: Cursor.statements,
parent: Syntax(self))
return CodeBlockItemListSyntax(childData!)
}
set(value) {
self = withStatements(value)
}
}
/// Adds the provided `Statement` to the node's `statements`
/// collection.
/// - param element: The new `Statement` to add to the node's
/// `statements` collection.
/// - returns: A copy of the receiver with the provided `Statement`
/// appended to its `statements` collection.
public func addStatement(_ element: CodeBlockItemSyntax) -> SwitchCaseSyntax {
var collection: RawSyntax
if let col = raw[Cursor.statements] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.codeBlockItemList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.statements)
return SwitchCaseSyntax(newData)
}
/// Returns a copy of the receiver with its `statements` replaced.
/// - param newChild: The new `statements` to replace the node's
/// current `statements`, if present.
public func withStatements(
_ newChild: CodeBlockItemListSyntax?) -> SwitchCaseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.codeBlockItemList)
let newData = data.replacingChild(raw, at: Cursor.statements)
return SwitchCaseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is AttributeSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(AttributeSyntax.self))
}
// Check child #1 child is Syntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #2 child is CodeBlockItemListSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(CodeBlockItemListSyntax.self))
}
}
}
extension SwitchCaseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"unknownAttr": unknownAttr.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"label": Syntax(label).asProtocol(SyntaxProtocol.self),
"statements": Syntax(statements).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - SwitchDefaultLabelSyntax
public struct SwitchDefaultLabelSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case defaultKeyword
case colon
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `SwitchDefaultLabelSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .switchDefaultLabel else { return nil }
self._syntaxNode = syntax
}
/// Creates a `SwitchDefaultLabelSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .switchDefaultLabel)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var defaultKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.defaultKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withDefaultKeyword(value)
}
}
/// Returns a copy of the receiver with its `defaultKeyword` replaced.
/// - param newChild: The new `defaultKeyword` to replace the node's
/// current `defaultKeyword`, if present.
public func withDefaultKeyword(
_ newChild: TokenSyntax?) -> SwitchDefaultLabelSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.defaultKeyword)
let newData = data.replacingChild(raw, at: Cursor.defaultKeyword)
return SwitchDefaultLabelSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> SwitchDefaultLabelSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return SwitchDefaultLabelSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension SwitchDefaultLabelSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"defaultKeyword": Syntax(defaultKeyword).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - CaseItemSyntax
public struct CaseItemSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case pattern
case whereClause
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `CaseItemSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .caseItem else { return nil }
self._syntaxNode = syntax
}
/// Creates a `CaseItemSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .caseItem)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var pattern: PatternSyntax {
get {
let childData = data.child(at: Cursor.pattern,
parent: Syntax(self))
return PatternSyntax(childData!)
}
set(value) {
self = withPattern(value)
}
}
/// Returns a copy of the receiver with its `pattern` replaced.
/// - param newChild: The new `pattern` to replace the node's
/// current `pattern`, if present.
public func withPattern(
_ newChild: PatternSyntax?) -> CaseItemSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.pattern)
let newData = data.replacingChild(raw, at: Cursor.pattern)
return CaseItemSyntax(newData)
}
public var whereClause: WhereClauseSyntax? {
get {
let childData = data.child(at: Cursor.whereClause,
parent: Syntax(self))
if childData == nil { return nil }
return WhereClauseSyntax(childData!)
}
set(value) {
self = withWhereClause(value)
}
}
/// Returns a copy of the receiver with its `whereClause` replaced.
/// - param newChild: The new `whereClause` to replace the node's
/// current `whereClause`, if present.
public func withWhereClause(
_ newChild: WhereClauseSyntax?) -> CaseItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.whereClause)
return CaseItemSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> CaseItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return CaseItemSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is PatternSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(PatternSyntax.self))
}
// Check child #1 child is WhereClauseSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(WhereClauseSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension CaseItemSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"pattern": Syntax(pattern).asProtocol(SyntaxProtocol.self),
"whereClause": whereClause.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - CatchItemSyntax
public struct CatchItemSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case pattern
case whereClause
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `CatchItemSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .catchItem else { return nil }
self._syntaxNode = syntax
}
/// Creates a `CatchItemSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .catchItem)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var pattern: PatternSyntax? {
get {
let childData = data.child(at: Cursor.pattern,
parent: Syntax(self))
if childData == nil { return nil }
return PatternSyntax(childData!)
}
set(value) {
self = withPattern(value)
}
}
/// Returns a copy of the receiver with its `pattern` replaced.
/// - param newChild: The new `pattern` to replace the node's
/// current `pattern`, if present.
public func withPattern(
_ newChild: PatternSyntax?) -> CatchItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.pattern)
return CatchItemSyntax(newData)
}
public var whereClause: WhereClauseSyntax? {
get {
let childData = data.child(at: Cursor.whereClause,
parent: Syntax(self))
if childData == nil { return nil }
return WhereClauseSyntax(childData!)
}
set(value) {
self = withWhereClause(value)
}
}
/// Returns a copy of the receiver with its `whereClause` replaced.
/// - param newChild: The new `whereClause` to replace the node's
/// current `whereClause`, if present.
public func withWhereClause(
_ newChild: WhereClauseSyntax?) -> CatchItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.whereClause)
return CatchItemSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> CatchItemSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return CatchItemSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is PatternSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(PatternSyntax.self))
}
// Check child #1 child is WhereClauseSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(WhereClauseSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension CatchItemSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"pattern": pattern.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"whereClause": whereClause.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - SwitchCaseLabelSyntax
public struct SwitchCaseLabelSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case caseKeyword
case caseItems
case colon
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `SwitchCaseLabelSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .switchCaseLabel else { return nil }
self._syntaxNode = syntax
}
/// Creates a `SwitchCaseLabelSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .switchCaseLabel)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var caseKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.caseKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withCaseKeyword(value)
}
}
/// Returns a copy of the receiver with its `caseKeyword` replaced.
/// - param newChild: The new `caseKeyword` to replace the node's
/// current `caseKeyword`, if present.
public func withCaseKeyword(
_ newChild: TokenSyntax?) -> SwitchCaseLabelSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.caseKeyword)
let newData = data.replacingChild(raw, at: Cursor.caseKeyword)
return SwitchCaseLabelSyntax(newData)
}
public var caseItems: CaseItemListSyntax {
get {
let childData = data.child(at: Cursor.caseItems,
parent: Syntax(self))
return CaseItemListSyntax(childData!)
}
set(value) {
self = withCaseItems(value)
}
}
/// Adds the provided `CaseItem` to the node's `caseItems`
/// collection.
/// - param element: The new `CaseItem` to add to the node's
/// `caseItems` collection.
/// - returns: A copy of the receiver with the provided `CaseItem`
/// appended to its `caseItems` collection.
public func addCaseItem(_ element: CaseItemSyntax) -> SwitchCaseLabelSyntax {
var collection: RawSyntax
if let col = raw[Cursor.caseItems] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.caseItemList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.caseItems)
return SwitchCaseLabelSyntax(newData)
}
/// Returns a copy of the receiver with its `caseItems` replaced.
/// - param newChild: The new `caseItems` to replace the node's
/// current `caseItems`, if present.
public func withCaseItems(
_ newChild: CaseItemListSyntax?) -> SwitchCaseLabelSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.caseItemList)
let newData = data.replacingChild(raw, at: Cursor.caseItems)
return SwitchCaseLabelSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> SwitchCaseLabelSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return SwitchCaseLabelSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is CaseItemListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(CaseItemListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension SwitchCaseLabelSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"caseKeyword": Syntax(caseKeyword).asProtocol(SyntaxProtocol.self),
"caseItems": Syntax(caseItems).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - CatchClauseSyntax
public struct CatchClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case catchKeyword
case catchItems
case body
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `CatchClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .catchClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `CatchClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .catchClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var catchKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.catchKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withCatchKeyword(value)
}
}
/// Returns a copy of the receiver with its `catchKeyword` replaced.
/// - param newChild: The new `catchKeyword` to replace the node's
/// current `catchKeyword`, if present.
public func withCatchKeyword(
_ newChild: TokenSyntax?) -> CatchClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.catchKeyword)
let newData = data.replacingChild(raw, at: Cursor.catchKeyword)
return CatchClauseSyntax(newData)
}
public var catchItems: CatchItemListSyntax? {
get {
let childData = data.child(at: Cursor.catchItems,
parent: Syntax(self))
if childData == nil { return nil }
return CatchItemListSyntax(childData!)
}
set(value) {
self = withCatchItems(value)
}
}
/// Adds the provided `CatchItem` to the node's `catchItems`
/// collection.
/// - param element: The new `CatchItem` to add to the node's
/// `catchItems` collection.
/// - returns: A copy of the receiver with the provided `CatchItem`
/// appended to its `catchItems` collection.
public func addCatchItem(_ element: CatchItemSyntax) -> CatchClauseSyntax {
var collection: RawSyntax
if let col = raw[Cursor.catchItems] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.catchItemList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.catchItems)
return CatchClauseSyntax(newData)
}
/// Returns a copy of the receiver with its `catchItems` replaced.
/// - param newChild: The new `catchItems` to replace the node's
/// current `catchItems`, if present.
public func withCatchItems(
_ newChild: CatchItemListSyntax?) -> CatchClauseSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.catchItems)
return CatchClauseSyntax(newData)
}
public var body: CodeBlockSyntax {
get {
let childData = data.child(at: Cursor.body,
parent: Syntax(self))
return CodeBlockSyntax(childData!)
}
set(value) {
self = withBody(value)
}
}
/// Returns a copy of the receiver with its `body` replaced.
/// - param newChild: The new `body` to replace the node's
/// current `body`, if present.
public func withBody(
_ newChild: CodeBlockSyntax?) -> CatchClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.codeBlock)
let newData = data.replacingChild(raw, at: Cursor.body)
return CatchClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is CatchItemListSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(CatchItemListSyntax.self))
}
// Check child #2 child is CodeBlockSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(CodeBlockSyntax.self))
}
}
}
extension CatchClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"catchKeyword": Syntax(catchKeyword).asProtocol(SyntaxProtocol.self),
"catchItems": catchItems.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"body": Syntax(body).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - GenericWhereClauseSyntax
public struct GenericWhereClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case whereKeyword
case requirementList
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `GenericWhereClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .genericWhereClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `GenericWhereClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .genericWhereClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var whereKeyword: TokenSyntax {
get {
let childData = data.child(at: Cursor.whereKeyword,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withWhereKeyword(value)
}
}
/// Returns a copy of the receiver with its `whereKeyword` replaced.
/// - param newChild: The new `whereKeyword` to replace the node's
/// current `whereKeyword`, if present.
public func withWhereKeyword(
_ newChild: TokenSyntax?) -> GenericWhereClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.whereKeyword)
let newData = data.replacingChild(raw, at: Cursor.whereKeyword)
return GenericWhereClauseSyntax(newData)
}
public var requirementList: GenericRequirementListSyntax {
get {
let childData = data.child(at: Cursor.requirementList,
parent: Syntax(self))
return GenericRequirementListSyntax(childData!)
}
set(value) {
self = withRequirementList(value)
}
}
/// Adds the provided `Requirement` to the node's `requirementList`
/// collection.
/// - param element: The new `Requirement` to add to the node's
/// `requirementList` collection.
/// - returns: A copy of the receiver with the provided `Requirement`
/// appended to its `requirementList` collection.
public func addRequirement(_ element: GenericRequirementSyntax) -> GenericWhereClauseSyntax {
var collection: RawSyntax
if let col = raw[Cursor.requirementList] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.genericRequirementList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.requirementList)
return GenericWhereClauseSyntax(newData)
}
/// Returns a copy of the receiver with its `requirementList` replaced.
/// - param newChild: The new `requirementList` to replace the node's
/// current `requirementList`, if present.
public func withRequirementList(
_ newChild: GenericRequirementListSyntax?) -> GenericWhereClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.genericRequirementList)
let newData = data.replacingChild(raw, at: Cursor.requirementList)
return GenericWhereClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is GenericRequirementListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(GenericRequirementListSyntax.self))
}
}
}
extension GenericWhereClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"whereKeyword": Syntax(whereKeyword).asProtocol(SyntaxProtocol.self),
"requirementList": Syntax(requirementList).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - GenericRequirementSyntax
public struct GenericRequirementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case body
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `GenericRequirementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .genericRequirement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `GenericRequirementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .genericRequirement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var body: Syntax {
get {
let childData = data.child(at: Cursor.body,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withBody(value)
}
}
/// Returns a copy of the receiver with its `body` replaced.
/// - param newChild: The new `body` to replace the node's
/// current `body`, if present.
public func withBody(
_ newChild: Syntax?) -> GenericRequirementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.body)
return GenericRequirementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> GenericRequirementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return GenericRequirementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension GenericRequirementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"body": Syntax(body).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - SameTypeRequirementSyntax
public struct SameTypeRequirementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftTypeIdentifier
case equalityToken
case rightTypeIdentifier
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `SameTypeRequirementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .sameTypeRequirement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `SameTypeRequirementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .sameTypeRequirement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftTypeIdentifier: TypeSyntax {
get {
let childData = data.child(at: Cursor.leftTypeIdentifier,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withLeftTypeIdentifier(value)
}
}
/// Returns a copy of the receiver with its `leftTypeIdentifier` replaced.
/// - param newChild: The new `leftTypeIdentifier` to replace the node's
/// current `leftTypeIdentifier`, if present.
public func withLeftTypeIdentifier(
_ newChild: TypeSyntax?) -> SameTypeRequirementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.leftTypeIdentifier)
return SameTypeRequirementSyntax(newData)
}
public var equalityToken: TokenSyntax {
get {
let childData = data.child(at: Cursor.equalityToken,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withEqualityToken(value)
}
}
/// Returns a copy of the receiver with its `equalityToken` replaced.
/// - param newChild: The new `equalityToken` to replace the node's
/// current `equalityToken`, if present.
public func withEqualityToken(
_ newChild: TokenSyntax?) -> SameTypeRequirementSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.spacedBinaryOperator(""))
let newData = data.replacingChild(raw, at: Cursor.equalityToken)
return SameTypeRequirementSyntax(newData)
}
public var rightTypeIdentifier: TypeSyntax {
get {
let childData = data.child(at: Cursor.rightTypeIdentifier,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withRightTypeIdentifier(value)
}
}
/// Returns a copy of the receiver with its `rightTypeIdentifier` replaced.
/// - param newChild: The new `rightTypeIdentifier` to replace the node's
/// current `rightTypeIdentifier`, if present.
public func withRightTypeIdentifier(
_ newChild: TypeSyntax?) -> SameTypeRequirementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.rightTypeIdentifier)
return SameTypeRequirementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TypeSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TypeSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
}
}
extension SameTypeRequirementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftTypeIdentifier": Syntax(leftTypeIdentifier).asProtocol(SyntaxProtocol.self),
"equalityToken": Syntax(equalityToken).asProtocol(SyntaxProtocol.self),
"rightTypeIdentifier": Syntax(rightTypeIdentifier).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - GenericParameterSyntax
public struct GenericParameterSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case attributes
case name
case colon
case inheritedType
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `GenericParameterSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .genericParameter else { return nil }
self._syntaxNode = syntax
}
/// Creates a `GenericParameterSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .genericParameter)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var attributes: AttributeListSyntax? {
get {
let childData = data.child(at: Cursor.attributes,
parent: Syntax(self))
if childData == nil { return nil }
return AttributeListSyntax(childData!)
}
set(value) {
self = withAttributes(value)
}
}
/// Adds the provided `Attribute` to the node's `attributes`
/// collection.
/// - param element: The new `Attribute` to add to the node's
/// `attributes` collection.
/// - returns: A copy of the receiver with the provided `Attribute`
/// appended to its `attributes` collection.
public func addAttribute(_ element: Syntax) -> GenericParameterSyntax {
var collection: RawSyntax
if let col = raw[Cursor.attributes] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.attributeList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.attributes)
return GenericParameterSyntax(newData)
}
/// Returns a copy of the receiver with its `attributes` replaced.
/// - param newChild: The new `attributes` to replace the node's
/// current `attributes`, if present.
public func withAttributes(
_ newChild: AttributeListSyntax?) -> GenericParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.attributes)
return GenericParameterSyntax(newData)
}
public var name: TokenSyntax {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> GenericParameterSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.name)
return GenericParameterSyntax(newData)
}
public var colon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> GenericParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.colon)
return GenericParameterSyntax(newData)
}
public var inheritedType: TypeSyntax? {
get {
let childData = data.child(at: Cursor.inheritedType,
parent: Syntax(self))
if childData == nil { return nil }
return TypeSyntax(childData!)
}
set(value) {
self = withInheritedType(value)
}
}
/// Returns a copy of the receiver with its `inheritedType` replaced.
/// - param newChild: The new `inheritedType` to replace the node's
/// current `inheritedType`, if present.
public func withInheritedType(
_ newChild: TypeSyntax?) -> GenericParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.inheritedType)
return GenericParameterSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> GenericParameterSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return GenericParameterSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 5)
// Check child #0 child is AttributeListSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(AttributeListSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TypeSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #4 child is TokenSyntax or missing
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension GenericParameterSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"attributes": attributes.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"name": Syntax(name).asProtocol(SyntaxProtocol.self),
"colon": colon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"inheritedType": inheritedType.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - GenericParameterClauseSyntax
public struct GenericParameterClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftAngleBracket
case genericParameterList
case rightAngleBracket
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `GenericParameterClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .genericParameterClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `GenericParameterClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .genericParameterClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftAngleBracket: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftAngleBracket,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftAngleBracket(value)
}
}
/// Returns a copy of the receiver with its `leftAngleBracket` replaced.
/// - param newChild: The new `leftAngleBracket` to replace the node's
/// current `leftAngleBracket`, if present.
public func withLeftAngleBracket(
_ newChild: TokenSyntax?) -> GenericParameterClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftAngle)
let newData = data.replacingChild(raw, at: Cursor.leftAngleBracket)
return GenericParameterClauseSyntax(newData)
}
public var genericParameterList: GenericParameterListSyntax {
get {
let childData = data.child(at: Cursor.genericParameterList,
parent: Syntax(self))
return GenericParameterListSyntax(childData!)
}
set(value) {
self = withGenericParameterList(value)
}
}
/// Adds the provided `GenericParameter` to the node's `genericParameterList`
/// collection.
/// - param element: The new `GenericParameter` to add to the node's
/// `genericParameterList` collection.
/// - returns: A copy of the receiver with the provided `GenericParameter`
/// appended to its `genericParameterList` collection.
public func addGenericParameter(_ element: GenericParameterSyntax) -> GenericParameterClauseSyntax {
var collection: RawSyntax
if let col = raw[Cursor.genericParameterList] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.genericParameterList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.genericParameterList)
return GenericParameterClauseSyntax(newData)
}
/// Returns a copy of the receiver with its `genericParameterList` replaced.
/// - param newChild: The new `genericParameterList` to replace the node's
/// current `genericParameterList`, if present.
public func withGenericParameterList(
_ newChild: GenericParameterListSyntax?) -> GenericParameterClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.genericParameterList)
let newData = data.replacingChild(raw, at: Cursor.genericParameterList)
return GenericParameterClauseSyntax(newData)
}
public var rightAngleBracket: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightAngleBracket,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightAngleBracket(value)
}
}
/// Returns a copy of the receiver with its `rightAngleBracket` replaced.
/// - param newChild: The new `rightAngleBracket` to replace the node's
/// current `rightAngleBracket`, if present.
public func withRightAngleBracket(
_ newChild: TokenSyntax?) -> GenericParameterClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightAngle)
let newData = data.replacingChild(raw, at: Cursor.rightAngleBracket)
return GenericParameterClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is GenericParameterListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(GenericParameterListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension GenericParameterClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftAngleBracket": Syntax(leftAngleBracket).asProtocol(SyntaxProtocol.self),
"genericParameterList": Syntax(genericParameterList).asProtocol(SyntaxProtocol.self),
"rightAngleBracket": Syntax(rightAngleBracket).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - ConformanceRequirementSyntax
public struct ConformanceRequirementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftTypeIdentifier
case colon
case rightTypeIdentifier
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `ConformanceRequirementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .conformanceRequirement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `ConformanceRequirementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .conformanceRequirement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftTypeIdentifier: TypeSyntax {
get {
let childData = data.child(at: Cursor.leftTypeIdentifier,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withLeftTypeIdentifier(value)
}
}
/// Returns a copy of the receiver with its `leftTypeIdentifier` replaced.
/// - param newChild: The new `leftTypeIdentifier` to replace the node's
/// current `leftTypeIdentifier`, if present.
public func withLeftTypeIdentifier(
_ newChild: TypeSyntax?) -> ConformanceRequirementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.leftTypeIdentifier)
return ConformanceRequirementSyntax(newData)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> ConformanceRequirementSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return ConformanceRequirementSyntax(newData)
}
public var rightTypeIdentifier: TypeSyntax {
get {
let childData = data.child(at: Cursor.rightTypeIdentifier,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withRightTypeIdentifier(value)
}
}
/// Returns a copy of the receiver with its `rightTypeIdentifier` replaced.
/// - param newChild: The new `rightTypeIdentifier` to replace the node's
/// current `rightTypeIdentifier`, if present.
public func withRightTypeIdentifier(
_ newChild: TypeSyntax?) -> ConformanceRequirementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.rightTypeIdentifier)
return ConformanceRequirementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TypeSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TypeSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
}
}
extension ConformanceRequirementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftTypeIdentifier": Syntax(leftTypeIdentifier).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"rightTypeIdentifier": Syntax(rightTypeIdentifier).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - CompositionTypeElementSyntax
public struct CompositionTypeElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case type
case ampersand
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `CompositionTypeElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .compositionTypeElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `CompositionTypeElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .compositionTypeElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var type: TypeSyntax {
get {
let childData = data.child(at: Cursor.type,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withType(value)
}
}
/// Returns a copy of the receiver with its `type` replaced.
/// - param newChild: The new `type` to replace the node's
/// current `type`, if present.
public func withType(
_ newChild: TypeSyntax?) -> CompositionTypeElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.type)
return CompositionTypeElementSyntax(newData)
}
public var ampersand: TokenSyntax? {
get {
let childData = data.child(at: Cursor.ampersand,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withAmpersand(value)
}
}
/// Returns a copy of the receiver with its `ampersand` replaced.
/// - param newChild: The new `ampersand` to replace the node's
/// current `ampersand`, if present.
public func withAmpersand(
_ newChild: TokenSyntax?) -> CompositionTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.ampersand)
return CompositionTypeElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TypeSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension CompositionTypeElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"type": Syntax(type).asProtocol(SyntaxProtocol.self),
"ampersand": ampersand.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - TupleTypeElementSyntax
public struct TupleTypeElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case inOut
case name
case secondName
case colon
case type
case ellipsis
case initializer
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `TupleTypeElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .tupleTypeElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `TupleTypeElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .tupleTypeElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var inOut: TokenSyntax? {
get {
let childData = data.child(at: Cursor.inOut,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withInOut(value)
}
}
/// Returns a copy of the receiver with its `inOut` replaced.
/// - param newChild: The new `inOut` to replace the node's
/// current `inOut`, if present.
public func withInOut(
_ newChild: TokenSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.inOut)
return TupleTypeElementSyntax(newData)
}
public var name: TokenSyntax? {
get {
let childData = data.child(at: Cursor.name,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withName(value)
}
}
/// Returns a copy of the receiver with its `name` replaced.
/// - param newChild: The new `name` to replace the node's
/// current `name`, if present.
public func withName(
_ newChild: TokenSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.name)
return TupleTypeElementSyntax(newData)
}
public var secondName: TokenSyntax? {
get {
let childData = data.child(at: Cursor.secondName,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withSecondName(value)
}
}
/// Returns a copy of the receiver with its `secondName` replaced.
/// - param newChild: The new `secondName` to replace the node's
/// current `secondName`, if present.
public func withSecondName(
_ newChild: TokenSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.secondName)
return TupleTypeElementSyntax(newData)
}
public var colon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.colon)
return TupleTypeElementSyntax(newData)
}
public var type: TypeSyntax {
get {
let childData = data.child(at: Cursor.type,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withType(value)
}
}
/// Returns a copy of the receiver with its `type` replaced.
/// - param newChild: The new `type` to replace the node's
/// current `type`, if present.
public func withType(
_ newChild: TypeSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.type)
return TupleTypeElementSyntax(newData)
}
public var ellipsis: TokenSyntax? {
get {
let childData = data.child(at: Cursor.ellipsis,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withEllipsis(value)
}
}
/// Returns a copy of the receiver with its `ellipsis` replaced.
/// - param newChild: The new `ellipsis` to replace the node's
/// current `ellipsis`, if present.
public func withEllipsis(
_ newChild: TokenSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.ellipsis)
return TupleTypeElementSyntax(newData)
}
public var initializer: InitializerClauseSyntax? {
get {
let childData = data.child(at: Cursor.initializer,
parent: Syntax(self))
if childData == nil { return nil }
return InitializerClauseSyntax(childData!)
}
set(value) {
self = withInitializer(value)
}
}
/// Returns a copy of the receiver with its `initializer` replaced.
/// - param newChild: The new `initializer` to replace the node's
/// current `initializer`, if present.
public func withInitializer(
_ newChild: InitializerClauseSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.initializer)
return TupleTypeElementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> TupleTypeElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return TupleTypeElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 8)
// Check child #0 child is TokenSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #4 child is TypeSyntax
assert(rawChildren[4].raw != nil)
if let raw = rawChildren[4].raw {
let info = rawChildren[4].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #5 child is TokenSyntax or missing
if let raw = rawChildren[5].raw {
let info = rawChildren[5].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #6 child is InitializerClauseSyntax or missing
if let raw = rawChildren[6].raw {
let info = rawChildren[6].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(InitializerClauseSyntax.self))
}
// Check child #7 child is TokenSyntax or missing
if let raw = rawChildren[7].raw {
let info = rawChildren[7].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension TupleTypeElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"inOut": inOut.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"name": name.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"secondName": secondName.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"colon": colon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"type": Syntax(type).asProtocol(SyntaxProtocol.self),
"ellipsis": ellipsis.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"initializer": initializer.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - GenericArgumentSyntax
public struct GenericArgumentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case argumentType
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `GenericArgumentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .genericArgument else { return nil }
self._syntaxNode = syntax
}
/// Creates a `GenericArgumentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .genericArgument)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var argumentType: TypeSyntax {
get {
let childData = data.child(at: Cursor.argumentType,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withArgumentType(value)
}
}
/// Returns a copy of the receiver with its `argumentType` replaced.
/// - param newChild: The new `argumentType` to replace the node's
/// current `argumentType`, if present.
public func withArgumentType(
_ newChild: TypeSyntax?) -> GenericArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.argumentType)
return GenericArgumentSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> GenericArgumentSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return GenericArgumentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TypeSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension GenericArgumentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"argumentType": Syntax(argumentType).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - GenericArgumentClauseSyntax
public struct GenericArgumentClauseSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case leftAngleBracket
case arguments
case rightAngleBracket
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `GenericArgumentClauseSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .genericArgumentClause else { return nil }
self._syntaxNode = syntax
}
/// Creates a `GenericArgumentClauseSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .genericArgumentClause)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var leftAngleBracket: TokenSyntax {
get {
let childData = data.child(at: Cursor.leftAngleBracket,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLeftAngleBracket(value)
}
}
/// Returns a copy of the receiver with its `leftAngleBracket` replaced.
/// - param newChild: The new `leftAngleBracket` to replace the node's
/// current `leftAngleBracket`, if present.
public func withLeftAngleBracket(
_ newChild: TokenSyntax?) -> GenericArgumentClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.leftAngle)
let newData = data.replacingChild(raw, at: Cursor.leftAngleBracket)
return GenericArgumentClauseSyntax(newData)
}
public var arguments: GenericArgumentListSyntax {
get {
let childData = data.child(at: Cursor.arguments,
parent: Syntax(self))
return GenericArgumentListSyntax(childData!)
}
set(value) {
self = withArguments(value)
}
}
/// Adds the provided `Argument` to the node's `arguments`
/// collection.
/// - param element: The new `Argument` to add to the node's
/// `arguments` collection.
/// - returns: A copy of the receiver with the provided `Argument`
/// appended to its `arguments` collection.
public func addArgument(_ element: GenericArgumentSyntax) -> GenericArgumentClauseSyntax {
var collection: RawSyntax
if let col = raw[Cursor.arguments] {
collection = col.appending(element.raw)
} else {
collection = RawSyntax.create(kind: SyntaxKind.genericArgumentList,
layout: [element.raw], length: element.raw.totalLength, presence: .present)
}
let newData = data.replacingChild(collection,
at: Cursor.arguments)
return GenericArgumentClauseSyntax(newData)
}
/// Returns a copy of the receiver with its `arguments` replaced.
/// - param newChild: The new `arguments` to replace the node's
/// current `arguments`, if present.
public func withArguments(
_ newChild: GenericArgumentListSyntax?) -> GenericArgumentClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.genericArgumentList)
let newData = data.replacingChild(raw, at: Cursor.arguments)
return GenericArgumentClauseSyntax(newData)
}
public var rightAngleBracket: TokenSyntax {
get {
let childData = data.child(at: Cursor.rightAngleBracket,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withRightAngleBracket(value)
}
}
/// Returns a copy of the receiver with its `rightAngleBracket` replaced.
/// - param newChild: The new `rightAngleBracket` to replace the node's
/// current `rightAngleBracket`, if present.
public func withRightAngleBracket(
_ newChild: TokenSyntax?) -> GenericArgumentClauseSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.rightAngle)
let newData = data.replacingChild(raw, at: Cursor.rightAngleBracket)
return GenericArgumentClauseSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is GenericArgumentListSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(GenericArgumentListSyntax.self))
}
// Check child #2 child is TokenSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension GenericArgumentClauseSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"leftAngleBracket": Syntax(leftAngleBracket).asProtocol(SyntaxProtocol.self),
"arguments": Syntax(arguments).asProtocol(SyntaxProtocol.self),
"rightAngleBracket": Syntax(rightAngleBracket).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - TypeAnnotationSyntax
public struct TypeAnnotationSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case colon
case type
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `TypeAnnotationSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .typeAnnotation else { return nil }
self._syntaxNode = syntax
}
/// Creates a `TypeAnnotationSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .typeAnnotation)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> TypeAnnotationSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return TypeAnnotationSyntax(newData)
}
public var type: TypeSyntax {
get {
let childData = data.child(at: Cursor.type,
parent: Syntax(self))
return TypeSyntax(childData!)
}
set(value) {
self = withType(value)
}
}
/// Returns a copy of the receiver with its `type` replaced.
/// - param newChild: The new `type` to replace the node's
/// current `type`, if present.
public func withType(
_ newChild: TypeSyntax?) -> TypeAnnotationSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.type)
let newData = data.replacingChild(raw, at: Cursor.type)
return TypeAnnotationSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TypeSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TypeSyntax.self))
}
}
}
extension TypeAnnotationSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"type": Syntax(type).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - TuplePatternElementSyntax
public struct TuplePatternElementSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case labelName
case labelColon
case pattern
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `TuplePatternElementSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .tuplePatternElement else { return nil }
self._syntaxNode = syntax
}
/// Creates a `TuplePatternElementSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .tuplePatternElement)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
public var labelName: TokenSyntax? {
get {
let childData = data.child(at: Cursor.labelName,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withLabelName(value)
}
}
/// Returns a copy of the receiver with its `labelName` replaced.
/// - param newChild: The new `labelName` to replace the node's
/// current `labelName`, if present.
public func withLabelName(
_ newChild: TokenSyntax?) -> TuplePatternElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.labelName)
return TuplePatternElementSyntax(newData)
}
public var labelColon: TokenSyntax? {
get {
let childData = data.child(at: Cursor.labelColon,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withLabelColon(value)
}
}
/// Returns a copy of the receiver with its `labelColon` replaced.
/// - param newChild: The new `labelColon` to replace the node's
/// current `labelColon`, if present.
public func withLabelColon(
_ newChild: TokenSyntax?) -> TuplePatternElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.labelColon)
return TuplePatternElementSyntax(newData)
}
public var pattern: PatternSyntax {
get {
let childData = data.child(at: Cursor.pattern,
parent: Syntax(self))
return PatternSyntax(childData!)
}
set(value) {
self = withPattern(value)
}
}
/// Returns a copy of the receiver with its `pattern` replaced.
/// - param newChild: The new `pattern` to replace the node's
/// current `pattern`, if present.
public func withPattern(
_ newChild: PatternSyntax?) -> TuplePatternElementSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.pattern)
let newData = data.replacingChild(raw, at: Cursor.pattern)
return TuplePatternElementSyntax(newData)
}
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> TuplePatternElementSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return TuplePatternElementSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 4)
// Check child #0 child is TokenSyntax or missing
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is PatternSyntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(PatternSyntax.self))
}
// Check child #3 child is TokenSyntax or missing
if let raw = rawChildren[3].raw {
let info = rawChildren[3].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension TuplePatternElementSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"labelName": labelName.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"labelColon": labelColon.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"pattern": Syntax(pattern).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - AvailabilityArgumentSyntax
///
/// A single argument to an `@available` argument like `*`, `iOS 10.1`,
/// or `message: "This has been deprecated"`.
///
public struct AvailabilityArgumentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case entry
case trailingComma
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AvailabilityArgumentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .availabilityArgument else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AvailabilityArgumentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .availabilityArgument)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The actual argument
public var entry: Syntax {
get {
let childData = data.child(at: Cursor.entry,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withEntry(value)
}
}
/// Returns a copy of the receiver with its `entry` replaced.
/// - param newChild: The new `entry` to replace the node's
/// current `entry`, if present.
public func withEntry(
_ newChild: Syntax?) -> AvailabilityArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.entry)
return AvailabilityArgumentSyntax(newData)
}
///
/// A trailing comma if the argument is followed by another
/// argument
///
public var trailingComma: TokenSyntax? {
get {
let childData = data.child(at: Cursor.trailingComma,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withTrailingComma(value)
}
}
/// Returns a copy of the receiver with its `trailingComma` replaced.
/// - param newChild: The new `trailingComma` to replace the node's
/// current `trailingComma`, if present.
public func withTrailingComma(
_ newChild: TokenSyntax?) -> AvailabilityArgumentSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.trailingComma)
return AvailabilityArgumentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension AvailabilityArgumentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"entry": Syntax(entry).asProtocol(SyntaxProtocol.self),
"trailingComma": trailingComma.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
// MARK: - AvailabilityLabeledArgumentSyntax
///
/// A argument to an `@available` attribute that consists of a label and
/// a value, e.g. `message: "This has been deprecated"`.
///
public struct AvailabilityLabeledArgumentSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case label
case colon
case value
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AvailabilityLabeledArgumentSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .availabilityLabeledArgument else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AvailabilityLabeledArgumentSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .availabilityLabeledArgument)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
/// The label of the argument
public var label: TokenSyntax {
get {
let childData = data.child(at: Cursor.label,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withLabel(value)
}
}
/// Returns a copy of the receiver with its `label` replaced.
/// - param newChild: The new `label` to replace the node's
/// current `label`, if present.
public func withLabel(
_ newChild: TokenSyntax?) -> AvailabilityLabeledArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.label)
return AvailabilityLabeledArgumentSyntax(newData)
}
/// The colon separating label and value
public var colon: TokenSyntax {
get {
let childData = data.child(at: Cursor.colon,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withColon(value)
}
}
/// Returns a copy of the receiver with its `colon` replaced.
/// - param newChild: The new `colon` to replace the node's
/// current `colon`, if present.
public func withColon(
_ newChild: TokenSyntax?) -> AvailabilityLabeledArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.colon)
let newData = data.replacingChild(raw, at: Cursor.colon)
return AvailabilityLabeledArgumentSyntax(newData)
}
/// The value of this labeled argument
public var value: Syntax {
get {
let childData = data.child(at: Cursor.value,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withValue(value)
}
}
/// Returns a copy of the receiver with its `value` replaced.
/// - param newChild: The new `value` to replace the node's
/// current `value`, if present.
public func withValue(
_ newChild: Syntax?) -> AvailabilityLabeledArgumentSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.value)
return AvailabilityLabeledArgumentSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is TokenSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is Syntax
assert(rawChildren[2].raw != nil)
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
}
}
extension AvailabilityLabeledArgumentSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"label": Syntax(label).asProtocol(SyntaxProtocol.self),
"colon": Syntax(colon).asProtocol(SyntaxProtocol.self),
"value": Syntax(value).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - AvailabilityVersionRestrictionSyntax
///
/// An argument to `@available` that restricts the availability on a
/// certain platform to a version, e.g. `iOS 10` or `swift 3.4`.
///
public struct AvailabilityVersionRestrictionSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case platform
case version
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `AvailabilityVersionRestrictionSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .availabilityVersionRestriction else { return nil }
self._syntaxNode = syntax
}
/// Creates a `AvailabilityVersionRestrictionSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .availabilityVersionRestriction)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
///
/// The name of the OS on which the availability should be
/// restricted or 'swift' if the availability should be
/// restricted based on a Swift version.
///
public var platform: TokenSyntax {
get {
let childData = data.child(at: Cursor.platform,
parent: Syntax(self))
return TokenSyntax(childData!)
}
set(value) {
self = withPlatform(value)
}
}
/// Returns a copy of the receiver with its `platform` replaced.
/// - param newChild: The new `platform` to replace the node's
/// current `platform`, if present.
public func withPlatform(
_ newChild: TokenSyntax?) -> AvailabilityVersionRestrictionSyntax {
let raw = newChild?.raw ?? RawSyntax.missingToken(TokenKind.identifier(""))
let newData = data.replacingChild(raw, at: Cursor.platform)
return AvailabilityVersionRestrictionSyntax(newData)
}
public var version: VersionTupleSyntax {
get {
let childData = data.child(at: Cursor.version,
parent: Syntax(self))
return VersionTupleSyntax(childData!)
}
set(value) {
self = withVersion(value)
}
}
/// Returns a copy of the receiver with its `version` replaced.
/// - param newChild: The new `version` to replace the node's
/// current `version`, if present.
public func withVersion(
_ newChild: VersionTupleSyntax?) -> AvailabilityVersionRestrictionSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.versionTuple)
let newData = data.replacingChild(raw, at: Cursor.version)
return AvailabilityVersionRestrictionSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 2)
// Check child #0 child is TokenSyntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #1 child is VersionTupleSyntax
assert(rawChildren[1].raw != nil)
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(VersionTupleSyntax.self))
}
}
}
extension AvailabilityVersionRestrictionSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"platform": Syntax(platform).asProtocol(SyntaxProtocol.self),
"version": Syntax(version).asProtocol(SyntaxProtocol.self),
])
}
}
// MARK: - VersionTupleSyntax
///
/// A version number of the form major.minor.patch in which the minor
/// and patch part may be ommited.
///
public struct VersionTupleSyntax: SyntaxProtocol, SyntaxHashable {
enum Cursor: Int {
case majorMinor
case patchPeriod
case patchVersion
}
public let _syntaxNode: Syntax
/// Converts the given `Syntax` node to a `VersionTupleSyntax` if possible. Returns
/// `nil` if the conversion is not possible.
public init?(_ syntax: Syntax) {
guard syntax.raw.kind == .versionTuple else { return nil }
self._syntaxNode = syntax
}
/// Creates a `VersionTupleSyntax` node from the given `SyntaxData`. This assumes
/// that the `SyntaxData` is of the correct kind. If it is not, the behaviour
/// is undefined.
internal init(_ data: SyntaxData) {
assert(data.raw.kind == .versionTuple)
self._syntaxNode = Syntax(data)
}
public var syntaxNodeType: SyntaxProtocol.Type {
return Swift.type(of: self)
}
///
/// In case the version consists only of the major version, an
/// integer literal that specifies the major version. In case
/// the version consists of major and minor version number, a
/// floating literal in which the decimal part is interpreted
/// as the minor version.
///
public var majorMinor: Syntax {
get {
let childData = data.child(at: Cursor.majorMinor,
parent: Syntax(self))
return Syntax(childData!)
}
set(value) {
self = withMajorMinor(value)
}
}
/// Returns a copy of the receiver with its `majorMinor` replaced.
/// - param newChild: The new `majorMinor` to replace the node's
/// current `majorMinor`, if present.
public func withMajorMinor(
_ newChild: Syntax?) -> VersionTupleSyntax {
let raw = newChild?.raw ?? RawSyntax.missing(SyntaxKind.unknown)
let newData = data.replacingChild(raw, at: Cursor.majorMinor)
return VersionTupleSyntax(newData)
}
///
/// If the version contains a patch number, the period
/// separating the minor from the patch number.
///
public var patchPeriod: TokenSyntax? {
get {
let childData = data.child(at: Cursor.patchPeriod,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withPatchPeriod(value)
}
}
/// Returns a copy of the receiver with its `patchPeriod` replaced.
/// - param newChild: The new `patchPeriod` to replace the node's
/// current `patchPeriod`, if present.
public func withPatchPeriod(
_ newChild: TokenSyntax?) -> VersionTupleSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.patchPeriod)
return VersionTupleSyntax(newData)
}
///
/// The patch version if specified.
///
public var patchVersion: TokenSyntax? {
get {
let childData = data.child(at: Cursor.patchVersion,
parent: Syntax(self))
if childData == nil { return nil }
return TokenSyntax(childData!)
}
set(value) {
self = withPatchVersion(value)
}
}
/// Returns a copy of the receiver with its `patchVersion` replaced.
/// - param newChild: The new `patchVersion` to replace the node's
/// current `patchVersion`, if present.
public func withPatchVersion(
_ newChild: TokenSyntax?) -> VersionTupleSyntax {
let raw = newChild?.raw
let newData = data.replacingChild(raw, at: Cursor.patchVersion)
return VersionTupleSyntax(newData)
}
public func _validateLayout() {
let rawChildren = Array(RawSyntaxChildren(Syntax(self)))
assert(rawChildren.count == 3)
// Check child #0 child is Syntax
assert(rawChildren[0].raw != nil)
if let raw = rawChildren[0].raw {
let info = rawChildren[0].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(Syntax.self))
}
// Check child #1 child is TokenSyntax or missing
if let raw = rawChildren[1].raw {
let info = rawChildren[1].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
// Check child #2 child is TokenSyntax or missing
if let raw = rawChildren[2].raw {
let info = rawChildren[2].syntaxInfo
let absoluteRaw = AbsoluteRawSyntax(raw: raw, info: info)
let syntaxData = SyntaxData(absoluteRaw, parent: Syntax(self))
let syntaxChild = Syntax(syntaxData)
assert(syntaxChild.is(TokenSyntax.self))
}
}
}
extension VersionTupleSyntax: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [
"majorMinor": Syntax(majorMinor).asProtocol(SyntaxProtocol.self),
"patchPeriod": patchPeriod.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
"patchVersion": patchVersion.map(Syntax.init)?.asProtocol(SyntaxProtocol.self) as Any,
])
}
}
| 35.523087 | 122 | 0.669396 |
16361b8a0912228a3a086d696553afdce372fd9f
| 2,309 |
import UIKit
import Alamofire
import SWXMLHash
import enum Result.Result
public class Translator {
struct API {
static let issueTokenURL = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"
static let translateURL = "https://api.microsofttranslator.com/v2/Http.svc/Translate"
}
public typealias TranslationResult = Result<String, NSError>
public enum TokenStatus {
case idle
case available(String)
case requesting
case failure(Error)
}
public enum TranslationError: Error {
case tokenUnavailable
case unexpectedResponse(String)
}
public var tokenStatus: TokenStatus = .idle
public init(subscriptionKey: String) {
let headers = ["Ocp-Apim-Subscription-Key": subscriptionKey]
tokenStatus = .requesting
Alamofire.request(API.issueTokenURL, method: .post, headers: headers).responseString { (response) in
switch response.result {
case .success(let str):
self.tokenStatus = .available(str)
case .failure(let error):
self.tokenStatus = .failure(error)
}
}
}
public func translate(input: String, to toLanguage: String, completion: @escaping (TranslationResult) -> ()) {
switch tokenStatus {
case .available(let token):
Alamofire.request(API.translateURL, method: .get, parameters: ["text": input, "to": toLanguage], headers: ["Authorization": "Bearer \(token)"]).responseString(completionHandler: { (response) in
switch response.result {
case .success(let str):
let xml = SWXMLHash.parse(str)
guard let result = xml["string"].element?.text else {
completion(.failure(TranslationError.unexpectedResponse(str) as NSError))
return
}
completion(.success(result))
case .failure(let error):
completion(.failure(error as NSError))
}
})
case .idle, .requesting, .failure(_):
completion(.failure(TranslationError.tokenUnavailable as NSError))
}
}
}
| 36.078125 | 205 | 0.584236 |
8a620a5139c2ad9348d9fcc600a6c820a35e9c36
| 1,438 |
import Foundation
/// # Reference
/// [CONNACK – Acknowledge connection request](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033)
public final class ConnAckPacket: MQTTPacket {
private let variableHeader: VariableHeader
public var returnCode: ReturnCode {
variableHeader.returnCode
}
public var sessionPresent: Bool {
variableHeader.sessionPresent
}
init(fixedHeader: FixedHeader, data: inout Data) throws {
guard data.hasSize(2) else {
throw DecodeError.malformedData
}
let sessionPresent = (data.read1ByteInt() & 1) == 1
let returnCode = try ReturnCode(code: data.read1ByteInt())
variableHeader = VariableHeader(sessionPresent: sessionPresent, returnCode: returnCode)
super.init(fixedHeader: fixedHeader)
}
}
extension ConnAckPacket {
struct VariableHeader {
let sessionPresent: Bool
let returnCode: ReturnCode
}
public enum ReturnCode: UInt8 {
case accepted = 0
case unaceptable = 1
case identifierRejected = 2
case serverUnavailable = 3
case badUserCredential = 4
case notAuthorized = 5
init(code: UInt8) throws {
guard let returnCode = ReturnCode(rawValue: code) else {
throw DecodeError.malformedConnAckReturnCode
}
self = returnCode
}
}
}
| 29.346939 | 128 | 0.648818 |
5b7319c0e8896574aeae82180bac9f6f3b54c0d0
| 4,745 |
//
// NSManagedObject+JSON.swift
// KoreBotSDK
//
// Created by Srinivas Vasadi on 08/03/19.
// Copyright © 2019 Srinivas Vasadi. All rights reserved.
//
import UIKit
import CoreData
public extension NSManagedObject {
// MARK: - dateFormatter
class func dateFormatter() -> DateFormatter? {
var dateFormatter: DateFormatter?
if dateFormatter == nil {
dateFormatter = DateFormatter()
dateFormatter?.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter?.locale = NSLocale.system
}
return dateFormatter
}
// MARK: -
public func safeSetValues(for keyedValues:[String : Any], WSMap map: [String : Any]) {
let attributes = entity.attributesByName
for (attribute, _) in attributes {
if let actualAttribute = map[attribute] as? String {
var finalValue: Any? = nil
if let value = keyedValues[actualAttribute] {
if value is NSNull {
continue
}
let attributeType = attributes[attribute]?.attributeType
if attributeType == .stringAttributeType, let value = value as? NSNumber {
finalValue = value.stringValue
} else if (attributeType == .integer16AttributeType || attributeType == .integer32AttributeType || attributeType == .integer64AttributeType || attributeType == .booleanAttributeType), let value = value as? String {
finalValue = Int(value)
} else if (attributeType == .floatAttributeType), let value = value as? String {
finalValue = Double(value)
} else if attributeType == .stringAttributeType, let value = value as? String {
finalValue = value
}
setValue(finalValue, forKey: attribute)
}
}
}
}
public func safeSetValues(for keyedValues:[String : Any], WSMap map: [String : Any], dateFormatter: DateFormatter) {
let attributes = entity.attributesByName
for (attribute, _) in attributes {
if let actualAttribute = map[attribute] as? String {
var finalValue: Any? = nil
if let value = keyedValues[actualAttribute], let attributeType = attributes[attribute]?.attributeType {
if value is NSNull {
continue
}
if attributeType == .stringAttributeType, let value = value as? NSNumber {
finalValue = value.stringValue
} else if (attributeType == .integer16AttributeType || attributeType == .integer32AttributeType || attributeType == .integer64AttributeType || attributeType == .booleanAttributeType), let value = value as? String {
finalValue = Int(value)
} else if attributeType == .floatAttributeType, let value = value as? String {
finalValue = Double(value)
} else if attributeType == .dateAttributeType, let value = value as? String {
finalValue = dateFormatter.date(from: value)
} else if attributeType == .stringAttributeType, let value = value as? String {
finalValue = value
}
setValue(finalValue, forKey: attribute)
}
}
}
}
public func safeSetValue(_ value: Any, forKey attribute: String) {
let attributes = entity.attributesByName
if let attributeType = attributes[attribute]?.attributeType {
var finalValue: Any? = value
if value is NSNull {
return
}
if attributeType == .stringAttributeType, let value = value as? NSNumber {
finalValue = value.stringValue
} else if (attributeType == .integer16AttributeType || attributeType == .integer32AttributeType || attributeType == .integer64AttributeType || attributeType == .booleanAttributeType), let value = value as? String {
finalValue = Int(value)
} else if attributeType == .floatAttributeType, let value = value as? String {
finalValue = Double(value)
} else if attributeType == .dateAttributeType, let value = value as? String, let dateFormatter = NSManagedObject.dateFormatter() {
finalValue = dateFormatter.date(from: value)
}
setValue(finalValue, forKey: attribute)
}
}
}
| 47.929293 | 234 | 0.565227 |
23a2d8e5ee6a33ecfab5e13b47e9fb72af780758
| 2,702 |
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import XCTest
@testable import SignalServiceKit
class ViewOnceMessagesTest: SSKBaseTestSwift {
private var tsAccountManager: TSAccountManager {
return TSAccountManager.sharedInstance()
}
// MARK: -
override func setUp() {
super.setUp()
tsAccountManager.registerForTests(withLocalNumber: "+13334445555", uuid: UUID())
}
override func tearDown() {
super.tearDown()
}
// MARK: -
func test_expiration() {
let messageCount = { () -> Int in
return self.databaseStorage.readReturningResult { transaction in
return TSInteraction.anyFetchAll(transaction: transaction).count
}
}
let latestCopy = { (message: TSMessage) -> TSMessage in
let uniqueId = message.uniqueId
return self.databaseStorage.readReturningResult { transaction in
return TSMessage.anyFetch(uniqueId: uniqueId, transaction: transaction) as! TSMessage
}
}
// Factory 1 builds messages that are not view-once messages.
let factory1 = IncomingMessageFactory()
factory1.isViewOnceMessageBuilder = {
return false
}
self.write { transaction in
_ = factory1.create(transaction: transaction)
}
XCTAssertEqual(1, messageCount())
// Factory 2 builds view-once messages.
let factory2 = IncomingMessageFactory()
factory2.isViewOnceMessageBuilder = {
return true
}
var viewOnceMessage: TSMessage?
self.write { transaction in
viewOnceMessage = factory2.create(transaction: transaction)
}
XCTAssertEqual(2, messageCount())
guard let message = viewOnceMessage else {
XCTFail("Missing message.")
return
}
XCTAssertTrue(message.isViewOnceMessage)
XCTAssertFalse(message.isViewOnceComplete)
XCTAssertTrue(latestCopy(message).isViewOnceMessage)
XCTAssertFalse(latestCopy(message).isViewOnceComplete)
self.write { transaction in
ViewOnceMessages.markAsComplete(message: message,
sendSyncMessages: false,
transaction: transaction)
}
XCTAssertTrue(message.isViewOnceMessage)
XCTAssertTrue(message.isViewOnceComplete)
XCTAssertTrue(latestCopy(message).isViewOnceMessage)
XCTAssertTrue(latestCopy(message).isViewOnceComplete)
XCTAssertEqual(2, messageCount())
}
}
| 28.442105 | 101 | 0.625093 |
dd8fcc2762cb69d5541b67b4c35efa5765ce4b69
| 395 |
//
// NSNumber.swift
// RxLisk
//
// Created by Konrad on 5/14/19.
// Copyright © 2019 Limbo. All rights reserved.
//
import Foundation
extension UInt64 {
/// String from UInt64
var string: String {
return String(self)
}
}
extension Double {
/// Fixed point
var fixedPoint: UInt64 {
return UInt64(self * LiskConstants.fixedPoint)
}
}
| 15.192308 | 54 | 0.6 |
9cb0d183f5272bb04afd31c72a655b3e56a2b8a8
| 1,041 |
//
// ListController.swift
// Traviler
//
// Created by Mohammed Iskandar on 28/12/2020.
//
import UIKit
class ListController: UIViewController {
var dataSource: [Business]!
var listTitle: String!
var dataIndexPath: Int?
var isCategoryList: Bool! = false
override func loadView() {
self.view = ListView()
self.view.backgroundColor = Style.Colors.backgroundColor
self.navigationController?.navigationBar.prefersLargeTitles = true
if let listView = view as? ListView {
let collectionView = ListCollectionViewController()
collectionView.dataSource = self.dataSource
self.addChild(collectionView)
listView.collectionView = collectionView.view
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.title = self.listTitle
}
}
| 26.692308 | 74 | 0.646494 |
e6d0b09028a811eb3a20c09276df56eb0aa3b725
| 334 |
// File name: ScoreManager.swift
// Author name: Abdeali Mody
// Student ID: 301085484
// Description: Initializtion of score and lives labels.
// Copyright © 2021 Abdeali Mody. All rights reserved.
import SpriteKit
import UIKit
class ScoreManager
{
public static var Score: Int = 0
public static var Lives: Int = 5
}
| 20.875 | 57 | 0.721557 |
bb8968812e60b63bca51c9396f3f698e86f6f7b1
| 4,259 |
//
// AST.swift
// SwiftCookInSwift
//
// Created by Alexey Dubovskoy on 07/12/2020.
// Copyright © 2020 Alexey Dubovskoy. All rights reserved.
//
import Foundation
public protocol AST {}
public enum ConstantNode: AST {
case integer(Int)
case decimal(Decimal)
case string(String)
}
public struct ValuesNode: AST {
var values: [ConstantNode]
init() {
values = []
}
init(_ value: ConstantNode) {
values = [value]
}
init(_ value: String) {
values = [ConstantNode(value)]
}
init(_ value: Int) {
values = [ConstantNode(value)]
}
init(_ value: Decimal) {
values = [ConstantNode(value)]
}
mutating func add(_ value: ConstantNode) {
values.append(value)
}
func isEmpty() -> Bool {
return values.isEmpty
}
}
struct DirectionNode: AST {
let value: String
init(_ value: String) {
self.value = value
}
}
struct MetadataNode: AST {
let key: String
let value: ValuesNode
init(_ key: String, _ value: ValuesNode) {
self.key = key
self.value = value
}
init(_ key: String, _ value: ConstantNode) {
self.key = key
self.value = ValuesNode(value)
}
init(_ key: String, _ value: String) {
self.value = ValuesNode(ConstantNode.string(value))
self.key = key
}
init(_ key: String, _ value: Int) {
self.value = ValuesNode(ConstantNode.integer(value))
self.key = key
}
init(_ key: String, _ value: Decimal) {
self.value = ValuesNode(ConstantNode.decimal(value))
self.key = key
}
}
struct AmountNode: AST {
let quantity: ValuesNode
let units: String
init(quantity: ValuesNode, units: String = "") {
self.quantity = quantity
self.units = units
}
init(quantity: ConstantNode, units: String = "") {
self.quantity = ValuesNode(quantity)
self.units = units
}
init(quantity: String, units: String = "") {
self.quantity = ValuesNode(ConstantNode.string(quantity))
self.units = units
}
init(quantity: Int, units: String = "") {
self.quantity = ValuesNode(ConstantNode.integer(quantity))
self.units = units
}
init(quantity: Decimal, units: String = "") {
self.quantity = ValuesNode(ConstantNode.decimal(quantity))
self.units = units
}
}
struct IngredientNode: AST {
let name: String
let amount: AmountNode
init(name: String, amount: AmountNode) {
self.name = name
self.amount = amount
}
}
struct EquipmentNode: AST {
let name: String
let quantity: ValuesNode?
init(name: String, quantity: ValuesNode? = nil) {
self.name = name
self.quantity = quantity
}
}
struct TimerNode: AST {
let quantity: ValuesNode
let units: String
let name: String
init(quantity: ValuesNode, units: String, name: String = "") {
self.quantity = quantity
self.units = units
self.name = name
}
init(quantity: ConstantNode, units: String, name: String = "") {
self.quantity = ValuesNode(quantity)
self.units = units
self.name = name
}
init(quantity: String, units: String, name: String = "") {
self.quantity = ValuesNode(ConstantNode.string(quantity))
self.units = units
self.name = name
}
init(quantity: Int, units: String, name: String = "") {
self.quantity = ValuesNode(ConstantNode.integer(quantity))
self.units = units
self.name = name
}
init(quantity: Decimal, units: String, name: String = "") {
self.quantity = ValuesNode(ConstantNode.decimal(quantity))
self.units = units
self.name = name
}
}
struct StepNode: AST {
let instructions: [AST]
init(instructions: [AST]) {
self.instructions = instructions
}
}
struct RecipeNode: AST {
let steps: [StepNode]
let metadata: [MetadataNode]
init(steps: [StepNode], metadata: [MetadataNode]) {
self.steps = steps
self.metadata = metadata
}
init(steps: [StepNode]) {
self.steps = steps
self.metadata = []
}
}
| 20.980296 | 68 | 0.593097 |
db2ca42bd9f7c1a5bb0812bfabb6ddc7c8ee1a94
| 2,628 |
//
// DrawerControl.swift
// SwiftDrawer
//
// Created by Millman on 2019/6/30.
//
import Foundation
import SwiftUI
import Combine
public class DrawerControl: ObservableObject {
public let didChange = PassthroughSubject<DrawerControl, Never>()
private var statusObserver = [AnyCancellable]()
//private var statusObserver = [Subscribers.Sink<PassthroughSubject<SliderStatus,Never>>]()
private(set) var status = [SliderType: SliderStatus]() {
didSet {
statusObserver.forEach {
$0.cancel()
}
statusObserver.removeAll()
status.forEach { (info) in
let observer = info.value.didChange.sink { [weak self](s) in
let maxRate = self?.status.sorted { (s0, s1) -> Bool in
s0.value.showRate > s1.value.showRate
}.first?.value.showRate ?? 0
if self?.maxShowRate == maxRate {
return
}
self?.maxShowRate = maxRate
}
statusObserver.append(observer)
}
}
}
private(set) var sliderView = [SliderType: AnyView]() {
didSet {
didChange.send(self)
}
}
private(set) var main: AnyView? {
didSet {
didChange.send(self)
}
}
private(set) var maxShowRate: CGFloat = .zero {
didSet {
didChange.send(self)
}
}
public func setSlider<Slider: SliderViewProtocol>(view: Slider,
widthType: SliderWidth = .percent(rate: 0.6),
shadowRadius: CGFloat = 10) {
let status = SliderStatus(type: view.type)
status.maxWidth = widthType
status.shadowRadius = shadowRadius
self.status[view.type] = status
self.sliderView[view.type] = AnyView(SliderContainer(content: view, drawerControl: self))
}
public func setMain<Main: View>(view: Main) {
let container = MainContainer(content: view, drawerControl: self)
self.main = AnyView(container)
}
public func show(type: SliderType, isShow: Bool) {
let haveMoving = self.status.first { $0.value.currentStatus.isMoving } != nil
if haveMoving {
return
}
self.status[type]?.currentStatus = isShow ? .show: .hide
}
public func hideAllSlider() {
self.status.forEach {
$0.value.currentStatus = .hide
}
}
}
| 30.917647 | 99 | 0.537671 |
76c14e810c329168c2ee3675f553b3f06f1c3b97
| 820 |
/**
A composite reporter that goes through a list of reporters, running all that are available on the current machine.
*/
public class ReportWithEverything: EquatableFailureReporter {
private let reporters: [EquatableFailureReporter]
public init(_ reporters: EquatableFailureReporter...) {
self.reporters = reporters
}
public override func report(received: String, approved: String) -> Bool {
var worked = false
for reporter in reporters {
worked = reporter.report(received: received, approved: approved) || worked
}
return worked
}
public override func isEqualTo(_ other: ApprovalFailureReporter) -> Bool {
guard let other = other as? ReportWithEverything else { return false }
return reporters == other.reporters
}
}
| 34.166667 | 115 | 0.687805 |
f9604db5a85b5c1723a0c751ba6255a62e5df1af
| 2,474 |
import Foundation
import ResultStreamModels
import XCTest
final class RSTestSuiteStartedTests: XCTestCase {
func test() {
let input = """
{
"_type": {
"_name": "StreamedEvent"
},
"name": {
"_type": {
"_name": "String"
},
"_value": "testSuiteStarted"
},
"structuredPayload": {
"_type": {
"_name": "TestEventPayload",
"_supertype": {
"_name": "AnyStreamedEventPayload"
}
},
"resultInfo": {
"_type": {
"_name": "StreamedActionResultInfo"
},
"resultIndex": {
"_type": {
"_name": "Int"
},
"_value": "1"
}
},
"testIdentifier": {
"_type": {
"_name": "ActionTestSummaryGroup",
"_supertype": {
"_name": "ActionTestSummaryIdentifiableObject",
"_supertype": {
"_name": "ActionAbstractTestSummary"
}
}
},
"identifier": {
"_type": {
"_name": "String"
},
"_value": "ClassName (id)"
},
"name": {
"_type": {
"_name": "String"
},
"_value": "ClassName (name)"
}
}
}
}
"""
check(
input: input,
equals: RSTestSuiteStarted(
structuredPayload: RSTestEventPayload(
resultInfo: RSStreamedActionResultInfo(resultIndex: 1),
testIdentifier: ActionTestSummaryGroup(
identifier: "ClassName (id)",
name: "ClassName (name)",
duration: nil,
subtests: nil
)
)
)
)
}
}
| 30.925 | 75 | 0.310428 |
fe3bc97dd09c6517d684ef9d6bf4d64cef3d4d37
| 1,388 |
//
// MoviePresenterTests.swift
// Architectures
//
// Created by Fabijan Bajo on 03/06/2017.
//
//
import XCTest
@testable import MVP
class MoviePresenterTests: XCTestCase {
// MARK: - Properties
var presenter: ResultsViewPresenter!
// MARK: - Configuration
override func setUp() {
super.setUp()
// Configure presenter with view
let resultsVC = ResultsViewController()
let movie = Movie(title: "Foo", posterPath: "path1", movieID: 0, releaseDate: "2017-03-23", averageRating: 8.0)
presenter = MovieResultsPresenter(view: resultsVC, testableMovies: [movie])
}
override func tearDown() {
super.tearDown()
}
// Presenter outputs presentable instance struct
func test_PresentableInstance_ConvertsCorrectly() {
let presentableMovie = presenter.presentableInstance(index: 0) as! MovieResultsPresenter.PresentableInstance
XCTAssertEqual(presentableMovie.title, "Foo")
XCTAssertEqual(presentableMovie.fullSizeURL, URL(string: "https://image.tmdb.org/t/p/original/path1")!)
XCTAssertEqual(presentableMovie.thumbnailURL, URL(string:"https://image.tmdb.org/t/p/w300/path1")!)
XCTAssertEqual(presentableMovie.releaseDateText, "2017-03-23")
XCTAssertEqual(presentableMovie.ratingText, "8.0")
}
}
| 29.531915 | 119 | 0.668588 |
efb4961b62ac72c310fa6b88afb4b3aafad4c9e6
| 7,288 |
import KsApi
import LiveStream
import Prelude
import ReactiveSwift
import Result
public protocol ProjectPamphletContentViewModelInputs {
func configureWith(project: Project, liveStreamEvents: [LiveStreamEvent])
func tappedComments()
func tapped(liveStreamEvent: LiveStreamEvent)
func tappedPledgeAnyAmount()
func tapped(rewardOrBacking: Either<Reward, Backing>)
func tappedUpdates()
func viewDidAppear(animated: Bool)
func viewDidLoad()
func viewWillAppear(animated: Bool)
}
public protocol ProjectPamphletContentViewModelOutputs {
var goToBacking: Signal<Project, NoError> { get }
var goToComments: Signal<Project, NoError> { get }
var goToLiveStream: Signal<(Project, LiveStreamEvent), NoError> { get }
var goToLiveStreamCountdown: Signal<(Project, LiveStreamEvent), NoError> { get }
var goToRewardPledge: Signal<(Project, Reward), NoError> { get }
var goToUpdates: Signal<Project, NoError> { get }
var loadMinimalProjectIntoDataSource: Signal<Project, NoError> { get }
var loadProjectAndLiveStreamsIntoDataSource: Signal<(Project, [LiveStreamEvent]), NoError> { get }
}
public protocol ProjectPamphletContentViewModelType {
var inputs: ProjectPamphletContentViewModelInputs { get }
var outputs: ProjectPamphletContentViewModelOutputs { get }
}
public final class ProjectPamphletContentViewModel: ProjectPamphletContentViewModelType,
ProjectPamphletContentViewModelInputs, ProjectPamphletContentViewModelOutputs {
//swiftlint:disable:next function_body_length
public init() {
let projectAndLiveStreamEvents = Signal.combineLatest(
self.configDataProperty.signal.skipNil(),
self.viewDidLoadProperty.signal
)
.map(first)
let project = projectAndLiveStreamEvents.map(first)
let loadDataSourceOnSwipeCompletion = self.viewDidAppearAnimatedProperty.signal
.filter(isTrue)
.ignoreValues()
.flatMap { _ in
// NB: skip a run loop to ease the initial rendering of the cells and the swipe animation
SignalProducer(value: ()).delay(0, on: AppEnvironment.current.scheduler)
}
let loadDataSourceOnModalCompletion = self.viewWillAppearAnimatedProperty.signal
.filter(isFalse)
.ignoreValues()
let timeToLoadDataSource = Signal.merge(
loadDataSourceOnSwipeCompletion,
loadDataSourceOnModalCompletion
)
.take(first: 1)
self.loadProjectAndLiveStreamsIntoDataSource = Signal.combineLatest(
projectAndLiveStreamEvents,
timeToLoadDataSource
)
.map { projectAndLive, _ in (projectAndLive.0, projectAndLive.1) }
self.loadMinimalProjectIntoDataSource = project
.takePairWhen(self.viewWillAppearAnimatedProperty.signal)
.take(first: 1)
.filter(second)
.map(first)
let rewardOrBackingTapped = Signal.merge(
self.tappedRewardOrBackingProperty.signal.skipNil(),
self.tappedPledgeAnyAmountProperty.signal.mapConst(.left(Reward.noReward))
)
self.goToRewardPledge = project
.takePairWhen(rewardOrBackingTapped)
.map(goToRewardPledgeData(forProject:rewardOrBacking:))
.skipNil()
self.goToBacking = project
.takePairWhen(rewardOrBackingTapped)
.map(goToBackingData(forProject:rewardOrBacking:))
.skipNil()
self.goToComments = project
.takeWhen(self.tappedCommentsProperty.signal)
self.goToUpdates = project
.takeWhen(self.tappedUpdatesProperty.signal)
self.goToLiveStream = project
.takePairWhen(
self.tappedLiveStreamProperty.signal.skipNil()
.filter(shouldGoToLiveStream(withLiveStreamEvent:))
)
self.goToLiveStreamCountdown = project
.takePairWhen(
self.tappedLiveStreamProperty.signal.skipNil()
.filter({ !shouldGoToLiveStream(withLiveStreamEvent:$0) })
)
}
fileprivate let configDataProperty = MutableProperty<(Project, [LiveStreamEvent])?>(nil)
public func configureWith(project: Project, liveStreamEvents: [LiveStreamEvent]) {
self.configDataProperty.value = (project, liveStreamEvents)
}
fileprivate let tappedCommentsProperty = MutableProperty()
public func tappedComments() {
self.tappedCommentsProperty.value = ()
}
private let tappedLiveStreamProperty = MutableProperty<LiveStreamEvent?>(nil)
public func tapped(liveStreamEvent: LiveStreamEvent) {
self.tappedLiveStreamProperty.value = liveStreamEvent
}
fileprivate let tappedPledgeAnyAmountProperty = MutableProperty()
public func tappedPledgeAnyAmount() {
self.tappedPledgeAnyAmountProperty.value = ()
}
fileprivate let tappedRewardOrBackingProperty = MutableProperty<Either<Reward, Backing>?>(nil)
public func tapped(rewardOrBacking: Either<Reward, Backing>) {
self.tappedRewardOrBackingProperty.value = rewardOrBacking
}
fileprivate let tappedUpdatesProperty = MutableProperty()
public func tappedUpdates() {
self.tappedUpdatesProperty.value = ()
}
fileprivate let viewDidAppearAnimatedProperty = MutableProperty(false)
public func viewDidAppear(animated: Bool) {
self.viewDidAppearAnimatedProperty.value = animated
}
fileprivate let viewDidLoadProperty = MutableProperty()
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
fileprivate let viewWillAppearAnimatedProperty = MutableProperty(false)
public func viewWillAppear(animated: Bool) {
self.viewWillAppearAnimatedProperty.value = animated
}
public let goToBacking: Signal<Project, NoError>
public let goToComments: Signal<Project, NoError>
public let goToLiveStream: Signal<(Project, LiveStreamEvent), NoError>
public let goToLiveStreamCountdown: Signal<(Project, LiveStreamEvent), NoError>
public let goToRewardPledge: Signal<(Project, Reward), NoError>
public let goToUpdates: Signal<Project, NoError>
public let loadMinimalProjectIntoDataSource: Signal<Project, NoError>
public let loadProjectAndLiveStreamsIntoDataSource: Signal<(Project, [LiveStreamEvent]), NoError>
public var inputs: ProjectPamphletContentViewModelInputs { return self }
public var outputs: ProjectPamphletContentViewModelOutputs { return self }
}
private func reward(forBacking backing: Backing, inProject project: Project) -> Reward? {
return backing.reward
?? project.rewards.filter { $0.id == backing.rewardId }.first
?? Reward.noReward
}
private func shouldGoToLiveStream(withLiveStreamEvent liveStreamEvent: LiveStreamEvent) -> Bool {
return liveStreamEvent.liveNow
|| liveStreamEvent.startDate < AppEnvironment.current.dateType.init().date
}
private func goToRewardPledgeData(forProject project: Project, rewardOrBacking: Either<Reward, Backing>)
-> (Project, Reward)? {
guard project.state == .live else { return nil }
switch rewardOrBacking {
case let .left(reward):
guard reward.remaining != .some(0) else { return nil }
return (project, reward)
case let .right(backing):
guard let reward = reward(forBacking: backing, inProject: project) else { return nil }
return (project, reward)
}
}
private func goToBackingData(forProject project: Project, rewardOrBacking: Either<Reward, Backing>)
-> Project? {
guard project.state != .live && rewardOrBacking.right != nil else {
return nil
}
return project
}
| 35.038462 | 104 | 0.754391 |
fc41667784beb583123c5df59b8005ae5743ee7e
| 1,569 |
//
// TestLocation.swift
//
//
// Created by Emma on 11/15/21.
//
@testable import WMATA
import XCTest
final class WMATALocationTests: XCTestCase {
func testInit() {
let location = WMATALocation(radius: 1, latitude: 1.0, longitude: 1.0)
XCTAssertEqual(location.coordinates.latitude, 1.0)
XCTAssertEqual(location.coordinates.longitude, 1.0)
}
func testCoordinatesInit() {
let location = WMATALocation(
radius: 1,
coordinates: .init(latitude: 1.0, longitude: 1.0)
)
XCTAssertEqual(location.coordinates.latitude, 1.0)
XCTAssertEqual(location.coordinates.longitude, 1.0)
}
func testLocationQueryItems() {
let location = WMATALocation(
radius: 1,
coordinates: .init(latitude: 1.0, longitude: 1.0)
)
let queryItems = location.queryItems()
XCTAssertEqual(queryItems[0], .init(name: "Lat", value: "1.0"))
XCTAssertEqual(queryItems[1], .init(name: "Lon", value: "1.0"))
XCTAssertEqual(queryItems[2], .init(name: "Radius", value: "1"))
}
func testCoordinatesQueryItems() {
let location = WMATALocation(
radius: 1,
coordinates: .init(latitude: 1.0, longitude: 1.0)
)
let queryItems = location.coordinates.queryItems()
XCTAssertEqual(queryItems.first!, .init(name: "Lat", value: "1.0"))
XCTAssertEqual(queryItems.last!, .init(name: "Lon", value: "1.0"))
}
}
| 29.055556 | 78 | 0.586998 |
21af516c8763ea3f12b3e583d3a04c15b566bc7a
| 556 |
//
// Count.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Count) on 2019-05-21.
// 2019, SMART Health IT.
//
import Foundation
/**
A measured or measurable amount.
A measured amount (or an amount that can potentially be measured). Note that measured amounts include amounts that are
not precisely quantified, including amounts involving arbitrary units and floating currencies.
*/
open class Count: Quantity {
override open class var resourceType: String {
get { return "Count" }
}
}
| 22.24 | 118 | 0.73741 |
fb275a59b5b88b267b924e2f596c06d34f6fdb04
| 719 |
// Copyright 2021 Suol Innovations 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
struct TestState: Equatable {
var intValue: Int = 0
var stringValue: String = ""
}
| 32.681818 | 76 | 0.726008 |
ff5e73e95223ee1b87593ffff670c35022954e2a
| 3,126 |
//
// AmuseMenuView.swift
// DYLive
//
// Created by 渠晓友 on 2017/5/4.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class AmuseMenuView: UIView {
// MARK: - 控件属性
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var groups : [AnchorGroup]? {
didSet{
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.dataSource = self
collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
// 设置一些布局
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .horizontal
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
}
}
// MARK: - 快速返回对象的类方法
extension AmuseMenuView{
class func creatMenuView() -> AmuseMenuView{
return (Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as? AmuseMenuView)!
}
}
// MARK: - 代理fangfa
extension AmuseMenuView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups?.count == 0 || groups == nil { return 0 }
let pageNum = ((groups?.count)! - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell
// 子页面是 8个/页 所以单独处理一下数据再复制
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
func setupCellDataWithCell(cell : AmuseMenuViewCell , indexPath : IndexPath) {
//在原来的groups中 分页 按对应的 8个/页 划分对应的页
// 1页 : 0 - 7
// 2页 : 8 - 15
// 3页 : 16 - 23
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
// 越界处理
if endIndex >= (self.groups?.count)! - 1 {
endIndex = (self.groups?.count)! - 1
}
// 赋值
cell.groups = Array(groups![startIndex...endIndex])
}
}
// MARK: - 页面滚动,代理使用
extension AmuseMenuView : UICollectionViewDelegate
{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentPage = Int(collectionView.contentOffset.x / self.bounds.size.width + 0.5)
pageControl.currentPage = currentPage
}
}
| 27.421053 | 125 | 0.628599 |
294295e451da91adc2a526566969dfaa88a7599c
| 511 |
//
// Copyright © 2021 Toby O'Connell. All rights reserved.
//
import UIKit
public extension UIButton {
@discardableResult
func addAction(_ action: @escaping () -> Void) -> Self {
addAction(.init(handler: { _ in action() }), for: .touchUpInside)
return self
}
}
public extension UITextField {
@discardableResult
func addAction(_ action: @escaping () -> Void) -> Self {
addAction(.init(handler: { _ in action() }), for: .editingChanged)
return self
}
}
| 23.227273 | 74 | 0.624266 |
3adee97950bf9bd7d766b036f6fa9e1291cf5910
| 716 |
//
// Bytes+SecureRandom.swift
// Keystore
//
// Created by Koray Koska on 27.06.18.
// Copyright © 2018 Boilertalk. All rights reserved.
//
import Foundation
#if os(Linux) || os(FreeBSD)
import Glibc
#else
import Darwin
#endif
extension Array where Element == UInt8 {
static func secureRandom(count: Int) -> [UInt8]? {
var array = [UInt8](repeating: 0, count: count)
let fd = open("/dev/urandom", O_RDONLY)
guard fd != -1 else {
return nil
}
defer {
close(fd)
}
let ret = read(fd, &array, MemoryLayout<UInt8>.size * array.count)
guard ret > 0 else {
return nil
}
return array
}
}
| 18.842105 | 74 | 0.562849 |
39c0ef2cccaeb30010d9001d73c2f79fa5d8ee5b
| 3,479 |
//
// ObjectToRecordOperationTests.swift
// CloudCore
//
// Created by Vasily Ulianov on 03.03.17.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import XCTest
import CoreData
import CloudKit
@testable import CloudCore
class ObjectToRecordOperationTests: CoreDataTestCase {
func createTestObject(in context: NSManagedObjectContext) -> (TestEntity, CKRecord) {
let managedObject = CorrectObject().insert(in: context)
let record = try! managedObject.setRecordInformation(for: .private)
XCTAssertNil(record.value(forKey: "string"))
return (managedObject, record)
}
func testGoodOperation() {
let (managedObject, record) = createTestObject(in: context)
let operation = ObjectToRecordOperation(scope: .private, record: record, changedAttributes: nil, serviceAttributeNames: TestEntity.entity().serviceAttributeNames!)
let conversionExpectation = expectation(description: "ConversionCompleted")
operation.errorCompletionBlock = { XCTFail($0) }
operation.conversionCompletionBlock = { record in
conversionExpectation.fulfill()
assertEqualAttributes(managedObject, record)
}
operation.parentContext = self.context
operation.start()
waitForExpectations(timeout: 1, handler: nil)
}
func testContextIsNotDefined() {
let record = createTestObject(in: context).1
let operation = ObjectToRecordOperation(scope: .private, record: record, changedAttributes: nil, serviceAttributeNames: TestEntity.entity().serviceAttributeNames!)
let errorExpectation = expectation(description: "ErrorCalled")
operation.errorCompletionBlock = { error in
if case CloudCoreError.coreData = error {
errorExpectation.fulfill()
} else {
XCTFail("Unexpected error received")
}
}
operation.conversionCompletionBlock = { _ in
XCTFail("Called success completion block while error has been expected")
}
operation.start()
waitForExpectations(timeout: 1, handler: nil)
}
func testNoManagedObjectForOperation() {
let record = CorrectObject().makeRecord()
let _ = TestEntity(context: context)
let operation = ObjectToRecordOperation(scope: .private, record: record, changedAttributes: nil, serviceAttributeNames: TestEntity.entity().serviceAttributeNames!)
operation.parentContext = self.context
let errorExpectation = expectation(description: "ErrorCalled")
operation.errorCompletionBlock = { error in
if case CloudCoreError.coreData = error {
errorExpectation.fulfill()
} else {
XCTFail("Unexpected error received")
}
}
operation.conversionCompletionBlock = { _ in
XCTFail("Called success completion block while error has been expected")
}
operation.start()
waitForExpectations(timeout: 1, handler: nil)
}
func testOperationPerfomance() {
var records = [CKRecord]()
for _ in 1...300 {
let record = createTestObject(in: context).1
records.append(record)
}
try! context.save()
measure {
let backgroundContext = self.persistentContainer.newBackgroundContext()
let queue = OperationQueue()
for record in records {
let operation = ObjectToRecordOperation(scope: .private, record: record, changedAttributes: nil, serviceAttributeNames: TestEntity.entity().serviceAttributeNames!)
operation.errorCompletionBlock = { XCTFail($0) }
operation.parentContext = backgroundContext
queue.addOperation(operation)
}
queue.waitUntilAllOperationsAreFinished()
}
}
}
| 31.627273 | 179 | 0.742167 |
e059ffdb1f0ece0b66b6341d2dc90e9e1b03ef36
| 10,666 |
//
// MessageReplace.swift
// WatchQ
//
// Created by H1-157 on 2015/09/01.
// Copyright (c) 2015年 DaisukeMiyamoto. All rights reserved.
//
import Foundation
class MessageReplace:NSObject
{
//ステータスクラスマネージャー
var statusManager = StatusManager()
//csvパーサー
var perthCsv = PerthCsv()
/////////////////// use for replaceing the word ///////////////////
//索引文字記録
var usedWordDict = [String:String]()
//プレイヤー入力
var playerInput = ""
override init()
{
//初期化
usedWordDict = [String:String]()
}
//文章の<>の中身を探し出す
func replaceSentence(sentence:String)->String
{
var getChara = false
var getText:String = ""
var returnSentence = sentence
for ch in sentence.characters
{
if ch == "%"{ getChara = true }
else if ch == ">"{
getChara = false
getText += ">"
returnSentence = replaceWord(returnSentence, text: getText)
getText = ""
}
if getChara == true
{
let str = String(ch)
getText += str
}
}
return returnSentence
}
//<>の中身を置換
func replaceWord(sentence:String, text:String)->String
{
let usedWordNum = usedWordDict.count + 1
switch text
{
case "%<飼い主>":
let playerName = statusManager.loadString("playerName")
usedWordDict["%<索引["+String(usedWordNum)+"]>"] = playerName
return sentence.stringByReplacingOccurrencesOfString("%<飼い主>", withString: playerName, options: [], range: nil)
case "%<ペット名>":
let petName = statusManager.loadString("petName")
usedWordDict["%<索引["+String(usedWordNum)+"]>"] = petName
return sentence.stringByReplacingOccurrencesOfString("%<ペット名>", withString: petName, options: [], range: nil)
case "%<プレイヤー入力>":
usedWordDict["%<索引["+String(usedWordNum)+"]>"] = playerInput
return sentence.stringByReplacingOccurrencesOfString("%<プレイヤー入力>", withString: playerInput, options: [], range: nil)
case "%<現在時刻>":
let time = timeNow()
usedWordDict["%<索引["+String(usedWordNum)+"]>"] = time
return sentence.stringByReplacingOccurrencesOfString("%<現在時刻>", withString: time, options: [], range: nil)
//ここ以降置き換える単語をペットの辞書から取得
case "%<食べ物>":
let foodWordList = WordsManager.fetchWordByProperty("food")
let randNum = Int(arc4random_uniform(UInt32(foodWordList.count)))
let foodName = foodWordList[randNum].word
let usedWordNum = usedWordDict.count + 1
usedWordDict["%<索引["+String(usedWordNum)+"]>"] = foodName
return sentence.stringByReplacingOccurrencesOfString("%<食べ物>", withString: foodName, options: [], range: nil)
default:
break
}
//記録されている文字がなければそのまま返す
if usedWordDict.count == 0 { return ""}
//索引の置き換え
for indexNum in 1...usedWordDict.count
{
let dictKey = "%<索引["+String(indexNum)+"]>"
if text == dictKey
{
return sentence.stringByReplacingOccurrencesOfString(dictKey, withString: usedWordDict[dictKey]!, options: [], range: nil)
}
}
return sentence
}
//現在時刻を返す
func timeNow() -> String
{
let now = NSDate() // 現在日時の取得
let dateFormatter = NSDateFormatter()
// ロケールの設定
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP")
// スタイルの設定
dateFormatter.timeStyle = .ShortStyle
dateFormatter.dateStyle = .NoStyle
let timeString = String(dateFormatter.stringFromDate(now))
var timeFullString = ""
for item in timeString.characters
{
timeFullString += convertHalf2Full(item)
}
return String(timeFullString)+"分"
}
//もっといい方法があればそれに置き換える
func convertHalf2Full(chra: Character) -> String
{
switch chra{
case "1":
return "1"
case "2":
return "2"
case "3":
return "3"
case "4":
return "4"
case "5":
return "5"
case "6":
return "6"
case "7":
return "7"
case "8":
return "8"
case "9":
return "9"
case "0":
return "0"
case ":":
return "時"
default:
return String(chra)
}
}
/////////////////// use for replaceing the word end ///////////////////
/////////////////// use for pet balloon ///////////////////
func selectPhrase(foodStateValue: Int, sleepStateValue: Int, funStateValue: Int, healthStateValue: Int, relationshipStateValue: Int, isSleeping: Bool, balloonConverSession:[[String:String]]) -> [String:String]
{
//候補配列
var candidateArray = [[String:String]]()
if isSleeping
{
candidateArray.append(balloonConverSession[5])
candidateArray.append(balloonConverSession[6])
//そこからランダムに選択
let arrayLength:Int = Int(candidateArray.count)
let randNum = Int(arc4random_uniform(UInt32(arrayLength)))
return candidateArray[randNum]
}
//balloonConverSessionから条件に入るもののみを候補配列にappendする
for elementDict in balloonConverSession
{
var flag = 0
flag += cheackCondition(elementDict,
conditionName:"condition1",
foodStateValue: foodStateValue,
sleepStateValue: sleepStateValue,
funStateValue: funStateValue,
healthStateValue: healthStateValue,
relationshipStateValue: relationshipStateValue,
isSleeping: isSleeping)
flag += cheackCondition(elementDict,
conditionName:"condition2",
foodStateValue: foodStateValue,
sleepStateValue: sleepStateValue,
funStateValue: funStateValue,
healthStateValue: healthStateValue,
relationshipStateValue: relationshipStateValue,
isSleeping: isSleeping)
if flag == 0
{
candidateArray.append(elementDict)
}
}
//そこからランダムに選択
let arrayLength:Int = Int(candidateArray.count)
let randNum = Int(arc4random_uniform(UInt32(arrayLength)))
return candidateArray[randNum]
}
func cheackCondition(targetDict:[String:String], conditionName:String,foodStateValue: Int, sleepStateValue: Int, funStateValue: Int, healthStateValue: Int, relationshipStateValue: Int, isSleeping: Bool) -> Int
{
let paraX = Int(targetDict[conditionName+"para1"]!)!
let paraY = Int(targetDict[conditionName+"para2"]!)!
switch targetDict[conditionName]!
{
case "1"://no condition
return 0
case "2":// food is in X ~ Y
if checkNumIsInside(foodStateValue, minNum: paraX, maxNum: paraY) { return 0 }
return 1
case "3":// fun is in X ~ Y
if checkNumIsInside(funStateValue, minNum: paraX, maxNum: paraY) { return 0 }
return 1
case "4":// sleep is in X ~ Y
if checkNumIsInside(sleepStateValue, minNum: paraX, maxNum: paraY) { return 0 }
return 1
case "5":// health is in X ~ Y
if checkNumIsInside(healthStateValue, minNum: paraX, maxNum: paraY) { return 0 }
return 1
case "6":// relationship is in X ~ Y
if checkNumIsInside(foodStateValue, minNum: paraX, maxNum: paraY) { return 0 }
return 1
case "7":// quiz correct number is X
break
case "8":// minigame win
break
case "9":// minigame draw
break
case "10":// minigame lose
break
case "11":// equip item number X
//ここの処理大変そう
break
case "12":// is sleeping
return 1
case "13":// time is in X ~ Y
break
case "14":// day is in X ~ Y
break
case "15":// heartrate is in X ~ Y
break
case "16":// walktime is in X ~ Y
break
case "17":// bodytempurture is in X ~ Y
break
default:
break
}
return 0
}
func checkNumIsInside(targetNum:Int, minNum:Int, maxNum:Int) -> Bool
{
if minNum <= targetNum || targetNum <= maxNum
{
return true
}
return false
}
/////////////////// use for pet balloon end ///////////////////
/////////////////// use for pet talking part ///////////////////
//何かないかなー
func filterByStatus(foodStateValue: Int, sleepStateValue: Int, funStateValue: Int, healthStateValue: Int, relationshipStateValue: Int, isSleeping: Bool, converSession:[[String:String]]) -> [[String:String]]
{
//候補配列
var candidateArray = [[String:String]]()
//balloonConverSessionから条件に入るもののみを候補配列にappendする
for elementDict in converSession
{
var flag = 0
flag += cheackCondition(elementDict,
conditionName:"condition1",
foodStateValue: foodStateValue,
sleepStateValue: sleepStateValue,
funStateValue: funStateValue,
healthStateValue: healthStateValue,
relationshipStateValue: relationshipStateValue,
isSleeping: isSleeping)
flag += cheackCondition(elementDict,
conditionName:"condition2",
foodStateValue: foodStateValue,
sleepStateValue: sleepStateValue,
funStateValue: funStateValue,
healthStateValue: healthStateValue,
relationshipStateValue: relationshipStateValue,
isSleeping: isSleeping)
if flag == 0
{
candidateArray.append(elementDict)
}
}
return candidateArray
}
/////////////////// use for pet talking part end ///////////////////
}
| 32.919753 | 213 | 0.532815 |
6162d0427ddcdd32c6afa4863afff4b89dd8c1ab
| 5,092 |
//
// WCTableCellNode.swift
// WeChatSwift
//
// Created by xu.shuifeng on 2019/8/5.
// Copyright © 2019 alexiscn. All rights reserved.
//
import AsyncDisplayKit
/// WeChat Common Table Cell Node
/// -------------------------
/// [Icon?]--[Title]------[>]
/// -------------------------
class WCTableCellNode: ASCellNode {
var valueChangedHandler: ((Bool) -> Void)?
private let iconNode = ASNetworkImageNode()
private let titleNode = ASTextNode()
private let arrowNode = ASImageNode()
private let lineNode = ASDisplayNode()
private let badgeNode = BadgeNode()
private var switchNode: ASDisplayNode?
private lazy var switchButton: UISwitch = {
let button = UISwitch()
button.onTintColor = Colors.Brand
return button
}()
private let model: WCTableCellModel
private let isLastCell: Bool
init(model: WCTableCellModel, isLastCell: Bool) {
self.model = model
self.isLastCell = isLastCell
super.init()
automaticallyManagesSubnodes = true
if model.wc_imageURL != nil {
iconNode.url = model.wc_imageURL
} else {
iconNode.image = model.wc_image
}
titleNode.attributedText = model.wc_attributedStringForTitle()
lineNode.backgroundColor = Colors.DEFAULT_SEPARTOR_LINE_COLOR
arrowNode.image = UIImage.SVGImage(named: "icons_outlined_arrow")
badgeNode.update(count: model.wc_badgeCount, showDot: false)
if model.wc_showSwitch {
isUserInteractionEnabled = true
let isOn = model.wc_switchValue
switchNode = ASDisplayNode(viewBlock: { [weak self] () -> UIView in
let button = self?.switchButton ?? UISwitch()
button.isOn = isOn
return button
})
}
if model.wc_imageCornerRadius > 0 {
iconNode.cornerRadius = model.wc_imageCornerRadius
iconNode.cornerRoundingType = .precomposited
}
}
override func didLoad() {
super.didLoad()
backgroundColor = .white
if model.wc_showSwitch {
switchButton.addTarget(self, action: #selector(switchButtonValueChanged(_:)), for: .valueChanged)
}
}
@objc private func switchButtonValueChanged(_ sender: UISwitch) {
valueChangedHandler?(sender.isOn)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
if model.wc_cellStyle == .centerButton || model.wc_cellStyle == .destructiveButton {
let stack = ASStackLayoutSpec.horizontal()
stack.horizontalAlignment = .middle
stack.verticalAlignment = .center
stack.children = [titleNode]
stack.style.preferredSize = CGSize(width: constrainedSize.max.width, height: 56)
return stack
}
var elements: [ASLayoutElement] = []
var leading: CGFloat = 0.0
// Append Image
if model.wc_image != nil || model.wc_imageURL != nil {
iconNode.style.spacingBefore = 16
iconNode.style.preferredSize = model.wc_imageLayoutSize
elements.append(iconNode)
leading += 16.0 + model.wc_imageLayoutSize.width
}
// Append Title
titleNode.style.spacingBefore = 16.0
elements.append(titleNode)
leading += 16.0
// Append Badge
if model.wc_badgeCount > 0 {
badgeNode.style.preferredSize = CGSize(width: 30, height: 30)
elements.append(badgeNode)
}
// Append Spacer
let spacer = ASLayoutSpec()
spacer.style.flexGrow = 1.0
spacer.style.flexShrink = 1.0
elements.append(spacer)
if let accessory = model.wc_accessoryNode {
elements.append(accessory)
}
if let switchNode = self.switchNode {
// Append Switch
switchNode.style.preferredSize = CGSize(width: 51, height: 31)
switchNode.style.spacingAfter = 16
elements.append(switchNode)
} else {
// Append Arrow
arrowNode.style.preferredSize = CGSize(width: 12, height: 24)
arrowNode.style.spacingBefore = 10
arrowNode.style.spacingAfter = 16
arrowNode.isHidden = !model.wc_showArrow
elements.append(arrowNode)
}
let stack = ASStackLayoutSpec.horizontal()
stack.alignItems = .center
stack.children = elements
stack.style.preferredSize = CGSize(width: constrainedSize.max.width, height: 56)
lineNode.isHidden = isLastCell
lineNode.style.preferredSize = CGSize(width: Constants.screenWidth - leading, height: Constants.lineHeight)
lineNode.style.layoutPosition = CGPoint(x: leading, y: 56 - Constants.lineHeight)
return ASAbsoluteLayoutSpec(children: [stack, lineNode])
}
}
| 34.174497 | 115 | 0.600157 |
2311ca37c75cfd65246a0f54f1a93651fab90eab
| 1,180 |
//
// UIView+Common.swift
// Hupu
//
// Created by 张驰 on 2018/6/28.
// Copyright © 2018年 张驰. All rights reserved.
//
import UIKit
public extension UIView {
var x:CGFloat {
set {
self.frame.origin.x = newValue
}
get {
return self.frame.minX
}
}
var y:CGFloat {
set {
self.frame.origin.y = newValue
}
get {
return self.frame.minY
}
}
var width:CGFloat {
set {
self.frame.size.width = newValue
}
get {
return self.frame.width
}
}
var height:CGFloat {
set {
self.frame.size.height = newValue
}
get {
return self.frame.height
}
}
var centerX:CGFloat {
set {
self.frame.origin.x = newValue - self.width/2
}
get {
return self.x + self.width/2
}
}
var centerY:CGFloat {
set {
self.frame.origin.x = newValue + self.height/2
}
get {
return self.y + self.height/2
}
}
}
| 17.101449 | 58 | 0.441525 |
9b7090d7b34ed264304694cffcda06aa151f8190
| 312 |
import Foundation
public struct PaymentSourceDeleteInput: GraphMutationInput {
let paymentSourceId: String
public init(paymentSourceId: String) {
self.paymentSourceId = paymentSourceId
}
public func toInputDictionary() -> [String: Any] {
return ["paymentSourceId": self.paymentSourceId]
}
}
| 22.285714 | 60 | 0.753205 |
234662a23d2d431a8d6e7ff814a89ff8cb18cd96
| 13,506 |
//
// Modified MIT License
//
// Copyright (c) 2010-2018 Kite Tech Ltd. https://www.kite.ly
//
// 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 software MAY ONLY be used with the Kite Tech Ltd platform and MAY NOT be modified
// to be used with any competitor platforms. This means the software MAY NOT be modified
// to place orders with any competitors to Kite Tech Ltd, all orders MUST go through the
// Kite Tech Ltd platform servers.
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
@objc protocol PhotobookPageViewDelegate: class {
@objc optional func didTapOnPage(_ page: PhotobookPageView, at index: Int)
@objc optional func didTapOnAsset(at index: Int)
@objc optional func didTapOnText(at index: Int)
}
enum PhotobookPageViewInteraction {
case disabled // The user cannot tap on the page
case wholePage // The user can tap anywhere on the page for a single action
case assetAndText // The user can tap on the page and the text for two different actions
}
enum TextBoxMode {
case placeHolder // Shows a placeholder "Add your own text" or the user's input if available
case userTextOnly // Only shows the user's input if available. Blank otherwise.
case linesPlaceholder // Shows a graphical representation of text in the form of two lines
}
class PhotobookPageView: UIView {
weak var delegate: PhotobookPageViewDelegate?
var pageIndex: Int?
var aspectRatio: CGFloat? {
didSet {
guard let aspectRatio = aspectRatio else { return }
let priority = self.aspectRatioConstraint.priority
self.removeConstraint(self.aspectRatioConstraint)
aspectRatioConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: self, attribute: .height, multiplier: aspectRatio, constant: 0)
aspectRatioConstraint.priority = priority
self.addConstraint(aspectRatioConstraint)
}
}
var isVisible: Bool = false {
didSet {
for subview in subviews {
subview.isHidden = !isVisible
}
}
}
var color: ProductColor = .white
private var hasSetupGestures = false
var productLayout: ProductLayout?
var interaction: PhotobookPageViewInteraction = .disabled {
didSet {
if oldValue != interaction {
hasSetupGestures = false
setupGestures()
}
}
}
var bleed: CGFloat?
private var isShowingTextPlaceholder = false
@IBOutlet private weak var bleedAssetContainerView: UIView! // Hierarchical order: assetContainerView, bleedingAssetContainerView & assetImageView
@IBOutlet private weak var assetContainerView: UIView!
@IBOutlet private weak var assetPlaceholderIconImageView: UIImageView!
@IBOutlet private weak var assetImageView: UIImageView!
@IBOutlet private weak var textAreaView: UIView?
@IBOutlet private weak var pageTextLabel: UILabel? {
didSet {
pageTextLabel!.alpha = 0.0
pageTextLabel!.layer.anchorPoint = CGPoint(x: 0.0, y: 0.0)
}
}
@IBOutlet private weak var textLabelPlaceholderBoxView: TextLabelPlaceholderBoxView? {
didSet { textLabelPlaceholderBoxView!.alpha = 0.0 }
}
@IBOutlet private var aspectRatioConstraint: NSLayoutConstraint!
var product: PhotobookProduct!
override func layoutSubviews() {
setupImageBox(with: productLayout?.productLayoutAsset?.currentImage)
adjustTextLabel()
setupGestures()
}
private func setupGestures() {
guard !hasSetupGestures else { return }
if let gestureRecognizers = gestureRecognizers {
for gestureRecognizer in gestureRecognizers {
removeGestureRecognizer(gestureRecognizer)
}
}
switch interaction {
case .wholePage:
let pageTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapOnPage(_:)))
addGestureRecognizer(pageTapGestureRecognizer)
case .assetAndText:
let assetTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapOnAsset(_:)))
assetContainerView.addGestureRecognizer(assetTapGestureRecognizer)
let textTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapOnText(_:)))
textAreaView?.addGestureRecognizer(textTapGestureRecognizer)
default:
break
}
hasSetupGestures = true
}
func setupLayoutBoxes(animated: Bool = true) {
guard assetImageView.image == nil && productLayout?.layout.imageLayoutBox != nil && animated else {
setupImageBox(animated: false)
setupTextBox()
return
}
assetImageView.alpha = 0.0
setupImageBox()
setupTextBox()
}
private var containerView: UIView! {
return bleedAssetContainerView != nil ? bleedAssetContainerView! : assetContainerView!
}
func setupImageBox(with assetImage: UIImage? = nil, animated: Bool = true, loadThumbnailFirst: Bool = true) {
// Avoid recalculating transforms with intermediate heights, e.g. when UICollectionViewCells are still determining their height
let finalBounds = bounds.width > 0 && (aspectRatio ?? 0.0) > 0.0 ? CGSize(width: bounds.width, height: bounds.width / aspectRatio!) : bounds.size
guard let imageBox = productLayout?.layout.imageLayoutBox,
finalBounds.width > 0.0 && finalBounds.height > 0.0 else {
assetContainerView.alpha = 0.0
return
}
assetContainerView.alpha = 1.0
assetContainerView.frame = imageBox.rectContained(in: finalBounds)
if bleedAssetContainerView != nil {
bleedAssetContainerView.frame = imageBox.bleedRect(in: assetContainerView.bounds.size, withBleed: bleed)
}
setImagePlaceholder()
guard let index = pageIndex, let asset = productLayout?.asset else {
assetImageView.image = nil
return
}
if let assetImage = assetImage {
setImage(image: assetImage)
return
}
var size = assetContainerView.bounds.size
if productLayout!.hasBeenEdited { size = 3.0 * size }
AssetLoadingManager.shared.image(for: asset, size: size, loadThumbnailFirst: loadThumbnailFirst, progressHandler: nil, completionHandler: { [weak welf = self] (image, _) in
guard welf?.pageIndex == index, let image = image, let productLayoutAsset = welf?.productLayout?.productLayoutAsset else { return }
if productLayoutAsset.currentImage == nil || (asset.identifier == productLayoutAsset.currentIdentifier && productLayoutAsset.currentImage!.size.width <= image.size.width) {
productLayoutAsset.currentImage = image
}
productLayoutAsset.currentIdentifier = asset.identifier
welf?.setImage(image: productLayoutAsset.currentImage!)
UIView.animate(withDuration: animated ? 0.1 : 0.0) {
welf?.assetImageView.alpha = 1.0
}
})
}
var shouldSetImage: Bool = false
func clearImage() {
assetImageView.image = nil
}
private func setImage(image: UIImage) {
guard let productLayoutAsset = productLayout?.productLayoutAsset,
let asset = productLayoutAsset.asset,
shouldSetImage
else { return }
assetImageView.transform = .identity
assetImageView.frame = CGRect(x: 0.0, y: 0.0, width: asset.size.width, height: asset.size.height)
assetImageView.image = image
assetImageView.center = CGPoint(x: containerView.bounds.midX, y: containerView.bounds.midY)
productLayoutAsset.containerSize = containerView.bounds.size
assetImageView.transform = productLayoutAsset.transform
}
func setupTextBox(mode: TextBoxMode = .placeHolder) {
guard let textBox = productLayout?.layout.textLayoutBox else {
if let placeholderView = textLabelPlaceholderBoxView { placeholderView.alpha = 0.0 }
if let pageTextLabel = pageTextLabel { pageTextLabel.alpha = 0.0 }
return
}
if mode == .linesPlaceholder, let placeholderView = textLabelPlaceholderBoxView {
placeholderView.alpha = 1.0
placeholderView.frame = textBox.rectContained(in: bounds.size)
placeholderView.color = color
placeholderView.setNeedsDisplay()
return
}
guard let pageTextLabel = pageTextLabel else { return }
pageTextLabel.alpha = 1.0
if (productLayout?.text ?? "").isEmpty && mode == .placeHolder {
pageTextLabel.text = NSLocalizedString("Views/Photobook Frame/PhotobookPageView/pageTextLabel/placeholder",
value: "Add your own text",
comment: "Placeholder text to show on a cover / page")
isShowingTextPlaceholder = true
} else {
pageTextLabel.text = productLayout?.text
isShowingTextPlaceholder = false
}
adjustTextLabel()
setTextColor()
}
private func adjustTextLabel() {
guard let pageTextLabel = pageTextLabel, let textBox = productLayout?.layout.textLayoutBox else { return }
let finalFrame = textBox.rectContained(in: bounds.size)
let originalSize = pageIndex == 0 ? product.photobookTemplate.coverSize : product.photobookTemplate.pageSize
pageTextLabel.transform = .identity
pageTextLabel.frame = CGRect(x: finalFrame.minX, y: finalFrame.minY, width: originalSize.width * textBox.rect.width, height: originalSize.height * textBox.rect.height)
textAreaView?.frame = finalFrame
let scale = finalFrame.width / (originalSize.width * textBox.rect.width)
guard pageTextLabel.text != nil else {
pageTextLabel.transform = pageTextLabel.transform.scaledBy(x: scale, y: scale)
return
}
let fontType = isShowingTextPlaceholder ? .plain : (productLayout!.fontType ?? .plain)
var fontSize = fontType.sizeForScreenToPageRatio()
if isShowingTextPlaceholder { fontSize *= 2.0 } // Make text larger so the placeholder can be read
pageTextLabel.attributedText = fontType.attributedText(with: pageTextLabel.text!, fontSize: fontSize, fontColor: color.fontColor())
let textHeight = pageTextLabel.attributedText!.height(for: pageTextLabel.bounds.width)
if textHeight < pageTextLabel.bounds.height { pageTextLabel.frame.size.height = ceil(textHeight) }
pageTextLabel.transform = pageTextLabel.transform.scaledBy(x: scale, y: scale)
}
private func setImagePlaceholder() {
let iconSize = min(assetContainerView.bounds.width, assetContainerView.bounds.height)
assetContainerView.backgroundColor = Colors.lightGrey
assetPlaceholderIconImageView.bounds.size = CGSize(width: iconSize * 0.2, height: iconSize * 0.2)
assetPlaceholderIconImageView.center = CGPoint(x: assetContainerView.bounds.midX, y: assetContainerView.bounds.midY)
assetPlaceholderIconImageView.alpha = 1.0
}
func setTextColor() {
if let pageTextLabel = pageTextLabel { pageTextLabel.textColor = color.fontColor() }
if let placeholderView = textLabelPlaceholderBoxView {
placeholderView.color = color
placeholderView.setNeedsDisplay()
}
}
@objc private func didTapOnPage(_ sender: UITapGestureRecognizer) {
guard let index = pageIndex else { return }
delegate?.didTapOnPage?(self, at: index)
}
@objc private func didTapOnAsset(_ sender: UITapGestureRecognizer) {
guard let index = pageIndex else { return }
delegate?.didTapOnAsset?(at: index)
}
@objc private func didTapOnText(_ sender: UITapGestureRecognizer) {
guard let index = pageIndex else { return }
delegate?.didTapOnText?(at: index)
}
}
| 42.740506 | 184 | 0.662076 |
211e9376bf80747bbdd78818a86ed210bb499a71
| 1,158 |
// RUN: rm -rf %t && mkdir -p %t
// Use fake mangled names here with the name of the imported module.
// swift-ide-test isn't testing the full demangling algorithm.
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-ast-typechecked -source-filename %s -swift-version 3 -find-mangled _T0So16ImportantCStructa | %FileCheck -check-prefix=CHECK-TOP-ALIAS %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-ast-typechecked -source-filename %s -swift-version 4 -find-mangled _T0So16ImportantCStructa | %FileCheck -check-prefix=CHECK-TOP-ALIAS %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-ast-typechecked -source-filename %s -swift-version 3 -find-mangled _T0So13InnerInSwift4a | %FileCheck -check-prefix=CHECK-NESTED-ALIAS %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-ast-typechecked -source-filename %s -swift-version 4 -find-mangled _T0So13InnerInSwift4a | %FileCheck -check-prefix=CHECK-NESTED-ALIAS %s
import APINotesFrameworkTest
// CHECK-TOP-ALIAS: typealias ImportantCStruct = VeryImportantCStruct
// CHECK-NESTED-ALIAS: typealias InnerInSwift4 = Outer.Inner
| 72.375 | 206 | 0.772021 |
18ad2e1006ed19e0016d9d7142bcdd9b16ec6bf5
| 1,047 |
//
// NetworkManager.swift
// SimpleWeather
//
// Created by Neutral Magnet on 2/23/21.
//
import Foundation
import Apollo
final class NetworkManager {
static let shared = NetworkManager()
private(set) lazy var apollo: ApolloClient = {
let client = URLSessionClient()
// Cache
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsURL = URL(fileURLWithPath: documentsPath)
let sqliteFileURL = documentsURL.appendingPathComponent("simple_weather_db.sqlite")
let cache = try! SQLiteNormalizedCache(fileURL: sqliteFileURL)
let store = ApolloStore(cache: cache)
let provider = LegacyInterceptorProvider(store: store)
let url = URL(string: "https://graphql-weather-api.herokuapp.com/")!
let transport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: url)
return ApolloClient(networkTransport: transport, store: store)
}()
}
| 33.774194 | 113 | 0.694365 |
017e44238812bde723cba57e2f3c1e71f4d2c37a
| 627 |
//
// Array2D.swift
// iosTris
//
// Created by Joshua Beard on 1/2/18.
// Copyright © 2018 Joshua Beard. All rights reserved.
//
class Array2D<T> {
let columns: Int
let rows: Int
var array: Array<T?>
init(columns: Int, rows: Int) {
self.columns = columns
self.rows = rows
array = Array<T?>(repeating: nil, count: rows * columns)
}
subscript(column: Int, row: Int) -> T? {
get {
return array[(row * columns) + column]
}
set(newValue) {
array[(row * columns) + column] = newValue
}
}
}
| 19.59375 | 64 | 0.511962 |
e905fb61aac58c9737daeeea9be9e57d294290a5
| 117,814 |
//
// SettingsViewController.swift
// piwigo
//
// Created by Spencer Baker on 1/20/15.
// Copyright (c) 2015 bakercrew. All rights reserved.
//
// Converted to Swift 5 by Eddy Lelièvre-Berna on 12/04/2020.
//
import Intents
import MessageUI
import UIKit
import piwigoKit
enum SettingsSection : Int {
case server
case logout
case albums
case images
case imageUpload
case appearance
case cache
case clear
case about
case count
}
enum kImageUploadSetting : Int {
case author
case prefix
}
let kHelpUsTitle = "Help Us!"
let kHelpUsTranslatePiwigo = "Piwigo is only partially translated in your language. Could you please help us complete the translation?"
@objc protocol ChangedSettingsDelegate: NSObjectProtocol {
func didChangeDefaultAlbum()
}
@objc
class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, MFMailComposeViewControllerDelegate {
@objc weak var settingsDelegate: ChangedSettingsDelegate?
@IBOutlet var settingsTableView: UITableView!
private var tableViewBottomConstraint: NSLayoutConstraint?
private var doneBarButton: UIBarButtonItem?
private var helpBarButton: UIBarButtonItem?
private var statistics = ""
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Get Server Infos if possible
if NetworkVars.hasAdminRights {
DispatchQueue.global(qos: .userInitiated).async {
self.getInfos()
}
}
// Title
title = NSLocalizedString("tabBar_preferences", comment: "Settings")
// Button for returning to albums/images
doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(quitSettings))
doneBarButton?.accessibilityIdentifier = "Done"
// Button for displaying help pages
let helpButton = UIButton(type: .infoLight)
helpButton.addTarget(self, action: #selector(displayHelp), for: .touchUpInside)
helpBarButton = UIBarButtonItem(customView: helpButton)
helpBarButton?.accessibilityIdentifier = "Help"
// Table view identifier
settingsTableView.accessibilityIdentifier = "settings"
// Set colors, fonts, etc.
applyColorPalette()
// Check whether we should display the max size options
if UploadVars.resizeImageOnUpload,
UploadVars.photoMaxSize == 0, UploadVars.videoMaxSize == 0 {
UploadVars.resizeImageOnUpload = false
}
// Check whether we should show the prefix option
if UploadVars.prefixFileNameBeforeUpload,
UploadVars.defaultPrefix.isEmpty {
UploadVars.prefixFileNameBeforeUpload = false
}
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Navigation bar
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
navigationController?.navigationBar.titleTextAttributes = attributes
if #available(iOS 11.0, *) {
let attributesLarge = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontLargeTitle()
]
navigationController?.navigationBar.largeTitleTextAttributes = attributesLarge
navigationController?.navigationBar.prefersLargeTitles = true
}
navigationController?.navigationBar.barStyle = AppVars.isDarkPaletteActive ? .black : .default
navigationController?.navigationBar.tintColor = .piwigoColorOrange()
navigationController?.navigationBar.barTintColor = .piwigoColorBackground()
navigationController?.navigationBar.backgroundColor = .piwigoColorBackground()
if #available(iOS 15.0, *) {
/// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance,
/// which by default produces a transparent background, to all navigation bars.
let barAppearance = UINavigationBarAppearance()
barAppearance.configureWithOpaqueBackground()
barAppearance.backgroundColor = .piwigoColorBackground()
navigationController?.navigationBar.standardAppearance = barAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
}
// Table view
settingsTableView?.separatorColor = .piwigoColorSeparator()
settingsTableView?.indicatorStyle = AppVars.isDarkPaletteActive ? .white : .black
settingsTableView?.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set navigation buttons
navigationItem.setLeftBarButtonItems([doneBarButton].compactMap { $0 }, animated: true)
navigationItem.setRightBarButtonItems([helpBarButton].compactMap { $0 }, animated: true)
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: PwgNotifications.paletteChanged, object: nil)
// Register auto-upload option enabled
NotificationCenter.default.addObserver(self, selector: #selector(updateAutoUpload),
name: PwgNotifications.autoUploadEnabled, object: nil)
// Register auto-upload option disabled
NotificationCenter.default.addObserver(self, selector: #selector(updateAutoUpload),
name: PwgNotifications.autoUploadDisabled, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if #available(iOS 10, *) {
let langCode = NSLocale.current.languageCode
// print("=> langCode: ", String(describing: langCode))
// print(String(format: "=> now:%.0f > last:%.0f + %.0f", Date().timeIntervalSinceReferenceDate, AppVars.dateOfLastTranslationRequest, k2WeeksInDays))
if (Date().timeIntervalSinceReferenceDate > AppVars.dateOfLastTranslationRequest + AppVars.kPiwigoOneMonth) && ((langCode == "ar") || (langCode == "fa") || (langCode == "pl") || (langCode == "pt-BR") || (langCode == "sk")) {
// Store date of last translation request
AppVars.dateOfLastTranslationRequest = Date().timeIntervalSinceReferenceDate
// Request a translation
let alert = UIAlertController(title: kHelpUsTitle, message: kHelpUsTranslatePiwigo, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("alertNoButton", comment: "No"), style: .destructive, handler: { action in
})
let defaultAction = UIAlertAction(title: NSLocalizedString("alertYesButton", comment: "Yes"), style: .default, handler: { action in
if let url = URL(string: "https://crowdin.com/project/piwigo-mobile") {
UIApplication.shared.openURL(url)
}
})
alert.addAction(cancelAction)
alert.addAction(defaultAction)
alert.view.tintColor = .piwigoColorOrange()
if #available(iOS 13.0, *) {
alert.overrideUserInterfaceStyle = AppVars.isDarkPaletteActive ? .dark : .light
} else {
// Fallback on earlier versions
}
present(alert, animated: true, completion: {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alert.view.tintColor = .piwigoColorOrange()
})
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
//Reload the tableview on orientation change, to match the new width of the table.
coordinator.animate(alongsideTransition: { context in
// On iPad, the Settings section is presented in a centered popover view
if UIDevice.current.userInterfaceIdiom == .pad {
let mainScreenBounds = UIScreen.main.bounds
self.popoverPresentationController?.sourceRect = CGRect(x: mainScreenBounds.midX,
y: mainScreenBounds.midY,
width: 0, height: 0)
self.preferredContentSize = CGSize(width: kPiwigoPadSettingsWidth,
height: ceil(mainScreenBounds.height * 2 / 3))
}
// Reload table view
self.settingsTableView?.reloadData()
})
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: PwgNotifications.paletteChanged, object: nil)
// Unregister auto-upload option enabler
NotificationCenter.default.removeObserver(self, name: PwgNotifications.autoUploadEnabled, object: nil)
// Unregister auto-upload option disabler
NotificationCenter.default.removeObserver(self, name: PwgNotifications.autoUploadDisabled, object: nil)
}
@objc func quitSettings() {
dismiss(animated: true)
}
@objc func displayHelp() {
let helpSB = UIStoryboard(name: "HelpViewController", bundle: nil)
let helpVC = helpSB.instantiateViewController(withIdentifier: "HelpViewController") as? HelpViewController
if let helpVC = helpVC {
// Update this list after deleting/creating Help##ViewControllers
if #available(iOS 14, *) {
helpVC.displayHelpPagesWithIndex = [0,4,5,1,3,6,2]
} else if #available(iOS 13, *) {
helpVC.displayHelpPagesWithIndex = [0,4,5,1,3,2]
} else {
helpVC.displayHelpPagesWithIndex = [0,4,5,3,2]
}
if UIDevice.current.userInterfaceIdiom == .phone {
helpVC.popoverPresentationController?.permittedArrowDirections = .up
navigationController?.present(helpVC, animated:true)
} else {
helpVC.modalPresentationStyle = .currentContext
helpVC.modalTransitionStyle = .flipHorizontal
helpVC.popoverPresentationController?.sourceView = view
navigationController?.present(helpVC, animated: true)
}
}
}
@objc func updateAutoUpload(_ notification: Notification) {
// NOP if the option is not available
if !NetworkVars.usesUploadAsync { return }
// Reload section instead of row because user's rights may have changed after logout/login
settingsTableView?.reloadSections(IndexSet(integer: SettingsSection.imageUpload.rawValue), with: .automatic)
// Inform user if the AutoUploadViewController is not presented
children.forEach { if $0 is AutoUploadViewController { return } }
if let title = notification.userInfo?["title"] as? String, !title.isEmpty,
let message = notification.userInfo?["message"] as? String {
dismissPiwigoError(withTitle: title, message: message) { }
}
}
// MARK: - UITableView - Header
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = section
if !(NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
// Header strings
var titleString = ""
var textString = ""
switch activeSection {
case SettingsSection.server.rawValue:
if (NetworkVars.serverProtocol == "https://") {
titleString = String(format: "%@ %@",
NSLocalizedString("settingsHeader_server", comment: "Piwigo Server"),
NetworkVars.pwgVersion)
} else {
titleString = String(format: "%@ %@\n",
NSLocalizedString("settingsHeader_server", comment: "Piwigo Server"),
NetworkVars.pwgVersion)
textString = NSLocalizedString("settingsHeader_notSecure", comment: "Website Not Secure!")
}
case SettingsSection.logout.rawValue, SettingsSection.clear.rawValue:
return 1
case SettingsSection.albums.rawValue:
titleString = NSLocalizedString("tabBar_albums", comment: "Albums")
case SettingsSection.images.rawValue:
titleString = NSLocalizedString("settingsHeader_images", comment: "Images")
case SettingsSection.imageUpload.rawValue:
titleString = NSLocalizedString("settingsHeader_upload", comment: "Default Upload Settings")
case SettingsSection.appearance.rawValue:
titleString = NSLocalizedString("settingsHeader_appearance", comment: "Appearance")
case SettingsSection.cache.rawValue:
titleString = NSLocalizedString("settingsHeader_cache", comment: "Cache Settings (Used/Total)")
case SettingsSection.about.rawValue:
titleString = NSLocalizedString("settingsHeader_about", comment: "Information")
default:
break
}
// Header height
let context = NSStringDrawingContext()
context.minimumScaleFactor = 1.0
let titleAttributes = [
NSAttributedString.Key.font: UIFont.piwigoFontBold()
]
let titleRect = titleString.boundingRect(with: CGSize(width: tableView.frame.size.width - 30.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: titleAttributes, context: context)
// Header height
var headerHeight: Int
if textString.count > 0 {
let textAttributes = [
NSAttributedString.Key.font: UIFont.piwigoFontSmall()
]
let textRect = textString.boundingRect(with: CGSize(width: tableView.frame.size.width - 30.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: textAttributes, context: context)
headerHeight = Int(fmax(44.0, ceil(titleRect.size.height + textRect.size.height)))
} else {
headerHeight = Int(fmax(44.0, ceil(titleRect.size.height)))
}
return CGFloat(headerHeight)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = section
if !(NetworkVars.hasAdminRights || (NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
// Header strings
var titleString = ""
var textString = ""
switch activeSection {
case SettingsSection.server.rawValue:
if (NetworkVars.serverProtocol == "https://") {
titleString = String(format: "%@ %@",
NSLocalizedString("settingsHeader_server", comment: "Piwigo Server"),
NetworkVars.pwgVersion)
} else {
titleString = String(format: "%@ %@\n",
NSLocalizedString("settingsHeader_server", comment: "Piwigo Server"),
NetworkVars.pwgVersion)
textString = NSLocalizedString("settingsHeader_notSecure", comment: "Website Not Secure!")
}
case SettingsSection.logout.rawValue, SettingsSection.clear.rawValue:
return nil
case SettingsSection.albums.rawValue:
titleString = NSLocalizedString("tabBar_albums", comment: "Albums")
case SettingsSection.images.rawValue:
titleString = NSLocalizedString("settingsHeader_images", comment: "Images")
case SettingsSection.imageUpload.rawValue:
titleString = NSLocalizedString("settingsHeader_upload", comment: "Default Upload Settings")
case SettingsSection.appearance.rawValue:
titleString = NSLocalizedString("settingsHeader_appearance", comment: "Appearance")
case SettingsSection.cache.rawValue:
titleString = NSLocalizedString("settingsHeader_cache", comment: "Cache Settings (Used/Total)")
case SettingsSection.about.rawValue:
titleString = NSLocalizedString("settingsHeader_about", comment: "Information")
default:
break
}
let headerAttributedString = NSMutableAttributedString(string: "")
// Title
let titleAttributedString = NSMutableAttributedString(string: titleString)
titleAttributedString.addAttribute(.font, value: UIFont.piwigoFontBold(), range: NSRange(location: 0, length: titleString.count))
headerAttributedString.append(titleAttributedString)
// Text
if textString.count > 0 {
let textAttributedString = NSMutableAttributedString(string: textString)
textAttributedString.addAttribute(.font, value: UIFont.piwigoFontSmall(), range: NSRange(location: 0, length: textString.count))
headerAttributedString.append(textAttributedString)
}
// Header label
let headerLabel = UILabel()
headerLabel.translatesAutoresizingMaskIntoConstraints = false
headerLabel.textColor = .piwigoColorHeader()
headerLabel.numberOfLines = 0
headerLabel.adjustsFontSizeToFitWidth = false
headerLabel.lineBreakMode = .byWordWrapping
headerLabel.attributedText = headerAttributedString
// Header view
let header = UIView()
header.backgroundColor = UIColor.clear
header.addSubview(headerLabel)
header.addConstraint(NSLayoutConstraint.constraintView(fromBottom: headerLabel, amount: 4)!)
if #available(iOS 11, *) {
header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-[header]-|", options: [], metrics: nil, views: [
"header": headerLabel
]))
} else {
header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-15-[header]-15-|", options: [], metrics: nil, views: [
"header": headerLabel
]))
}
return header
}
// MARK: - UITableView - Rows
func numberOfSections(in tableView: UITableView) -> Int {
let hasUploadSection = NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)
return SettingsSection.count.rawValue - (hasUploadSection ? 0 : 1)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = section
if !(NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
var nberOfRows = 0
switch activeSection {
case SettingsSection.server.rawValue:
nberOfRows = 2
case SettingsSection.logout.rawValue:
nberOfRows = 1
case SettingsSection.albums.rawValue:
nberOfRows = 4
case SettingsSection.images.rawValue:
nberOfRows = 5
case SettingsSection.imageUpload.rawValue:
nberOfRows = 7 + (NetworkVars.hasAdminRights ? 1 : 0)
nberOfRows += (UploadVars.resizeImageOnUpload ? 2 : 0)
nberOfRows += (UploadVars.compressImageOnUpload ? 1 : 0)
nberOfRows += (UploadVars.prefixFileNameBeforeUpload ? 1 : 0)
nberOfRows += (NetworkVars.usesUploadAsync ? 1 : 0)
case SettingsSection.appearance.rawValue:
nberOfRows = 1
case SettingsSection.cache.rawValue:
nberOfRows = 2
case SettingsSection.clear.rawValue:
nberOfRows = 1
case SettingsSection.about.rawValue:
nberOfRows = 8
default:
break
}
return nberOfRows
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = indexPath.section
if !(NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
var tableViewCell = UITableViewCell()
switch activeSection {
// MARK: Server
case SettingsSection.server.rawValue /* Piwigo Server */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
switch indexPath.row {
case 0:
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
let title = NSLocalizedString("settings_server", comment: "Address")
var detail: String
detail = String(format: "%@%@", NetworkVars.serverProtocol, NetworkVars.serverPath)
cell.configure(with: title, detail: detail)
cell.accessoryType = UITableViewCell.AccessoryType.none
cell.accessibilityIdentifier = "server"
case 1:
let title = NSLocalizedString("settings_username", comment: "Username")
var detail: String
if NetworkVars.username.isEmpty {
detail = NSLocalizedString("settings_notLoggedIn", comment: " - Not Logged In - ")
} else {
detail = NetworkVars.username
}
cell.configure(with: title, detail: detail)
cell.accessoryType = UITableViewCell.AccessoryType.none
cell.accessibilityIdentifier = "user"
default:
break
}
tableViewCell = cell
case SettingsSection.logout.rawValue /* Login/Logout Button */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonTableViewCell", for: indexPath) as? ButtonTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a ButtonTableViewCell!")
return ButtonTableViewCell()
}
if NetworkVars.username.isEmpty {
cell.configure(with: NSLocalizedString("login", comment: "Login"))
} else {
cell.configure(with: NSLocalizedString("settings_logout", comment: "Logout"))
}
cell.accessibilityIdentifier = "logout"
tableViewCell = cell
// MARK: Albums
case SettingsSection.albums.rawValue /* Albums */:
switch indexPath.row {
case 0 /* Default album */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let title = NSLocalizedString("setDefaultCategory_title", comment: "Default Album")
var detail: String
if AlbumVars.defaultCategory == 0 {
if view.bounds.size.width > 375 {
detail = NSLocalizedString("categorySelection_root", comment: "Root Album")
} else {
detail = NSLocalizedString("categorySelection_root<375pt", comment: "Root")
}
} else {
if let albumName = CategoriesData.sharedInstance().getCategoryById(AlbumVars.defaultCategory).name {
detail = albumName
} else {
if view.bounds.size.width > 375 {
detail = NSLocalizedString("categorySelection_root", comment: "Root Album")
} else {
detail = NSLocalizedString("categorySelection_root<375pt", comment: "Root")
}
AlbumVars.defaultCategory = 0
}
}
cell.configure(with: title, detail: detail)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultAlbum"
tableViewCell = cell
case 1 /* Thumbnail file */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let albumImageSize = kPiwigoImageSize(AlbumVars.defaultAlbumThumbnailSize)
let defaultAlbum = PiwigoImageData.name(forAlbumThumbnailSizeType: albumImageSize, withInfo: false)!
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String
if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
title = NSLocalizedString("defaultAlbumThumbnailFile>414px", comment: "Album Thumbnail File")
} else if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = NSLocalizedString("defaultThumbnailFile>320px", comment: "Thumbnail File")
} else {
title = NSLocalizedString("defaultThumbnailFile", comment: "File")
}
cell.configure(with: title, detail: defaultAlbum)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultAlbumThumbnailFile"
tableViewCell = cell
case 2 /* Default Sort */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let defSort = kPiwigoSort(rawValue: AlbumVars.defaultSort)
let defaultSort = CategorySortViewController.getNameForCategorySortType(defSort!)
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 Plus screen width
title = NSLocalizedString("defaultImageSort>414px", comment: "Default Sort of Images")
} else if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = NSLocalizedString("defaultImageSort>320px", comment: "Default Sort")
} else {
title = NSLocalizedString("defaultImageSort", comment: "Sort")
}
cell.configure(with: title, detail: defaultSort)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultSort"
tableViewCell = cell
case 3 /* Number of recent albums */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SliderTableViewCell", for: indexPath) as? SliderTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SliderTableViewCell!")
return SliderTableViewCell()
}
// Slider value
let value = Float(AlbumVars.maxNberRecentCategories)
// Slider configuration
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String = ""
if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
title = NSLocalizedString("maxNberOfRecentAlbums>414px", comment: "Number of Recent Albums")
} else if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = NSLocalizedString("maxNberOfRecentAlbums>320px", comment: "Recent Albums")
} else {
title = NSLocalizedString("maxNberOfRecentAlbums", comment: "Recent")
}
cell.configure(with: title, value: value, increment: 1, minValue: 3, maxValue: 10, prefix: "", suffix: "/10")
cell.cellSliderBlock = { newValue in
// Update settings
AlbumVars.maxNberRecentCategories = Int(newValue)
}
cell.accessibilityIdentifier = "maxNberRecentAlbums"
tableViewCell = cell
default:
break
}
// MARK: Images
case SettingsSection.images.rawValue /* Images */:
switch indexPath.row {
case 0 /* Thumbnail file */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let defaultSize = PiwigoImageData.name(forImageThumbnailSizeType: kPiwigoImageSize(AlbumVars.defaultThumbnailSize), withInfo: false)!
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String
if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
title = NSLocalizedString("defaultThumbnailFile>414px", comment: "Image Thumbnail File")
} else if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = NSLocalizedString("defaultThumbnailFile>320px", comment: "Thumbnail File")
} else {
title = NSLocalizedString("defaultThumbnailFile", comment: "File")
}
cell.configure(with: title, detail: defaultSize)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultImageThumbnailFile"
tableViewCell = cell
case 1 /* Number of thumbnails */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SliderTableViewCell", for: indexPath) as? SliderTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SliderTableViewCell!")
return SliderTableViewCell()
}
// Min/max number of thumbnails per row depends on selected file
let defaultWidth = PiwigoImageData.width(forImageSizeType: kPiwigoImageSize(AlbumVars.defaultThumbnailSize))
let minNberOfImages = ImagesCollection.imagesPerRowInPortrait(for: nil, maxWidth: defaultWidth)
// Slider value, chek that default number fits inside selected range
if Float(AlbumVars.thumbnailsPerRowInPortrait) > (2 * minNberOfImages) {
AlbumVars.thumbnailsPerRowInPortrait = Int(2 * minNberOfImages)
}
if Float(AlbumVars.thumbnailsPerRowInPortrait) < minNberOfImages {
AlbumVars.thumbnailsPerRowInPortrait = Int(minNberOfImages)
}
let value = Float(AlbumVars.thumbnailsPerRowInPortrait)
// Slider configuration
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String
if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
title = NSLocalizedString("defaultNberOfThumbnails>414px", comment: "Number per Row")
} else if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = NSLocalizedString("defaultNberOfThumbnails>320px", comment: "Number/Row")
} else {
title = NSLocalizedString("defaultNberOfThumbnails", comment: "Number")
}
cell.configure(with: title, value: value, increment: 1, minValue: minNberOfImages, maxValue: minNberOfImages * 2, prefix: "", suffix: "/\(Int(minNberOfImages * 2))")
cell.cellSliderBlock = { newValue in
// Update settings
AlbumVars.thumbnailsPerRowInPortrait = Int(newValue)
}
cell.accessibilityIdentifier = "nberThumbnailFiles"
tableViewCell = cell
case 2 /* Display titles on thumbnails */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 320 {
cell.configure(with: NSLocalizedString("settings_displayTitles>320px", comment: "Display Titles on Thumbnails"))
} else {
cell.configure(with: NSLocalizedString("settings_displayTitles", comment: "Titles on Thumbnails"))
}
// Switch status
cell.cellSwitch.setOn(AlbumVars.displayImageTitles, animated: true)
cell.cellSwitch.accessibilityIdentifier = "switchImageTitles"
cell.cellSwitchBlock = { switchState in
AlbumVars.displayImageTitles = switchState
}
cell.accessibilityIdentifier = "displayImageTitles"
tableViewCell = cell
case 3 /* Default Size of Previewed Images */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let defaultSize = PiwigoImageData.name(forImageSizeType: kPiwigoImageSize(ImageVars.shared.defaultImagePreviewSize), withInfo: false)!
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String
if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
title = NSLocalizedString("defaultPreviewFile>414px", comment: "Preview Image File")
} else if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = NSLocalizedString("defaultPreviewFile>320px", comment: "Preview File")
} else {
title = NSLocalizedString("defaultPreviewFile", comment: "Preview")
}
cell.configure(with: title, detail: defaultSize)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultImagePreviewSize"
tableViewCell = cell
case 4 /* Share Image Metadata Options */:
if #available(iOS 10, *) {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 screen width
cell.configure(with: NSLocalizedString("settings_shareGPSdata>375px", comment: "Share with Private Metadata"), detail: "")
} else {
cell.configure(with: NSLocalizedString("settings_shareGPSdata", comment: "Share Private Metadata"), detail: "")
}
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultShareOptions"
tableViewCell = cell
} else {
// Single On/Off share metadata option
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 screen width
cell.configure(with: NSLocalizedString("settings_shareGPSdata>375px", comment: "Share Private Metadata"))
} else {
cell.configure(with: NSLocalizedString("settings_shareGPSdata", comment: "Share Metadata"))
}
cell.cellSwitch.setOn(ImageVars.shared.shareMetadataTypeAirDrop, animated: true)
cell.cellSwitchBlock = { switchState in
ImageVars.shared.shareMetadataTypeAirDrop = switchState
}
cell.accessibilityIdentifier = "shareMetadataOptions"
tableViewCell = cell
}
default:
break
}
// MARK: Upload Settings
case SettingsSection.imageUpload.rawValue /* Default Upload Settings */:
var row = indexPath.row
row += (!NetworkVars.hasAdminRights && (row > 0)) ? 1 : 0
row += (!UploadVars.resizeImageOnUpload && (row > 3)) ? 2 : 0
row += (!UploadVars.compressImageOnUpload && (row > 6)) ? 1 : 0
row += (!UploadVars.prefixFileNameBeforeUpload && (row > 8)) ? 1 : 0
row += (!NetworkVars.usesUploadAsync && (row > 10)) ? 1 : 0
switch row {
case 0 /* Author Name? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldTableViewCell", for: indexPath) as? TextFieldTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a TextFieldTableViewCell!")
return TextFieldTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String
let input: String = UploadVars.defaultAuthor
let placeHolder: String = NSLocalizedString("settings_defaultAuthorPlaceholder", comment: "Author Name")
if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = NSLocalizedString("settings_defaultAuthor>320px", comment: "Author Name")
} else {
title = NSLocalizedString("settings_defaultAuthor", comment: "Author")
}
cell.configure(with: title, input: input, placeHolder: placeHolder)
cell.rightTextField.delegate = self
cell.rightTextField.tag = kImageUploadSetting.author.rawValue
cell.accessibilityIdentifier = "defaultAuthorName"
tableViewCell = cell
case 1 /* Privacy Level? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let defaultLevel = kPiwigoPrivacy(rawValue: UploadVars.defaultPrivacyLevel)!.name
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 Plus screen width
cell.configure(with: NSLocalizedString("privacyLevel", comment: "Privacy Level"), detail: defaultLevel)
} else {
cell.configure(with: NSLocalizedString("settings_defaultPrivacy", comment: "Privacy"), detail: defaultLevel)
}
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultPrivacyLevel"
tableViewCell = cell
case 2 /* Strip private Metadata? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 screen width
cell.configure(with: NSLocalizedString("settings_stripGPSdata>375px", comment: "Strip Private Metadata Before Upload"))
} else {
cell.configure(with: NSLocalizedString("settings_stripGPSdata", comment: "Strip Private Metadata"))
}
cell.cellSwitch.setOn(UploadVars.stripGPSdataOnUpload, animated: true)
cell.cellSwitchBlock = { switchState in
UploadVars.stripGPSdataOnUpload = switchState
}
cell.accessibilityIdentifier = "stripMetadataBeforeUpload"
tableViewCell = cell
case 3 /* Resize Before Upload? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_photoResize", comment: "Resize Before Upload"))
cell.cellSwitch.setOn(UploadVars.resizeImageOnUpload, animated: true)
cell.cellSwitchBlock = { switchState in
// Number of rows will change accordingly
UploadVars.resizeImageOnUpload = switchState
// Position of the row that should be added/removed
let photoAtIndexPath = IndexPath(row: 3 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
let videoAtIndexPath = IndexPath(row: 4 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
if switchState {
// Insert row in existing table
self.settingsTableView?.insertRows(at: [photoAtIndexPath, videoAtIndexPath], with: .automatic)
} else {
// Remove row in existing table
self.settingsTableView?.deleteRows(at: [photoAtIndexPath, videoAtIndexPath], with: .automatic)
}
}
cell.accessibilityIdentifier = "resizeBeforeUpload"
tableViewCell = cell
case 4 /* Upload Photo Size */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: "… " + NSLocalizedString("severalImages", comment: "Photos"),
detail: pwgPhotoMaxSizes(rawValue: UploadVars.photoMaxSize)?.name ?? pwgPhotoMaxSizes(rawValue: 0)!.name)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultUploadPhotoSize"
tableViewCell = cell
case 5 /* Upload Video Size */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: "… " + NSLocalizedString("severalVideos", comment: "Videos"),
detail: pwgVideoMaxSizes(rawValue: UploadVars.videoMaxSize)?.name ?? pwgVideoMaxSizes(rawValue: 0)!.name)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "defaultUploadVideoSize"
tableViewCell = cell
case 6 /* Compress before Upload? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
cell.configure(with: NSLocalizedString("settings_photoCompress>375px", comment: "Compress Photo Before Upload"))
} else {
cell.configure(with: NSLocalizedString("settings_photoCompress", comment: "Compress Before Upload"))
}
cell.cellSwitch.setOn(UploadVars.compressImageOnUpload, animated: true)
cell.cellSwitchBlock = { switchState in
// Number of rows will change accordingly
UploadVars.compressImageOnUpload = switchState
// Position of the row that should be added/removed
let rowAtIndexPath = IndexPath(row: 4 + (NetworkVars.hasAdminRights ? 1 : 0)
+ (UploadVars.resizeImageOnUpload ? 2 : 0),
section: SettingsSection.imageUpload.rawValue)
if switchState {
// Insert row in existing table
self.settingsTableView?.insertRows(at: [rowAtIndexPath], with: .automatic)
} else {
// Remove row in existing table
self.settingsTableView?.deleteRows(at: [rowAtIndexPath], with: .automatic)
}
}
cell.accessibilityIdentifier = "compressBeforeUpload"
tableViewCell = cell
case 7 /* Image Quality slider */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SliderTableViewCell", for: indexPath) as? SliderTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SliderTableViewCell!")
return SliderTableViewCell()
}
// Slider value
let value = Float(UploadVars.photoQuality)
// Slider configuration
let title = String(format: "… %@", NSLocalizedString("settings_photoQuality", comment: "Quality"))
cell.configure(with: title, value: value, increment: 1, minValue: 50, maxValue: 98, prefix: "", suffix: "%")
cell.cellSliderBlock = { newValue in
// Update settings
UploadVars.photoQuality = Int16(newValue)
}
cell.accessibilityIdentifier = "compressionRatio"
tableViewCell = cell
case 8 /* Prefix Filename Before Upload switch */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 screen width
cell.configure(with: NSLocalizedString("settings_prefixFilename>414px", comment: "Prefix Photo Filename Before Upload"))
} else if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
cell.configure(with: NSLocalizedString("settings_prefixFilename>375px", comment: "Prefix Filename Before Upload"))
} else {
cell.configure(with: NSLocalizedString("settings_prefixFilename", comment: "Prefix Filename"))
}
cell.cellSwitch.setOn(UploadVars.prefixFileNameBeforeUpload, animated: true)
cell.cellSwitchBlock = { switchState in
// Number of rows will change accordingly
UploadVars.prefixFileNameBeforeUpload = switchState
// Position of the row that should be added/removed
let rowAtIndexPath = IndexPath(row: 5 + (NetworkVars.hasAdminRights ? 1 : 0)
+ (UploadVars.resizeImageOnUpload ? 2 : 0)
+ (UploadVars.compressImageOnUpload ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
if switchState {
// Insert row in existing table
self.settingsTableView?.insertRows(at: [rowAtIndexPath], with: .automatic)
} else {
// Remove row in existing table
self.settingsTableView?.deleteRows(at: [rowAtIndexPath], with: .automatic)
}
}
cell.accessibilityIdentifier = "prefixBeforeUpload"
tableViewCell = cell
case 9 /* Filename prefix? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldTableViewCell", for: indexPath) as? TextFieldTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a TextFieldTableViewCell!")
return TextFieldTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var title: String
let input: String = UploadVars.defaultPrefix
let placeHolder: String = NSLocalizedString("settings_defaultPrefixPlaceholder", comment: "Prefix Filename")
if view.bounds.size.width > 320 {
// i.e. larger than iPhone 5 screen width
title = String(format:"… %@", NSLocalizedString("settings_defaultPrefix>320px", comment: "Filename Prefix"))
} else {
title = String(format:"… %@", NSLocalizedString("settings_defaultPrefix", comment: "Prefix"))
}
cell.configure(with: title, input: input, placeHolder: placeHolder)
cell.rightTextField.delegate = self
cell.rightTextField.tag = kImageUploadSetting.prefix.rawValue
cell.accessibilityIdentifier = "prefixFileName"
tableViewCell = cell
case 10 /* Wi-Fi Only? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_wifiOnly", comment: "Wi-Fi Only"))
cell.cellSwitch.setOn(UploadVars.wifiOnlyUploading, animated: true)
cell.cellSwitchBlock = { switchState in
// Change option
UploadVars.wifiOnlyUploading = switchState
// Relaunch uploads in background queue if disabled
if switchState == false {
// Update upload tasks in background queue
// May not restart the uploads
UploadManager.shared.backgroundQueue.async {
UploadManager.shared.findNextImageToUpload()
}
}
}
cell.accessibilityIdentifier = "wifiOnly"
tableViewCell = cell
case 11 /* Auto-upload */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let title: String
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 screen width
title = NSLocalizedString("settings_autoUpload>414px", comment: "Auto Upload in the Background")
} else {
title = NSLocalizedString("settings_autoUpload", comment: "Auto Upload")
}
let detail: String
if UploadVars.isAutoUploadActive == true {
detail = NSLocalizedString("settings_autoUploadEnabled", comment: "On")
} else {
detail = NSLocalizedString("settings_autoUploadDisabled", comment: "Off")
}
cell.configure(with: title, detail: detail)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "autoUpload"
tableViewCell = cell
case 12 /* Delete image after upload? */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6,7 screen width
cell.configure(with: NSLocalizedString("settings_deleteImage>375px", comment: "Delete Image After Upload"))
} else {
cell.configure(with: NSLocalizedString("settings_deleteImage", comment: "Delete After Upload"))
}
cell.cellSwitch.setOn(UploadVars.deleteImageAfterUpload, animated: true)
cell.cellSwitchBlock = { switchState in
UploadVars.deleteImageAfterUpload = switchState
}
cell.accessibilityIdentifier = "deleteAfterUpload"
tableViewCell = cell
default:
break
}
// MARK: Appearance
case SettingsSection.appearance.rawValue /* Appearance */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
let title = NSLocalizedString("settingsHeader_colorPalette", comment: "Color Palette")
let detail: String
if AppVars.isLightPaletteModeActive == true {
detail = NSLocalizedString("settings_lightColor", comment: "Light")
} else if AppVars.isDarkPaletteModeActive == true {
detail = NSLocalizedString("settings_darkColor", comment: "Dark")
} else {
detail = NSLocalizedString("settings_switchPalette", comment: "Automatic")
}
cell.configure(with: title, detail: detail)
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "colorPalette"
tableViewCell = cell
// MARK: Cache Settings
case SettingsSection.cache.rawValue /* Cache Settings */:
switch indexPath.row {
case 0 /* Disk */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SliderTableViewCell", for: indexPath) as? SliderTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SliderTableViewCell!")
return SliderTableViewCell()
}
// Slider value
let value = Float(AppVars.diskCache)
// Slider configuration
let currentDiskSize = Float(NetworkVarsObjc.imageCache?.currentDiskUsage ?? 0)
let currentDiskSizeInMB: Float = currentDiskSize / (1024.0 * 1024.0)
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var prefix:String
if view.bounds.size.width > 375 {
// i.e. larger than iPhones 6,7 screen width
prefix = String(format: "%.1f/", currentDiskSizeInMB)
} else {
prefix = String(format: "%ld/", lroundf(currentDiskSizeInMB))
}
let suffix = NSLocalizedString("settings_cacheMegabytes", comment: "MB")
cell.configure(with: NSLocalizedString("settings_cacheDisk", comment: "Disk"),
value: value,
increment: Float(AppVars.kPiwigoDiskCacheInc),
minValue: Float(AppVars.kPiwigoDiskCacheMin),
maxValue: Float(AppVars.kPiwigoDiskCacheMax),
prefix: prefix, suffix: suffix)
cell.cellSliderBlock = { newValue in
// Update settings
AppVars.diskCache = Int(newValue)
// Update disk cache size
NetworkVarsObjc.imageCache?.diskCapacity = AppVars.diskCache * 1024 * 1024
}
cell.accessibilityIdentifier = "diskCache"
tableViewCell = cell
case 1 /* Memory */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SliderTableViewCell", for: indexPath) as? SliderTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SliderTableViewCell!")
return SliderTableViewCell()
}
// Slider value
let value = Float(AppVars.memoryCache)
// Slider configuration
let currentMemSize = Float(NetworkVarsObjc.thumbnailCache?.memoryUsage ?? 0)
let currentMemSizeInMB: Float = currentMemSize / (1024.0 * 1024.0)
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
var prefix:String
if view.bounds.size.width > 375 {
// i.e. larger than iPhone 6,7 screen width
prefix = String(format: "%.1f/", currentMemSizeInMB)
} else {
prefix = String(format: "%ld/", lroundf(currentMemSizeInMB))
}
let suffix = NSLocalizedString("settings_cacheMegabytes", comment: "MB")
cell.configure(with: NSLocalizedString("settings_cacheMemory", comment: "Memory"),
value: value,
increment: Float(AppVars.kPiwigoMemoryCacheInc),
minValue: Float(AppVars.kPiwigoMemoryCacheMin),
maxValue: Float(AppVars.kPiwigoMemoryCacheMax),
prefix: prefix, suffix: suffix)
cell.cellSliderBlock = { newValue in
// Update settings
AppVars.memoryCache = Int(newValue)
// Update memory cache size
NetworkVarsObjc.thumbnailCache?.memoryCapacity = UInt64(AppVars.memoryCache * 1024 * 1024)
}
cell.accessibilityIdentifier = "memoryCache"
tableViewCell = cell
default:
break
}
case SettingsSection.clear.rawValue /* Clear Cache Button */:
switch indexPath.row {
case 0 /* Clear */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonTableViewCell", for: indexPath) as? ButtonTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a ButtonTableViewCell!")
return ButtonTableViewCell()
}
// See https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
if view.bounds.size.width > 414 {
// i.e. larger than iPhones 6, 7 screen width
cell.configure(with: NSLocalizedString("settings_cacheClearAll", comment: "Clear Photo Cache"))
} else {
cell.configure(with: NSLocalizedString("settings_cacheClear", comment: "Clear Cache"))
}
cell.accessibilityIdentifier = "clearCache"
tableViewCell = cell
default:
break
}
// MARK: Information
case SettingsSection.about.rawValue /* Information */:
switch indexPath.row {
case 0 /* @piwigo (Twitter) */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_twitter", comment: "@piwigo"), detail: "")
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "piwigoInfo"
tableViewCell = cell
case 1 /* Contact Us */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_contactUs", comment: "Contact Us"), detail: "")
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
if !MFMailComposeViewController.canSendMail() {
cell.titleLabel.textColor = .piwigoColorRightLabel()
}
cell.accessibilityIdentifier = "mailContact"
tableViewCell = cell
case 2 /* Support Forum */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_supportForum", comment: "Support Forum"), detail: "")
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "supportForum"
tableViewCell = cell
case 3 /* Rate Piwigo Mobile */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
if let object = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") {
cell.configure(with: "\(NSLocalizedString("settings_rateInAppStore", comment: "Rate Piwigo Mobile")) \(object)", detail: "")
}
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "ratePiwigo"
tableViewCell = cell
case 4 /* Translate Piwigo Mobile */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_translateWithCrowdin", comment: "Translate Piwigo Mobile"), detail: "")
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
tableViewCell = cell
case 5 /* Release Notes */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_releaseNotes", comment: "Release Notes"), detail: "")
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "releaseNotes"
tableViewCell = cell
case 6 /* Acknowledgements */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_acknowledgements", comment: "Acknowledgements"), detail: "")
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "acknowledgements"
tableViewCell = cell
case 7 /* Privacy Policy */:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTableViewCell", for: indexPath) as? LabelTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a LabelTableViewCell!")
return LabelTableViewCell()
}
cell.configure(with: NSLocalizedString("settings_privacy", comment: "Privacy Policy"), detail: "")
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.accessibilityIdentifier = "privacyPolicy"
tableViewCell = cell
default:
break
}
default:
break
}
tableViewCell.isAccessibilityElement = true
return tableViewCell
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = indexPath.section
if !(NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
var result = true
switch activeSection {
// MARK: Server
case SettingsSection.server.rawValue /* Piwigo Server */:
result = false
case SettingsSection.logout.rawValue /* Logout Button */:
result = true
// MARK: Albums
case SettingsSection.albums.rawValue /* Albums */:
switch indexPath.row {
case 0 /* Default album */, 1 /* Default Thumbnail File */, 2 /* Default Sort */:
result = true
default:
result = false
}
// MARK: Images
case SettingsSection.images.rawValue /* Images */:
switch indexPath.row {
case 0 /* Default Thumbnail File */,
3 /* Default Size of Previewed Images */,
4 /* Share Image Metadata Options */:
result = true
default:
result = false
}
// MARK: Upload Settings
case SettingsSection.imageUpload.rawValue /* Default Upload Settings */:
var row = indexPath.row
row += (!NetworkVars.hasAdminRights && (row > 0)) ? 1 : 0
row += (!UploadVars.resizeImageOnUpload && (row > 3)) ? 2 : 0
row += (!UploadVars.compressImageOnUpload && (row > 6)) ? 1 : 0
row += (!UploadVars.prefixFileNameBeforeUpload && (row > 8)) ? 1 : 0
row += (!NetworkVars.usesUploadAsync && (row > 10)) ? 1 : 0
switch row {
case 1 /* Privacy Level */,
4 /* Upload Photo Size */,
5 /* Upload Video Size */,
11 /* Auto upload */:
result = true
default:
result = false
}
// MARK: Appearance
case SettingsSection.appearance.rawValue /* Appearance */:
result = true
// MARK: Cache Settings
case SettingsSection.cache.rawValue /* Cache Settings */:
result = false
case SettingsSection.clear.rawValue /* Cache Settings */:
result = true
// MARK: Information
case SettingsSection.about.rawValue /* Information */:
switch indexPath.row {
case 1 /* Contact Us */:
result = MFMailComposeViewController.canSendMail() ? true : false
case 0 /* Twitter */,
2 /* Support Forum */,
3 /* Rate Piwigo Mobile */,
4 /* Translate Piwigo Mobile */,
5 /* Release Notes */,
6 /* Acknowledgements */,
7 /* Privacy Policy */:
result = true
default:
result = false
}
default:
result = false
}
return result
}
// MARK: - UITableView - Footer
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// No footer by default (nil => 0 point)
var footer = ""
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = section
if !(NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
// Any footer text?
switch activeSection {
case SettingsSection.logout.rawValue:
if (!UploadVars.serverFileTypes.isEmpty) {
footer = "\(NSLocalizedString("settingsFooter_formats", comment: "The server accepts the following file formats")): \(UploadVars.serverFileTypes.replacingOccurrences(of: ",", with: ", "))."
}
case SettingsSection.about.rawValue:
footer = statistics
default:
return 16.0
}
// Footer height?
let attributes = [
NSAttributedString.Key.font: UIFont.piwigoFontSmall()
]
let context = NSStringDrawingContext()
context.minimumScaleFactor = 1.0
let footerRect = footer.boundingRect(with: CGSize(width: tableView.frame.size.width - 30.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: context)
return ceil(footerRect.size.height + 10.0)
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// Footer label
let footerLabel = UILabel()
footerLabel.translatesAutoresizingMaskIntoConstraints = false
footerLabel.font = .piwigoFontSmall()
footerLabel.textColor = .piwigoColorHeader()
footerLabel.textAlignment = .center
footerLabel.numberOfLines = 0
footerLabel.adjustsFontSizeToFitWidth = false
footerLabel.lineBreakMode = .byWordWrapping
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = section
if !(NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
// Footer text
switch activeSection {
case SettingsSection.logout.rawValue:
if !UploadVars.serverFileTypes.isEmpty {
footerLabel.text = "\(NSLocalizedString("settingsFooter_formats", comment: "The server accepts the following file formats")): \(UploadVars.serverFileTypes.replacingOccurrences(of: ",", with: ", "))."
}
case SettingsSection.about.rawValue:
footerLabel.text = statistics
default:
break
}
// Footer view
let footer = UIView()
footer.backgroundColor = UIColor.clear
footer.addSubview(footerLabel)
footer.addConstraint(NSLayoutConstraint.constraintView(fromTop: footerLabel, amount: 4)!)
if #available(iOS 11, *) {
footer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-[footer]-|", options: [], metrics: nil, views: [
"footer": footerLabel
]))
} else {
footer.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-15-[footer]-15-|", options: [], metrics: nil, views: [
"footer": footerLabel
]))
}
return footer
}
private func getInfos() {
// Initialisation
statistics = ""
// Collect stats from server
let JSONsession = PwgSession.shared
JSONsession.postRequest(withMethod: kPiwigoGetInfos, paramDict: [:],
countOfBytesClientExpectsToReceive: 1000) { jsonData, error in
// Any error?
/// - Network communication errors
/// - Returned JSON data is empty
/// - Cannot decode data returned by Piwigo server
/// -> nothing presented in the footer
if error != nil { return }
// Decode the JSON and collect statistics.
do {
// Decode the JSON into codable type TagJSON.
let decoder = JSONDecoder()
let uploadJSON = try decoder.decode(GetInfosJSON.self, from: jsonData)
// Piwigo error?
if (uploadJSON.errorCode != 0) {
#if DEBUG
let error = NSError(domain: "Piwigo", code: uploadJSON.errorCode,
userInfo: [NSLocalizedDescriptionKey : uploadJSON.errorMessage])
debugPrint(error)
#endif
return
}
// Collect statistics
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
for info in uploadJSON.data {
guard let value = info.value, let nber = Int(value) else { continue }
switch info.name ?? "" {
case "nb_elements":
if let nberPhotos = numberFormatter.string(from: NSNumber(value: nber)) {
let nberImages = nber > 1 ?
String(format: NSLocalizedString("severalImagesCount", comment: "%@ photos"), nberPhotos) :
String(format: NSLocalizedString("singleImageCount", comment: "%@ photo"), nberPhotos)
if !nberImages.isEmpty { self.appendStats(nberImages) }
}
case "nb_categories":
if let nberCats = numberFormatter.string(from: NSNumber(value: nber)) {
let nberCategories = nber > 1 ?
String(format: NSLocalizedString("severalAlbumsCount", comment: "%@ albums"), nberCats) :
String(format: NSLocalizedString("singleAlbumCount", comment: "%@ album"), nberCats)
if !nberCategories.isEmpty { self.appendStats(nberCategories) }
}
case "nb_tags":
if let nberTags = numberFormatter.string(from: NSNumber(value: nber)) {
let nberTags = nber > 1 ?
String(format: NSLocalizedString("severalTagsCount", comment: "%@ tags"), nberTags) :
String(format: NSLocalizedString("singleTagCount", comment: "%@ tag"), nberTags)
if !nberTags.isEmpty { self.appendStats(nberTags) }
}
case "nb_users":
if let nberUsers = numberFormatter.string(from: NSNumber(value: nber)) {
let nberUsers = nber > 1 ?
String(format: NSLocalizedString("severalUsersCount", comment: "%@ users"), nberUsers) :
String(format: NSLocalizedString("singleUserCount", comment: "%@ user"), nberUsers)
if !nberUsers.isEmpty { self.appendStats(nberUsers) }
}
case "nb_groups":
if let nberGroups = numberFormatter.string(from: NSNumber(value: nber)) {
let nberGroups = nber > 1 ?
String(format: NSLocalizedString("severalGroupsCount", comment: "%@ groups"), nberGroups) :
String(format: NSLocalizedString("singleGroupCount", comment: "%@ group"), nberGroups)
if !nberGroups.isEmpty { self.appendStats(nberGroups) }
}
case "nb_comments":
if let nberComments = numberFormatter.string(from: NSNumber(value: nber)) {
let nberComments = nber > 1 ?
String(format: NSLocalizedString("severalCommentsCount", comment: "%@ comments"), nberComments) :
String(format: NSLocalizedString("singleCommentCount", comment: "%@ comment"), nberComments)
if !nberComments.isEmpty { self.appendStats(nberComments) }
}
default:
break
}
}
} catch let error as NSError {
// Data cannot be digested
#if DEBUG
debugPrint(error)
#endif
return
}
}
}
private func appendStats(_ info: String) {
if statistics.isEmpty {
statistics.append(info)
} else {
statistics.append(" | " + info)
}
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// User can upload images/videos if he/she is logged in and has:
// — admin rights
// — normal rights with upload access to some categories with Community
var activeSection = indexPath.section
if !(NetworkVars.hasAdminRights ||
(NetworkVars.hasNormalRights && NetworkVars.usesCommunityPluginV29)) {
// Bypass the Upload section
if activeSection > SettingsSection.images.rawValue {
activeSection += 1
}
}
switch activeSection {
// MARK: Server
case SettingsSection.server.rawValue /* Piwigo Server */:
break
// MARK: Logout
case SettingsSection.logout.rawValue /* Logout */:
loginLogout()
// MARK: Albums
case SettingsSection.albums.rawValue /* Albums */:
switch indexPath.row {
case 0 /* Default album */:
let categorySB = UIStoryboard(name: "SelectCategoryViewControllerGrouped", bundle: nil)
guard let categoryVC = categorySB.instantiateViewController(withIdentifier: "SelectCategoryViewControllerGrouped") as? SelectCategoryViewController else { return }
categoryVC.setInput(parameter: AlbumVars.defaultCategory,
for: kPiwigoCategorySelectActionSetDefaultAlbum)
categoryVC.delegate = self
navigationController?.pushViewController(categoryVC, animated: true)
case 1 /* Thumbnail file selection */:
let defaultThumbnailSizeSB = UIStoryboard(name: "DefaultAlbumThumbnailSizeViewController", bundle: nil)
guard let defaultThumbnailSizeVC = defaultThumbnailSizeSB.instantiateViewController(withIdentifier: "DefaultAlbumThumbnailSizeViewController") as? DefaultAlbumThumbnailSizeViewController else { return }
defaultThumbnailSizeVC.delegate = self
navigationController?.pushViewController(defaultThumbnailSizeVC, animated: true)
case 2 /* Sort method selection */:
let categorySB = UIStoryboard(name: "CategorySortViewController", bundle: nil)
guard let categoryVC = categorySB.instantiateViewController(withIdentifier: "CategorySortViewController") as? CategorySortViewController else {return }
categoryVC.sortDelegate = self
navigationController?.pushViewController(categoryVC, animated: true)
default:
break
}
// MARK: Images
case SettingsSection.images.rawValue /* Images */:
switch indexPath.row {
case 0 /* Thumbnail file selection */:
let defaultThumbnailSizeSB = UIStoryboard(name: "DefaultImageThumbnailSizeViewController", bundle: nil)
guard let defaultThumbnailSizeVC = defaultThumbnailSizeSB.instantiateViewController(withIdentifier: "DefaultImageThumbnailSizeViewController") as? DefaultImageThumbnailSizeViewController else { return }
defaultThumbnailSizeVC.delegate = self
navigationController?.pushViewController(defaultThumbnailSizeVC, animated: true)
case 3 /* Image file selection */:
let defaultImageSizeSB = UIStoryboard(name: "DefaultImageSizeViewController", bundle: nil)
guard let defaultImageSizeVC = defaultImageSizeSB.instantiateViewController(withIdentifier: "DefaultImageSizeViewController") as? DefaultImageSizeViewController else { return }
defaultImageSizeVC.delegate = self
navigationController?.pushViewController(defaultImageSizeVC, animated: true)
case 4 /* Share image metadata options */:
let metadataOptionsSB = UIStoryboard(name: "ShareMetadataViewController", bundle: nil)
guard let metadataOptionsVC = metadataOptionsSB.instantiateViewController(withIdentifier: "ShareMetadataViewController") as? ShareMetadataViewController else { return }
navigationController?.pushViewController(metadataOptionsVC, animated: true)
default:
break
}
// MARK: Upload Settings
case SettingsSection.imageUpload.rawValue /* Default upload Settings */:
var row = indexPath.row
row += (!NetworkVars.hasAdminRights && (row > 0)) ? 1 : 0
row += (!UploadVars.resizeImageOnUpload && (row > 3)) ? 2 : 0
row += (!UploadVars.compressImageOnUpload && (row > 6)) ? 1 : 0
row += (!UploadVars.prefixFileNameBeforeUpload && (row > 8)) ? 1 : 0
row += (!NetworkVars.usesUploadAsync && (row > 10)) ? 1 : 0
switch row {
case 1 /* Default privacy selection */:
let privacySB = UIStoryboard(name: "SelectPrivacyViewController", bundle: nil)
guard let privacyVC = privacySB.instantiateViewController(withIdentifier: "SelectPrivacyViewController") as? SelectPrivacyViewController else { return }
privacyVC.delegate = self
privacyVC.privacy = kPiwigoPrivacy(rawValue: UploadVars.defaultPrivacyLevel) ?? .everybody
navigationController?.pushViewController(privacyVC, animated: true)
case 4 /* Upload Photo Size */:
let uploadPhotoSizeSB = UIStoryboard(name: "UploadPhotoSizeViewController", bundle: nil)
guard let uploadPhotoSizeVC = uploadPhotoSizeSB.instantiateViewController(withIdentifier: "UploadPhotoSizeViewController") as? UploadPhotoSizeViewController else { return }
uploadPhotoSizeVC.delegate = self
uploadPhotoSizeVC.photoMaxSize = UploadVars.photoMaxSize
navigationController?.pushViewController(uploadPhotoSizeVC, animated: true)
case 5 /* Upload Video Size */:
let uploadVideoSizeSB = UIStoryboard(name: "UploadVideoSizeViewController", bundle: nil)
guard let uploadVideoSizeVC = uploadVideoSizeSB.instantiateViewController(withIdentifier: "UploadVideoSizeViewController") as? UploadVideoSizeViewController else { return }
uploadVideoSizeVC.delegate = self
uploadVideoSizeVC.videoMaxSize = UploadVars.videoMaxSize
navigationController?.pushViewController(uploadVideoSizeVC, animated: true)
case 11 /* Auto Upload */:
let autoUploadSB = UIStoryboard(name: "AutoUploadViewController", bundle: nil)
guard let autoUploadVC = autoUploadSB.instantiateViewController(withIdentifier: "AutoUploadViewController") as? AutoUploadViewController else { return }
navigationController?.pushViewController(autoUploadVC, animated: true)
default:
break
}
// MARK: Appearance
case SettingsSection.appearance.rawValue /* Appearance */:
if #available(iOS 13.0, *) {
let colorPaletteSB = UIStoryboard(name: "ColorPaletteViewController", bundle: nil)
guard let colorPaletteVC = colorPaletteSB.instantiateViewController(withIdentifier: "ColorPaletteViewController") as? ColorPaletteViewController else { return }
navigationController?.pushViewController(colorPaletteVC, animated: true)
} else {
let colorPaletteSB = UIStoryboard(name: "ColorPaletteViewControllerOld", bundle: nil)
guard let colorPaletteVC = colorPaletteSB.instantiateViewController(withIdentifier: "ColorPaletteViewControllerOld") as? ColorPaletteViewControllerOld else { return }
navigationController?.pushViewController(colorPaletteVC, animated: true)
}
// MARK: Cache Settings
case SettingsSection.clear.rawValue /* Cache Clear */:
switch indexPath.row {
case 0 /* Clear cache */:
#if DEBUG
let alert = UIAlertController(title: "", message:NSLocalizedString("settings_cacheClearMsg", comment: "Are you sure you want to clear the cache? This will make albums and images take a while to load again."), preferredStyle: .actionSheet)
#else
let alert = UIAlertController(title: NSLocalizedString("settings_cacheClear", comment: "Clear Cache"), message: NSLocalizedString("settings_cacheClearMsg", comment: "Are you sure you want to clear the cache? This will make albums and images take a while to load again."), preferredStyle: .alert)
#endif
let dismissAction = UIAlertAction(title: NSLocalizedString("alertDismissButton", comment: "Dismiss"), style: .cancel, handler: nil)
#if DEBUG
let clearTagsAction = UIAlertAction(title: "Clear All Tags",
style: .default, handler: { action in
// Delete all tags in background queue
TagsProvider().clearTags()
TagsData.sharedInstance().clearCache()
})
alert.addAction(clearTagsAction)
let titleClearLocations = "Clear All Locations"
let clearLocationsAction = UIAlertAction(title: titleClearLocations,
style: .default, handler: { action in
// Delete all locations in background queue
LocationsProvider().clearLocations()
})
alert.addAction(clearLocationsAction)
let clearUploadsAction = UIAlertAction(title: "Clear All Upload Requests",
style: .default, handler: { action in
// Delete all upload requests in the main thread
UploadsProvider().clearUploads()
})
alert.addAction(clearUploadsAction)
#endif
let clearAction = UIAlertAction(title: NSLocalizedString("alertClearButton", comment: "Clear"), style: .destructive, handler: { action in
// Delete image cache
ClearCache.clearAllCache(exceptCategories: true) {
// Reload tableView
self.settingsTableView?.reloadData()
}
})
// Add actions
alert.addAction(dismissAction)
alert.addAction(clearAction)
// Determine position of cell in table view
let rowAtIndexPath = IndexPath(row: 0, section: SettingsSection.clear.rawValue)
let rectOfCellInTableView = settingsTableView?.rectForRow(at: rowAtIndexPath)
// Present list of actions
alert.view.tintColor = .piwigoColorOrange()
if #available(iOS 13.0, *) {
alert.overrideUserInterfaceStyle = AppVars.isDarkPaletteActive ? .dark : .light
} else {
// Fallback on earlier versions
}
alert.popoverPresentationController?.sourceView = settingsTableView
alert.popoverPresentationController?.permittedArrowDirections = [.up, .down]
alert.popoverPresentationController?.sourceRect = rectOfCellInTableView ?? CGRect.zero
present(alert, animated: true, completion: {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alert.view.tintColor = .piwigoColorOrange()
})
default:
break
}
// MARK: Information
case SettingsSection.about.rawValue /* About — Informations */:
switch indexPath.row {
case 0 /* Open @piwigo on Twitter */:
if let url = URL(string: NSLocalizedString("settings_twitterURL", comment: "https://twitter.com/piwigo")) {
UIApplication.shared.openURL(url)
}
case 1 /* Prepare draft email */:
if MFMailComposeViewController.canSendMail() {
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
// Configure the fields of the interface.
composeVC.setToRecipients([
NSLocalizedString("contact_email", tableName: "PrivacyPolicy", bundle: Bundle.main, value: "", comment: "Contact email")
])
// Collect version and build numbers
let appVersionString = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
let appBuildString = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
// Compile ticket number from current date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmm"
dateFormatter.locale = NSLocale(localeIdentifier: NetworkVars.language) as Locale
let date = Date()
let ticketDate = dateFormatter.string(from: date)
// Set subject
composeVC.setSubject("[Ticket#\(ticketDate)]: \(NSLocalizedString("settings_appName", comment: "Piwigo Mobile")) \(NSLocalizedString("settings_feedback", comment: "Feedback"))")
// Collect system and device data
var systemInfo = utsname()
uname(&systemInfo)
let size = Int(_SYS_NAMELEN) // is 32, but posix AND its init is 256....
let deviceModel: String = DeviceUtilities.name(forCode: withUnsafeMutablePointer(to: &systemInfo.machine) {p in
p.withMemoryRebound(to: CChar.self, capacity: size, {p2 in
return String(cString: p2)
})
})
let deviceOS = UIDevice.current.systemName
let deviceOSversion = UIDevice.current.systemVersion
// Set message body
composeVC.setMessageBody("\(NSLocalizedString("settings_appName", comment: "Piwigo Mobile")) \(appVersionString ?? "") (\(appBuildString ?? ""))\n\(deviceModel ) — \(deviceOS) \(deviceOSversion)\n==============>>\n\n", isHTML: false)
// Present the view controller modally.
present(composeVC, animated: true)
}
case 2 /* Open Piwigo support forum webpage with default browser */:
if let url = URL(string: NSLocalizedString("settings_pwgForumURL", comment: "http://piwigo.org/forum")) {
UIApplication.shared.openURL(url)
}
case 3 /* Open Piwigo App Store page for rating */:
// See https://itunes.apple.com/us/app/piwigo/id472225196?ls=1&mt=8
if let url = URL(string: "itms-apps://itunes.apple.com/app/piwigo/id472225196?action=write-review") {
UIApplication.shared.openURL(url)
}
case 4 /* Open Piwigo Crowdin page for translating */:
if let url = URL(string: "https://crowdin.com/project/piwigo-mobile") {
UIApplication.shared.openURL(url)
}
case 5 /* Open Release Notes page */:
let releaseNotesSB = UIStoryboard(name: "ReleaseNotesViewController", bundle: nil)
let releaseNotesVC = releaseNotesSB.instantiateViewController(withIdentifier: "ReleaseNotesViewController") as? ReleaseNotesViewController
if let releaseNotesVC = releaseNotesVC {
navigationController?.pushViewController(releaseNotesVC, animated: true)
}
case 6 /* Open Acknowledgements page */:
let aboutSB = UIStoryboard(name: "AboutViewController", bundle: nil)
let aboutVC = aboutSB.instantiateViewController(withIdentifier: "AboutViewController") as? AboutViewController
if let aboutVC = aboutVC {
navigationController?.pushViewController(aboutVC, animated: true)
}
case 7 /* Open Privacy Policy page */:
let privacyPolicySB = UIStoryboard(name: "PrivacyPolicyViewController", bundle: nil)
let privacyPolicyVC = privacyPolicySB.instantiateViewController(withIdentifier: "PrivacyPolicyViewController") as? PrivacyPolicyViewController
if let privacyPolicyVC = privacyPolicyVC {
navigationController?.pushViewController(privacyPolicyVC, animated: true)
}
default:
break
}
default:
break
}
}
// MARK: - Actions Methods
func loginLogout() {
if NetworkVars.username.isEmpty {
// Clear caches and display login view
self.closeSessionAndClearCache()
return
}
// Ask user for confirmation
let alert = UIAlertController(title: "", message: NSLocalizedString("logoutConfirmation_message", comment: "Are you sure you want to logout?"), preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: NSLocalizedString("alertCancelButton", comment: "Cancel"), style: .cancel, handler: { action in
})
let logoutAction = UIAlertAction(title: NSLocalizedString("logoutConfirmation_title", comment: "Logout"), style: .destructive, handler: { action in
SessionService.sessionLogout(onCompletion: { task, success in
if success {
self.closeSessionAndClearCache()
} else {
let alert = UIAlertController(title: NSLocalizedString("logoutFail_title", comment: "Logout Failed"), message: NSLocalizedString("internetCancelledConnection_title", comment: "Connection Cancelled"), preferredStyle: .alert)
let dismissAction = UIAlertAction(title: NSLocalizedString("alertDismissButton", comment: "Dismiss"), style: .cancel, handler: { action in
self.closeSessionAndClearCache()
})
// Add action
alert.addAction(dismissAction)
// Present list of actions
alert.view.tintColor = .piwigoColorOrange()
if #available(iOS 13.0, *) {
alert.overrideUserInterfaceStyle = AppVars.isDarkPaletteActive ? .dark : .light
} else {
// Fallback on earlier versions
}
self.present(alert, animated: true, completion: {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alert.view.tintColor = .piwigoColorOrange()
})
}
}, onFailure: { task, error in
// Failed! This may be due to the replacement of a self-signed certificate.
// So we inform the user that there may be something wrong with the server,
// or simply a connection drop.
let alert = UIAlertController(title: NSLocalizedString("logoutFail_title", comment: "Logout Failed"), message: NSLocalizedString("internetCancelledConnection_title", comment: "Connection Cancelled"), preferredStyle: .alert)
let dismissAction = UIAlertAction(title: NSLocalizedString("alertDismissButton", comment: "Dismiss"), style: .cancel, handler: { action in
self.closeSessionAndClearCache()
})
// Add action
alert.addAction(dismissAction)
// Present list of actions
alert.view.tintColor = .piwigoColorOrange()
if #available(iOS 13.0, *) {
alert.overrideUserInterfaceStyle = AppVars.isDarkPaletteActive ? .dark : .light
} else {
// Fallback on earlier versions
}
self.present(alert, animated: true, completion: {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alert.view.tintColor = .piwigoColorOrange()
})
})
})
// Add actions
alert.addAction(cancelAction)
alert.addAction(logoutAction)
// Determine position of cell in table view
let rowAtIndexPath = IndexPath(row: 0, section: SettingsSection.logout.rawValue)
let rectOfCellInTableView = settingsTableView?.rectForRow(at: rowAtIndexPath)
// Present list of actions
alert.view.tintColor = .piwigoColorOrange()
if #available(iOS 13.0, *) {
alert.overrideUserInterfaceStyle = AppVars.isDarkPaletteActive ? .dark : .light
} else {
// Fallback on earlier versions
}
alert.popoverPresentationController?.sourceView = settingsTableView
alert.popoverPresentationController?.permittedArrowDirections = [.up, .down]
alert.popoverPresentationController?.sourceRect = rectOfCellInTableView ?? CGRect.zero
present(alert, animated: true, completion: {
// Bugfix: iOS9 - Tint not fully Applied without Reapplying
alert.view.tintColor = .piwigoColorOrange()
})
}
func closeSessionAndClearCache() {
// Session closed
NetworkVarsObjc.sessionManager?.invalidateSessionCancelingTasks(true, resetSession: true)
NetworkVarsObjc.imagesSessionManager?.invalidateSessionCancelingTasks(true, resetSession: true)
NetworkVarsObjc.imageCache?.removeAllCachedResponses()
NetworkVars.hadOpenedSession = false
// Back to default values
AlbumVars.defaultCategory = 0
AlbumVars.recentCategories = "0"
NetworkVars.usesCommunityPluginV29 = false
NetworkVars.hasAdminRights = false
// Disable Auto-Uploading and clear settings
UploadVars.isAutoUploadActive = false
UploadVars.autoUploadCategoryId = NSNotFound
UploadVars.autoUploadAlbumId = ""
UploadVars.autoUploadTagIds = ""
UploadVars.autoUploadComments = ""
// Erase cache
ClearCache.clearAllCache(exceptCategories: false,
completionHandler: {
if #available(iOS 13.0, *) {
guard let window = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window else {
return
}
let loginVC: LoginViewController
if UIDevice.current.userInterfaceIdiom == .phone {
loginVC = LoginViewController_iPhone()
} else {
loginVC = LoginViewController_iPad()
}
let nav = LoginNavigationController(rootViewController: loginVC)
nav.isNavigationBarHidden = true
window.rootViewController = nav
UIView.transition(with: window, duration: 0.5,
options: .transitionCrossDissolve,
animations: nil, completion: nil)
} else {
// Fallback on earlier versions
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.loadLoginView()
}
})
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
// Check the result or perform other tasks.
// Dismiss the mail compose view controller.
dismiss(animated: true)
}
// MARK: - UITextFieldDelegate Methods
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
settingsTableView?.endEditing(true)
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
switch textField.tag {
case kImageUploadSetting.author.rawValue:
UploadVars.defaultAuthor = textField.text ?? ""
case kImageUploadSetting.prefix.rawValue:
UploadVars.defaultPrefix = textField.text ?? ""
if UploadVars.defaultPrefix.isEmpty {
UploadVars.prefixFileNameBeforeUpload = false
// Remove row in existing table
let prefixIndexPath = IndexPath(row: 5 + (NetworkVars.hasAdminRights ? 1 : 0)
+ (UploadVars.resizeImageOnUpload ? 2 : 0)
+ (UploadVars.compressImageOnUpload ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
settingsTableView?.deleteRows(at: [prefixIndexPath], with: .automatic)
// Refresh flag
let indexPath = IndexPath(row: prefixIndexPath.row - 1,
section: SettingsSection.imageUpload.rawValue)
settingsTableView?.reloadRows(at: [indexPath], with: .automatic)
}
default:
break
}
}
}
// MARK: - SelectCategoryDelegate Methods
extension SettingsViewController: SelectCategoryDelegate {
func didSelectCategory(withId categoryId: Int) {
// Do nothing if new default album is unknown or unchanged
if categoryId == NSNotFound ||
categoryId == AlbumVars.defaultCategory
{ return }
// Save new choice
AlbumVars.defaultCategory = categoryId
// Refresh settings row
let indexPath = IndexPath(row: 0, section: SettingsSection.albums.rawValue)
settingsTableView.reloadRows(at: [indexPath], with: .automatic)
// Switch to new default album
settingsDelegate?.didChangeDefaultAlbum()
}
}
// MARK: - DefaultAlbumThumbnailSizeDelegate Methods
extension SettingsViewController: DefaultAlbumThumbnailSizeDelegate {
func didSelectAlbumDefaultThumbnailSize(_ thumbnailSize: kPiwigoImageSize) {
// Do nothing if size is unchanged
if thumbnailSize == kPiwigoImageSize(AlbumVars.defaultAlbumThumbnailSize) { return }
// Save new choice
AlbumVars.defaultAlbumThumbnailSize = thumbnailSize.rawValue
// Refresh settings row
let indexPath = IndexPath(row: 1, section: SettingsSection.albums.rawValue)
settingsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
// MARK: - CategorySortDelegate Methods
extension SettingsViewController: CategorySortDelegate {
func didSelectCategorySortType(_ sortType: kPiwigoSort) {
// Do nothing if sort type is unchanged
if sortType == kPiwigoSort(rawValue: AlbumVars.defaultSort) { return }
// Save new choice
AlbumVars.defaultSort = sortType.rawValue
// Refresh settings
let indexPath = IndexPath(row: 2, section: SettingsSection.albums.rawValue)
settingsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
// MARK: - DefaultImageThumbnailSizeDelegate Methods
extension SettingsViewController: DefaultImageThumbnailSizeDelegate {
func didSelectImageDefaultThumbnailSize(_ thumbnailSize: kPiwigoImageSize) {
// Do nothing if size is unchanged
if thumbnailSize == kPiwigoImageSize(AlbumVars.defaultThumbnailSize) { return }
// Save new choice
AlbumVars.defaultThumbnailSize = thumbnailSize.rawValue
// Refresh settings
let indexPath = IndexPath(row: 0, section: SettingsSection.images.rawValue)
settingsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
// MARK: - DefaultImageSizeDelegate Methods
extension SettingsViewController: DefaultImageSizeDelegate {
func didSelectImageDefaultSize(_ imageSize: kPiwigoImageSize) {
// Do nothing if size is unchanged
if imageSize == kPiwigoImageSize(ImageVars.shared.defaultImagePreviewSize) { return }
// Save new choice
ImageVars.shared.defaultImagePreviewSize = imageSize.rawValue
// Refresh settings
let indexPath = IndexPath(row: 3, section: SettingsSection.images.rawValue)
settingsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
// MARK: - SelectedPrivacyDelegate Methods
extension SettingsViewController: SelectPrivacyDelegate {
func didSelectPrivacyLevel(_ privacyLevel: kPiwigoPrivacy) {
// Do nothing if privacy level is unchanged
if privacyLevel == kPiwigoPrivacy(rawValue: UploadVars.defaultPrivacyLevel) { return }
// Save new choice
UploadVars.defaultPrivacyLevel = privacyLevel.rawValue
// Refresh settings
let indexPath = IndexPath(row: 1, section: SettingsSection.imageUpload.rawValue)
settingsTableView.reloadRows(at: [indexPath], with: .automatic)
}
}
// MARK: - UploadPhotoSizeDelegate Methods
extension SettingsViewController: UploadPhotoSizeDelegate {
func didSelectUploadPhotoSize(_ newSize: Int16) {
// Was the size modified?
if newSize != UploadVars.photoMaxSize {
// Save new choice
UploadVars.photoMaxSize = newSize
// Refresh corresponding row
let photoAtIndexPath = IndexPath(row: 3 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
settingsTableView.reloadRows(at: [photoAtIndexPath], with: .automatic)
}
// Hide rows if needed
if UploadVars.photoMaxSize == 0, UploadVars.videoMaxSize == 0 {
UploadVars.resizeImageOnUpload = false
// Position of the rows which should be removed
let photoAtIndexPath = IndexPath(row: 3 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
let videoAtIndexPath = IndexPath(row: 4 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
// Remove row in existing table
settingsTableView?.deleteRows(at: [photoAtIndexPath, videoAtIndexPath], with: .automatic)
// Refresh flag
let indexPath = IndexPath(row: photoAtIndexPath.row - 1,
section: SettingsSection.imageUpload.rawValue)
settingsTableView?.reloadRows(at: [indexPath], with: .automatic)
}
}
}
// MARK: - UploadVideoSizeDelegate Methods
extension SettingsViewController: UploadVideoSizeDelegate {
func didSelectUploadVideoSize(_ newSize: Int16) {
// Was the size modified?
if newSize != UploadVars.videoMaxSize {
// Save new choice after verification
UploadVars.videoMaxSize = newSize
// Refresh corresponding row
let videoAtIndexPath = IndexPath(row: 4 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
settingsTableView.reloadRows(at: [videoAtIndexPath], with: .automatic)
}
// Hide rows if needed
if UploadVars.photoMaxSize == 0, UploadVars.videoMaxSize == 0 {
UploadVars.resizeImageOnUpload = false
// Position of the rows which should be removed
let photoAtIndexPath = IndexPath(row: 3 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
let videoAtIndexPath = IndexPath(row: 4 + (NetworkVars.hasAdminRights ? 1 : 0),
section: SettingsSection.imageUpload.rawValue)
// Remove rows in existing table
settingsTableView?.deleteRows(at: [photoAtIndexPath, videoAtIndexPath], with: .automatic)
// Refresh flag
let indexPath = IndexPath(row: photoAtIndexPath.row - 1,
section: SettingsSection.imageUpload.rawValue)
settingsTableView?.reloadRows(at: [indexPath], with: .automatic)
}
}
}
| 53.093285 | 311 | 0.592969 |
acf7c73e08bb4f7c9d32474b1fbdd9e6f4f6972f
| 3,516 |
//
// Bond+UITextView.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
private var textDynamicHandleUITextView: UInt8 = 0;
extension UITextView: Bondable {
public var dynText: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleUITextView) {
return (d as? Dynamic<String>)!
} else {
let d: InternalDynamic<String> = dynamicObservableFor(UITextViewTextDidChangeNotification, object: self) {
notification -> String in
if let textView = notification.object as? UITextView {
return textView.text ?? ""
} else {
return ""
}
}
let bond = Bond<String>() { [weak self] v in if let s = self { s.text = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textDynamicHandleUITextView, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedDynamic: Dynamic<String> {
return self.dynText
}
public var designatedBond: Bond<String> {
return self.dynText.valueBond
}
}
public func ->> (left: UITextView, right: Bond<String>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == String>(left: UITextView, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextView, right: UITextView) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextView, right: UILabel) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextView, right: UITextField) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == String>(left: T, right: UITextView) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<String>, right: UITextView) {
left ->> right.designatedBond
}
public func <->> (left: UITextView, right: UITextView) {
left.designatedDynamic <->> right.designatedDynamic
}
public func <->> (left: Dynamic<String>, right: UITextView) {
left <->> right.designatedDynamic
}
public func <->> (left: UITextView, right: Dynamic<String>) {
left.designatedDynamic <->> right
}
public func <->> (left: UITextView, right: UITextField) {
left.designatedDynamic <->> right.designatedDynamic
}
| 32.859813 | 128 | 0.703925 |
75baab9f46645ff03cb6c2706344941cec544527
| 1,582 |
//: [Previous](@previous)
import UIKit
/*:
- Note: Swift数组和OC有很大的区别:
OC数组可以存储任意类型的`对象`, Swift必须在存储对象的时候声明相应的类型, 类型必须要声明正确, 比如定义的是存储 Int类型的数组不能存储其他类型的值
OC数组必须是存储对象, Swift可以存储基本数据类型
*/
/*:
## 一. 定义:
\[类型\]\(\) \/\/ [类型] 表示某类型的数组, 小括号() 表示实例化对象
*/
let emptyArray1 = [String]() // 创建一个不可变的空数组
var emptyArray2 = [String]() // 创建一个可变的空数组
var emptyArray3 = Array(repeating: 0.0, count: 3) // 创建使用默认值为0.0的数组
var shoppingList1: [String] = ["Eggs", "Milk"] // 使用数组字面量创建数组
var shoppingList2 = ["Eggs", "Milk"] // 使用数组字面量创建数组, 不指定数组类型, 隐式设置类型
var arrM = [Any]() // 创建一个可以存储任意值的空数组
//: ## 二. 操作:
//: ### 1. 添加值
//: #### 1.1 添加单个值
arrM.append("Hello") // append() 函数, 在数组最尾添加元素
arrM.append("w")
//: #### 1.2 添加某个数组的所有的值
arrM += ["你好", "我的", "世界"] // 通过加法赋值运算符 += 可以拼接某个数组的所有元素
//: #### 1.3 插入值
arrM.insert("-", at: 1) // insert() 函数, 在指定索引插入元素
//: ### 2.替换
//: #### 2.1 替换某个索引位置的值
arrM[2] = "World" // 直接给索引位置元素赋值就可以替换值
//: #### 2.1 替换某个区间范围的值
/*:
- Note:
3...5: 表示 3到5, 包含5
3..<5: 表示 3到5, 不包含5
*/
arrM[3...5] = ["!"] // 把 索引3到5的值替换成 "!", 不是每个都替换, 是一起替换掉, 可以理解成: 删除3到5区间的值, 再插入 右边的值
//: ### 3. 删除
arrM.remove(at: 1) // remove() 函数 删除某个索引的值
arrM.removeLast() // removeLast() 删除最后一个元素
//: ### 4. 遍历数组
//: > Swift4 苹果已经废弃了C语言的遍历方式
//: #### 4.1 不要索引
for item in arrM {
print(item)
}
//: #### 4.2 带索引
for (idx, value) in arrM.enumerated() { // 用数组的 enumerated() 方法遍历, 这样可以获得 索引值
print("\(idx) : \(value)")
}
//: ### 5. 检查
//: #### 5.1 检查是否是空的
if arrM.isEmpty {
print("数组是空的")
} else {
print("数组有值")
}
print(arrM)
| 17.977273 | 88 | 0.573957 |
9ca708d7558754889bdda7eeabb3458f63e973b3
| 5,316 |
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A class used to populate a `DataItemCollectionViewCell` for a given `DataItem`. The composer class handles processing and caching images for `DataItem`s.
*/
import UIKit
class DataItemCellComposer {
// MARK: Properties
/// Cache used to store processed images, keyed on `DataItem` identifiers.
static private var processedImageCache = NSCache()
/**
A dictionary of `NSOperationQueue`s for `DataItemCollectionViewCell`s. The
queues contain operations that process images for `DataItem`s before updating
the cell's `UIImageView`.
*/
private var operationQueues = [DataItemCollectionViewCell: NSOperationQueue]()
// MARK: Implementation
func composeCell(cell: DataItemCollectionViewCell, withDataItem dataItem: DataItem) {
// Cancel any queued operations to process images for the cell.
let operationQueue = operationQueueForCell(cell)
operationQueue.cancelAllOperations()
// Set the cell's properties.
cell.representedDataItem = dataItem
cell.label.text = dataItem.title
cell.imageView.alpha = 1.0
cell.imageView.image = DataItemCellComposer.processedImageCache.objectForKey(dataItem.identifier) as? UIImage
// No further work is necessary if the cell's image view has an image.
guard cell.imageView.image == nil else { return }
/*
Initial rendering of a jpeg image can be expensive. To avoid stalling
the main thread, we create an operation to process the `DataItem`'s
image before updating the cell's image view.
The execution block is added after the operation is created to allow
the block to check if the operation has been cancelled.
*/
let processImageOperation = NSBlockOperation()
processImageOperation.addExecutionBlock { [unowned processImageOperation] in
// Ensure the operation has not been cancelled.
guard !processImageOperation.cancelled else { return }
// Load and process the image.
guard let image = self.processImageNamed(dataItem.imageName) else { return }
// Store the processed image in the cache.
DataItemCellComposer.processedImageCache.setObject(image, forKey: dataItem.identifier)
NSOperationQueue.mainQueue().addOperationWithBlock {
// Check that the cell is still showing the same `DataItem`.
guard dataItem == cell.representedDataItem else { return }
// Update the cell's `UIImageView` and then fade it into view.
cell.imageView.alpha = 0.0
cell.imageView.image = image
UIView.animateWithDuration(0.25) {
cell.imageView.alpha = 1.0
}
}
}
operationQueue.addOperation(processImageOperation)
}
// MARK: Convenience
/**
Returns the `NSOperationQueue` for a given cell. Creates and stores a new
queue if one doesn't already exist.
*/
private func operationQueueForCell(cell: DataItemCollectionViewCell) -> NSOperationQueue {
if let queue = operationQueues[cell] {
return queue
}
let queue = NSOperationQueue()
operationQueues[cell] = queue
return queue
}
/**
Loads a UIImage for a given name and returns a version that has been drawn
into a `CGBitmapContext`.
*/
private func processImageNamed(imageName: String) -> UIImage? {
// Load the image.
guard let image = UIImage(named: imageName) else { return nil }
/*
We only need to process jpeg images. Do no processing if the image
name doesn't have a jpg suffix.
*/
guard imageName.hasSuffix(".jpg") else { return image }
// Create a `CGColorSpace` and `CGBitmapInfo` value that is appropriate for the device.
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue
// Create a bitmap context of the same size as the image.
let imageWidth = Int(Float(image.size.width))
let imageHeight = Int(Float(image.size.height))
let bitmapContext = CGBitmapContextCreate(nil, imageWidth, imageHeight, 8, imageWidth * 4, colorSpace, bitmapInfo)
// Draw the image into the graphics context.
guard let imageRef = image.CGImage else { fatalError("Unable to get a CGImage from a UIImage.") }
CGContextDrawImage(bitmapContext, CGRect(origin: CGPoint.zero, size: image.size), imageRef)
// Create a new `CGImage` from the contents of the graphics context.
guard let newImageRef = CGBitmapContextCreateImage(bitmapContext) else { return image }
// Return a new `UIImage` created from the `CGImage`.
return UIImage(CGImage: newImageRef)
}
}
| 41.209302 | 157 | 0.639955 |
e0d3bf3501d51ebe09f1b2b268abac4db6df2ddc
| 2,687 |
//
// AUIClosuresTableViewController.swift
// AUIKit
//
// Created by Ihor Myroniuk on 05.02.2022.
//
import Foundation
import UIKit
open class AUIClosuresTableViewController: AUIEmptyTableViewController {
// MARK: Cells
open var targetIndexPathForMoveFromRowAtClosure: ((AUITableViewCellController, AUITableViewCellController) -> AUITableViewCellController)?
open override func targetIndexPathForMoveFromRowAt(sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
let sourceSection = sourceIndexPath.section
let sourceRow = sourceIndexPath.row
let sourceCellController = sectionControllers[sourceSection].cellControllers[sourceRow]
let destinationSection = proposedDestinationIndexPath.section
let destinationRow = proposedDestinationIndexPath.row
let destinationCellController = sectionControllers[destinationSection].cellControllers[destinationRow]
let targetCellController = targetIndexPathForMoveFromRowAtClosure?(sourceCellController, destinationCellController)
return indexPathForCellController(targetCellController) ?? sourceIndexPath
}
private func indexPathForCellController(_ cellController: AUITableViewCellController?) -> IndexPath? {
guard let cellController = cellController else { return nil }
let sectionsCount = sectionControllers.count
for section in 0..<sectionsCount {
let cellControllers = sectionControllers[section].cellControllers
let rowsCount = cellControllers.count
for row in 0..<rowsCount {
if cellController === cellControllers[row] {
let indexPath = IndexPath(row: row, section: section)
return indexPath
}
}
}
return nil
}
open var moveCellControllerClosure: ((AUITableViewCellController, AUITableViewCellController) -> Void)?
open override func moveRowAt(sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let sourceSection = sourceIndexPath.section
let sourceRow = sourceIndexPath.row
let sourceCellController = sectionControllers[sourceSection].cellControllers[sourceRow]
let destinationSection = destinationIndexPath.section
let destinationRow = destinationIndexPath.row
let destinationCellController = sectionControllers[destinationSection].cellControllers[destinationRow]
super.moveRowAt(sourceIndexPath: sourceIndexPath, to: destinationIndexPath)
moveCellControllerClosure?(sourceCellController, destinationCellController)
}
}
| 47.140351 | 158 | 0.739859 |
1a12fe29c9017a27501c1f7b966f474fcb6efa4d
| 6,611 |
//
// AddExpenseViewController.swift
// Billingo
//
// Created by Zuzana Plesingerova on 01.06.16.
// Copyright © 2016 MU. All rights reserved.
//
import UIKit
import Firebase
class AddExpenseViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var groupID: String?
var payerID: String?
var groupMembers: [Member]?
@IBOutlet weak var expenseName: UITextField!
@IBOutlet weak var expenseCost: UITextField!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
var indexOfMyId: Int = 0
for index in 0 ..< groupMembers!.count {
if groupMembers![index].memberID == payerID {
indexOfMyId = index
break
}
}
groupMembers?.removeAtIndex(indexOfMyId)
tableView.delegate = self
tableView.dataSource = self
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addExpense(sender: AnyObject) {
if self.expenseName.text!.characters.count > 0 {
if self.expenseCost.text!.characters.count > 0 {
let expenseCostAdapted = expenseCost.text!.stringByReplacingOccurrencesOfString(",", withString: ".")
var count: Int = 0
for i in expenseCostAdapted.characters {
if i == "." {
count += 1
}
}
if count <= 1 {
var reason: String
var totalCost: Double
reason = expenseName.text!
totalCost = Double.init(expenseCostAdapted)!
let time: NSDate = NSDate()
var count: Int = 0
var payments: [String:Double] = [:]
var list = [AddExpenseTableViewCell]()
for section in 0 ..< 1 {
let rowCount = tableView.numberOfRowsInSection(section)
//var list = [AddExpenseTableViewCell]()
for row in 0 ..< rowCount {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) as! AddExpenseTableViewCell
list.append(cell)
}
for cell in list {
if cell.isTrue {
count += 1
//payments[cell.name.text!] = String.init(totalCost/(Double.init(count) + 1))
//payments["a031b1f3-4b7a-447b-8174-f6ac25b8a6e5"] = totalCost/(Double.init(count) + 1)
}
}
}
var index: Int = 0
payments[payerID!] = totalCost/(Double.init(count + 1))
for cell in list {
if cell.isTrue {
if cell.name.text == groupMembers![index].memberName {
payments[groupMembers![index].memberID] = totalCost/(Double.init(count + 1))
}
}
index += 1
}
//let paymentCost = String.init(totalCost/Double.init(count))
//let payment = Payment()
//let payment1 = Payment()
saveNewExpense(groupID!, payments: payments, payerID: payerID!, reason: reason, time: time, totalCost: totalCost)
self.navigationController!.popViewControllerAnimated(true)
}
else {
self.showError("Wrong number format!")
expenseCost.text = ""
}
}
else {
self.showError("You need to add cost!")
}
}
else {
self.showError("You need to add name of expense!")
}
}
func saveNewExpense(groupID:String, payments:[String:Double], payerID:String, reason:String, time:NSDate, totalCost:Double){
let expensesRef = Firebase(url: Constants.baseURL + "groups/\(groupID)/expenses/")
let jsonExpense = ["reason":"\(reason)", "payer":"\(payerID)", "createTime":(Int.init(time.timeIntervalSince1970)), "totalCost":(totalCost)]
let newExpense = expensesRef.childByAutoId()
newExpense.setValue(jsonExpense)
newExpense.childByAppendingPath("payments").setValue(payments)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupMembers!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AddExpenseCell", forIndexPath: indexPath) as! AddExpenseTableViewCell
let member = groupMembers![indexPath.row]
/*if !(member.memberID == payerID!) {
cell.name.text = member.memberName
}*/
cell.name.text = member.memberName
return cell
}
func showError(errorMessage :String) -> Void {
let alertControllerSimple = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
}
alertControllerSimple.addAction(OKAction)
self.presentViewController(alertControllerSimple, animated: true) {
// ...
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 38.888235 | 148 | 0.536681 |
6274cbf8215fea0899607a253eba4b16b10bbd67
| 6,152 |
//
// PreviewColorView.swift
// SheetyColors
//
// Created by Christoph Wendt on 08.02.19.
//
import Capable
import UIKit
class PreviewColorView: UIView {
var primaryKeyLabel: UILabel!
var primaryValueLabel: UILabel!
var secondaryKeyLabel: UILabel!
var secondaryValueLabel: UILabel!
var infoButton: UIButton!
var labelStackView: UIStackView!
var colorLayer: CALayer!
var transparencyPatternLayer: CALayer!
var isColorViewLabelShown: Bool!
var color: UIColor = .clear {
didSet {
colorLayer?.backgroundColor = color.cgColor
updateTextColor()
}
}
var textColor: UIColor = .clear {
didSet {
for label in [primaryKeyLabel, primaryValueLabel, secondaryKeyLabel, secondaryValueLabel] {
label?.textColor = textColor
}
infoButton.tintColor = textColor
}
}
var primaryKeyText: String = "" {
didSet {
primaryKeyLabel.text = primaryKeyText
}
}
var primaryValueText: String = "" {
didSet {
primaryValueLabel.text = primaryValueText
}
}
var secondaryKeyText: String = "" {
didSet {
secondaryKeyLabel.text = secondaryKeyText
}
}
var secondaryValueText: String = "" {
didSet {
secondaryValueLabel.text = secondaryValueText
}
}
convenience init(withColor color: UIColor) {
self.init(frame: .zero)
self.color = color
colorLayer.backgroundColor = self.color.cgColor
updateTextColor()
}
override init(frame: CGRect) {
super.init(frame: frame)
isColorViewLabelShown = false
setupColorView()
setupLabels()
setupButton()
setupConstraints()
setupGestureRecognizer()
updateLabelVisibility(withDuration: 0.0)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateTextColor() {
if color.cgColor.alpha < 0.4 {
guard let defaultTextColor = UIColor(named: "PrimaryColor", in: Bundle.framework, compatibleWith: nil) else { return }
textColor = defaultTextColor
} else {
textColor = UIColor.getTextColor(onBackgroundColor: color)!
}
}
private func setupColorView() {
transparencyPatternLayer = CALayer()
if let transparencyIcon = UIImage(named: "Transparency", in: Bundle.framework, compatibleWith: nil) {
transparencyPatternLayer.backgroundColor = UIColor(patternImage: transparencyIcon).cgColor
}
layer.addSublayer(transparencyPatternLayer)
colorLayer = CALayer()
layer.addSublayer(colorLayer)
}
private func setupLabels() {
primaryKeyLabel = UILabel(frame: .zero)
primaryValueLabel = UILabel(frame: .zero)
secondaryKeyLabel = UILabel(frame: .zero)
secondaryValueLabel = UILabel(frame: .zero)
let keyLabels = [primaryKeyLabel, secondaryKeyLabel]
let valueLabels = [primaryValueLabel, secondaryValueLabel]
for label in keyLabels {
label?.font = UIFont.monospacedDigitSystemFont(ofSize: UIFont.systemFontSize, weight: .regular)
}
for label in valueLabels {
label?.font = UIFont.monospacedDigitSystemFont(ofSize: UIFont.systemFontSize, weight: .light)
}
guard let keyViews = keyLabels as? [UIView], let valueViews = valueLabels as? [UIView] else { return }
let keyLabelStackView = UIStackView(arrangedSubviews: keyViews)
keyLabelStackView.axis = .vertical
let valueLabelStackView = UIStackView(arrangedSubviews: valueViews)
valueLabelStackView.axis = .vertical
labelStackView = UIStackView(arrangedSubviews: [keyLabelStackView, valueLabelStackView])
labelStackView.axis = .horizontal
labelStackView.spacing = 8.0
addSubview(labelStackView)
}
private func setupButton() {
infoButton = UIButton(type: UIButton.ButtonType.infoDark)
addSubview(infoButton)
infoButton.addTarget(self, action: #selector(infoButtonPressed(_:)), for: .touchUpInside)
}
private func setupConstraints() {
anchor(heightConstant: 100.0)
labelStackView.anchor(top: topAnchor, paddingTop: 10.0, left: leftAnchor, paddingLeft: 10.0)
infoButton.anchor(top: topAnchor, paddingTop: 10.0, right: rightAnchor, paddingRight: 10.0)
}
private func setupGestureRecognizer() {
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
addGestureRecognizer(tap)
}
override func layoutSubviews() {
super.layoutSubviews()
colorLayer.frame = bounds
transparencyPatternLayer.frame = bounds
}
}
// MARK: - Handle User Interaction
extension PreviewColorView {
@objc func handleTap(_: UIView) {
if isColorViewLabelShown {
hideLabels()
} else {
displayLabels()
}
}
@objc func infoButtonPressed(_: UIButton) {
if !isColorViewLabelShown {
displayLabels()
}
}
}
// MARK: - Animations
extension PreviewColorView {
func displayLabels(withDuration duration: TimeInterval = 0.4) {
guard !isColorViewLabelShown else { return }
isColorViewLabelShown = true
updateLabelVisibility(withDuration: duration)
}
func hideLabels(withDuration duration: TimeInterval = 0.4) {
guard isColorViewLabelShown else { return }
isColorViewLabelShown = false
updateLabelVisibility(withDuration: duration)
}
func updateLabelVisibility(withDuration duration: TimeInterval) {
UIView.animate(withDuration: duration) {
for label in [self.primaryKeyLabel, self.primaryValueLabel, self.secondaryKeyLabel, self.secondaryValueLabel] {
label?.alpha = self.isColorViewLabelShown ? 1.0 : 0.0
}
self.infoButton.alpha = self.isColorViewLabelShown ? 0.0 : 1.0
}
}
}
| 30.305419 | 130 | 0.644831 |
8a8606ef210b23011445eca77dc7b907f79591de
| 361 |
//
// ViewController.swift
// Canvas_CodePath
//
// Created by SiuChun Kung on 10/8/18.
// Copyright © 2018 SiuChun Kung. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
| 17.190476 | 80 | 0.67313 |
1a848cfa8d3decbff62618f174b6d4aa7fe21da1
| 18,044 |
// 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
//
class TestCalendar: XCTestCase {
static var allTests: [(String, (TestCalendar) -> () throws -> Void)] {
return [
("test_allCalendars", test_allCalendars),
("test_gettingDatesOnGregorianCalendar", test_gettingDatesOnGregorianCalendar ),
("test_gettingDatesOnHebrewCalendar", test_gettingDatesOnHebrewCalendar ),
("test_gettingDatesOnChineseCalendar", test_gettingDatesOnChineseCalendar),
("test_gettingDatesOnISO8601Calendar", test_gettingDatesOnISO8601Calendar),
("test_gettingDatesOnPersianCalendar",
test_gettingDatesOnPersianCalendar),
("test_copy",test_copy),
("test_addingDates", test_addingDates),
("test_datesNotOnWeekend", test_datesNotOnWeekend),
("test_datesOnWeekend", test_datesOnWeekend),
("test_customMirror", test_customMirror),
("test_ampmSymbols", test_ampmSymbols),
("test_currentCalendarRRstability", test_currentCalendarRRstability),
]
}
func test_allCalendars() {
for identifier in [
Calendar.Identifier.buddhist,
Calendar.Identifier.chinese,
Calendar.Identifier.coptic,
Calendar.Identifier.ethiopicAmeteAlem,
Calendar.Identifier.ethiopicAmeteMihret,
Calendar.Identifier.gregorian,
Calendar.Identifier.hebrew,
Calendar.Identifier.indian,
Calendar.Identifier.islamic,
Calendar.Identifier.islamicCivil,
Calendar.Identifier.islamicTabular,
Calendar.Identifier.islamicUmmAlQura,
Calendar.Identifier.iso8601,
Calendar.Identifier.japanese,
Calendar.Identifier.persian,
Calendar.Identifier.republicOfChina
] {
let calendar = Calendar(identifier: identifier)
XCTAssertEqual(identifier,calendar.identifier)
}
}
func test_gettingDatesOnGregorianCalendar() {
let date = Date(timeIntervalSince1970: 1449332351)
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents([.year, .month, .day], from: date)
XCTAssertEqual(components.year, 2015)
XCTAssertEqual(components.month, 12)
XCTAssertEqual(components.day, 5)
// Test for problem reported by Malcolm Barclay via swift-corelibs-dev
// https://lists.swift.org/pipermail/swift-corelibs-dev/Week-of-Mon-20161128/001031.html
let fromDate = Date()
let interval = 200
let toDate = Date(timeInterval: TimeInterval(interval), since: fromDate)
let fromToComponents = calendar.dateComponents([.second], from: fromDate, to: toDate)
XCTAssertEqual(fromToComponents.second, interval);
// Issue with 32-bit CF calendar vector on Linux
// Crashes on macOS 10.12.2/Foundation 1349.25
// (Possibly related) rdar://24384757
/*
let interval2 = Int(INT32_MAX) + 1
let toDate2 = Date(timeInterval: TimeInterval(interval2), since: fromDate)
let fromToComponents2 = calendar.dateComponents([.second], from: fromDate, to: toDate2)
XCTAssertEqual(fromToComponents2.second, interval2);
*/
}
func test_gettingDatesOnISO8601Calendar() {
let date = Date(timeIntervalSince1970: 1449332351)
var calendar = Calendar(identifier: .iso8601)
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents([.year, .month, .day], from: date)
XCTAssertEqual(components.year, 2015)
XCTAssertEqual(components.month, 12)
XCTAssertEqual(components.day, 5)
}
func test_gettingDatesOnHebrewCalendar() {
let date = Date(timeIntervalSince1970: 1552580351)
var calendar = Calendar(identifier: .hebrew)
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents([.year, .month, .day], from: date)
XCTAssertEqual(components.year, 5779)
XCTAssertEqual(components.month, 7)
XCTAssertEqual(components.day, 7)
XCTAssertEqual(components.isLeapMonth, false)
}
func test_gettingDatesOnChineseCalendar() {
let date = Date(timeIntervalSince1970: 1591460351.0)
var calendar = Calendar(identifier: .chinese)
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents([.year, .month, .day], from: date)
XCTAssertEqual(components.year, 37)
XCTAssertEqual(components.month, 4)
XCTAssertEqual(components.day, 15)
XCTAssertEqual(components.isLeapMonth, true)
}
func test_gettingDatesOnPersianCalendar() {
let date = Date(timeIntervalSince1970: 1539146705)
var calendar = Calendar(identifier: .persian)
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents([.year, .month, .day], from: date)
XCTAssertEqual(components.year, 1397)
XCTAssertEqual(components.month, 7)
XCTAssertEqual(components.day, 18)
}
func test_ampmSymbols() {
let calendar = Calendar(identifier: .gregorian)
XCTAssertEqual(calendar.amSymbol, "AM")
XCTAssertEqual(calendar.pmSymbol, "PM")
}
func test_currentCalendarRRstability() {
var AMSymbols = [String]()
for _ in 1...10 {
let cal = Calendar.current
AMSymbols.append(cal.amSymbol)
}
XCTAssertEqual(AMSymbols.count, 10, "Accessing current calendar should work over multiple callouts")
}
func test_copy() {
var calendar = Calendar.current
//Mutate below fields and check if change is being reflected in copy.
calendar.firstWeekday = 2
calendar.minimumDaysInFirstWeek = 2
let copy = calendar
XCTAssertTrue(copy == calendar)
//verify firstWeekday and minimumDaysInFirstWeek of 'copy'.
XCTAssertEqual(copy.firstWeekday, 2)
XCTAssertEqual(copy.minimumDaysInFirstWeek, 2)
}
func test_addingDates() {
let calendar = Calendar(identifier: .gregorian)
let thisDay = calendar.date(from: DateComponents(year: 2016, month: 10, day: 4))!
let diffComponents = DateComponents(day: 1)
let dayAfter = calendar.date(byAdding: diffComponents, to: thisDay)
let dayAfterComponents = calendar.dateComponents([.year, .month, .day], from: dayAfter!)
XCTAssertEqual(dayAfterComponents.year, 2016)
XCTAssertEqual(dayAfterComponents.month, 10)
XCTAssertEqual(dayAfterComponents.day, 5)
}
func test_datesNotOnWeekend() {
let calendar = Calendar(identifier: .gregorian)
let mondayInDecember = calendar.date(from: DateComponents(year: 2018, month: 12, day: 10))!
XCTAssertFalse(calendar.isDateInWeekend(mondayInDecember))
let tuesdayInNovember = calendar.date(from: DateComponents(year: 2017, month: 11, day: 14))!
XCTAssertFalse(calendar.isDateInWeekend(tuesdayInNovember))
let wednesdayInFebruary = calendar.date(from: DateComponents(year: 2016, month: 2, day: 17))!
XCTAssertFalse(calendar.isDateInWeekend(wednesdayInFebruary))
let thursdayInOctober = calendar.date(from: DateComponents(year: 2015, month: 10, day: 22))!
XCTAssertFalse(calendar.isDateInWeekend(thursdayInOctober))
let fridayInSeptember = calendar.date(from: DateComponents(year: 2014, month: 9, day: 26))!
XCTAssertFalse(calendar.isDateInWeekend(fridayInSeptember))
}
func test_datesOnWeekend() {
let calendar = Calendar(identifier: .gregorian)
let saturdayInJanuary = calendar.date(from: DateComponents(year:2017, month: 1, day: 7))!
XCTAssertTrue(calendar.isDateInWeekend(saturdayInJanuary))
let sundayInFebruary = calendar.date(from: DateComponents(year: 2016, month: 2, day: 14))!
XCTAssertTrue(calendar.isDateInWeekend(sundayInFebruary))
}
func test_customMirror() {
let calendar = Calendar(identifier: .gregorian)
let calendarMirror = calendar.customMirror
XCTAssertEqual(calendar.identifier, calendarMirror.descendant("identifier") as? Calendar.Identifier)
XCTAssertEqual(calendar.locale, calendarMirror.descendant("locale") as? Locale)
XCTAssertEqual(calendar.timeZone, calendarMirror.descendant("timeZone") as? TimeZone)
XCTAssertEqual(calendar.firstWeekday, calendarMirror.descendant("firstWeekday") as? Int)
XCTAssertEqual(calendar.minimumDaysInFirstWeek, calendarMirror.descendant("minimumDaysInFirstWeek") as? Int)
}
}
class TestNSDateComponents: XCTestCase {
static var allTests: [(String, (TestNSDateComponents) -> () throws -> Void)] {
return [
("test_hash", test_hash),
("test_copyNSDateComponents", test_copyNSDateComponents),
("test_dateDifferenceComponents", test_dateDifferenceComponents),
]
}
func test_hash() {
let c1 = NSDateComponents()
c1.year = 2018
c1.month = 8
c1.day = 1
let c2 = NSDateComponents()
c2.year = 2018
c2.month = 8
c2.day = 1
XCTAssertEqual(c1, c2)
XCTAssertEqual(c1.hash, c2.hash)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.calendar,
throughValues: [
Calendar(identifier: .gregorian),
Calendar(identifier: .buddhist),
Calendar(identifier: .chinese),
Calendar(identifier: .coptic),
Calendar(identifier: .hebrew),
Calendar(identifier: .indian),
Calendar(identifier: .islamic),
Calendar(identifier: .iso8601),
Calendar(identifier: .japanese),
Calendar(identifier: .persian)])
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.timeZone,
throughValues: (-10...10).map { TimeZone(secondsFromGMT: 3600 * $0) })
// Note: These assume components aren't range checked.
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.era,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.year,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.quarter,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.month,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.day,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.hour,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.minute,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.second,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.nanosecond,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.weekOfYear,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.weekOfMonth,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.yearForWeekOfYear,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.weekday,
throughValues: 0...20)
checkHashing_NSCopying(
initialValue: NSDateComponents(),
byMutating: \NSDateComponents.weekdayOrdinal,
throughValues: 0...20)
// isLeapMonth does not have enough values to test it here.
}
func test_copyNSDateComponents() {
let components = NSDateComponents()
components.year = 1987
components.month = 3
components.day = 17
components.hour = 14
components.minute = 20
components.second = 0
let copy = components.copy(with: nil) as! NSDateComponents
XCTAssertTrue(components.isEqual(copy))
XCTAssertTrue(components == copy)
XCTAssertFalse(components === copy)
XCTAssertEqual(copy.year, 1987)
XCTAssertEqual(copy.month, 3)
XCTAssertEqual(copy.day, 17)
XCTAssertEqual(copy.isLeapMonth, false)
//Mutate NSDateComponents and verify that it does not reflect in the copy
components.hour = 12
XCTAssertEqual(components.hour, 12)
XCTAssertEqual(copy.hour, 14)
}
func test_dateDifferenceComponents() {
// 1970-01-01 00:00:00
let date1 = Date(timeIntervalSince1970: 0)
// 1971-06-21 00:00:00
let date2 = Date(timeIntervalSince1970: 46310400)
// 2286-11-20 17:46:40
let date3 = Date(timeIntervalSince1970: 10_000_000_000)
// 2286-11-20 17:46:41
let date4 = Date(timeIntervalSince1970: 10_000_000_001)
// The date components below assume UTC/GMT time zone.
guard let timeZone = TimeZone(abbreviation: "UTC") else {
XCTFail("Unable to create UTC TimeZone for Test")
return
}
var calendar = Calendar.current
calendar.timeZone = timeZone
let diff1 = calendar.dateComponents([.month, .year, .day], from: date1, to: date2)
XCTAssertEqual(diff1.year, 1)
XCTAssertEqual(diff1.month, 5)
XCTAssertEqual(diff1.isLeapMonth, false)
XCTAssertEqual(diff1.day, 20)
XCTAssertNil(diff1.era)
XCTAssertNil(diff1.yearForWeekOfYear)
XCTAssertNil(diff1.quarter)
XCTAssertNil(diff1.weekOfYear)
XCTAssertNil(diff1.weekOfMonth)
XCTAssertNil(diff1.weekdayOrdinal)
XCTAssertNil(diff1.weekday)
XCTAssertNil(diff1.hour)
XCTAssertNil(diff1.minute)
XCTAssertNil(diff1.second)
XCTAssertNil(diff1.nanosecond)
XCTAssertNil(diff1.calendar)
XCTAssertNil(diff1.timeZone)
let diff2 = calendar.dateComponents([.weekOfMonth], from: date2, to: date1)
XCTAssertEqual(diff2.weekOfMonth, -76)
XCTAssertEqual(diff2.isLeapMonth, false)
let diff3 = calendar.dateComponents([.weekday], from: date2, to: date1)
XCTAssertEqual(diff3.weekday, -536)
XCTAssertEqual(diff3.isLeapMonth, false)
let diff4 = calendar.dateComponents([.weekday, .weekOfMonth], from: date1, to: date2)
XCTAssertEqual(diff4.weekday, 4)
XCTAssertEqual(diff4.weekOfMonth, 76)
XCTAssertEqual(diff4.isLeapMonth, false)
let diff5 = calendar.dateComponents([.weekday, .weekOfYear], from: date1, to: date2)
XCTAssertEqual(diff5.weekday, 4)
XCTAssertEqual(diff5.weekOfYear, 76)
XCTAssertEqual(diff5.isLeapMonth, false)
let diff6 = calendar.dateComponents([.month, .weekOfMonth], from: date1, to: date2)
XCTAssertEqual(diff6.month, 17)
XCTAssertEqual(diff6.weekOfMonth, 2)
XCTAssertEqual(diff6.isLeapMonth, false)
let diff7 = calendar.dateComponents([.weekOfYear, .weekOfMonth], from: date2, to: date1)
XCTAssertEqual(diff7.weekOfYear, -76)
XCTAssertEqual(diff7.weekOfMonth, 0)
XCTAssertEqual(diff7.isLeapMonth, false)
let diff8 = calendar.dateComponents([.era, .quarter, .year, .month, .day, .hour, .minute, .second, .nanosecond, .calendar, .timeZone], from: date2, to: date3)
XCTAssertEqual(diff8.era, 0)
XCTAssertEqual(diff8.year, 315)
XCTAssertEqual(diff8.quarter, 0)
XCTAssertEqual(diff8.month, 4)
XCTAssertEqual(diff8.day, 30)
XCTAssertEqual(diff8.hour, 17)
XCTAssertEqual(diff8.minute, 46)
XCTAssertEqual(diff8.second, 40)
XCTAssertEqual(diff8.nanosecond, 0)
XCTAssertEqual(diff8.isLeapMonth, false)
XCTAssertNil(diff8.calendar)
XCTAssertNil(diff8.timeZone)
let diff9 = calendar.dateComponents([.era, .quarter, .year, .month, .day, .hour, .minute, .second, .nanosecond, .calendar, .timeZone], from: date4, to: date3)
XCTAssertEqual(diff9.era, 0)
XCTAssertEqual(diff9.year, 0)
XCTAssertEqual(diff9.quarter, 0)
XCTAssertEqual(diff9.month, 0)
XCTAssertEqual(diff9.day, 0)
XCTAssertEqual(diff9.hour, 0)
XCTAssertEqual(diff9.minute, 0)
XCTAssertEqual(diff9.second, -1)
XCTAssertEqual(diff9.nanosecond, 0)
XCTAssertEqual(diff9.isLeapMonth, false)
XCTAssertNil(diff9.calendar)
XCTAssertNil(diff9.timeZone)
}
}
| 41.672055 | 166 | 0.651241 |
7187258f63407fcbef7c46ceb751654927ac6da5
| 5,837 |
//
// FPMTKView.swift
// FilterPlayground
//
// Created by Leo Thomas on 13.10.17.
// Copyright © 2017 Leo Thomas. All rights reserved.
//
import MetalKit
class FPMTKView: MTKView, MTKViewDelegate {
weak var externalDelegate: MTKViewDelegate?
override var delegate: MTKViewDelegate? {
set {
externalDelegate = newValue
}
get {
return self
}
}
var customNeedsDisplay = false
var timer: Timer?
#if os(iOS)
weak var statisticsView: StatisticsView?
#endif
convenience init(device: MTLDevice?, delegate: MTKViewDelegate) {
self.init(frame: .zero, device: device)
self.delegate = delegate
enableSetNeedsDisplay = true
if Settings.showStatistics {
showStatistics()
}
#if os(iOS)
if traitCollection.horizontalSizeClass != .compact {
contentMode = .scaleAspectFit
contentScaleFactor = UIScreen.main.scale
let dragInteraction = UIDragInteraction(delegate: self)
addInteraction(dragInteraction)
}
#endif
autoResizeDrawable = false
framebufferOnly = false
super.delegate = self
}
private override init(frame frameRect: CGRect, device: MTLDevice?) {
super.init(frame: frameRect, device: device)
NotificationCenter.default.addObserver(self, selector: #selector(frameRateChanged), name: FrameRateManager.frameRateChangedNotificationName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(showStatisticsSettingChanged), name: Settings.showStatisticsChangedNotificationName, object: nil)
activateTimer()
}
required init(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#if os(iOS) || os(tvOS)
override func setNeedsDisplay() {
#if (targetEnvironment(simulator))
backgroundColor = .randomColor
#endif
customNeedsDisplay = true
}
#endif
func activateTimer() {
timer = Timer.scheduledTimer(withTimeInterval: FrameRateManager.shared.frameInterval, repeats: true, block: didUpdate)
timer?.fire()
}
func deactivateTimer() {
timer?.invalidate()
}
func didUpdate(timer _: Timer) {
guard customNeedsDisplay else { return }
customNeedsDisplay = false
super.setNeedsDisplay()
}
@objc func frameRateChanged() {
deactivateTimer()
activateTimer()
}
func showStatistics() {
#if os(iOS) || os(tvOS)
// TODO: hide statistics if the view is inside a PIP window
guard statisticsView == nil else { return }
let newStatisticsView = StatisticsView(frame: CGRect(x: 0, y: bounds.height - 44, width: bounds.width, height: 44))
newStatisticsView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
addSubview(newStatisticsView)
statisticsView = newStatisticsView
#endif
}
@objc func showStatisticsSettingChanged() {
if Settings.showStatistics {
showStatistics()
} else {
#if os(iOS) || os(tvOS)
statisticsView?.removeFromSuperview()
#else
print("implement statistics view for mac")
#endif
}
}
// MARK: - MTKViewDelegate
func mtkView(_ view: MTKView, drawableSizeWillChange _: CGSize) {
externalDelegate?.mtkView(view, drawableSizeWillChange: drawableSize)
}
let numberOfSkippedFrames = 10
// we skip frames an average because updating the label with 60 or 120 hz is too fast
var totalExecutionTimes: [Double] = [Double](repeating: 0, count: 10)
var gpuExecutionTimes: [Double] = [Double](repeating: 0, count: 10)
var framesCount = 0
var totalStartTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()
var gpuStartTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()
override var intrinsicContentSize: CGSize {
return drawableSize
}
func draw(in view: MTKView) {
externalDelegate?.draw(in: view)
gpuStartTime = CFAbsoluteTimeGetCurrent()
}
func bufferCompletionHandler(buffer _: MTLCommandBuffer) {
guard framesCount == numberOfSkippedFrames else {
framesCount += 1
return
}
#if os(iOS) || os(tvOS)
statisticsView?.updateStatistics(frameRate: Double(numberOfSkippedFrames) / totalExecutionTimes.average(), time: gpuExecutionTimes.average())
#endif
let time = CFAbsoluteTimeGetCurrent()
totalExecutionTimes.removeFirst()
totalExecutionTimes.append(time - totalStartTime)
totalStartTime = time
gpuExecutionTimes.removeFirst()
gpuExecutionTimes.append(time - gpuStartTime)
// TODO: find way for more precise gpu execution time
framesCount = 0
}
}
#if os(iOS)
extension FPMTKView: UIDragInteractionDelegate {
// MARK: UIDragInteractionDelegate
func dragInteraction(_: UIDragInteraction, itemsForBeginning _: UIDragSession) -> [UIDragItem] {
#if !(targetEnvironment(simulator))
guard let texture = self.currentDrawable?.texture,
let image = UIImage(texture: texture) else { return [] }
let imageItemProvider = NSItemProvider(object: image)
let dragItem = UIDragItem(itemProvider: imageItemProvider)
dragItem.previewProvider = {
UIDragPreview(view: DragInteractionImageView(image: image))
}
return [dragItem]
#else
return []
#endif
}
}
#endif
| 32.977401 | 170 | 0.628405 |
4b0c9e6be36ed32c92a87de20dd68154547975fb
| 971 |
//
// AndroidPad.swift
// UserAgency
//
// Created by Terry Huang on 2020/12/24.
//
import Foundation
public class AndroidPad: UserDevice {
weak var userApp: UserApp?
var osVersion = "11"
/*
// Chrome
Linux; Android {$osVersion}
Linux; Android {$osVersion}; {$deviceId}
// FireFox
Android {$osVersion}; Tablet;
Android {$osVersion}; Tablet; {$deviceId};
// Edge
Linux; Android {$osVersion}
Linux; Android {$osVersion}; {$deviceId}
*/
public init() {
}
public func setUserApp(_ app: UserApp?) {
userApp = app
}
public func getResultSystemInformation() -> String {
if userApp == nil {
return ""
}
if userApp is Firefox {
return String(format: "Android %@; Tablet;",
arguments: [osVersion])
}
return String(format: "Linux; Android %@",
arguments: [osVersion])
}
}
| 19.42 | 56 | 0.546859 |
8a98cf19ec5232d5db98fece4c76d77c771cfa63
| 1,741 |
//
// FloatingPointType.swift
// Sluthware
//
// Created by Pat Sluth on 2017-08-08.
// Copyright © 2017 patsluth. All rights reserved.
//
import Foundation
import CoreGraphics
public protocol FloatingPointType: BinaryFloatingPoint, Codable
{
init(_ value: IntegerLiteralType)
init(_ value: Float)
init(_ value: Double)
init(_ value: CGFloat)
func to<T: FloatingPointType>() -> T
}
extension Float: FloatingPointType { public func to<T: FloatingPointType>() -> T { return T(self) } }
extension Double: FloatingPointType { public func to<T: FloatingPointType>() -> T { return T(self) } }
extension CGFloat: FloatingPointType { public func to<T: FloatingPointType>() -> T { return T(self) } }
public extension Float
{
init<T: FloatingPointType>(_ value: T)
{
let _value: Float = value.to()
self.init(_value)
}
}
public extension Double
{
init<T: FloatingPointType>(_ value: T)
{
let _value: Double = value.to()
self.init(_value)
}
}
public extension CGFloat
{
init<T: FloatingPointType>(_ value: T)
{
let _value: CGFloat = value.to()
self.init(_value)
}
}
public extension FloatingPointType
{
func value(percentage: Self, between min: Self, and max: Self) -> Self
{
return ((percentage * (max - min)) + min)
}
func percentage(between min: Self, and max: Self) -> Self
{
return ((self - min) / (max - min))
}
func rounded(to places: Int) -> Self
{
let divisor = Self(pow(10.0, Double(places)))
return (self * divisor).rounded() / divisor
}
}
public extension FloatingPointType
{
typealias Parts = (integer: Int, decimal: Self)
var parts: Parts {
return Parts(integer: Int(floor(self)),
decimal: self.truncatingRemainder(dividingBy: 1.0))
}
}
| 15.972477 | 103 | 0.676623 |
8fd8fb49234f12a547ed9dbd3e374d4c01a52cca
| 2,150 |
//
// AppDelegate.swift
// DSSky
//
// Created by 左得胜 on 2019/2/21.
// Copyright © 2019 左得胜. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AMapLocationTool.shared.registerAMap()
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:.
}
}
| 43.877551 | 285 | 0.747442 |
4b53b866341e200be4c8f649621c6b5c47f62777
| 414 |
//
// PhotoUseCase.swift
// Github Repository
//
// Created by Macbook on 9/6/19.
// Copyright © 2019 Macbook. All rights reserved.
//
import Foundation
import RxSwift
import Moya
final class PhotoUseCasePlatform: PhotoUseCase {
private let network = Network<Photo, PhotoTarget>()
func photos() -> Observable<[Photo]> {
return network.getItems(.photos)
}
}
| 18.818182 | 58 | 0.640097 |
5bf66ab54eaf7133fe483a8b14627b3c135dcecc
| 2,340 |
// 8 january 2017
import Foundation
import CoreFoundation
import CoreGraphics
import CoreText
let our_CGFLOAT_MAX: CGFloat = CGFloat.greatestFiniteMagnitude
func iterative() {
var s = "This is a test string."
for _ in 0..<10 {
s += " This is a test string."
}
let cs = s as! NSString as! CFString
func runForFont(_ d: CTFontDescriptor, _ s: CGFloat) {
let f = CTFontCreateWithFontDescriptor(d, s, nil)
let attrs = CFDictionaryCreateMutable(nil, 0,
[kCFCopyStringDictionaryKeyCallBacks],
[kCFTypeDictionaryValueCallBacks])
CFDictionaryAddValue(attrs,
Unmanaged.passUnretained(kCTFontAttributeName).toOpaque(),
Unmanaged.passUnretained(f).toOpaque())
let cfas = CFAttributedStringCreate(nil, cs, attrs)
let fs = CTFramesetterCreateWithAttributedString(cfas!)
var range = CFRangeMake(0, CFAttributedStringGetLength(cfas))
var fitRange = CFRange()
let size = CTFramesetterSuggestFrameSizeWithConstraints(fs, range, nil,
CGSize.init(width: 200, height: our_CGFLOAT_MAX),
&fitRange)
let rect = CGRect(origin: CGPoint.init(x: 0 /*5*/, y: 0 /*2.5*/), size: size)
let path = CGPath(rect: rect, transform: nil)
let frame = CTFramesetterCreateFrame(fs, range, path, nil)
let lines = CTFrameGetLines(frame)
let n = CFArrayGetCount(lines)
if n < 2 {
return
}
range.length = 2
let pts = UnsafeMutablePointer<CGPoint>.allocate(capacity: 2)
CTFrameGetLineOrigins(frame, range, pts)
let ptheight = pts[0].y - pts[1].y // unflipped
let pl = CFArrayGetValueAtIndex(lines, 0)
let line = Unmanaged<CTLine>.fromOpaque(pl!).takeUnretainedValue()
let bounds = CTLineGetBoundsWithOptions(line, [])
let nm = CTFontDescriptorCopyAttribute(d, kCTFontDisplayNameAttribute) as! CFString
print("baseline diff \(ptheight) bounds \(bounds.size.height) difference \(ptheight - bounds.size.height) - \(s) \(nm)")
}
func runForDesc(_ d: CTFontDescriptor) {
for ps in [CGFloat](arrayLiteral: 0, 8, 10, 12, 14, 16, 18, 20, 22, 24, 36, 48, 72) {
runForFont(d, ps)
}
}
let fc = CTFontCollectionCreateFromAvailableFonts(nil)
let descs = CTFontCollectionCreateMatchingFontDescriptors(fc)
let n = CFArrayGetCount(descs)
for i in 0..<n {
let pd = CFArrayGetValueAtIndex(descs, i)
let d = Unmanaged<CTFontDescriptor>.fromOpaque(pd!).takeUnretainedValue()
runForDesc(d)
}
}
iterative()
| 37.142857 | 122 | 0.732906 |
713e64c1b5f4f074d590a563918fd400aad3714b
| 753 |
// swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SearchField",
defaultLocalization: "en",
platforms: [
.iOS(.v13),
.macOS(.v11),
.tvOS(.v13),
.watchOS(.v6)
],
products: [
.library(
name: "SearchField",
targets: ["SearchField"]),
],
dependencies: [
],
targets: [
.target(
name: "SearchField",
dependencies: [],
resources: [.process("Resources")]
),
.testTarget(
name: "SearchFieldTests",
dependencies: ["SearchField"]
),
]
)
| 22.147059 | 96 | 0.519256 |
efd424d2a72687893a81bb98f226cf574288acd2
| 1,015 |
//
// Color+Extension.swift
// MrWindDelivery
//
// Created by 孙超杰 on 16/5/23.
// Copyright © 2016年 Gezbox Inc. All rights reserved.
//
// 拓展UIColor自定义颜色和随机颜色
import UIKit
extension UIColor {
class func colorWithCustom(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1)
}
convenience init(hex: Int, alpha: CGFloat = 1) {
let components = (
R: CGFloat((hex >> 16) & 0xff) / 255,
G: CGFloat((hex >> 08) & 0xff) / 255,
B: CGFloat((hex >> 00) & 0xff) / 255
)
self.init(red: components.R, green: components.G, blue: components.B, alpha: alpha)
}
// class func randomColor() -> UIColor {
// let r = CGFloat(arc4random_uniform(256))
// let g = CGFloat(arc4random_uniform(256))
// let b = CGFloat(arc4random_uniform(256))
// return UIColor.colorWithCustom(r, g: g, b: b)
// }
}
| 27.432432 | 91 | 0.55665 |
61a19ac0750398b2637bc659cb28b541ce37413d
| 559 |
//
// EstructuraLogin.swift
// AKSwiftSlideMenu
//
// Created by Bet Data Analysis on 9/15/19.
// Copyright © 2019 Kode. All rights reserved.
//
import UIKit
public struct EstructuraLogin:Decodable
{
let idUsuario:integer_t
let usuario:String?
let correo:String?
let validado:String?
let codValidacion:String?
let serieActual:String?
let paquete:String?
let fechaPaquete:String?
let error:String?
let codigoAmistad:String?
let amigosbuenPedo:String?
let fechaCreacion:String?
let token:String?
}
| 19.964286 | 47 | 0.699463 |
1ead7dc38abf35d284132250aeae12182af17807
| 4,559 |
//
// GIGScannerViewController.swift
// GiGLibrary
//
// Created by Judith Medina on 7/5/16.
// Copyright © 2016 Gigigo SL. All rights reserved.
//
import UIKit
import AVFoundation
public protocol GIGScannerDelegate {
func didSuccessfullyScan(_ scannedValue: String, tye: String)
}
open class GIGScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var delegate: GIGScannerDelegate?
fileprivate let session: AVCaptureSession
fileprivate let device: AVCaptureDevice
fileprivate let output: AVCaptureMetadataOutput
fileprivate var preview: AVCaptureVideoPreviewLayer?
fileprivate var input: AVCaptureDeviceInput?
// MARK: - INIT
required public init?(coder aDecoder: NSCoder) {
self.session = AVCaptureSession()
self.device = AVCaptureDevice.default(for: AVMediaType.video)!
self.output = AVCaptureMetadataOutput()
do {
self.input = try AVCaptureDeviceInput(device: device)
}
catch _ {
//Error handling, if needed
}
super.init(coder: aDecoder)
}
deinit {
}
override open func viewDidLoad() {
self.setupScannerWithProperties()
}
// MARK: - PUBLIC
public func isCameraAvailable() -> Bool {
let authCamera = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch authCamera {
case AVAuthorizationStatus.authorized:
return true
case AVAuthorizationStatus.denied:
return false
case AVAuthorizationStatus.restricted:
return false
case AVAuthorizationStatus.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { success in
// return true
})
return true
@unknown default:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { success in
// return true
})
return true
}
}
public func setupScanner(_ metadataObject: [AnyObject]?) {
guard let metadata = metadataObject as? [AVMetadataObject.ObjectType] else {return}
self.output.metadataObjectTypes = metadata
if self.output.availableMetadataObjectTypes.count > 0 {
self.output.metadataObjectTypes = metadata
}
}
public func startScanning() {
self.session.startRunning()
}
public func stopScanning() {
self.session.stopRunning()
}
public func enableTorch(_ enable: Bool) {
try! self.device.lockForConfiguration()
if self.device.hasTorch {
if enable {
self.device.torchMode = .on
}
else {
self.device.torchMode = .off
}
}
self.device.unlockForConfiguration()
}
public func focusCamera(_ focusPoint: CGPoint) {
do {
try self.device.lockForConfiguration()
self.device.focusPointOfInterest = focusPoint
self.device.focusMode = AVCaptureDevice.FocusMode.continuousAutoFocus
self.device.exposurePointOfInterest = focusPoint
self.device.exposureMode = AVCaptureDevice.ExposureMode.continuousAutoExposure
} catch let error as NSError {
print(error.localizedDescription)
}
}
// MARK: - PRIVATE
func setupScannerWithProperties() {
if self.session.canAddInput(self.input!) {
self.session.addInput(self.input!)
}
self.session.addOutput(self.output)
self.output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
self.setupScanner(self.setupOutputWithDefaultValues() as [AnyObject]?)
self.setupPreviewLayer()
}
func setupOutputWithDefaultValues() -> [AVMetadataObject.ObjectType] {
let metadata = [AVMetadataObject.ObjectType.upce, AVMetadataObject.ObjectType.code39, AVMetadataObject.ObjectType.code39Mod43,
AVMetadataObject.ObjectType.ean13, AVMetadataObject.ObjectType.ean8, AVMetadataObject.ObjectType.code93, AVMetadataObject.ObjectType.code128,
AVMetadataObject.ObjectType.pdf417, AVMetadataObject.ObjectType.aztec, AVMetadataObject.ObjectType.qr];
return metadata
}
func setupPreviewLayer() {
self.preview = AVCaptureVideoPreviewLayer(session: self.session)
self.preview?.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.preview?.frame = self.view.bounds
self.view.layer.addSublayer(self.preview!)
}
public func metadataOutput(captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
for metadata in metadataObjects {
let readableCode = metadata as? AVMetadataMachineReadableCodeObject
guard let value = readableCode?.stringValue,
let type = readableCode?.type
else {return}
self.delegate?.didSuccessfullyScan(value, tye: type.rawValue)
}
}
}
| 25.757062 | 154 | 0.744242 |
4bc4d12c8bb801ca238a4a3d541dffd23dfd33f3
| 90,972 |
/*
Copyright 2017 Avery Pierce
Copyright 2017 Vector Creations Ltd
Copyright 2019 The Matrix.org Foundation C.I.C
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
/// Represents account data type
public enum MXAccountDataType: Equatable, Hashable {
case direct
case pushRules
case ignoredUserList
case other(String)
var rawValue: String {
switch self {
case .direct: return kMXAccountDataTypeDirect
case .pushRules: return kMXAccountDataTypePushRules
case .ignoredUserList: return kMXAccountDataKeyIgnoredUser
case .other(let value): return value
}
}
}
/// Method of inviting a user to a room
public enum MXRoomInvitee: Equatable, Hashable {
/// Invite a user by username
case userId(String)
/// Invite a user by email
case email(String)
/// Invite a user using a third-party mechanism.
/// `method` is the method to use, eg. "email".
/// `address` is the address of the user.
case thirdPartyId(MX3PID)
}
public extension MXRestClient {
// MARK: - Initialization
/**
Create an instance based on homeserver url.
- parameters:
- homeServer: The homeserver address.
- handler: the block called to handle unrecognized certificate (`nil` if unrecognized certificates are ignored).
- returns: a `MXRestClient` instance.
*/
@nonobjc convenience init(homeServer: URL, unrecognizedCertificateHandler handler: MXHTTPClientOnUnrecognizedCertificate?) {
self.init(__homeServer: homeServer.absoluteString, andOnUnrecognizedCertificateBlock: handler)
}
/**
Create an instance based on existing user credentials.
- parameters:
- credentials: A set of existing user credentials.
- handler: the block called to handle unrecognized certificate (`nil` if unrecognized certificates are ignored).
- returns: a `MXRestClient` instance.
*/
@nonobjc convenience init(credentials: MXCredentials, unrecognizedCertificateHandler handler: MXHTTPClientOnUnrecognizedCertificate? = nil, persistentTokenDataHandler: MXRestClientPersistTokenDataHandler? = nil, unauthenticatedHandler: MXRestClientUnauthenticatedHandler? = nil) {
self.init(__credentials: credentials, andOnUnrecognizedCertificateBlock: handler, andPersistentTokenDataHandler: persistentTokenDataHandler, andUnauthenticatedHandler: unauthenticatedHandler)
}
// MARK: - Registration Operations
/**
Check whether a username is already in use.
- parameters:
- username: The user name to test.
- completion: A block object called when the operation is completed.
- inUse: Whether the username is in use
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func isUserNameInUse(_ username: String, completion: @escaping (_ inUse: Bool) -> Void) -> MXHTTPOperation {
return __isUserName(inUse: username, callback: completion)
}
/**
Get the list of register flows supported by the home server.
- parameters:
- completion: A block object called when the operation is completed.
- response: Provides the server response as an `MXAuthenticationSession` instance.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getRegisterSession(completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation {
return __getRegisterSession(currySuccess(completion), failure: curryFailure(completion))
}
/**
Generic registration action request.
As described in [the specification](http://matrix.org/docs/spec/client_server/r0.2.0.html#client-authentication),
some registration flows require to complete several stages in order to complete user registration.
This can lead to make several requests to the home server with different kinds of parameters.
This generic method with open parameters and response exists to handle any kind of registration flow stage.
At the end of the registration process, the SDK user should be able to construct a MXCredentials object
from the response of the last registration action request.
- parameters:
- parameters: the parameters required for the current registration stage
- completion: A block object called when the operation completes.
- response: Provides the raw JSON response from the server.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func register(parameters: [String: Any], completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __register(withParameters: parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/*
TODO: This method accepts a nil username. Maybe this should be called "anonymous registration"? Would it make sense to have a separate API for that case?
We could also create an enum called "MXRegistrationType" with associated values, e.g. `.username(String)` and `.anonymous`
*/
/**
Register a user.
This method manages the full flow for simple login types and returns the credentials of the newly created matrix user.
- parameters:
- loginType: the login type. Only `MXLoginFlowType.password` and `MXLoginFlowType.dummy` (m.login.password and m.login.dummy) are supported.
- username: the user id (ex: "@bob:matrix.org") or the user id localpart (ex: "bob") of the user to register. Can be nil.
- password: the user's password.
- completion: A block object called when the operation completes.
- response: Provides credentials to use to create a `MXRestClient`.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func register(loginType: MXLoginFlowType = .password, username: String?, password: String, completion: @escaping (_ response: MXResponse<MXCredentials>) -> Void) -> MXHTTPOperation {
return __register(withLoginType: loginType.identifier, username: username, password: password, success: currySuccess(completion), failure: curryFailure(completion))
}
/// The register fallback page to make registration via a web browser or a web view.
var registerFallbackURL: URL {
let fallbackString = __registerFallback()!
return URL(string: fallbackString)!
}
// MARK: - Login Operation
/**
Get the list of login flows supported by the home server.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides the server response as an MXAuthenticationSession instance.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getLoginSession(completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation {
return __getLoginSession(currySuccess(completion), failure: curryFailure(completion))
}
/**
Generic login action request.
As described in [the specification](http://matrix.org/docs/spec/client_server/r0.2.0.html#client-authentication),
some login flows require to complete several stages in order to complete authentication.
This can lead to make several requests to the home server with different kinds of parameters.
This generic method with open parameters and response exists to handle any kind of authentication flow stage.
At the end of the registration process, the SDK user should be able to construct a MXCredentials object
from the response of the last authentication action request.
- parameters:
- parameters: the parameters required for the current login stage
- completion: A block object called when the operation completes.
- response: Provides the raw JSON response from the server.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func login(parameters: [String: Any], completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __login(parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Log a user in.
This method manages the full flow for simple login types and returns the credentials of the logged matrix user.
- parameters:
- type: the login type. Only `MXLoginFlowType.password` (m.login.password) is supported.
- username: the user id (ex: "@bob:matrix.org") or the user id localpart (ex: "bob") of the user to authenticate.
- password: the user's password.
- completion: A block object called when the operation succeeds.
- response: Provides credentials for this user on `success`
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func login(type loginType: MXLoginFlowType = .password, username: String, password: String, completion: @escaping (_ response: MXResponse<MXCredentials>) -> Void) -> MXHTTPOperation {
return __login(withLoginType: loginType.identifier, username: username, password: password, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the login fallback page to make login via a web browser or a web view.
Presently only server auth v1 is supported.
- returns: the fallback page URL.
*/
var loginFallbackURL: URL {
let fallbackString = __loginFallback()!
return URL(string: fallbackString)!
}
/**
Reset the account password.
- parameters:
- parameters: a set of parameters containing a threepid credentials and the new password.
- completion: A block object called when the operation completes.
- response: indicates whether the operation succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func resetPassword(parameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __resetPassword(withParameters: parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Replace the account password.
- parameters:
- old: the current password to update.
- new: the new password.
- completion: A block object called when the operation completes
- response: indicates whether the operation succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func changePassword(from old: String, to new: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __changePassword(old, with: new, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Invalidate the access token, so that it can no longer be used for authorization.
- parameters:
- completion: A block object called when the operation completes.
- response: Indicates whether the operation succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func logout(completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __logout(currySuccess(completion), failure: curryFailure(completion))
}
/**
Deactivate the user's account, removing all ability for the user to login again.
This API endpoint uses the User-Interactive Authentication API.
An access token should be submitted to this endpoint if the client has an active session.
The homeserver may change the flows available depending on whether a valid access token is provided.
- parameters:
- authParameters The additional authentication information for the user-interactive authentication API.
- eraseAccount Indicating whether the account should be erased.
- completion: A block object called when the operation completes.
- response: indicates whether the request succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func deactivateAccount(withAuthParameters authParameters: [String: Any], eraseAccount: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __deactivateAccount(withAuthParameters: authParameters, eraseAccount: eraseAccount, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Account data
/**
Set some account_data for the client.
- parameters:
- data: the new data to set for this event type.
- type: The event type of the account_data to set. Custom types should be namespaced to avoid clashes.
- completion: A block object called when the operation completes
- response: indicates whether the request succeeded or not
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setAccountData(_ data: [String: Any], for type: MXAccountDataType, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setAccountData(data, forType: type.rawValue, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Push Notifications
/**
Update the pusher for this device on the Home Server.
- parameters:
- pushkey: The pushkey for this pusher. This should be the APNS token formatted as required for your push gateway (base64 is the recommended formatting).
- kind: The kind of pusher your push gateway requires. Generally `.http`. Specify `.none` to disable the pusher.
- appId: The app ID of this application as required by your push gateway.
- appDisplayName: A human readable display name for this app.
- deviceDisplayName: A human readable display name for this device.
- profileTag: The profile tag for this device. Identifies this device in push rules.
- lang: The user's preferred language for push, eg. 'en' or 'en-US'
- data: Dictionary of data as required by your push gateway (generally the notification URI and aps-environment for APNS).
- completion: A block object called when the operation succeeds.
- response: indicates whether the request succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setPusher(pushKey: String, kind: MXPusherKind, appId: String, appDisplayName: String, deviceDisplayName: String, profileTag: String, lang: String, data: [String: Any], append: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setPusherWithPushkey(pushKey, kind: kind.objectValue, appId: appId, appDisplayName: appDisplayName, deviceDisplayName: deviceDisplayName, profileTag: profileTag, lang: lang, data: data, append: append, success: currySuccess(completion), failure: curryFailure(completion))
}
// TODO: setPusherWithPushKey - futher refinement
/*
This method is very long. Some of the parameters seem related,
specifically: appId, appDisplayName, deviceDisplayName, and profileTag.
Perhaps these parameters can be lifted out into a sparate struct?
Something like "MXPusherDescriptor"?
*/
/**
Get all push notifications rules.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides the push rules on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func pushRules(completion: @escaping (_ response: MXResponse<MXPushRulesResponse>) -> Void) -> MXHTTPOperation {
return __pushRules(currySuccess(completion), failure: curryFailure(completion))
}
/*
TODO: Consider refactoring. The following three methods all contain (ruleId:, scope:, kind:).
Option 1: Encapsulate those parameters as a tuple or struct called `MXPushRuleDescriptor`
This would be appropriate if these three parameters typically get passed around as a set,
or if the rule is uniquely identified by this combination of parameters. (eg. one `ruleId`
can have different settings for varying scopes and kinds).
Option 2: Refactor all of these to a single function that takes a "MXPushRuleAction"
as the fourth paramerer. This approach might look like this:
enum MXPushRuleAction {
case enable
case disable
case add(actions: [Any], pattern: String, conditions: [[String: Any]])
case remove
}
func pushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, action: MXPushRuleAction, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation ? {
switch action {
case .enable:
// ... Call the `enablePushRule` method
case .disable:
// ... Call the `enablePushRule` method
case let .add(actions, pattern, conditions):
// ... Call the `addPushRule` method
case let .remove:
// ... Call the `removePushRule` method
}
}
Option 3: Leave these APIs as-is.
*/
/**
Enable/Disable a push notification rule.
- parameters:
- ruleId: The identifier for the rule.
- scope: Either 'global' or 'device/<profile_tag>' to specify global rules or device rules for the given profile_tag.
- kind: The kind of rule, ie. 'override', 'underride', 'sender', 'room', 'content' (see MXPushRuleKind).
- enabled: YES to enable
- completion: A block object called when the operation completes
- response: Indiciates whether the operation was successful
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setPushRuleEnabled(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, enabled: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __enablePushRule(ruleId, scope: scope.identifier, kind: kind.identifier, enable: enabled, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a push notification rule.
- parameters:
- ruleId: The identifier for the rule.
- scope: Either `.global` or `.device(profileTag:)` to specify global rules or device rules for the given profile_tag.
- kind: The kind of rule, ie. `.override`, `.underride`, `.sender`, `.room`, `.content`.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func removePushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __removePushRule(ruleId, scope: scope.identifier, kind: kind.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Create a new push rule.
- parameters:
- ruleId: The identifier for the rule (it depends on rule kind: user id for sender rule, room id for room rule...).
- scope: Either `.global` or `.device(profileTag:)` to specify global rules or device rules for the given profile_tag.
- kind: The kind of rule, ie. `.override`, `.underride`, `.sender`, `.room`, `.content`.
- actions: The rule actions: notify, don't notify, set tweak...
- pattern: The pattern relevant for content rule.
- conditions: The conditions relevant for override and underride rule.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addPushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, actions: [Any], pattern: String, conditions: [[String: Any]], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __addPushRule(ruleId, scope: scope.identifier, kind: kind.identifier, actions: actions, pattern: pattern, conditions: conditions, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Room operations
/**
Send a generic non state event to a room.
- parameters:
- roomId: the id of the room.
- threadId: the id of the thread to send the message. nil by default.
- eventType: the type of the event.
- content: the content that will be sent to the server as a JSON object.
- txnId: the transaction id to use. If nil, one will be generated
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendEvent(toRoom roomId: String, threadId: String? = nil, eventType: MXEventType, content: [String: Any], txnId: String?, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendEvent(toRoom: roomId, threadId: threadId, eventType: eventType.identifier, content: content, txnId: txnId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Send a generic state event to a room.
- paramters:
- roomId: the id of the room.
- eventType: the type of the event.
- content: the content that will be sent to the server as a JSON object.
- stateKey: the optional state key.
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendStateEvent(toRoom roomId: String, eventType: MXEventType, content: [String: Any], stateKey: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendStateEvent(toRoom: roomId, eventType: eventType.identifier, content: content, stateKey: stateKey, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Send a message to a room
- parameters:
- roomId: the id of the room.
- threadId: the id of the thread to send the message. nil by default.
- messageType: the type of the message.
- content: the message content that will be sent to the server as a JSON object.
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
-returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendMessage(toRoom roomId: String, threadId: String? = nil, messageType: MXMessageType, content: [String: Any], completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendMessage(toRoom: roomId, threadId: threadId, msgType: messageType.identifier, content: content, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Send a text message to a room
- parameters:
- roomId: the id of the room.
- threadId: the id of the thread to send the message. nil by default.
- text: the text to send.
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendTextMessage(toRoom roomId: String, threadId: String? = nil, text: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendTextMessage(toRoom: roomId, threadId: threadId, text: text, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the topic of a room.
- parameters:
- roomId: the id of the room.
- topic: the topic to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setTopic(ofRoom roomId: String, topic: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomTopic(roomId, topic: topic, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the topic of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the topic of the room on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func topic(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __topic(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the avatar of a room.
- parameters:
- roomId: the id of the room.
- avatar: the avatar url to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setAvatar(ofRoom roomId: String, avatarUrl: URL, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomAvatar(roomId, avatar: avatarUrl.absoluteString, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the avatar of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room avatar url on success.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func avatar(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<URL>) -> Void) -> MXHTTPOperation {
return __avatar(ofRoom: roomId, success: currySuccess(transform: {return URL(string: $0 ?? "")}, completion), failure: curryFailure(completion))
}
/**
Set the name of a room.
- parameters:
- roomId: the id of the room.
- name: the name to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setName(ofRoom roomId: String, name: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomName(roomId, name: name, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the name of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room name on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func name(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __name(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the history visibility of a room.
- parameters:
- roomId: the id of the room
- historyVisibility: the visibily to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setHistoryVisibility(ofRoom roomId: String, historyVisibility: MXRoomHistoryVisibility, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomHistoryVisibility(roomId, historyVisibility: historyVisibility.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the history visibility of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room history visibility on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func historyVisibility(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomHistoryVisibility>) -> Void) -> MXHTTPOperation {
return __historyVisibility(ofRoom: roomId, success: currySuccess(transform: MXRoomHistoryVisibility.init, completion), failure: curryFailure(completion))
}
/**
Set the join rule of a room.
- parameters:
- roomId: the id of the room.
- joinRule: the rule to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setJoinRule(ofRoom roomId: String, joinRule: MXRoomJoinRule, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomJoinRule(roomId, joinRule: joinRule.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the join rule of a room.
- parameters:
- joinRule: the rule to set.
- roomId: the id of the room.
- allowedParentIds: Optional: list of allowedParentIds (required only for `restricted` join rule as per [MSC3083](https://github.com/matrix-org/matrix-doc/pull/3083) )
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setRoomJoinRule(_ joinRule: MXRoomJoinRule, forRoomWithId roomId: String, allowedParentIds: [String]?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomJoinRule(joinRule.identifier, forRoomWithId: roomId, allowedParentIds: allowedParentIds, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the join rule of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room join rule on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func joinRule(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomJoinRule>) -> Void) -> MXHTTPOperation {
return __joinRule(ofRoom: roomId, success: currySuccess(transform: MXRoomJoinRule.init, completion), failure: curryFailure(completion))
}
/**
Get the enhanced join rule of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes. It provides the room enhanced join rule as per [MSC3083](https://github.com/matrix-org/matrix-doc/pull/3083.
- response: Provides the room join rule on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func joinRule(ofRoomWithId roomId: String, completion: @escaping (_ response: MXResponse<MXRoomJoinRuleResponse>) -> Void) -> MXHTTPOperation {
return __joinRuleOfRoom(withId: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the guest access of a room.
- parameters:
- roomId: the id of the room.
- guestAccess: the guest access to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setGuestAccess(forRoom roomId: String, guestAccess: MXRoomGuestAccess, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomGuestAccess(roomId, guestAccess: guestAccess.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the guest access of a room.
- parameters:
- roomId the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room guest access on success.
- return: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func guestAccess(forRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomGuestAccess>) -> Void) -> MXHTTPOperation {
return __guestAccess(ofRoom: roomId, success: currySuccess(transform: MXRoomGuestAccess.init, completion), failure: curryFailure(completion))
}
/**
Set the directory visibility of a room on the current homeserver.
- parameters:
- roomId: the id of the room.
- directoryVisibility: the directory visibility to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func setDirectoryVisibility(ofRoom roomId: String, directoryVisibility: MXRoomDirectoryVisibility, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomDirectoryVisibility(roomId, directoryVisibility: directoryVisibility.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the visibility of a room in the current HS's room directory.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room directory visibility on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func directoryVisibility(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomDirectoryVisibility>) -> Void) -> MXHTTPOperation {
return __directoryVisibility(ofRoom: roomId, success: currySuccess(transform: MXRoomDirectoryVisibility.init, completion), failure: curryFailure(completion))
}
/**
Create a new mapping from room alias to room ID.
- parameters:
- roomId: the id of the room.
- roomAlias: the alias to add.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addAlias(forRoom roomId: String, alias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __addRoomAlias(roomId, alias: alias, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a mapping of room alias to room ID.
- parameters:
- roomAlias: the alias to remove.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func removeRoomAlias(_ roomAlias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __removeRoomAlias(roomAlias, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the canonical alias of the room.
- parameters:
- roomId: the id of the room.
- canonicalAlias: the canonical alias to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setCanonicalAlias(forRoom roomId: String, canonicalAlias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomCanonicalAlias(roomId, canonicalAlias: canonicalAlias, success: currySuccess(completion), failure: curryFailure(completion));
}
/**
Get the canonical alias.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the canonical alias on success
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func canonicalAlias(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __canonicalAlias(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Join a room, optionally where the user has been invited by a 3PID invitation.
- parameters:
- roomIdOrAlias: The id or an alias of the room to join.
- viaServers The server names to try and join through in addition to those that are automatically chosen.
- thirdPartySigned: The signed data obtained by the validation of the 3PID invitation, if 3PID validation is used. The validation is made by `self.signUrl()`.
- completion: A block object called when the operation completes.
- response: Provides the room id on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func joinRoom(_ roomIdOrAlias: String, viaServers: [String]? = nil, withThirdPartySigned dictionary: [String: Any]? = nil, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __joinRoom(roomIdOrAlias, viaServers: viaServers, withThirdPartySigned: dictionary, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Leave a room.
- parameters:
- roomId: the id of the room to leave.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func leaveRoom(_ roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __leaveRoom(roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Invite a user to a room.
A user can be invited one of three ways:
1. By their user ID
2. By their email address
3. By a third party
The `invitation` parameter specifies how this user should be reached.
- parameters:
- invitation: the way to reach the user.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func invite(_ invitation: MXRoomInvitee, toRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
switch invitation {
case .userId(let userId):
return __inviteUser(userId, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
case .email(let emailAddress):
return __inviteUser(byEmail: emailAddress, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
case .thirdPartyId(let descriptor):
return __invite(byThreePid: descriptor.medium.identifier, address: descriptor.address, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
}
/**
Kick a user from a room.
- parameters:
- userId: the user id.
- roomId: the id of the room.
- reason: the reason for being kicked
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func kickUser(_ userId: String, fromRoom roomId: String, reason: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __kickUser(userId, fromRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Ban a user in a room.
- parameters:
- userId: the user id.
- roomId: the id of the room.
- reason: the reason for being banned
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func banUser(_ userId: String, fromRoom roomId: String, reason: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __banUser(userId, inRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Unban a user in a room.
- parameters:
- userId: the user id.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func unbanUser(_ userId: String, fromRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __unbanUser(userId, inRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Create a room.
- parameters:
- parameters: The parameters for room creation.
- completion: A block object called when the operation completes.
- response: Provides a MXCreateRoomResponse object on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func createRoom(parameters: MXRoomCreationParameters, completion: @escaping (_ response: MXResponse<MXCreateRoomResponse>) -> Void) -> MXHTTPOperation {
return __createRoom(with: parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Create a room.
- parameters:
- parameters: The parameters. Refer to the matrix specification for details.
- completion: A block object called when the operation completes.
- response: Provides a MXCreateRoomResponse object on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func createRoom(parameters: [String: Any], completion: @escaping (_ response: MXResponse<MXCreateRoomResponse>) -> Void) -> MXHTTPOperation {
return __createRoom(parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get a list of messages for this room.
- parameters:
- roomId: the id of the room.
- from: the token to start getting results from.
- direction: `MXTimelineDirectionForwards` or `MXTimelineDirectionBackwards`
- limit: (optional, use -1 to not defined this value) the maximum nuber of messages to return.
- filter: to filter returned events with.
- completion: A block object called when the operation completes.
- response: Provides a `MXPaginationResponse` object on success.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func messages(forRoom roomId: String, from: String, direction: MXTimelineDirection, limit: UInt?, filter: MXRoomEventFilter, completion: @escaping (_ response: MXResponse<MXPaginationResponse>) -> Void) -> MXHTTPOperation {
// The `limit` variable should be set to -1 if it's not provided.
let _limit: Int
if let limit = limit {
_limit = Int(limit)
} else {
_limit = -1;
}
return __messages(forRoom: roomId, from: from, direction: direction, limit: _limit, filter: filter, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get a list of members for this room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXEvent` objects that are the type `m.room.member` on success.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func members(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[MXEvent]>) -> Void) -> MXHTTPOperation {
return __members(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get a list of all the current state events for this room.
This is equivalent to the events returned under the 'state' key for this room in initialSyncOfRoom.
See [the matrix documentation on state events](http://matrix.org/docs/api/client-server/#!/-rooms/get_state_events)
for more detail.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the raw home server JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func state(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __state(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Inform the home server that the user is typing (or not) in this room.
- parameters:
- roomId: the id of the room.
- typing: Use `true` if the user is currently typing.
- timeout: the length of time until the user should be treated as no longer typing. Can be set to `nil` if they are no longer typing.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendTypingNotification(inRoom roomId: String, typing: Bool, timeout: TimeInterval?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
// The `timeout` variable should be set to -1 if it's not provided.
let _timeout: Int
if let timeout = timeout {
// The `TimeInterval` type is a double value specified in seconds. Multiply by 1000 to get milliseconds.
_timeout = Int(timeout * 1000 /* milliseconds */)
} else {
_timeout = -1;
}
return __sendTypingNotification(inRoom: roomId, typing: typing, timeout: UInt(_timeout), success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Redact an event in a room.
- parameters:
- eventId: the id of the redacted event.
- roomId: the id of the room.
- reason: the redaction reason.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func redactEvent(_ eventId: String, inRoom roomId: String, reason: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __redactEvent(eventId, inRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Report an event.
- parameters:
- eventId: the id of the event event.
- roomId: the id of the room.
- score: the metric to let the user rate the severity of the abuse. It ranges from -100 “most offensive” to 0 “inoffensive”.
- reason: the redaction reason.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func reportEvent(_ eventId: String, inRoom roomId: String, score: Int, reason: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __reportEvent(eventId, inRoom: roomId, score: score, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get all the current information for this room, including messages and state events.
See [the matrix documentation](http://matrix.org/docs/api/client-server/#!/-rooms/get_room_sync_data)
for more detail.
- parameters:
- roomId: the id of the room.
- limit: the maximum number of messages to return.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func intialSync(ofRoom roomId: String, limit: UInt, completion: @escaping (_ response: MXResponse<MXRoomInitialSync>) -> Void) -> MXHTTPOperation {
return __initialSync(ofRoom: roomId, withLimit: Int(limit), success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Retrieve an event from its event id.
- parameters:
- eventId: the id of the event to get context around.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
*/
@nonobjc @discardableResult func event(withEventId eventId: String, completion: @escaping (_ response: MXResponse<MXEvent>) -> Void) -> MXHTTPOperation {
return __event(withEventId: eventId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Retrieve an event from its room id and event id.
- parameters:
- eventId: the id of the event to get context around.
- roomId: the id of the room to get events from.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
*/
@nonobjc @discardableResult func event(withEventId eventId: String, inRoom roomId: String, completion: @escaping (_ response: MXResponse<MXEvent>) -> Void) -> MXHTTPOperation {
return __event(withEventId: eventId, inRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the context surrounding an event.
This API returns a number of events that happened just before and after the specified event.
- parameters:
- eventId: the id of the event to get context around.
- roomId: the id of the room to get events from.
- limit: the maximum number of messages to return.
- filter the filter to pass in the request. Can be nil.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func context(ofEvent eventId: String, inRoom roomId: String, limit: UInt, filter: MXRoomEventFilter? = nil, completion: @escaping (_ response: MXResponse<MXEventContext>) -> Void) -> MXHTTPOperation {
return __context(ofEvent: eventId, inRoom: roomId, limit: limit, filter:filter, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the summary of a room
- parameters:
- roomIdOrAlias: the id of the room or its alias
- via: servers, that should be tried to request a summary from, if it can't be generated locally. These can be from a matrix URI, matrix.to link or a `m.space.child` event for example.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func roomSummary(with roomIdOrAlias: String, via: [String], completion: @escaping (_ response: MXResponse<MXPublicRoom>) -> Void) -> MXHTTPOperation {
return __roomSummary(with: roomIdOrAlias, via: via, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Upgrade a room to a new version
- parameters:
- roomId: the id of the room.
- roomVersion: the new room version
- completion: A block object called when the operation completes.
- response: Provides the ID of the replacement room on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func upgradeRoom(withId roomId: String, to roomVersion: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __upgradeRoom(withId: roomId, to: roomVersion, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Room tags operations
/**
List the tags of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXRoomTag` objects on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func tags(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[MXRoomTag]>) -> Void) -> MXHTTPOperation {
return __tags(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Add a tag to a room.
Use this method to update the order of an existing tag.
- parameters:
- tag: the new tag to add to the room.
- order: the order. @see MXRoomTag.order.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXRoomTag` objects on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addTag(_ tag: String, withOrder order: String, toRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __addTag(tag, withOrder: order, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a tag from a room.
- parameters:
- tag: the tag to remove.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXRoomTag` objects on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func removeTag(_ tag: String, fromRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __removeTag(tag, fromRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Room account data operations
/**
Update the tagged events
- parameters:
- roomId: the id of the room.
- content: the new tagged events content.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func updateTaggedEvents(_ roomId: String, withContent content: MXTaggedEvents, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __updateTaggedEvents(roomId, withContent: content, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the tagged events of a room
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides a `MXTaggedEvents` object on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getTaggedEvents(_ roomId: String, completion: @escaping (_ response: MXResponse<MXTaggedEvents>) -> Void) -> MXHTTPOperation {
return __getTaggedEvents(roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set a dedicated room account data field
- parameters:
- roomId: the id of the room.
- eventTypeString: the type of the event. @see MXEventType.
- content: the event content.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setRoomAccountData(_ roomId: String, eventType eventTypeString: String, withParameters content: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomAccountData(roomId, eventType: eventTypeString, withParameters: content, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the room account data field
- parameters:
- roomId: the id of the room.
- eventTypeString: the type of the event. @see MXEventType.
- completion: A block object called when the operation completes.
- response: Provides the raw JSON response from the server.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getRoomAccountData(_ roomId: String, eventType eventTypeString: String, completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __getRoomAccountData(roomId, eventType: eventTypeString, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Profile operations
/**
Set the logged-in user display name.
- parameters:
- displayname: the new display name.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setDisplayName(_ displayName: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setDisplayName(displayName, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the display name of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the display name on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func displayName(forUser userId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __displayName(forUser: userId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the logged-in user avatar url.
- parameters:
- urlString: The new avatar url.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setAvatarUrl(_ url: URL, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setAvatarUrl(url.absoluteString, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the avatar url of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the avatar url on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func avatarUrl(forUser userId: String, completion: @escaping (_ response: MXResponse<URL>) -> Void) -> MXHTTPOperation {
return __avatarUrl(forUser: userId, success: currySuccess(transform: { return URL(string: $0 ?? "") }, completion), failure: curryFailure(completion))
}
/**
Get the profile information of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the display name and avatar url if they are defined on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func profile(forUser userId: String, completion: @escaping (_ response: MXResponse<(String?, String?)>) -> Void) -> MXHTTPOperation {
return __profile(forUser: userId, success: { (displayName, avatarUrl) -> Void in
let profileInformation = (displayName, avatarUrl)
completion(MXResponse.success(profileInformation))
}, failure: curryFailure(completion))
}
/**
Link an authenticated 3rd party id to the Matrix user.
This API is deprecated, and you should instead use `addThirdPartyIdentifierOnly`
for homeservers that support it.
- parameters:
- sid: the id provided during the 3PID validation session (MXRestClient.requestEmailValidation).
- clientSecret: the same secret key used in the validation session.
- bind: whether the homeserver should also bind this third party identifier to the account's Matrix ID with the identity server.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addThirdPartyIdentifier(_ sid: String, clientSecret: String, bind: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __add3PID(sid, clientSecret: clientSecret, bind: bind, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Add a 3PID to your homeserver account.
This API does not use an identity server, as the homeserver is expected to
handle 3PID ownership validation.
You can check whether a homeserver supports this API via
`doesServerSupportSeparateAddAndBind`.
- parameters:
- sid: the session id provided during the 3PID validation session.
- clientSecret: the same secret key used in the validation session.
- authParameters: The additional authentication information for the user-interactive authentication API.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addThirdPartyIdentifierOnly(withSessionId sid: String, clientSecret: String, authParameters: [String: Any]?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __add3PIDOnly(withSessionId: sid, clientSecret: clientSecret, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a 3rd party id from the Matrix user information.
- parameters:
- address: the 3rd party id.
- medium: medium the type of the 3rd party id.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func remove3PID(address: String, medium: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __remove3PID(address, medium: medium, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
List all 3PIDs linked to the Matrix user account.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides the third-party identifiers on success
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func thirdPartyIdentifiers(_ completion: @escaping (_ response: MXResponse<[MXThirdPartyIdentifier]?>) -> Void) -> MXHTTPOperation {
return __threePIDs(currySuccess(completion), failure: curryFailure(completion))
}
/**
Bind a 3PID for discovery onto an identity server via the homeserver.
The identity server handles 3PID ownership validation and the homeserver records
the new binding to track where all 3PIDs for the account are bound.
You can check whether a homeserver supports this API via
`doesServerSupportSeparateAddAndBind`.
- parameters:
- sid: the session id provided during the 3PID validation session.
- clientSecret: the same secret key used in the validation session.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func bind3Pid(withSessionId sid: String, clientSecret: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __bind3Pid(withSessionId: sid, clientSecret: clientSecret, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Unbind a 3PID for discovery on an identity server via the homeserver.
- parameters:
- address: the 3rd party id.
- medium: medium the type of the 3rd party id.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func unbind3Pid(withAddress address: String, medium: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __unbind3Pid(withAddress: address, medium: medium, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Presence operations
// TODO: MXPresence could be refined to a Swift enum. presence+message could be combined in a struct, since they're closely related.
/**
Set the current user presence status.
- parameters:
- presence: the new presence status.
- statusMessage: the new message status.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setPresence(_ presence: MXPresence, statusMessage: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setPresence(presence, andStatusMessage: statusMessage, success: currySuccess(completion), failure: curryFailure(completion))
}
// TODO: MXPresenceResponse smells like a tuple (_ presence: MXPresence, timeActiveAgo: NSTimeInterval). Consider refining further.
/**
Get the presence status of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the `MXPresenceResponse` on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func presence(forUser userId: String, completion: @escaping (_ response: MXResponse<MXPresenceResponse>) -> Void) -> MXHTTPOperation {
return __presence(userId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Sync
/*
TODO: This API could be further refined.
`token` is an optional string, with nil meaning "initial sync".
This could be expressed better as an enum: .initial or .fromToken(String)
`presence` appears to support only two possible values: nil or "offline".
This could be expressed better as an enum: .online, or .offline
(are there any other valid values for this field? why would it be typed as a string?)
*/
/**
Synchronise the client's state and receive new messages.
Synchronise the client's state with the latest state on the server.
Client's use this API when they first log in to get an initial snapshot
of the state on the server, and then continue to call this API to get
incremental deltas to the state, and to receive new messages.
- parameters:
- token: the token to stream from (nil in case of initial sync).
- serverTimeout: the maximum time in ms to wait for an event.
- clientTimeout: the maximum time in ms the SDK must wait for the server response.
- presence: the optional parameter which controls whether the client is automatically marked as online by polling this API. If this parameter is omitted then the client is automatically marked as online when it uses this API. Otherwise if the parameter is set to "offline" then the client is not marked as being online when it uses this API.
- filterId: the ID of a filter created using the filter API (optinal).
- completion: A block object called when the operation completes.
- response: Provides the `MXSyncResponse` on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sync(fromToken token: String?, serverTimeout: UInt, clientTimeout: UInt, setPresence presence: String?, filterId: String? = nil, completion: @escaping (_ response: MXResponse<MXSyncResponse>) -> Void) -> MXHTTPOperation {
return __sync(fromToken: token, serverTimeout: serverTimeout, clientTimeout: clientTimeout, setPresence: presence, filter: filterId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Directory operations
/**
Get the list of public rooms hosted by the home server.
Pagination parameters (`limit` and `since`) should be used in order to limit
homeserver resources usage.
- parameters:
- server: (optional) the remote server to query for the room list. If nil, get the user homeserver's public room list.
- limit: (optional, use -1 to not defined this value) the maximum number of entries to return.
- since: (optional) token to paginate from.
- filter: (optional) the string to search for.
- thirdPartyInstanceId: (optional) returns rooms published to specific lists on a third party instance (like an IRC bridge).
- includeAllNetworks: if YES, returns all rooms that have been published to any list. NO to return rooms on the main, default list.
- completion: A block object called when the operation is complete.
- response: Provides an publicRoomsResponse instance on `success`
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func publicRooms(onServer server: String?, limit: UInt?, since: String? = nil, filter: String? = nil, thirdPartyInstanceId: String? = nil, includeAllNetworks: Bool = false, completion: @escaping (_ response: MXResponse<MXPublicRoomsResponse>) -> Void) -> MXHTTPOperation {
// The `limit` variable should be set to -1 if it's not provided.
let _limit: Int
if let limit = limit {
_limit = Int(limit)
} else {
_limit = -1;
}
return __publicRooms(onServer: server, limit: _limit, since: since, filter: filter, thirdPartyInstanceId: thirdPartyInstanceId, includeAllNetworks: includeAllNetworks, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the room ID corresponding to this room alias
- parameters:
- roomAlias: the alias of the room to look for.
- completion: A block object called when the operation completes.
- response: Provides the the ID of the room on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func roomId(forRoomAlias roomAlias: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __roomID(forRoomAlias: roomAlias, success: currySuccess(completion), failure: curryFailure(completion))
}
// Mark: - Media Repository API
/**
Upload content to HomeServer
- parameters:
- data: the content to upload.
- filename: optional filename
- mimetype: the content type (image/jpeg, audio/aac...)
- timeout: the maximum time the SDK must wait for the server response.
- uploadProgress: A block object called multiple times as the upload progresses. It's also called once the upload is complete
- progress: Provides the progress of the upload until it completes. This will provide the URL of the resource on successful completion, or an error message on unsuccessful completion.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func uploadContent(_ data: Data, filename: String? = nil, mimeType: String, timeout: TimeInterval, uploadProgress: @escaping (_ progress: MXProgress<URL>) -> Void) -> MXHTTPOperation {
return __uploadContent(data, filename: filename, mimeType: mimeType, timeout: timeout, success: { (urlString) in
if let urlString = urlString, let url = URL(string: urlString) {
uploadProgress(.success(url))
} else {
uploadProgress(.failure(_MXUnknownError()))
}
}, failure: { (error) in
uploadProgress(.failure(error ?? _MXUnknownError()))
}, uploadProgress: { (progress) in
uploadProgress(.progress(progress!))
})
}
// MARK: - VoIP API
/**
Get the TURN server configuration advised by the homeserver.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides a `MXTurnServerResponse` object (or nil if the HS has TURN config) on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func turnServer(_ completion: @escaping (_ response: MXResponse<MXTurnServerResponse?>) -> Void) -> MXHTTPOperation {
return __turnServer(currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - read receipt
/**
Send a read receipt.
- parameters:
- roomId: the id of the room.
- eventId: the id of the event.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendReadReceipt(toRoom roomId: String, forEvent eventId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __sendReadReceipt(roomId, eventId: eventId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Search
/**
Search a text in room messages.
- parameters:
- textPattern: the text to search for in message body.
- roomEventFilter: a nullable dictionary which defines the room event filtering during the search request.
- beforeLimit: the number of events to get before the matching results.
- afterLimit: the number of events to get after the matching results.
- nextBatch: the token to pass for doing pagination from a previous response.
- completion: A block object called when the operation completes.
- response: Provides the search results on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func searchMessages(withPattern textPattern: String, roomEventFilter: MXRoomEventFilter? = nil, beforeLimit: UInt = 0, afterLimit: UInt = 0, nextBatch: String, completion: @escaping (_ response: MXResponse<MXSearchRoomEventResults>) -> Void) -> MXHTTPOperation {
return __searchMessages(withText: textPattern, roomEventFilter: roomEventFilter, beforeLimit: beforeLimit, afterLimit: afterLimit, nextBatch: nextBatch, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Make a search.
- parameters:
- parameters: the search parameters as defined by the Matrix search spec (http://matrix.org/docs/api/client-server/#!/Search/post_search ).
- nextBatch: the token to pass for doing pagination from a previous response.
- completion: A block object called when the operation completes.
- response: Provides the search results on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func search(withParameters parameters: [String: Any], nextBatch: String, completion: @escaping (_ response: MXResponse<MXSearchRoomEventResults>) -> Void) -> MXHTTPOperation {
return __search(parameters, nextBatch: nextBatch, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Crypto
/**
Upload device and/or one-time keys.
- parameters:
- deviceKeys: the device keys to send.
- oneTimeKeys: the one-time keys to send.
- fallbackKeys: the fallback keys to send
- completion: A block object called when the operation completes.
- response: Provides information about the keys on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func uploadKeys(_ deviceKeys: [String: Any]?, oneTimeKeys: [String: Any]?, fallbackKeys: [String: Any]?, forDevice deviceId: String? = nil, completion: @escaping (_ response: MXResponse<MXKeysUploadResponse>) -> Void) -> MXHTTPOperation {
return __uploadKeys(deviceKeys, oneTimeKeys: oneTimeKeys, fallbackKeys: fallbackKeys, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Download device keys.
- parameters:
- userIds: list of users to get keys for.
- token: sync token to pass in the query request, to help the HS give the most recent results. It can be nil.
- completion: A block object called when the operation completes.
- response: Provides information about the keys on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func downloadKeys(forUsers userIds: [String], token: String? = nil, completion: @escaping (_ response: MXResponse<MXKeysQueryResponse>) -> Void) -> MXHTTPOperation {
return __downloadKeys(forUsers: userIds, token: token, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Claim one-time keys.
- parameters:
- usersDevices: a list of users, devices and key types to retrieve keys for.
- completion: A block object called when the operation completes.
- response: Provides information about the keys on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func claimOneTimeKeys(for usersDevices: MXUsersDevicesMap<NSString>, completion: @escaping (_ response: MXResponse<MXKeysClaimResponse>) -> Void) -> MXHTTPOperation {
return __claimOneTimeKeys(forUsersDevices: usersDevices, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Direct-to-device messaging
/**
Send an event to a specific list of devices
- paramaeters:
- eventType: the type of event to send
- contentMap: content to send. Map from user_id to device_id to content dictionary.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendDirectToDevice(eventType: String, contentMap: MXUsersDevicesMap<NSDictionary>, txnId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __send(toDevice: eventType, contentMap: contentMap, txnId: txnId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Device Management
/**
Get information about all devices for the current user.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides a list of devices on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func devices(completion: @escaping (_ response: MXResponse<[MXDevice]>) -> Void) -> MXHTTPOperation {
return __devices(currySuccess(completion), failure: curryFailure(completion))
}
/**
Get information on a single device, by device id.
- parameters:
- deviceId: The device identifier.
- completion: A block object called when the operation completes.
- response: Provides the requested device on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func device(withId deviceId: String, completion: @escaping (_ response: MXResponse<MXDevice>) -> Void) -> MXHTTPOperation {
return __device(byDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Update the display name of a given device.
- parameters:
- deviceName: The new device name. If not given, the display name is unchanged.
- deviceId: The device identifier.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setDeviceName(_ deviceName: String, forDevice deviceId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setDeviceName(deviceName, forDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get an authentication session to delete a device.
- parameters:
- deviceId: The device identifier.
- completion: A block object called when the operation completes.
- response: Provides the server response.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getSession(toDeleteDevice deviceId: String, completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation {
return __getSessionToDeleteDevice(byDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Delete the given device, and invalidates any access token associated with it.
This API endpoint uses the User-Interactive Authentication API.
- parameters:
- deviceId: The device identifier.
- authParameters: The additional authentication information for the user-interactive authentication API.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func deleteDevice(_ deviceId: String, authParameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __deleteDevice(byDeviceId: deviceId, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Spaces
/// Get the space children of a given space.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - maxDepth: Optional. The maximum depth in the tree (from the root room) to return. `-1` for no limit
/// - paginationToken: Optional. Pagination token given to retrieve the next set of rooms.
/// - parameters: Space children request parameters.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@nonobjc @discardableResult func getSpaceChildrenForSpace(withId spaceId: String, suggestedOnly: Bool, limit: Int?, maxDepth: Int?, paginationToken: String?, completion: @escaping (_ response: MXResponse<MXSpaceChildrenResponse>) -> Void) -> MXHTTPOperation {
return __getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit ?? -1, maxDepth: maxDepth ?? -1, paginationToken: paginationToken, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Home server capabilities
/// Get the capabilities of the homeserver
/// - Parameters:
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@nonobjc @discardableResult func homeServerCapabilities(completion: @escaping (_ response: MXResponse<MXHomeserverCapabilities>) -> Void) -> MXHTTPOperation {
return __homeServerCapabilities(success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Aggregations
/// Get relations for a given event.
/// - Parameters:
/// - eventId: the id of the event
/// - roomId: the id of the room
/// - relationType: Optional. The type of relation
/// - eventType: Optional. Event type to filter by
/// - from: Optional. The token to start getting results from
/// - direction: direction from the token
/// - limit: Optional. The maximum number of messages to return
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@nonobjc @discardableResult func relations(forEvent eventId: String,
inRoom roomId: String,
relationType: String?,
eventType: String?,
from: String?,
direction: MXTimelineDirection,
limit: UInt?,
completion: @escaping (_ response: MXResponse<MXAggregationPaginatedResponse>) -> Void) -> MXHTTPOperation {
let _limit: Int
if let limit = limit {
_limit = Int(limit)
} else {
_limit = -1
}
return __relations(forEvent: eventId, inRoom: roomId, relationType: relationType, eventType: eventType, from: from, direction: direction, limit: _limit, success: currySuccess(completion), failure: curryFailure(completion))
}
}
| 45.875946 | 350 | 0.676219 |
dba200f7ca5332adaf60ff3fc8dd74a2ec6993e2
| 5,698 |
//
// BookDetail.swift
// IVY_assignment
//
// Created by Sean Donato on 6/25/18.
// Copyright © 2018 Sean Donato. All rights reserved.
//
import UIKit
import Alamofire
import FacebookShare
import FacebookCore
class BookDetail: UIViewController {
@IBOutlet weak var titleLabelBD: UILabel!
@IBOutlet weak var lastCheckedOutLabelBD: UILabel!
@IBOutlet weak var tagsLabelBD: UILabel!
@IBOutlet weak var publisherLabelBD: UILabel!
@IBOutlet weak var authorLabelBD: UILabel!
var bookDictionary: Dictionary<String, Any>!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.title = "Detail"
let shareButton = UIBarButtonItem(barButtonSystemItem: .reply, target: self, action: #selector(BookDetail.facebookShare))
self.navigationItem.setRightBarButton(shareButton, animated: true)
setLabels()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setLabels(){
if let bookTitle :String = bookDictionary["title"] as? String{
titleLabelBD.text = bookTitle
}
if let author :String = bookDictionary["author"] as? String{
authorLabelBD.text = author
}
if let publisher :String = bookDictionary["publisher"] as? String{
publisherLabelBD.text = "publisher: " + publisher
}
if let tags :String = bookDictionary["categories"] as? String{
tagsLabelBD.text = "tags: " + tags
}
if let lastCheckedOut :String = bookDictionary["lastCheckedOut"] as? String{
if let lastCheckedOutBy :String = bookDictionary["lastCheckedOutBy"] as? String{
if(lastCheckedOut != ""){
lastCheckedOutLabelBD.text = "Last checked out by " + lastCheckedOutBy
+ "@" + lastCheckedOut
}else{
lastCheckedOutLabelBD.text = "never checked out"
}
}
}
}
@IBAction func askForName(_ sender: Any) {
let alertController = UIAlertController(title: "Enter Your Name", message: "", preferredStyle: UIAlertControllerStyle.alert)
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter Name"
}
let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
self.checkout(name: firstTextField.text!)
})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in })
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func checkout(name:String){
if let bID = bookDictionary["id"] as? NSInteger{
let bid2 = String(describing: bID)
let urlString = URLConstants.booksURLWithQueryString + bid2
let params = ["lastCheckedOutBy":name]
Alamofire.request(urlString,method: .put,parameters:params, encoding:URLEncoding.httpBody).validate(statusCode:200..<300).responseJSON { response in
switch response.result {
case .success:
let alertController = UIAlertController(title: "Success", message: "book added!", preferredStyle: .alert)
//
let action1 = UIAlertAction(title: "Ok", style: .default) { (action:UIAlertAction) in
self.navigationController?.popViewController(animated: true)
}
alertController.addAction(action1)
self.present(alertController, animated: true, completion: nil)
print("Validation Successful")
case .failure(let error):
let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
//
let action1 = UIAlertAction(title: "Ok", style: .default) { (action:UIAlertAction) in
print("");
}
alertController.addAction(action1)
self.present(alertController, animated: true, completion: nil)
print(error.localizedDescription)
}
}
}
}
@objc func facebookShare(){
//
// let bookTitle = bookDictionary["title"] as? String
//
// let urlx :URL = URL(string: "https://www.google.com")!
//
// let shareLink = LinkShareContent.init(url: urlx, quote: bookTitle)
//
// do{
// try ShareDialog.show(from: self, content: shareLink)
// }catch{
//
// }
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 33.517647 | 156 | 0.585293 |
fbb8c267984258c21644e974b0a3aa04c5cbf45b
| 2,176 |
//
// AppDelegate.swift
// Week 1 Project: Dropbox
//
// Created by Fremling, Alicia (Contractor) on 2/5/16.
// Copyright © 2016 FargoFremling. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.297872 | 285 | 0.754136 |
d6b7c041d0c45dd4a7b4aea5e8676acf16f635ba
| 671 |
//
// Constant.swift
// ByteCoin
//
// Created by Philip Yu on 5/19/20.
// Copyright © 2020 The App Brewery. All rights reserved.
//
import Foundation
struct Constant {
// MARK: - Properties
static let apiKey = fetchFromPlist(forResource: "ApiKeys", forKey: "API_KEY")
// MARK: - Functions
static func fetchFromPlist(forResource resource: String, forKey key: String) -> String? {
let filePath = Bundle.main.path(forResource: resource, ofType: "plist")
let plist = NSDictionary(contentsOfFile: filePath!)
let value = plist?.object(forKey: key) as? String
return value
}
}
| 23.964286 | 93 | 0.624441 |
76b6b54e3ab1026196b0454efc96c54e0426d70d
| 1,032 |
//
// Error.swift
// QuickSwift
//
// Created by tcui on 2/1/2018.
// Copyright © 2018 LuckyTR. All rights reserved.
//
public enum DemoError: Error {
public struct Context {
public let debugDescription: String
public let underlyingError: Error?
public init(debugDescription: String, underlyingError: Error? = nil) {
self.debugDescription = debugDescription
self.underlyingError = underlyingError
}
}
case fileSaveFailed(Any, Context)
case fileLoadFailed(String, Context)
public var userInfo: [String: Any]? {
let context: Context
switch self {
case .fileSaveFailed(_, let c): context = c
case .fileLoadFailed(_, let c): context = c
}
var userInfo: [String: Any] = [
"NSDebugDescription": context.debugDescription
]
if let underlyingError = context.underlyingError {
userInfo["NSUnderlyingError"] = underlyingError
}
return userInfo
}
}
| 25.170732 | 78 | 0.617248 |
ffabbe1f0595a3e8992ad379c31edb7d7b9ca6b4
| 6,437 |
//
// ViewController.swift
// OrderProject
//
// Created by 천지운 on 2020/05/01.
// Copyright © 2020 jwcheon. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Story Board
@IBOutlet var orderView: UIView!
@IBOutlet var jjajangCountLabel: UILabel!
@IBOutlet var jjambbongCountLabel: UILabel!
@IBOutlet var tangCountLabel: UILabel!
let jjaPrice = 5000 // 짜장 가격
let jjamPrice = 6000 // 짬뽕 가격
let tangPrice = 12000 // 탕수육 가격
// 각 수량 변수
var jjajangCount: Int = 0 {
didSet {
jjajangCountLabel.text = "\(jjajangCount)"
paymentMoney = calcPrice()
}
}
var jjamBbongCount: Int = 0 {
didSet {
jjambbongCountLabel.text = "\(jjamBbongCount)"
paymentMoney = calcPrice()
}
}
var tangCount: Int = 0 {
didSet {
tangCountLabel.text = "\(tangCount)"
paymentMoney = calcPrice()
}
}
// 현재 결제 금액 계산하는 메소드
private func calcPrice() -> Int {
return (jjajangCount * jjaPrice) + (jjamBbongCount * jjamPrice) + (tangCount * tangPrice)
}
// 소지금 변수
var remainMoney: Int = 70000 {
didSet {
myReadyMoneyLabel.text = "\(remainMoney)원"
}
}
// 결제 금액 변수
var paymentMoney: Int = 0 {
didSet {
paymentLabel.text = "\(paymentMoney)원"
}
}
// Code
let balanceView = UIView()
let titleReadyMoneyLabel = UILabel()
let myReadyMoneyLabel = UILabel()
let titlePaymentLabel = UILabel()
let paymentLabel = UILabel()
let resetButton = UIButton(type: .system)
let paymentButton = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
balanceViewSetting()
}
// 초기화 버튼 클릭시 초기화
@objc private func clickedInit(_ sender: UIButton) {
initMoney(false)
}
// 결제 버튼 클릭 시
@objc private func clickedPayment(_ sender: UIButton) {
let alert = UIAlertController(title: "결제하기", message: "총 결제금액은 \(paymentMoney)원 입니다.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "확인", style: .default, handler: { ACTION in
if self.remainMoney < self.paymentMoney {
let refusalAlert = UIAlertController(title: "결제 취소", message: "소지금이 부족합니다.", preferredStyle: .alert)
refusalAlert.addAction(UIAlertAction(title: "확인", style: .default, handler: nil))
self.initMoney(true)
self.present(refusalAlert, animated: true)
} else {
self.remainMoney -= self.paymentMoney
self.initMoney(true)
}
})
let cancelAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)
alert.addAction(okAction)
alert.addAction(cancelAction)
self.present(alert, animated: true)
}
private func initMoney(_ isPayment: Bool) {
// true면 결제했을 경우 초기화, false면 모두 초기화
jjajangCount = 0
jjamBbongCount = 0
tangCount = 0
paymentMoney = 0
if !isPayment {
remainMoney = 70000
}
}
private func balanceViewSetting() {
// View Setting
balanceView.frame = CGRect(x: 20, y: Int(orderView.frame.size.width) + 70, width: Int(orderView.frame.size.width), height: 90)
balanceView.backgroundColor = .white
view.addSubview(balanceView)
titleReadyMoneyLabel.frame = CGRect(x: 0, y: 0, width: 80, height: 40)
titleReadyMoneyLabel.text = "소지금"
titleReadyMoneyLabel.backgroundColor = .systemGreen
titleReadyMoneyLabel.font = .boldSystemFont(ofSize: 20)
titleReadyMoneyLabel.textAlignment = .center
balanceView.addSubview(titleReadyMoneyLabel)
myReadyMoneyLabel.frame = CGRect(x: titleReadyMoneyLabel.frame.size.width + 10, y: 0, width: 140, height: 40)
myReadyMoneyLabel.text = "70000원"
myReadyMoneyLabel.backgroundColor = .systemGreen
myReadyMoneyLabel.font = .boldSystemFont(ofSize: 20)
myReadyMoneyLabel.textAlignment = .right
balanceView.addSubview(myReadyMoneyLabel)
resetButton.frame = CGRect(x: balanceView.frame.width - 80, y: 0, width: 80, height: 40)
resetButton.setTitle("초기화", for: .normal)
resetButton.setTitleColor(.white, for: .normal)
resetButton.backgroundColor = .black
resetButton.titleLabel?.font = .boldSystemFont(ofSize: 20)
resetButton.addTarget(self, action: #selector(clickedInit(_:)), for: .touchUpInside)
balanceView.addSubview(resetButton)
titlePaymentLabel.frame = CGRect(x: 0, y: balanceView.frame.size.height - 40, width: 80, height: 40)
titlePaymentLabel.text = "결제금액"
titlePaymentLabel.backgroundColor = .systemGreen
titlePaymentLabel.font = .boldSystemFont(ofSize: 20)
titlePaymentLabel.textAlignment = .center
balanceView.addSubview(titlePaymentLabel)
paymentLabel.frame = CGRect(x: titlePaymentLabel.frame.size.width + 10, y: balanceView.frame.size.height - 40, width: 140, height: 40)
paymentLabel.text = "0원"
paymentLabel.backgroundColor = .systemGreen
paymentLabel.font = .boldSystemFont(ofSize: 20)
paymentLabel.textAlignment = .right
balanceView.addSubview(paymentLabel)
paymentButton.frame = CGRect(x: balanceView.frame.width - 80, y: balanceView.frame.size.height - 40, width: 80, height: 40)
paymentButton.setTitle("결제", for: .normal)
paymentButton.setTitleColor(.white, for: .normal)
paymentButton.backgroundColor = .black
paymentButton.titleLabel?.font = .boldSystemFont(ofSize: 20)
paymentButton.addTarget(self, action: #selector(clickedPayment(_:)), for: .touchUpInside)
balanceView.addSubview(paymentButton)
}
@IBAction func clickedJjajang(_ sender: UIButton) {
jjajangCount += 1
}
@IBAction func clickedJjam(_ sender: UIButton) {
jjamBbongCount += 1
}
@IBAction func clickedTang(_ sender: UIButton) {
tangCount += 1
}
}
| 33.701571 | 142 | 0.611776 |
ef6f21b62712b692c9e5005e7b1225bcba7c4daf
| 644 |
//
// OtherFileTest.swift
// Localize
//
// Copyright © 2017 @andresilvagomez.
//
import XCTest
import Localize
class OtherLangTest: XCTestCase {
override func setUp() {
super.setUp()
Localize.update(provider: .json)
Localize.update(bundle: Bundle(for: type(of: self)))
Localize.update(language: "it")
}
func testLocalizeKey() {
let localized = "hello".localize()
XCTAssertTrue(localized == "hello")
}
func testLocalizeKeyUsingDefaultLang() {
let localized = "hello.world".localize()
XCTAssertTrue(localized == "Hello world!")
}
}
| 20.774194 | 60 | 0.608696 |
20c824acab1785c60d9dbbf69a8dc57504ddc83e
| 1,447 |
import Foundation
import RxSwift
import RxCocoa
import RxDataSources
struct FeedbackSection {
typealias Item = FeedbackCellModel
var header: String
var items: [Item]
}
extension FeedbackSection: SectionModelType {
init(original: FeedbackSection, items: [Item]) {
self = original
self.items = items
}
}
/// === Glue ===
struct FeedbackCellModel {
let reason: Feedback
let isSelected: Bool
}
public class Feedback {
public let title: String
public let acceptsComment: Bool
public init(title: String, acceptsComment: Bool) {
self.title = title
self.acceptsComment = acceptsComment
}
}
protocol FeedbackCoordinatorType {
var reasons: Observable<[Feedback]> { get }
func submit(reason: Feedback, comment: String) -> Completable
}
class FeedbackCoordinator: FeedbackCoordinatorType {
var reasons: Observable<[Feedback]> {
Observable.just([
Feedback(title: "App is amazing", acceptsComment: false),
Feedback(title: "App needs improvement", acceptsComment: true),
Feedback(title: "App is good but can be improved", acceptsComment: true),
Feedback(title: "App does not need any improvement so no need to take comments either.", acceptsComment: false),
])
}
func submit(reason: Feedback, comment: String) -> Completable {
Observable<Void>.empty().ignoreElements()
}
}
| 26.309091 | 124 | 0.671044 |
ac39317d939ec5bf2c3df0f36eb4173d252ff77e
| 329 |
//
// IT.swift
// music
//
// Created by Jz D on 2020/1/21.
// Copyright © 2020 dengjiangzhou. All rights reserved.
//
import Foundation
struct DataOne {
static let std = DataOne()
let kinds = ["IT 公论"]
let datas = [["191 你说 Tim Cook 未来会不会去竞选美国总统?"]]
let sourceDicts = ["0_0": "190_IT"]
}
| 12.185185 | 56 | 0.580547 |
034cf270f5ec1a6db85cc9c0239e77c945af7091
| 1,178 |
//
// ScheduleGroupEntityListing.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class ScheduleGroupEntityListing: Codable {
public var entities: [ScheduleGroup]?
public var pageSize: Int?
public var pageNumber: Int?
public var total: Int64?
public var firstUri: String?
public var selfUri: String?
public var nextUri: String?
public var previousUri: String?
public var lastUri: String?
public var pageCount: Int?
public init(entities: [ScheduleGroup]?, pageSize: Int?, pageNumber: Int?, total: Int64?, firstUri: String?, selfUri: String?, nextUri: String?, previousUri: String?, lastUri: String?, pageCount: Int?) {
self.entities = entities
self.pageSize = pageSize
self.pageNumber = pageNumber
self.total = total
self.firstUri = firstUri
self.selfUri = selfUri
self.nextUri = nextUri
self.previousUri = previousUri
self.lastUri = lastUri
self.pageCount = pageCount
}
}
| 22.653846 | 206 | 0.617997 |
87197a495057dc9921a54e8f05656fd17d1a90b6
| 3,851 |
// Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import UIKit
protocol HomeLayoutDelegate: AnyObject {
func homeLayoutSection(for sectionIndex: Int) -> HomeViewController.Section?
}
extension UICollectionViewLayout {
class func homeLayout(delegate: HomeLayoutDelegate) -> UICollectionViewLayout {
let sectionProvider: UICollectionViewCompositionalLayoutSectionProvider = { sectionIndex, layoutEnvironment -> NSCollectionLayoutSection? in
guard let homeSection = delegate.homeLayoutSection(for: sectionIndex) else { return nil }
let section = layoutSection(for: homeSection, layoutEnvironment: layoutEnvironment)
return section
}
let config = UICollectionViewCompositionalLayoutConfiguration()
config.interSectionSpacing = 32.0
let layout = UICollectionViewCompositionalLayout(sectionProvider: sectionProvider, configuration: config)
layout.register(SectionSystemBackgroundDecorationView.self, forDecorationViewOfKind: SectionSystemBackgroundDecorationView.reusableViewIdentifier)
return layout
}
private static func layoutSection(for section: HomeViewController.Section, layoutEnvironment _: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection {
switch section {
case .actions:
return mainSection()
case .infos:
return infoSection()
case .settings:
return settingsSection()
}
}
private static func mainSection() -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(300.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(1000.0))
let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0.0, leading: 16.0, bottom: 0.0, trailing: 16.0)
section.interGroupSpacing = 32.0
let sectionBackgroundDecoration = NSCollectionLayoutDecorationItem.background(elementKind: SectionSystemBackgroundDecorationView.reusableViewIdentifier)
section.decorationItems = [sectionBackgroundDecoration]
return section
}
private static func infoSection() -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(100.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(100.0))
let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
return section
}
private static func settingsSection() -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(50.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(50.0))
let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
return section
}
}
| 41.408602 | 158 | 0.793041 |
8f9787a982d6f1f750d8afa23eac97ac5640ef47
| 299 |
//
// UIFont+Extension.swift
//
// Created by penguin on 2019/6/21.
// Copyright © 2019 Penguin. All rights reserved.
//
import Foundation
import UIKit
public extension UIFont {
/// 按钮字体
class func buttonFont() -> UIFont {
return UIFont.systemFont(ofSize: 14)
}
}
| 15.736842 | 50 | 0.632107 |
90922d46f87b59818401698cb8814e0a11f8fde0
| 247 |
//
// CatigoriesController.swift
// Budget Blocks
//
// Created by Lambda_School_Loaner_218 on 4/20/20.
// Copyright © 2020 Isaac Lyons. All rights reserved.
//
import Foundation
import CoreData
class CatigoriesController {
}
| 14.529412 | 54 | 0.696356 |
46ce83b12080e42c813e28185873019c4c561b35
| 345 |
//
// TextCellItem.swift
// RSFormView
//
// Created by Mauricio Cousillas on 6/20/19.
//
import Foundation
/**
Plain text row, no inputs.
*/
public final class TextCellItem: FormItem {
override public var cellIdentifier: String {
return FormTextCell.reuseIdentifier
}
public convenience init() {
self.init(with: [])
}
}
| 15.681818 | 46 | 0.681159 |
aca7609715afe828a6f10dd57fa73736671cda9f
| 1,320 |
// The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol ViewModel: Equatable {
}
public func ==<T>(lhs: T, rhs: T) -> Bool where T: ViewModel, T: AnyObject {
lhs === rhs
}
| 38.823529 | 81 | 0.734091 |
337c83b6ebf560a68510427ecd5a711dd41565f0
| 2,429 |
//
// GithubOAuthClient.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/04/09.
// Copyright GrooveLab
//
final class LineOAuthClient : OAuthClient {
let clientId: String
let clientSecret: String
let state: String = String.randomString(10)
required init(clientId: String, clientSecret: String) {
self.clientId = clientId
self.clientSecret = clientSecret
}
func authUrl(redirectUri: String) -> String {
return "https://access.line.me/dialog/oauth/weblogin?response_type=code&client_id=\(clientId)&redirect_uri=\(redirectUri)&state=\(state)"
}
func getAccessToken(code: String, extraData: String = "") throws -> String {
let url = "https://api.line.me/v1/oauth/accessToken"
/*
response example
success : {"access_token":"hoge","token_type":"bearer","scope":""}
error : {"error":"bad_verification_code","error_description":"The code passed is incorrect or expired.","error_uri":"https://developer.github.com/v3/oauth/#bad-verification-code"}
*/
guard let jsonObject = try request(url, headers: ["Content-Type": "application/x-www-form-urlencoded"], postParams: [
"grant_type": "authorization_code",
"client_id": clientId,
"client_secret": clientSecret,
"code": code,
"redirect_uri": extraData
]) else { throw OAuthClientError.Fail("jsonObject") }
guard let jsonMap = jsonObject as? [String: Any] else { throw OAuthClientError.Fail("jsonMap") }
guard let accessToken = jsonMap["access_token"] as? String else { throw OAuthClientError.Fail("accessToken") }
return accessToken
}
func getSocialUser(accessToken: String) throws -> OAuthSocialUser {
let url = "https://api.line.me//v1/profile"
/*
response example
{"login":"user name","id":1}
*/
guard let jsonObject = try request(url, headers: ["Authorization": "Bearer \(accessToken)"]) else { throw OAuthClientError.Fail("jsonObject") }
guard let jsonMap = jsonObject as? [String: Any] else { throw OAuthClientError.Fail("jsonMap") }
guard let id = jsonMap["mid"] as? String else { throw OAuthClientError.Fail("id")}
guard let name = jsonMap["displayName"] as? String else { throw OAuthClientError.Fail("name") }
return (id: id, name: name)
}
}
| 44.163636 | 190 | 0.639769 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.