repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
anilkumarbp/ringcentral-swift-v2 | RingCentral/Platform/Platform.swift | 1 | 11149 | //
// Platform.swift
// RingCentral.
//
// Created by Anil Kumar BP on 2/10/16
// Copyright © 2016 Anil Kumar BP. All rights reserved..
//
import Foundation
/// Platform used to call HTTP request methods.
public class Platform {
// platform Constants
public let ACCESS_TOKEN_TTL = "3600"; // 60 minutes
public let REFRESH_TOKEN_TTL = "604800"; // 1 week
public let TOKEN_ENDPOINT = "/restapi/oauth/token";
public let REVOKE_ENDPOINT = "/restapi/oauth/revoke";
public let API_VERSION = "v1.0";
public let URL_PREFIX = "/restapi";
// Platform credentials
internal var auth: Auth
internal var client: Client
internal let server: String
internal let appKey: String
internal let appSecret: String
internal var appName: String
internal var appVersion: String
internal var USER_AGENT: String
// Creating an enum
/// Constructor for the platform of the SDK
///
/// - parameter appKey: The appKey of your app
/// - parameter appSecet: The appSecret of your app
/// - parameter server: Choice of PRODUCTION or SANDBOX
public init(client: Client, appKey: String, appSecret: String, server: String, appName: String = "", appVersion: String = "") {
self.appKey = appKey
self.appName = appName != "" ? appName : "Unnamed"
self.appVersion = appVersion != "" ? appVersion : "0.0.0"
self.appSecret = appSecret
self.server = server
self.auth = Auth()
self.client = client
self.USER_AGENT = "Swift :" + "/App Name : " + appName + "/App Version :" + appVersion + "/Current iOS Version :" + "/RCSwiftSDK";
}
// Returns the auth object
///
public func returnAuth() -> Auth {
return self.auth
}
/// func createUrl
///
/// @param: path The username of the RingCentral account
/// @param: options The password of the RingCentral account
/// @response: ApiResponse The password of the RingCentral account
public func createUrl(path: String, options: [String: AnyObject]) -> String {
var builtUrl = ""
if(options["skipAuthCheck"] === true){
builtUrl = builtUrl + self.server + path
return builtUrl
}
builtUrl = builtUrl + self.server + self.URL_PREFIX + "/" + self.API_VERSION + path
return builtUrl
}
/// Authenticates the user with the correct credentials
///
/// - parameter username: The username of the RingCentral account
/// - parameter password: The password of the RingCentral account
public func login(username: String, ext: String, password: String, completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) {
requestToken(self.TOKEN_ENDPOINT,body: [
"grant_type": "password",
"username": username,
"extension": ext,
"password": password,
"access_token_ttl": self.ACCESS_TOKEN_TTL,
"refresh_token_ttl": self.REFRESH_TOKEN_TTL
]) {
(t,e) in
self.auth.setData(t!.getDict())
completion(apiresponse: t, apiexception: e)
}
}
/// Refreshes the Auth object so that the accessToken and refreshToken are updated.
///
/// **Caution**: Refreshing an accessToken will deplete it's current time, and will
/// not be appended to following accessToken.
public func refresh(completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) throws {
if(!self.auth.refreshTokenValid()){
throw ApiException(apiresponse: nil, error: NSException(name: "Refresh token has expired", reason: "reason", userInfo: nil))
// apiexception
// throw ApiException(apiresponse: nil, error: NSException(name: "Refresh token has expired", reason: "reason", userInfo: nil))
}
requestToken(self.TOKEN_ENDPOINT,body: [
"refresh_token": self.auth.refreshToken(),
"grant_type": "refresh_token",
"access_token_ttl": self.ACCESS_TOKEN_TTL,
"refresh_token_ttl": self.REFRESH_TOKEN_TTL
]) {
(t,e) in
self.auth.setData(t!.getDict())
completion(apiresponse: t, apiexception: e)
}
}
/// func inflateRequest ()
///
/// @param: request NSMutableURLRequest
/// @param: options list of options
/// @response: NSMutableURLRequest
public func inflateRequest(request: NSMutableURLRequest, options: [String: AnyObject], completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) -> NSMutableURLRequest {
if options["skipAuthCheck"] == nil {
ensureAuthentication() {
(t,e) in
completion(apiresponse: t, apiexception: e)
}
let authHeader = self.auth.tokenType() + " " + self.auth.accessToken()
request.setValue(authHeader, forHTTPHeaderField: "Authorization")
request.setValue(self.USER_AGENT, forHTTPHeaderField: "User-Agent")
}
return request
}
/// func sendRequest ()
///
/// @param: request NSMutableURLRequest
/// @param: options list of options
/// @response: ApiResponse Callback
public func sendRequest(request: NSMutableURLRequest, options: [String: AnyObject]!, completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) {
do{
try client.send(inflateRequest(request, options: options){
(t,e) in
completion(apiresponse: t, apiexception: e)
}) {
(t,e) in
completion(apiresponse: t, apiexception: e)
}
} catch {
print("error")
}
}
/// func requestToken ()
///
/// @param: path The token endpoint
/// @param: array The body
/// @return ApiResponse
func requestToken(path: String, body: [String:AnyObject], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let authHeader = "Basic" + " " + self.apiKey()
var headers: [String: String] = [:]
headers["Authorization"] = authHeader
headers["Content-type"] = "application/x-www-form-urlencoded;charset=UTF-8"
headers["User-Agent"] = self.USER_AGENT
var options: [String: AnyObject] = [:]
options["skipAuthCheck"] = true
let urlCreated = createUrl(path,options: options)
sendRequest(self.client.createRequest("POST", url: urlCreated, query: nil, body: body, headers: headers), options: options){
(r,e) in
completion(apiresponse: r,exception: e)
}
}
/// Base 64 encoding
func apiKey() -> String {
let plainData = (self.appKey + ":" + self.appSecret as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
return base64String
}
/// Logs the user out of the current account.
///
/// Kills the current accessToken and refreshToken.
public func logout(completion: (apiresponse: ApiResponse?,apiexception: NSException?) -> Void) {
requestToken(self.TOKEN_ENDPOINT,body: [
"token": self.auth.accessToken()
]) {
(t,e) in
self.auth.reset()
completion(apiresponse: t, apiexception: e)
}
}
/// Check if the accessToken is valid
func ensureAuthentication(completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
if (!self.auth.accessTokenValid()) {
do{
try refresh() {
(r,e) in
completion(apiresponse: r,exception: e)
}
} catch {
print("error")
}
}
}
// Generic Method calls ( HTTP ) GET
///
/// @param: url token endpoint
/// @param: query body
/// @return ApiResponse Callback
public func get(url: String, query: [String: String]?=["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("GET", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
// Generic Method calls ( HTTP ) POST
///
/// @param: url token endpoint
/// @param: body body
/// @return ApiResponse Callback
public func post(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("POST", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
// Generic Method calls ( HTTP ) PUT
///
/// @param: url token endpoint
/// @param: body body
/// @return ApiResponse Callback
public func put(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("PUT", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
// Generic Method calls ( HTTP ) DELETE
///
/// @param: url token endpoint
/// @param: query body
/// @return ApiResponse Callback
public func delete(url: String, query: [String: String] = ["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
let urlCreated = createUrl(url,options: options!)
sendRequest(self.client.createRequest("DELETE", url: urlCreated, query: query, body: body, headers: headers!), options: options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
}
| mit |
natecook1000/swift | test/Migrator/post_fixit_pass.swift | 2 | 633 | // RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/post_fixit_pass.swift.result -o /dev/null -F %S/mock-sdk -swift-version 3
// RUN: diff -u %S/post_fixit_pass.swift.expected %t/post_fixit_pass.swift.result
#if swift(>=4)
public struct SomeAttribute: RawRepresentable {
public init(rawValue: Int) { self.rawValue = rawValue }
public init(_ rawValue: Int) { self.rawValue = rawValue }
public var rawValue: Int
public typealias RawValue = Int
}
#else
public typealias SomeAttribute = Int
#endif
func foo(_ d: SomeAttribute) {
let i: Int = d
}
| apache-2.0 |
practicalswift/swift | validation-test/Evolution/test_backward_deploy_always_emit_into_client.swift | 1 | 397 | // RUN: %target-resilience-test --backward-deployment
// REQUIRES: executable_test
import StdlibUnittest
import backward_deploy_always_emit_into_client
var BackwardDeployTopLevelTest = TestSuite("BackwardDeployAlwaysEmitIntoClient")
BackwardDeployTopLevelTest.test("BackwardDeployAlwaysEmitIntoClient") {
expectEqual(serializedFunction(), getVersion() == 1 ? "new" : "old")
}
runAllTests()
| apache-2.0 |
practicalswift/swift | test/SILGen/mangling_private.swift | 4 | 3759 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -enable-sil-ownership -emit-module -o %t %S/Inputs/mangling_private_helper.swift
// RUN: %target-swift-emit-silgen -enable-sil-ownership %S/Inputs/mangling_private_helper.swift | %FileCheck %s -check-prefix=CHECK-BASE
// RUN: %target-swift-emit-silgen %s -I %t -enable-sil-ownership | %FileCheck %s
// RUN: cp %s %t
// RUN: %target-swift-emit-silgen %t/mangling_private.swift -I %t -enable-sil-ownership | %FileCheck %s
// RUN: cp %s %t/other_name.swift
// RUN: %target-swift-emit-silgen %t/other_name.swift -I %t -enable-sil-ownership -module-name mangling_private | %FileCheck %s -check-prefix=OTHER-NAME
import mangling_private_helper
// CHECK-LABEL: sil private [ossa] @$s16mangling_private0B4Func33_A3CCBB841DB59E79A4AD4EE458655068LLSiyF
// OTHER-NAME-LABEL: sil private [ossa] @$s16mangling_private0B4Func33_CF726049E48876D30EA29D63CF139F1DLLSiyF
private func privateFunc() -> Int {
return 0
}
public struct PublicStruct {
// CHECK-LABEL: sil private [ossa] @$s16mangling_private12PublicStructV0B6Method33_A3CCBB841DB59E79A4AD4EE458655068LLyyFZ
private static func privateMethod() {}
// CHECK-LABEL: sil private [ossa] @$s16mangling_private12PublicStructV1xACSi_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
private init(x: Int) {}
}
public struct InternalStruct {
// CHECK-LABEL: sil private [ossa] @$s16mangling_private14InternalStructV0B6Method33_A3CCBB841DB59E79A4AD4EE458655068LLyyFZ
private static func privateMethod() {}
// CHECK-LABEL: sil private [ossa] @$s16mangling_private14InternalStructV1xACSi_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
private init(x: Int) {}
}
private struct PrivateStruct {
// CHECK-LABEL: sil private [ossa] @$s16mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV0B6MethodyyFZ
private static func privateMethod() {}
// CHECK-LABEL: sil private [ossa] @$s16mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV1xADSi_tcfC
private init(x: Int) {}
struct Inner {
// CHECK-LABEL: sil private [ossa] @$s16mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV5InnerV0B6MethodyyFZ
private static func privateMethod() {}
// CHECK-LABEL: sil private [ossa] @$s16mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV5InnerV1xAFSi_tcfC
private init(x: Int) {}
}
}
func localTypes() {
struct LocalStruct {
private static func privateMethod() {}
}
}
extension PublicStruct {
// CHECK-LABEL: sil private [ossa] @$s16mangling_private12PublicStructV16extPrivateMethod33_A3CCBB841DB59E79A4AD4EE458655068LLyyF
private func extPrivateMethod() {}
// CHECK-LABEL: sil private [ossa] @$s16mangling_private12PublicStructV3extACSi_tc33_A3CCBB841DB59E79A4AD4EE458655068LlfC
private init(ext: Int) {}
}
extension PrivateStruct {
// CHECK-LABEL: sil private [ossa] @$s16mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV03extC6MethodyyF
private func extPrivateMethod() {}
// CHECK-LABEL: sil private [ossa] @$s16mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV3extADSi_tcfC
private init(ext: Int) {}
}
// CHECK-LABEL: sil private [ossa] @$s16mangling_private10localTypesyyF11LocalStructL_V0B6MethodyyFZ
// CHECK-LABEL: sil_vtable Sub {
class Sub : Base {
// CHECK-BASE: #Base.privateMethod!1: {{.*}} : @$s23mangling_private_helper4BaseC0B6Method33_0E108371B0D5773E608A345AC52C7674LLyyF
// CHECK-DAG: #Base.privateMethod!1: {{.*}} : @$s23mangling_private_helper4BaseC0B6Method33_0E108371B0D5773E608A345AC52C7674LLyyF
// CHECK-DAG: #Sub.subMethod!1: {{.*}} : @$s16mangling_private3SubC9subMethod33_A3CCBB841DB59E79A4AD4EE458655068LLyyF
private func subMethod() {}
} // CHECK: {{^[}]$}}
| apache-2.0 |
gizmosachin/VolumeBar | Sources/VolumeBar.swift | 1 | 4034 | //
// VolumeBar.swift
//
// Copyright (c) 2016-Present Sachin Patel (http://gizmosachin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import AudioToolbox
import MediaPlayer
public final class VolumeBar {
/// The shared VolumeBar singleton.
public static let shared = VolumeBar()
/// The stack view that displays the volume bar.
public var view: UIStackView?
// MARK: Animation
/// The minimum visible duration that VolumeBar will appear on screen after a volume button is pressed.
/// If VolumeBar is already showing and a volume button is pressed, VolumeBar will continue to show
/// and the duration it's displayed on screen will be extended by this number of seconds.
public var minimumVisibleDuration: TimeInterval = 1.5
/// The animation used to show VolumeBar.
public var showAnimation: VolumeBarAnimation = .fadeIn
/// The animation used to hide VolumeBar.
public var hideAnimation: VolumeBarAnimation = .fadeOut
// MARK: Style
/// The current style of VolumeBar.
public var style: VolumeBarStyle = VolumeBarStyle() {
didSet {
window?.apply(style: style)
if let stackView = view as? VolumeBarStackView {
stackView.apply(style: style)
}
}
}
// MARK: Internal
internal var window: VolumeBarWindow?
internal var timer: Timer?
internal var systemVolumeManager: SystemVolumeManager?
}
public extension VolumeBar {
// MARK: Lifecycle
/// Start VolumeBar and automatically show when the volume changes.
func start() {
// If we have a systemVolumeManager, we're already started.
guard systemVolumeManager == nil else { return }
let stackView = VolumeBarStackView()
stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let viewController = UIViewController()
viewController.view.addSubview(stackView)
self.view = stackView
self.window = VolumeBarWindow(viewController: viewController)
// Initial style
stackView.apply(style: style)
window?.apply(style: style)
// Start observing changes in system volume
systemVolumeManager = SystemVolumeManager()
systemVolumeManager?.addObserver(self)
systemVolumeManager?.addObserver(stackView)
}
/// Stop VolumeBar from automatically showing when the volume changes.
func stop() {
hide()
window = nil
systemVolumeManager = nil
}
}
public extension VolumeBar {
// MARK: Presentation
/// Show VolumeBar immediately using the current `showAnimation`.
func show() {
// Invalidate the timer and extend the on-screen duration
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: minimumVisibleDuration, target: self, selector: #selector(VolumeBar.hide), userInfo: nil, repeats: false)
window?.show(withAnimation: showAnimation)
}
/// Show VolumeBar immediately using the current `hideAnimation`.
@objc func hide() {
window?.hide(withAnimation: hideAnimation)
}
}
extension VolumeBar: SystemVolumeObserver {
internal func volumeChanged(to volume: Float) {
show()
}
}
| mit |
huangboju/Moots | Examples/Lumia/Lumia/Component/StateMachine/StateMachine.swift | 1 | 1717 | //
// StateMachine.swift
// Redstone
//
// Created by nixzhu on 2017/1/6.
// Copyright © 2017年 nixWork. All rights reserved.
//
public class StateMachine<State: Hashable, Transition: Hashable> {
public typealias Operation = () -> Void
private var body = [State: Operation?]()
public private(set) var previousState: State?
public private(set) var lastTransition: Transition?
public private(set) var currentState: State? {
willSet {
previousState = currentState
}
didSet {
if let state = currentState {
body[state]??()
}
}
}
public var initialState: State? {
didSet {
if oldValue == nil, initialState != nil {
currentState = initialState
}
}
}
private var stateTransitionTable: [State: [Transition: State]] = [:]
public init() {
}
public func add(state: State, entryOperation: Operation?) {
body[state] = entryOperation
}
public func add(transition: Transition, fromState: State, toState: State) {
var bag = stateTransitionTable[fromState] ?? [:]
bag[transition] = toState
stateTransitionTable[fromState] = bag
}
public func add(transition: Transition, fromStates: Set<State>, toState: State) {
fromStates.forEach {
add(transition: transition, fromState: $0, toState: toState)
}
}
public func fire(transition: Transition) {
guard let state = currentState else { return }
guard let toState = stateTransitionTable[state]?[transition] else { return }
lastTransition = transition
currentState = toState
}
}
| mit |
ayshrimali/Appium-UIAutomation | testProjects/iOS/Appium-UIAutomation/Appium-UIAutomation/HomeViewController.swift | 1 | 439 | //
// HomeViewController.swift
// Appium-UIAutomation
//
// Created by Anjum Shrimali on 4/5/17.
// Copyright © 2017 IshiSystems. All rights reserved.
//
import Foundation
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var txtWelcome: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
txtWelcome.text = "Welcome \(Utility.shared.displayName!)!"
}
}
| apache-2.0 |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDKTests/MercadoPagoSDKTests.swift | 3 | 923 | //
// MercadoPagoSDKTests.swift
// MercadoPagoSDKTests
//
// Created by Matias Gualino on 6/4/15.
// Copyright (c) 2015 MercadoPago. All rights reserved.
//
import UIKit
import XCTest
class MercadoPagoSDKTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
dvor/TextWiki | TextWikiTests/Modules/Application/Factory/ApplicationModuleFactoryTests.swift | 1 | 1696 | //
// ApplicationModuleFactoryTests.swift
// TextWiki
//
// Created by Dmytro Vorobiov on 23/05/2017.
// Copyright © 2017 Dmytro Vorobiov. All rights reserved.
//
import XCTest
class ApplicationModuleFactoryTests: 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 testCreate() {
//when
let (_, vc) = ApplicationModuleFactory.create()
guard let viewController = vc as? ApplicationViewController else {
XCTAssertTrue(false, "viewController should be ApplicationViewController class")
return
}
//then
XCTAssertNotNil(viewController.output, "ApplicationViewController is nil after configuration")
XCTAssertTrue(viewController.output is ApplicationPresenter, "output is not ApplicationPresenter")
let presenter: ApplicationPresenter = viewController.output as! ApplicationPresenter
XCTAssertNotNil(presenter.view, "view in ApplicationPresenter is nil after configuration")
XCTAssertNotNil(presenter.router, "router in ApplicationPresenter is nil after configuration")
XCTAssertTrue(presenter.router is ApplicationRouter, "router is not ApplicationRouter")
let interactor: ApplicationInteractor = presenter.interactor as! ApplicationInteractor
XCTAssertNotNil(interactor.output, "output in ApplicationInteractor is nil after configuration")
}
}
| mit |
coderMONSTER/iosstar | iOSStar/Model/DealModel/DealModel.swift | 1 | 2346 |
//
// DealModel.swift
// iOSStar
//
// Created by J-bb on 17/6/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import Foundation
import RealmSwift
class EntrustSuccessModel: Object {
dynamic var amount = 0
dynamic var buySell = 2
dynamic var id = 132
dynamic var openPrice = 13.0
dynamic var positionId:Int64 = 0
dynamic var positionTime:Int64 = 1496920841
dynamic var symbol = ""
}
class ReceiveMacthingModel: Object {
dynamic var buyUid = 0
dynamic var sellUid = 0
dynamic var openPositionTime:Int64 = 0
dynamic var openPrice:Double = 1.00
dynamic var orderId:Int64 = 2371231398736937636
dynamic var symbol = "1001"
dynamic var amount = 0
override static func primaryKey() -> String?{
return "orderId"
}
func cacheSelf() {
let realm = try! Realm()
try! realm.write {
realm.add(self, update: true)
}
}
class func getData() -> ReceiveMacthingModel? {
let realm = try! Realm()
let results = realm.objects(ReceiveMacthingModel.self)
return results.first
}
}
class SureOrderResultModel: Object {
dynamic var orderId:Int64 = 0
dynamic var status:Int32 = 0
}
class OrderResultModel: Object {
dynamic var orderId:Int64 = 0
dynamic var result:Int32 = 0
}
class EntrustListModel: Object {
dynamic var rtAmount = 0
dynamic var amount:Int64 = 0
dynamic var buySell = AppConst.DealType.buy.rawValue
dynamic var handle:Int32 = AppConst.OrderStatus.pending.rawValue
dynamic var id:Int64 = 142
dynamic var openCharge:Double = 0.0
dynamic var openPrice:Double = 0.0
dynamic var positionId:Int64 = 0
dynamic var positionTime:Int64 = 0
dynamic var symbol = ""
}
class OrderListModel: Object {
dynamic var amount:Int64 = 0
dynamic var buyUid:Int64 = 0
dynamic var sellUid:Int64 = 0
dynamic var closeTime:Int64 = 0
dynamic var grossProfit:Double = 0.0
dynamic var openCharge:Double = 0.0
dynamic var openTime:Int64 = 0
dynamic var orderId:Int64 = 0
dynamic var positionId:Int64 = 0
dynamic var result = false
dynamic var symbol = ""
dynamic var handle:Int32 = 0
dynamic var buyHandle:Int32 = 0
dynamic var sellHandle:Int32 = 0
dynamic var openPrice = 0.0
}
| gpl-3.0 |
svachmic/ios-url-remote | URLRemote/Classes/Controllers/ActionsCollectionViewController.swift | 1 | 10367 | //
// ActionsCollectionViewController.swift
// URLRemote
//
// Created by Svacha, Michal on 30/05/16.
// Copyright © 2016 Svacha, Michal. All rights reserved.
//
import UIKit
import Material
import Bond
import ReactiveKit
///
class ActionsCollectionViewController: UICollectionViewController, PersistenceStackController {
var stack: PersistenceStack! {
didSet {
viewModel = ActionsViewModel()
}
}
var viewModel: ActionsViewModel!
var menu: FABMenu?
var pageControl: UIPageControl?
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.isPagingEnabled = true
collectionView?.backgroundColor = UIColor(named: .gray)
collectionView?.register(CategoryViewCell.self, forSupplementaryViewOfKind: "header", withReuseIdentifier: Constants.CollectionViewCell.header)
self.setupNavigationController()
self.setupMenu()
self.setLoginNotifications()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - View setup
///
func setupNavigationController() {
let navigationController = self.navigationController as? ApplicationNavigationController
navigationController?.prepare()
navigationController?.statusBarStyle = .lightContent
navigationController?.navigationBar.barTintColor = UIColor(named: .yellow)
let logout = FlatButton(title: NSLocalizedString("LOGOUT", comment: ""))
logout.apply(Stylesheet.General.flatButton)
logout.reactive.tap.bind(to: self) { me, _ in
me.stack.authentication.logOut()
}.dispose(in: bag)
self.navigationItem.leftViews = [logout]
let settingsButton = MaterialFactory.genericIconButton(image: Icon.cm.settings)
settingsButton.reactive.tap.bind(to: self) { _, _ in
print("Settings coming soon!")
}.dispose(in: bag)
let editButton = MaterialFactory.genericIconButton(image: Icon.cm.edit)
editButton.reactive.tap.bind(to: self) { me, _ in
me.displayEditCategory()
}.dispose(in: bag)
self.navigationItem.rightViews = [editButton, settingsButton]
self.navigationItem.titleLabel.textColor = .white
self.navigationItem.detailLabel.textColor = .white
self.navigationItem.titleLabel.text = "URLRemote"
self.navigationItem.detailLabel.text = "Making your IoT awesome!"
}
///
func setLoginNotifications() {
stack.authentication
.dataSource()
.observeNext {
if let src = $0 {
self.viewModel.dataSource.value = src
self.setupCollectionDataSource()
} else {
self.viewModel.dataSource.value = nil
self.resetCollectionDataSource()
self.displayLogin()
}
}
.dispose(in: bag)
}
///
func setupCollectionDataSource() {
pageControl = UIPageControl()
pageControl?.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.4)
pageControl?.currentPageIndicatorTintColor = UIColor.lightGray
self.view.layout(pageControl!).bottom(30.0).centerHorizontally()
viewModel.data.bind(to: self) { me, data in
me.pageControl?.numberOfPages = data.dataSource.numberOfSections
me.collectionView?.reloadData()
me.collectionView?.collectionViewLayout.invalidateLayout()
}.dispose(in: bag)
}
///
func resetCollectionDataSource() {
pageControl?.removeFromSuperview()
collectionView?.contentOffset = CGPoint(x: 0, y: 0)
collectionView?.collectionViewLayout.invalidateLayout()
}
/// MARK: - ViewController presentation
///
func displayLogin() {
let loginController = self.storyboard?.instantiateViewController(withIdentifier: Constants.StoryboardID.login) as! LoginTableViewController
loginController.stack = stack
self.presentEmbedded(viewController: loginController, barTintColor: UIColor(named: .green))
}
///
func displayEntrySetup() {
let entryController = self.storyboard?.instantiateViewController(withIdentifier: Constants.StoryboardID.entrySetup) as! EntrySetupViewController
entryController.stack = stack
self.presentEmbedded(viewController: entryController, barTintColor: UIColor(named: .green))
}
///
func displayCategorySetup() {
let categoryDialog = AlertDialogBuilder
.dialog(title: "NEW_CATEGORY", text: "NEW_CATEGORY_DESC")
.cancelAction()
let okAction = UIAlertAction(
title: NSLocalizedString("OK", comment: ""),
style: .default,
handler: { _ in
if let textFields = categoryDialog.textFields, let textField = textFields[safe: 0], let text = textField.text, text != "" {
self.viewModel.createCategory(named: text)
}
})
categoryDialog.addAction(okAction)
categoryDialog.addTextField { textField in
textField.placeholder = NSLocalizedString("NEW_CATEGORY_PLACEHOLDER", comment: "")
textField.reactive
.isEmpty
.bind(to: okAction.reactive.enabled)
.dispose(in: categoryDialog.bag)
}
self.present(categoryDialog, animated: true, completion: nil)
}
///
func displayEditCategory() {
let visibleSection = collectionView?.indexPathsForVisibleSupplementaryElements(ofKind: "header")[safe: 0]?.section ?? 0
let editCategoryController = self.storyboard?.instantiateViewController(withIdentifier: Constants.StoryboardID.categoryEdit) as! CategoryEditTableViewController
editCategoryController.stack = stack
let category = viewModel.data[visibleSection].metadata
editCategoryController.viewModel.category = category
self.presentEmbedded(viewController: editCategoryController, barTintColor: UIColor(named: .green))
}
// MARK: - Collection view data source methods
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.width
let currentPage = Int(floor((scrollView.contentOffset.x - pageWidth / 2.0) / pageWidth) + 1.0)
pageControl?.currentPage = currentPage
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
collectionView.collectionViewLayout.invalidateLayout()
return viewModel.data.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.data[section].items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: Constants.CollectionViewCell.entry,
for: indexPath) as! ActionViewCell
cell.setUpView()
// Dispose all bindings because the cell objects are reused.
cell.bag.dispose()
cell.bind(with: viewModel.data[indexPath.section].items[indexPath.row])
return cell
}
@objc(collectionView:viewForSupplementaryElementOfKind:atIndexPath:)
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: "header", withReuseIdentifier: Constants.CollectionViewCell.header, for: indexPath) as! CategoryViewCell
header.setUpView()
header.bind(with: viewModel.data[indexPath.section].metadata)
return header
}
}
//
extension ActionsCollectionViewController: FABMenuDelegate {
///
private func genericMenuItem(image: String, title: String) -> FABMenuItem {
let item = FABMenuItem()
item.fabButton.image = UIImage(named: image)
item.fabButton.apply(Stylesheet.Actions.fabButton)
item.title = NSLocalizedString(title, comment: "")
return item
}
///
private func menuEntryItem() -> FABMenuItem {
let entryItem = genericMenuItem(image: "new_entry", title: "NEW_ENTRY")
entryItem.fabButton.depthPreset = .depth1
entryItem.fabButton.reactive.tap.observeNext { [weak self] in
self?.menu?.toggle()
self?.displayEntrySetup()
}.dispose(in: bag)
return entryItem
}
///
private func menuCategoryItem() -> FABMenuItem {
let categoryItem = genericMenuItem(image: "new_category", title: "NEW_CATEGORY")
categoryItem.fabButton.reactive.tap.observeNext { [weak self] in
self?.menu?.toggle()
self?.displayCategorySetup()
}.dispose(in: bag)
return categoryItem
}
///
func setupMenu() {
self.menu = FABMenu()
let addButton = FABButton(image: Icon.cm.add, tintColor: .white)
addButton.frame = CGRect(x: 0.0, y: 0.0, width: 48.0, height: 48.0)
addButton.pulseColor = .white
addButton.backgroundColor = UIColor(named: .green).darker()
addButton.reactive.tap
.observeNext { [weak self] in self?.menu?.toggle() }
.dispose(in: bag)
menu?.delegate = self
menu?.fabButton = addButton
menu?.fabMenuItems = [menuEntryItem(), menuCategoryItem()]
menu?.fabMenuItemSize = CGSize(width: 40.0, height: 40.0)
view.layout(menu!).size(addButton.frame.size).bottom(30).right(30)
}
/// MARK: - Menu delegate method
///
public func fabMenu(fabMenu menu: FABMenu, tappedAt point: CGPoint, isOutside: Bool) {
if isOutside {
menu.toggle()
}
}
}
| apache-2.0 |
netguru/inbbbox-ios | Inbbbox/Source Files/Managers/AutoScrollableShotsDataSource.swift | 1 | 3668 | //
// AutoScrollableShotsDataSource.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 28/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
class AutoScrollableShotsDataSource: NSObject {
fileprivate typealias AutoScrollableImageContent = (image: UIImage,
isDuplicateForExtendedContent: Bool)
fileprivate var content: [AutoScrollableImageContent]!
fileprivate(set) var extendedScrollableItemsCount = 0
var itemSize: CGSize {
return CGSize(width: collectionView.bounds.width,
height: collectionView.bounds.width)
}
let collectionView: UICollectionView
init(collectionView: UICollectionView, content: [UIImage]) {
self.collectionView = collectionView
self.content = content.map { ($0, false) }
super.init()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(AutoScrollableCollectionViewCell.self, type: .cell)
prepareExtendedContentToDisplayWithOffset(0)
}
@available(*, unavailable, message: "Use init(collectionView:content:) instead")
override init() {
fatalError("init() has not been implemented")
}
/// Prepares itself for animation and reloads collectionView.
func prepareForAnimation() {
extendedScrollableItemsCount = Int(ceil(collectionView.bounds.height /
itemSize.height))
prepareExtendedContentToDisplayWithOffset(extendedScrollableItemsCount)
collectionView.reloadData()
}
}
// MARK: UICollectionViewDataSource
extension AutoScrollableShotsDataSource: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableClass(AutoScrollableCollectionViewCell.self,
forIndexPath: indexPath,
type: .cell)
cell.imageView.image = content[indexPath.row].image
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return content.count
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension AutoScrollableShotsDataSource: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return itemSize
}
}
// MARK: Private
private extension AutoScrollableShotsDataSource {
func prepareExtendedContentToDisplayWithOffset(_ offset: Int) {
let images = content.filter { !$0.isDuplicateForExtendedContent }
var extendedContent = [AutoScrollableImageContent]()
for index in 0..<(images.count + 2 * offset) {
let indexSubscript: Int
var isDuplicateForExtendedContent = true
if index < offset {
indexSubscript = images.count - offset + index
} else if index > images.count + offset - 1 {
indexSubscript = index - images.count - offset
} else {
isDuplicateForExtendedContent = false
indexSubscript = index - offset
}
extendedContent.append((images[indexSubscript].image, isDuplicateForExtendedContent))
}
content = extendedContent
}
}
| gpl-3.0 |
twtstudio/WePeiYang-iOS | WePeiYang/LostFound/Controller/LostFoundPostForm.swift | 1 | 3499 | //
// LostFoundPostForm.swift
// WePeiYang
//
// Created by Qin Yubo on 16/2/15.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
import FXForms
class LostFoundPostForm: NSObject, FXForm {
var postType: Int = 0
var title: String?
var name: String?
var time: NSDate?
var place: String?
var phone: String?
var content: String?
var lostType: String?
var otherTag: String?
var foundPic: String?
func fields() -> [AnyObject]! {
if postType == 0 {
// Lost
return [
[
FXFormFieldHeader: "基本信息",
FXFormFieldTitle: "标题",
FXFormFieldKey: "title"
],
[
FXFormFieldTitle: "类型",
FXFormFieldKey: "lostType",
FXFormFieldOptions: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "0"],
FXFormFieldValueTransformer: LostFoundTypeTransformer()
],
[
FXFormFieldTitle: "时间",
FXFormFieldKey: "time",
FXFormFieldType: FXFormFieldTypeDateTime
],
[
FXFormFieldTitle: "地点",
FXFormFieldKey: "place"
],
[
FXFormFieldHeader: "联系信息",
FXFormFieldTitle: "姓名",
FXFormFieldKey: "name"
],
[
FXFormFieldTitle: "电话",
FXFormFieldKey: "phone",
FXFormFieldType: FXFormFieldTypePhone
],
[
FXFormFieldHeader: "附加信息",
FXFormFieldTitle: "附言",
FXFormFieldKey: "content",
FXFormFieldType: FXFormFieldTypeLongText
],
[
FXFormFieldTitle: "其他类型",
FXFormFieldKey: "otherTag",
FXFormFieldFooter: "如果您在“类型”一栏选择“其他”,您可以在这里填写具体类型。"
]
]
} else {
// Found
return [
[
FXFormFieldHeader: "基本信息",
FXFormFieldTitle: "标题",
FXFormFieldKey: "title"
],
[
FXFormFieldTitle: "时间",
FXFormFieldKey: "time",
FXFormFieldType: FXFormFieldTypeDateTime
],
[
FXFormFieldTitle: "地点",
FXFormFieldKey: "place"
],
[
FXFormFieldHeader: "联系信息",
FXFormFieldTitle: "姓名",
FXFormFieldKey: "name"
],
[
FXFormFieldTitle: "电话",
FXFormFieldKey: "phone",
FXFormFieldType: FXFormFieldTypePhone
],
[
FXFormFieldHeader: "附加信息",
FXFormFieldTitle: "附言",
FXFormFieldKey: "content",
FXFormFieldType: FXFormFieldTypeLongText
]
]
}
}
}
| mit |
fabianwilliams/O365MobileSDKTester | SDKTesterOffice365/SDKTesterOffice365/AppDelegate.swift | 1 | 2165 | //
// AppDelegate.swift
// SDKTesterOffice365
//
// Created by Richard diZerega on 11/17/14.
// Copyright (c) 2014 Richard diZerega. 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:.
}
}
| apache-2.0 |
insidegui/AppleEvents | Dependencies/swift-protobuf/Tests/SwiftProtobufTests/unittest_lite.pb.swift | 6 | 280597 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/protobuf/unittest_lite.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest.proto but with optimize_for = LITE_RUNTIME.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
enum ProtobufUnittest_ForeignEnumLite: SwiftProtobuf.Enum {
typealias RawValue = Int
case foreignLiteFoo // = 4
case foreignLiteBar // = 5
case foreignLiteBaz // = 6
init() {
self = .foreignLiteFoo
}
init?(rawValue: Int) {
switch rawValue {
case 4: self = .foreignLiteFoo
case 5: self = .foreignLiteBar
case 6: self = .foreignLiteBaz
default: return nil
}
}
var rawValue: Int {
switch self {
case .foreignLiteFoo: return 4
case .foreignLiteBar: return 5
case .foreignLiteBaz: return 6
}
}
}
#if swift(>=4.2)
extension ProtobufUnittest_ForeignEnumLite: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
enum ProtobufUnittest_V1EnumLite: SwiftProtobuf.Enum {
typealias RawValue = Int
case v1First // = 1
init() {
self = .v1First
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .v1First
default: return nil
}
}
var rawValue: Int {
switch self {
case .v1First: return 1
}
}
}
#if swift(>=4.2)
extension ProtobufUnittest_V1EnumLite: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
enum ProtobufUnittest_V2EnumLite: SwiftProtobuf.Enum {
typealias RawValue = Int
case v2First // = 1
case v2Second // = 2
init() {
self = .v2First
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .v2First
case 2: self = .v2Second
default: return nil
}
}
var rawValue: Int {
switch self {
case .v2First: return 1
case .v2Second: return 2
}
}
}
#if swift(>=4.2)
extension ProtobufUnittest_V2EnumLite: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
/// Same as TestAllTypes but with the lite runtime.
struct ProtobufUnittest_TestAllTypesLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Singular
var optionalInt32: Int32 {
get {return _storage._optionalInt32 ?? 0}
set {_uniqueStorage()._optionalInt32 = newValue}
}
/// Returns true if `optionalInt32` has been explicitly set.
var hasOptionalInt32: Bool {return _storage._optionalInt32 != nil}
/// Clears the value of `optionalInt32`. Subsequent reads from it will return its default value.
mutating func clearOptionalInt32() {_uniqueStorage()._optionalInt32 = nil}
var optionalInt64: Int64 {
get {return _storage._optionalInt64 ?? 0}
set {_uniqueStorage()._optionalInt64 = newValue}
}
/// Returns true if `optionalInt64` has been explicitly set.
var hasOptionalInt64: Bool {return _storage._optionalInt64 != nil}
/// Clears the value of `optionalInt64`. Subsequent reads from it will return its default value.
mutating func clearOptionalInt64() {_uniqueStorage()._optionalInt64 = nil}
var optionalUint32: UInt32 {
get {return _storage._optionalUint32 ?? 0}
set {_uniqueStorage()._optionalUint32 = newValue}
}
/// Returns true if `optionalUint32` has been explicitly set.
var hasOptionalUint32: Bool {return _storage._optionalUint32 != nil}
/// Clears the value of `optionalUint32`. Subsequent reads from it will return its default value.
mutating func clearOptionalUint32() {_uniqueStorage()._optionalUint32 = nil}
var optionalUint64: UInt64 {
get {return _storage._optionalUint64 ?? 0}
set {_uniqueStorage()._optionalUint64 = newValue}
}
/// Returns true if `optionalUint64` has been explicitly set.
var hasOptionalUint64: Bool {return _storage._optionalUint64 != nil}
/// Clears the value of `optionalUint64`. Subsequent reads from it will return its default value.
mutating func clearOptionalUint64() {_uniqueStorage()._optionalUint64 = nil}
var optionalSint32: Int32 {
get {return _storage._optionalSint32 ?? 0}
set {_uniqueStorage()._optionalSint32 = newValue}
}
/// Returns true if `optionalSint32` has been explicitly set.
var hasOptionalSint32: Bool {return _storage._optionalSint32 != nil}
/// Clears the value of `optionalSint32`. Subsequent reads from it will return its default value.
mutating func clearOptionalSint32() {_uniqueStorage()._optionalSint32 = nil}
var optionalSint64: Int64 {
get {return _storage._optionalSint64 ?? 0}
set {_uniqueStorage()._optionalSint64 = newValue}
}
/// Returns true if `optionalSint64` has been explicitly set.
var hasOptionalSint64: Bool {return _storage._optionalSint64 != nil}
/// Clears the value of `optionalSint64`. Subsequent reads from it will return its default value.
mutating func clearOptionalSint64() {_uniqueStorage()._optionalSint64 = nil}
var optionalFixed32: UInt32 {
get {return _storage._optionalFixed32 ?? 0}
set {_uniqueStorage()._optionalFixed32 = newValue}
}
/// Returns true if `optionalFixed32` has been explicitly set.
var hasOptionalFixed32: Bool {return _storage._optionalFixed32 != nil}
/// Clears the value of `optionalFixed32`. Subsequent reads from it will return its default value.
mutating func clearOptionalFixed32() {_uniqueStorage()._optionalFixed32 = nil}
var optionalFixed64: UInt64 {
get {return _storage._optionalFixed64 ?? 0}
set {_uniqueStorage()._optionalFixed64 = newValue}
}
/// Returns true if `optionalFixed64` has been explicitly set.
var hasOptionalFixed64: Bool {return _storage._optionalFixed64 != nil}
/// Clears the value of `optionalFixed64`. Subsequent reads from it will return its default value.
mutating func clearOptionalFixed64() {_uniqueStorage()._optionalFixed64 = nil}
var optionalSfixed32: Int32 {
get {return _storage._optionalSfixed32 ?? 0}
set {_uniqueStorage()._optionalSfixed32 = newValue}
}
/// Returns true if `optionalSfixed32` has been explicitly set.
var hasOptionalSfixed32: Bool {return _storage._optionalSfixed32 != nil}
/// Clears the value of `optionalSfixed32`. Subsequent reads from it will return its default value.
mutating func clearOptionalSfixed32() {_uniqueStorage()._optionalSfixed32 = nil}
var optionalSfixed64: Int64 {
get {return _storage._optionalSfixed64 ?? 0}
set {_uniqueStorage()._optionalSfixed64 = newValue}
}
/// Returns true if `optionalSfixed64` has been explicitly set.
var hasOptionalSfixed64: Bool {return _storage._optionalSfixed64 != nil}
/// Clears the value of `optionalSfixed64`. Subsequent reads from it will return its default value.
mutating func clearOptionalSfixed64() {_uniqueStorage()._optionalSfixed64 = nil}
var optionalFloat: Float {
get {return _storage._optionalFloat ?? 0}
set {_uniqueStorage()._optionalFloat = newValue}
}
/// Returns true if `optionalFloat` has been explicitly set.
var hasOptionalFloat: Bool {return _storage._optionalFloat != nil}
/// Clears the value of `optionalFloat`. Subsequent reads from it will return its default value.
mutating func clearOptionalFloat() {_uniqueStorage()._optionalFloat = nil}
var optionalDouble: Double {
get {return _storage._optionalDouble ?? 0}
set {_uniqueStorage()._optionalDouble = newValue}
}
/// Returns true if `optionalDouble` has been explicitly set.
var hasOptionalDouble: Bool {return _storage._optionalDouble != nil}
/// Clears the value of `optionalDouble`. Subsequent reads from it will return its default value.
mutating func clearOptionalDouble() {_uniqueStorage()._optionalDouble = nil}
var optionalBool: Bool {
get {return _storage._optionalBool ?? false}
set {_uniqueStorage()._optionalBool = newValue}
}
/// Returns true if `optionalBool` has been explicitly set.
var hasOptionalBool: Bool {return _storage._optionalBool != nil}
/// Clears the value of `optionalBool`. Subsequent reads from it will return its default value.
mutating func clearOptionalBool() {_uniqueStorage()._optionalBool = nil}
var optionalString: String {
get {return _storage._optionalString ?? String()}
set {_uniqueStorage()._optionalString = newValue}
}
/// Returns true if `optionalString` has been explicitly set.
var hasOptionalString: Bool {return _storage._optionalString != nil}
/// Clears the value of `optionalString`. Subsequent reads from it will return its default value.
mutating func clearOptionalString() {_uniqueStorage()._optionalString = nil}
var optionalBytes: Data {
get {return _storage._optionalBytes ?? SwiftProtobuf.Internal.emptyData}
set {_uniqueStorage()._optionalBytes = newValue}
}
/// Returns true if `optionalBytes` has been explicitly set.
var hasOptionalBytes: Bool {return _storage._optionalBytes != nil}
/// Clears the value of `optionalBytes`. Subsequent reads from it will return its default value.
mutating func clearOptionalBytes() {_uniqueStorage()._optionalBytes = nil}
var optionalGroup: ProtobufUnittest_TestAllTypesLite.OptionalGroup {
get {return _storage._optionalGroup ?? ProtobufUnittest_TestAllTypesLite.OptionalGroup()}
set {_uniqueStorage()._optionalGroup = newValue}
}
/// Returns true if `optionalGroup` has been explicitly set.
var hasOptionalGroup: Bool {return _storage._optionalGroup != nil}
/// Clears the value of `optionalGroup`. Subsequent reads from it will return its default value.
mutating func clearOptionalGroup() {_uniqueStorage()._optionalGroup = nil}
var optionalNestedMessage: ProtobufUnittest_TestAllTypesLite.NestedMessage {
get {return _storage._optionalNestedMessage ?? ProtobufUnittest_TestAllTypesLite.NestedMessage()}
set {_uniqueStorage()._optionalNestedMessage = newValue}
}
/// Returns true if `optionalNestedMessage` has been explicitly set.
var hasOptionalNestedMessage: Bool {return _storage._optionalNestedMessage != nil}
/// Clears the value of `optionalNestedMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalNestedMessage() {_uniqueStorage()._optionalNestedMessage = nil}
var optionalForeignMessage: ProtobufUnittest_ForeignMessageLite {
get {return _storage._optionalForeignMessage ?? ProtobufUnittest_ForeignMessageLite()}
set {_uniqueStorage()._optionalForeignMessage = newValue}
}
/// Returns true if `optionalForeignMessage` has been explicitly set.
var hasOptionalForeignMessage: Bool {return _storage._optionalForeignMessage != nil}
/// Clears the value of `optionalForeignMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalForeignMessage() {_uniqueStorage()._optionalForeignMessage = nil}
var optionalImportMessage: ProtobufUnittestImport_ImportMessageLite {
get {return _storage._optionalImportMessage ?? ProtobufUnittestImport_ImportMessageLite()}
set {_uniqueStorage()._optionalImportMessage = newValue}
}
/// Returns true if `optionalImportMessage` has been explicitly set.
var hasOptionalImportMessage: Bool {return _storage._optionalImportMessage != nil}
/// Clears the value of `optionalImportMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalImportMessage() {_uniqueStorage()._optionalImportMessage = nil}
var optionalNestedEnum: ProtobufUnittest_TestAllTypesLite.NestedEnum {
get {return _storage._optionalNestedEnum ?? .foo}
set {_uniqueStorage()._optionalNestedEnum = newValue}
}
/// Returns true if `optionalNestedEnum` has been explicitly set.
var hasOptionalNestedEnum: Bool {return _storage._optionalNestedEnum != nil}
/// Clears the value of `optionalNestedEnum`. Subsequent reads from it will return its default value.
mutating func clearOptionalNestedEnum() {_uniqueStorage()._optionalNestedEnum = nil}
var optionalForeignEnum: ProtobufUnittest_ForeignEnumLite {
get {return _storage._optionalForeignEnum ?? .foreignLiteFoo}
set {_uniqueStorage()._optionalForeignEnum = newValue}
}
/// Returns true if `optionalForeignEnum` has been explicitly set.
var hasOptionalForeignEnum: Bool {return _storage._optionalForeignEnum != nil}
/// Clears the value of `optionalForeignEnum`. Subsequent reads from it will return its default value.
mutating func clearOptionalForeignEnum() {_uniqueStorage()._optionalForeignEnum = nil}
var optionalImportEnum: ProtobufUnittestImport_ImportEnumLite {
get {return _storage._optionalImportEnum ?? .importLiteFoo}
set {_uniqueStorage()._optionalImportEnum = newValue}
}
/// Returns true if `optionalImportEnum` has been explicitly set.
var hasOptionalImportEnum: Bool {return _storage._optionalImportEnum != nil}
/// Clears the value of `optionalImportEnum`. Subsequent reads from it will return its default value.
mutating func clearOptionalImportEnum() {_uniqueStorage()._optionalImportEnum = nil}
var optionalStringPiece: String {
get {return _storage._optionalStringPiece ?? String()}
set {_uniqueStorage()._optionalStringPiece = newValue}
}
/// Returns true if `optionalStringPiece` has been explicitly set.
var hasOptionalStringPiece: Bool {return _storage._optionalStringPiece != nil}
/// Clears the value of `optionalStringPiece`. Subsequent reads from it will return its default value.
mutating func clearOptionalStringPiece() {_uniqueStorage()._optionalStringPiece = nil}
var optionalCord: String {
get {return _storage._optionalCord ?? String()}
set {_uniqueStorage()._optionalCord = newValue}
}
/// Returns true if `optionalCord` has been explicitly set.
var hasOptionalCord: Bool {return _storage._optionalCord != nil}
/// Clears the value of `optionalCord`. Subsequent reads from it will return its default value.
mutating func clearOptionalCord() {_uniqueStorage()._optionalCord = nil}
/// Defined in unittest_import_public.proto
var optionalPublicImportMessage: ProtobufUnittestImport_PublicImportMessageLite {
get {return _storage._optionalPublicImportMessage ?? ProtobufUnittestImport_PublicImportMessageLite()}
set {_uniqueStorage()._optionalPublicImportMessage = newValue}
}
/// Returns true if `optionalPublicImportMessage` has been explicitly set.
var hasOptionalPublicImportMessage: Bool {return _storage._optionalPublicImportMessage != nil}
/// Clears the value of `optionalPublicImportMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalPublicImportMessage() {_uniqueStorage()._optionalPublicImportMessage = nil}
var optionalLazyMessage: ProtobufUnittest_TestAllTypesLite.NestedMessage {
get {return _storage._optionalLazyMessage ?? ProtobufUnittest_TestAllTypesLite.NestedMessage()}
set {_uniqueStorage()._optionalLazyMessage = newValue}
}
/// Returns true if `optionalLazyMessage` has been explicitly set.
var hasOptionalLazyMessage: Bool {return _storage._optionalLazyMessage != nil}
/// Clears the value of `optionalLazyMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalLazyMessage() {_uniqueStorage()._optionalLazyMessage = nil}
/// Repeated
var repeatedInt32: [Int32] {
get {return _storage._repeatedInt32}
set {_uniqueStorage()._repeatedInt32 = newValue}
}
var repeatedInt64: [Int64] {
get {return _storage._repeatedInt64}
set {_uniqueStorage()._repeatedInt64 = newValue}
}
var repeatedUint32: [UInt32] {
get {return _storage._repeatedUint32}
set {_uniqueStorage()._repeatedUint32 = newValue}
}
var repeatedUint64: [UInt64] {
get {return _storage._repeatedUint64}
set {_uniqueStorage()._repeatedUint64 = newValue}
}
var repeatedSint32: [Int32] {
get {return _storage._repeatedSint32}
set {_uniqueStorage()._repeatedSint32 = newValue}
}
var repeatedSint64: [Int64] {
get {return _storage._repeatedSint64}
set {_uniqueStorage()._repeatedSint64 = newValue}
}
var repeatedFixed32: [UInt32] {
get {return _storage._repeatedFixed32}
set {_uniqueStorage()._repeatedFixed32 = newValue}
}
var repeatedFixed64: [UInt64] {
get {return _storage._repeatedFixed64}
set {_uniqueStorage()._repeatedFixed64 = newValue}
}
var repeatedSfixed32: [Int32] {
get {return _storage._repeatedSfixed32}
set {_uniqueStorage()._repeatedSfixed32 = newValue}
}
var repeatedSfixed64: [Int64] {
get {return _storage._repeatedSfixed64}
set {_uniqueStorage()._repeatedSfixed64 = newValue}
}
var repeatedFloat: [Float] {
get {return _storage._repeatedFloat}
set {_uniqueStorage()._repeatedFloat = newValue}
}
var repeatedDouble: [Double] {
get {return _storage._repeatedDouble}
set {_uniqueStorage()._repeatedDouble = newValue}
}
var repeatedBool: [Bool] {
get {return _storage._repeatedBool}
set {_uniqueStorage()._repeatedBool = newValue}
}
var repeatedString: [String] {
get {return _storage._repeatedString}
set {_uniqueStorage()._repeatedString = newValue}
}
var repeatedBytes: [Data] {
get {return _storage._repeatedBytes}
set {_uniqueStorage()._repeatedBytes = newValue}
}
var repeatedGroup: [ProtobufUnittest_TestAllTypesLite.RepeatedGroup] {
get {return _storage._repeatedGroup}
set {_uniqueStorage()._repeatedGroup = newValue}
}
var repeatedNestedMessage: [ProtobufUnittest_TestAllTypesLite.NestedMessage] {
get {return _storage._repeatedNestedMessage}
set {_uniqueStorage()._repeatedNestedMessage = newValue}
}
var repeatedForeignMessage: [ProtobufUnittest_ForeignMessageLite] {
get {return _storage._repeatedForeignMessage}
set {_uniqueStorage()._repeatedForeignMessage = newValue}
}
var repeatedImportMessage: [ProtobufUnittestImport_ImportMessageLite] {
get {return _storage._repeatedImportMessage}
set {_uniqueStorage()._repeatedImportMessage = newValue}
}
var repeatedNestedEnum: [ProtobufUnittest_TestAllTypesLite.NestedEnum] {
get {return _storage._repeatedNestedEnum}
set {_uniqueStorage()._repeatedNestedEnum = newValue}
}
var repeatedForeignEnum: [ProtobufUnittest_ForeignEnumLite] {
get {return _storage._repeatedForeignEnum}
set {_uniqueStorage()._repeatedForeignEnum = newValue}
}
var repeatedImportEnum: [ProtobufUnittestImport_ImportEnumLite] {
get {return _storage._repeatedImportEnum}
set {_uniqueStorage()._repeatedImportEnum = newValue}
}
var repeatedStringPiece: [String] {
get {return _storage._repeatedStringPiece}
set {_uniqueStorage()._repeatedStringPiece = newValue}
}
var repeatedCord: [String] {
get {return _storage._repeatedCord}
set {_uniqueStorage()._repeatedCord = newValue}
}
var repeatedLazyMessage: [ProtobufUnittest_TestAllTypesLite.NestedMessage] {
get {return _storage._repeatedLazyMessage}
set {_uniqueStorage()._repeatedLazyMessage = newValue}
}
/// Singular with defaults
var defaultInt32: Int32 {
get {return _storage._defaultInt32 ?? 41}
set {_uniqueStorage()._defaultInt32 = newValue}
}
/// Returns true if `defaultInt32` has been explicitly set.
var hasDefaultInt32: Bool {return _storage._defaultInt32 != nil}
/// Clears the value of `defaultInt32`. Subsequent reads from it will return its default value.
mutating func clearDefaultInt32() {_uniqueStorage()._defaultInt32 = nil}
var defaultInt64: Int64 {
get {return _storage._defaultInt64 ?? 42}
set {_uniqueStorage()._defaultInt64 = newValue}
}
/// Returns true if `defaultInt64` has been explicitly set.
var hasDefaultInt64: Bool {return _storage._defaultInt64 != nil}
/// Clears the value of `defaultInt64`. Subsequent reads from it will return its default value.
mutating func clearDefaultInt64() {_uniqueStorage()._defaultInt64 = nil}
var defaultUint32: UInt32 {
get {return _storage._defaultUint32 ?? 43}
set {_uniqueStorage()._defaultUint32 = newValue}
}
/// Returns true if `defaultUint32` has been explicitly set.
var hasDefaultUint32: Bool {return _storage._defaultUint32 != nil}
/// Clears the value of `defaultUint32`. Subsequent reads from it will return its default value.
mutating func clearDefaultUint32() {_uniqueStorage()._defaultUint32 = nil}
var defaultUint64: UInt64 {
get {return _storage._defaultUint64 ?? 44}
set {_uniqueStorage()._defaultUint64 = newValue}
}
/// Returns true if `defaultUint64` has been explicitly set.
var hasDefaultUint64: Bool {return _storage._defaultUint64 != nil}
/// Clears the value of `defaultUint64`. Subsequent reads from it will return its default value.
mutating func clearDefaultUint64() {_uniqueStorage()._defaultUint64 = nil}
var defaultSint32: Int32 {
get {return _storage._defaultSint32 ?? -45}
set {_uniqueStorage()._defaultSint32 = newValue}
}
/// Returns true if `defaultSint32` has been explicitly set.
var hasDefaultSint32: Bool {return _storage._defaultSint32 != nil}
/// Clears the value of `defaultSint32`. Subsequent reads from it will return its default value.
mutating func clearDefaultSint32() {_uniqueStorage()._defaultSint32 = nil}
var defaultSint64: Int64 {
get {return _storage._defaultSint64 ?? 46}
set {_uniqueStorage()._defaultSint64 = newValue}
}
/// Returns true if `defaultSint64` has been explicitly set.
var hasDefaultSint64: Bool {return _storage._defaultSint64 != nil}
/// Clears the value of `defaultSint64`. Subsequent reads from it will return its default value.
mutating func clearDefaultSint64() {_uniqueStorage()._defaultSint64 = nil}
var defaultFixed32: UInt32 {
get {return _storage._defaultFixed32 ?? 47}
set {_uniqueStorage()._defaultFixed32 = newValue}
}
/// Returns true if `defaultFixed32` has been explicitly set.
var hasDefaultFixed32: Bool {return _storage._defaultFixed32 != nil}
/// Clears the value of `defaultFixed32`. Subsequent reads from it will return its default value.
mutating func clearDefaultFixed32() {_uniqueStorage()._defaultFixed32 = nil}
var defaultFixed64: UInt64 {
get {return _storage._defaultFixed64 ?? 48}
set {_uniqueStorage()._defaultFixed64 = newValue}
}
/// Returns true if `defaultFixed64` has been explicitly set.
var hasDefaultFixed64: Bool {return _storage._defaultFixed64 != nil}
/// Clears the value of `defaultFixed64`. Subsequent reads from it will return its default value.
mutating func clearDefaultFixed64() {_uniqueStorage()._defaultFixed64 = nil}
var defaultSfixed32: Int32 {
get {return _storage._defaultSfixed32 ?? 49}
set {_uniqueStorage()._defaultSfixed32 = newValue}
}
/// Returns true if `defaultSfixed32` has been explicitly set.
var hasDefaultSfixed32: Bool {return _storage._defaultSfixed32 != nil}
/// Clears the value of `defaultSfixed32`. Subsequent reads from it will return its default value.
mutating func clearDefaultSfixed32() {_uniqueStorage()._defaultSfixed32 = nil}
var defaultSfixed64: Int64 {
get {return _storage._defaultSfixed64 ?? -50}
set {_uniqueStorage()._defaultSfixed64 = newValue}
}
/// Returns true if `defaultSfixed64` has been explicitly set.
var hasDefaultSfixed64: Bool {return _storage._defaultSfixed64 != nil}
/// Clears the value of `defaultSfixed64`. Subsequent reads from it will return its default value.
mutating func clearDefaultSfixed64() {_uniqueStorage()._defaultSfixed64 = nil}
var defaultFloat: Float {
get {return _storage._defaultFloat ?? 51.5}
set {_uniqueStorage()._defaultFloat = newValue}
}
/// Returns true if `defaultFloat` has been explicitly set.
var hasDefaultFloat: Bool {return _storage._defaultFloat != nil}
/// Clears the value of `defaultFloat`. Subsequent reads from it will return its default value.
mutating func clearDefaultFloat() {_uniqueStorage()._defaultFloat = nil}
var defaultDouble: Double {
get {return _storage._defaultDouble ?? 52000}
set {_uniqueStorage()._defaultDouble = newValue}
}
/// Returns true if `defaultDouble` has been explicitly set.
var hasDefaultDouble: Bool {return _storage._defaultDouble != nil}
/// Clears the value of `defaultDouble`. Subsequent reads from it will return its default value.
mutating func clearDefaultDouble() {_uniqueStorage()._defaultDouble = nil}
var defaultBool: Bool {
get {return _storage._defaultBool ?? true}
set {_uniqueStorage()._defaultBool = newValue}
}
/// Returns true if `defaultBool` has been explicitly set.
var hasDefaultBool: Bool {return _storage._defaultBool != nil}
/// Clears the value of `defaultBool`. Subsequent reads from it will return its default value.
mutating func clearDefaultBool() {_uniqueStorage()._defaultBool = nil}
var defaultString: String {
get {return _storage._defaultString ?? "hello"}
set {_uniqueStorage()._defaultString = newValue}
}
/// Returns true if `defaultString` has been explicitly set.
var hasDefaultString: Bool {return _storage._defaultString != nil}
/// Clears the value of `defaultString`. Subsequent reads from it will return its default value.
mutating func clearDefaultString() {_uniqueStorage()._defaultString = nil}
var defaultBytes: Data {
get {return _storage._defaultBytes ?? Data(bytes: [119, 111, 114, 108, 100])}
set {_uniqueStorage()._defaultBytes = newValue}
}
/// Returns true if `defaultBytes` has been explicitly set.
var hasDefaultBytes: Bool {return _storage._defaultBytes != nil}
/// Clears the value of `defaultBytes`. Subsequent reads from it will return its default value.
mutating func clearDefaultBytes() {_uniqueStorage()._defaultBytes = nil}
var defaultNestedEnum: ProtobufUnittest_TestAllTypesLite.NestedEnum {
get {return _storage._defaultNestedEnum ?? .bar}
set {_uniqueStorage()._defaultNestedEnum = newValue}
}
/// Returns true if `defaultNestedEnum` has been explicitly set.
var hasDefaultNestedEnum: Bool {return _storage._defaultNestedEnum != nil}
/// Clears the value of `defaultNestedEnum`. Subsequent reads from it will return its default value.
mutating func clearDefaultNestedEnum() {_uniqueStorage()._defaultNestedEnum = nil}
var defaultForeignEnum: ProtobufUnittest_ForeignEnumLite {
get {return _storage._defaultForeignEnum ?? .foreignLiteBar}
set {_uniqueStorage()._defaultForeignEnum = newValue}
}
/// Returns true if `defaultForeignEnum` has been explicitly set.
var hasDefaultForeignEnum: Bool {return _storage._defaultForeignEnum != nil}
/// Clears the value of `defaultForeignEnum`. Subsequent reads from it will return its default value.
mutating func clearDefaultForeignEnum() {_uniqueStorage()._defaultForeignEnum = nil}
var defaultImportEnum: ProtobufUnittestImport_ImportEnumLite {
get {return _storage._defaultImportEnum ?? .importLiteBar}
set {_uniqueStorage()._defaultImportEnum = newValue}
}
/// Returns true if `defaultImportEnum` has been explicitly set.
var hasDefaultImportEnum: Bool {return _storage._defaultImportEnum != nil}
/// Clears the value of `defaultImportEnum`. Subsequent reads from it will return its default value.
mutating func clearDefaultImportEnum() {_uniqueStorage()._defaultImportEnum = nil}
var defaultStringPiece: String {
get {return _storage._defaultStringPiece ?? "abc"}
set {_uniqueStorage()._defaultStringPiece = newValue}
}
/// Returns true if `defaultStringPiece` has been explicitly set.
var hasDefaultStringPiece: Bool {return _storage._defaultStringPiece != nil}
/// Clears the value of `defaultStringPiece`. Subsequent reads from it will return its default value.
mutating func clearDefaultStringPiece() {_uniqueStorage()._defaultStringPiece = nil}
var defaultCord: String {
get {return _storage._defaultCord ?? "123"}
set {_uniqueStorage()._defaultCord = newValue}
}
/// Returns true if `defaultCord` has been explicitly set.
var hasDefaultCord: Bool {return _storage._defaultCord != nil}
/// Clears the value of `defaultCord`. Subsequent reads from it will return its default value.
mutating func clearDefaultCord() {_uniqueStorage()._defaultCord = nil}
/// For oneof test
var oneofField: OneOf_OneofField? {
get {return _storage._oneofField}
set {_uniqueStorage()._oneofField = newValue}
}
var oneofUint32: UInt32 {
get {
if case .oneofUint32(let v)? = _storage._oneofField {return v}
return 0
}
set {_uniqueStorage()._oneofField = .oneofUint32(newValue)}
}
var oneofNestedMessage: ProtobufUnittest_TestAllTypesLite.NestedMessage {
get {
if case .oneofNestedMessage(let v)? = _storage._oneofField {return v}
return ProtobufUnittest_TestAllTypesLite.NestedMessage()
}
set {_uniqueStorage()._oneofField = .oneofNestedMessage(newValue)}
}
var oneofString: String {
get {
if case .oneofString(let v)? = _storage._oneofField {return v}
return String()
}
set {_uniqueStorage()._oneofField = .oneofString(newValue)}
}
var oneofBytes: Data {
get {
if case .oneofBytes(let v)? = _storage._oneofField {return v}
return SwiftProtobuf.Internal.emptyData
}
set {_uniqueStorage()._oneofField = .oneofBytes(newValue)}
}
var oneofLazyNestedMessage: ProtobufUnittest_TestAllTypesLite.NestedMessage {
get {
if case .oneofLazyNestedMessage(let v)? = _storage._oneofField {return v}
return ProtobufUnittest_TestAllTypesLite.NestedMessage()
}
set {_uniqueStorage()._oneofField = .oneofLazyNestedMessage(newValue)}
}
/// Tests toString for non-repeated fields with a list suffix
var deceptivelyNamedList: Int32 {
get {return _storage._deceptivelyNamedList ?? 0}
set {_uniqueStorage()._deceptivelyNamedList = newValue}
}
/// Returns true if `deceptivelyNamedList` has been explicitly set.
var hasDeceptivelyNamedList: Bool {return _storage._deceptivelyNamedList != nil}
/// Clears the value of `deceptivelyNamedList`. Subsequent reads from it will return its default value.
mutating func clearDeceptivelyNamedList() {_uniqueStorage()._deceptivelyNamedList = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
/// For oneof test
enum OneOf_OneofField: Equatable {
case oneofUint32(UInt32)
case oneofNestedMessage(ProtobufUnittest_TestAllTypesLite.NestedMessage)
case oneofString(String)
case oneofBytes(Data)
case oneofLazyNestedMessage(ProtobufUnittest_TestAllTypesLite.NestedMessage)
#if !swift(>=4.1)
static func ==(lhs: ProtobufUnittest_TestAllTypesLite.OneOf_OneofField, rhs: ProtobufUnittest_TestAllTypesLite.OneOf_OneofField) -> Bool {
switch (lhs, rhs) {
case (.oneofUint32(let l), .oneofUint32(let r)): return l == r
case (.oneofNestedMessage(let l), .oneofNestedMessage(let r)): return l == r
case (.oneofString(let l), .oneofString(let r)): return l == r
case (.oneofBytes(let l), .oneofBytes(let r)): return l == r
case (.oneofLazyNestedMessage(let l), .oneofLazyNestedMessage(let r)): return l == r
default: return false
}
}
#endif
}
enum NestedEnum: SwiftProtobuf.Enum {
typealias RawValue = Int
case foo // = 1
case bar // = 2
case baz // = 3
init() {
self = .foo
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .foo
case 2: self = .bar
case 3: self = .baz
default: return nil
}
}
var rawValue: Int {
switch self {
case .foo: return 1
case .bar: return 2
case .baz: return 3
}
}
}
struct NestedMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var bb: Int32 {
get {return _bb ?? 0}
set {_bb = newValue}
}
/// Returns true if `bb` has been explicitly set.
var hasBb: Bool {return self._bb != nil}
/// Clears the value of `bb`. Subsequent reads from it will return its default value.
mutating func clearBb() {self._bb = nil}
var cc: Int64 {
get {return _cc ?? 0}
set {_cc = newValue}
}
/// Returns true if `cc` has been explicitly set.
var hasCc: Bool {return self._cc != nil}
/// Clears the value of `cc`. Subsequent reads from it will return its default value.
mutating func clearCc() {self._cc = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _bb: Int32? = nil
fileprivate var _cc: Int64? = nil
}
struct OptionalGroup {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var a: Int32 {
get {return _a ?? 0}
set {_a = newValue}
}
/// Returns true if `a` has been explicitly set.
var hasA: Bool {return self._a != nil}
/// Clears the value of `a`. Subsequent reads from it will return its default value.
mutating func clearA() {self._a = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _a: Int32? = nil
}
struct RepeatedGroup {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var a: Int32 {
get {return _a ?? 0}
set {_a = newValue}
}
/// Returns true if `a` has been explicitly set.
var hasA: Bool {return self._a != nil}
/// Clears the value of `a`. Subsequent reads from it will return its default value.
mutating func clearA() {self._a = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _a: Int32? = nil
}
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
#if swift(>=4.2)
extension ProtobufUnittest_TestAllTypesLite.NestedEnum: CaseIterable {
// Support synthesized by the compiler.
}
#endif // swift(>=4.2)
struct ProtobufUnittest_ForeignMessageLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var c: Int32 {
get {return _c ?? 0}
set {_c = newValue}
}
/// Returns true if `c` has been explicitly set.
var hasC: Bool {return self._c != nil}
/// Clears the value of `c`. Subsequent reads from it will return its default value.
mutating func clearC() {self._c = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _c: Int32? = nil
}
struct ProtobufUnittest_TestPackedTypesLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var packedInt32: [Int32] = []
var packedInt64: [Int64] = []
var packedUint32: [UInt32] = []
var packedUint64: [UInt64] = []
var packedSint32: [Int32] = []
var packedSint64: [Int64] = []
var packedFixed32: [UInt32] = []
var packedFixed64: [UInt64] = []
var packedSfixed32: [Int32] = []
var packedSfixed64: [Int64] = []
var packedFloat: [Float] = []
var packedDouble: [Double] = []
var packedBool: [Bool] = []
var packedEnum: [ProtobufUnittest_ForeignEnumLite] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct ProtobufUnittest_TestAllExtensionsLite: SwiftProtobuf.ExtensibleMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
var _protobuf_extensionFieldValues = SwiftProtobuf.ExtensionFieldValueSet()
}
struct ProtobufUnittest_OptionalGroup_extension_lite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var a: Int32 {
get {return _a ?? 0}
set {_a = newValue}
}
/// Returns true if `a` has been explicitly set.
var hasA: Bool {return self._a != nil}
/// Clears the value of `a`. Subsequent reads from it will return its default value.
mutating func clearA() {self._a = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _a: Int32? = nil
}
struct ProtobufUnittest_RepeatedGroup_extension_lite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var a: Int32 {
get {return _a ?? 0}
set {_a = newValue}
}
/// Returns true if `a` has been explicitly set.
var hasA: Bool {return self._a != nil}
/// Clears the value of `a`. Subsequent reads from it will return its default value.
mutating func clearA() {self._a = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _a: Int32? = nil
}
struct ProtobufUnittest_TestPackedExtensionsLite: SwiftProtobuf.ExtensibleMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
var _protobuf_extensionFieldValues = SwiftProtobuf.ExtensionFieldValueSet()
}
struct ProtobufUnittest_TestNestedExtensionLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Test that deprecated fields work. We only verify that they compile (at one
/// point this failed).
struct ProtobufUnittest_TestDeprecatedLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var deprecatedField: Int32 {
get {return _deprecatedField ?? 0}
set {_deprecatedField = newValue}
}
/// Returns true if `deprecatedField` has been explicitly set.
var hasDeprecatedField: Bool {return self._deprecatedField != nil}
/// Clears the value of `deprecatedField`. Subsequent reads from it will return its default value.
mutating func clearDeprecatedField() {self._deprecatedField = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _deprecatedField: Int32? = nil
}
/// See the comments of the same type in unittest.proto.
struct ProtobufUnittest_TestParsingMergeLite: SwiftProtobuf.ExtensibleMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var requiredAllTypes: ProtobufUnittest_TestAllTypesLite {
get {return _storage._requiredAllTypes ?? ProtobufUnittest_TestAllTypesLite()}
set {_uniqueStorage()._requiredAllTypes = newValue}
}
/// Returns true if `requiredAllTypes` has been explicitly set.
var hasRequiredAllTypes: Bool {return _storage._requiredAllTypes != nil}
/// Clears the value of `requiredAllTypes`. Subsequent reads from it will return its default value.
mutating func clearRequiredAllTypes() {_uniqueStorage()._requiredAllTypes = nil}
var optionalAllTypes: ProtobufUnittest_TestAllTypesLite {
get {return _storage._optionalAllTypes ?? ProtobufUnittest_TestAllTypesLite()}
set {_uniqueStorage()._optionalAllTypes = newValue}
}
/// Returns true if `optionalAllTypes` has been explicitly set.
var hasOptionalAllTypes: Bool {return _storage._optionalAllTypes != nil}
/// Clears the value of `optionalAllTypes`. Subsequent reads from it will return its default value.
mutating func clearOptionalAllTypes() {_uniqueStorage()._optionalAllTypes = nil}
var repeatedAllTypes: [ProtobufUnittest_TestAllTypesLite] {
get {return _storage._repeatedAllTypes}
set {_uniqueStorage()._repeatedAllTypes = newValue}
}
var optionalGroup: ProtobufUnittest_TestParsingMergeLite.OptionalGroup {
get {return _storage._optionalGroup ?? ProtobufUnittest_TestParsingMergeLite.OptionalGroup()}
set {_uniqueStorage()._optionalGroup = newValue}
}
/// Returns true if `optionalGroup` has been explicitly set.
var hasOptionalGroup: Bool {return _storage._optionalGroup != nil}
/// Clears the value of `optionalGroup`. Subsequent reads from it will return its default value.
mutating func clearOptionalGroup() {_uniqueStorage()._optionalGroup = nil}
var repeatedGroup: [ProtobufUnittest_TestParsingMergeLite.RepeatedGroup] {
get {return _storage._repeatedGroup}
set {_uniqueStorage()._repeatedGroup = newValue}
}
var unknownFields = SwiftProtobuf.UnknownStorage()
struct RepeatedFieldsGenerator {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var field1: [ProtobufUnittest_TestAllTypesLite] = []
var field2: [ProtobufUnittest_TestAllTypesLite] = []
var field3: [ProtobufUnittest_TestAllTypesLite] = []
var group1: [ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group1] = []
var group2: [ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group2] = []
var ext1: [ProtobufUnittest_TestAllTypesLite] = []
var ext2: [ProtobufUnittest_TestAllTypesLite] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
struct Group1 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var field1: ProtobufUnittest_TestAllTypesLite {
get {return _storage._field1 ?? ProtobufUnittest_TestAllTypesLite()}
set {_uniqueStorage()._field1 = newValue}
}
/// Returns true if `field1` has been explicitly set.
var hasField1: Bool {return _storage._field1 != nil}
/// Clears the value of `field1`. Subsequent reads from it will return its default value.
mutating func clearField1() {_uniqueStorage()._field1 = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct Group2 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var field1: ProtobufUnittest_TestAllTypesLite {
get {return _storage._field1 ?? ProtobufUnittest_TestAllTypesLite()}
set {_uniqueStorage()._field1 = newValue}
}
/// Returns true if `field1` has been explicitly set.
var hasField1: Bool {return _storage._field1 != nil}
/// Clears the value of `field1`. Subsequent reads from it will return its default value.
mutating func clearField1() {_uniqueStorage()._field1 = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
init() {}
}
struct OptionalGroup {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var optionalGroupAllTypes: ProtobufUnittest_TestAllTypesLite {
get {return _storage._optionalGroupAllTypes ?? ProtobufUnittest_TestAllTypesLite()}
set {_uniqueStorage()._optionalGroupAllTypes = newValue}
}
/// Returns true if `optionalGroupAllTypes` has been explicitly set.
var hasOptionalGroupAllTypes: Bool {return _storage._optionalGroupAllTypes != nil}
/// Clears the value of `optionalGroupAllTypes`. Subsequent reads from it will return its default value.
mutating func clearOptionalGroupAllTypes() {_uniqueStorage()._optionalGroupAllTypes = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
struct RepeatedGroup {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var repeatedGroupAllTypes: ProtobufUnittest_TestAllTypesLite {
get {return _storage._repeatedGroupAllTypes ?? ProtobufUnittest_TestAllTypesLite()}
set {_uniqueStorage()._repeatedGroupAllTypes = newValue}
}
/// Returns true if `repeatedGroupAllTypes` has been explicitly set.
var hasRepeatedGroupAllTypes: Bool {return _storage._repeatedGroupAllTypes != nil}
/// Clears the value of `repeatedGroupAllTypes`. Subsequent reads from it will return its default value.
mutating func clearRepeatedGroupAllTypes() {_uniqueStorage()._repeatedGroupAllTypes = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
init() {}
var _protobuf_extensionFieldValues = SwiftProtobuf.ExtensionFieldValueSet()
fileprivate var _storage = _StorageClass.defaultInstance
}
/// TestEmptyMessageLite is used to test unknown fields support in lite mode.
struct ProtobufUnittest_TestEmptyMessageLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Like above, but declare all field numbers as potential extensions. No
/// actual extensions should ever be defined for this type.
struct ProtobufUnittest_TestEmptyMessageWithExtensionsLite: SwiftProtobuf.ExtensibleMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
var _protobuf_extensionFieldValues = SwiftProtobuf.ExtensionFieldValueSet()
}
struct ProtobufUnittest_V1MessageLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var intField: Int32 {
get {return _intField ?? 0}
set {_intField = newValue}
}
/// Returns true if `intField` has been explicitly set.
var hasIntField: Bool {return self._intField != nil}
/// Clears the value of `intField`. Subsequent reads from it will return its default value.
mutating func clearIntField() {self._intField = nil}
var enumField: ProtobufUnittest_V1EnumLite {
get {return _enumField ?? .v1First}
set {_enumField = newValue}
}
/// Returns true if `enumField` has been explicitly set.
var hasEnumField: Bool {return self._enumField != nil}
/// Clears the value of `enumField`. Subsequent reads from it will return its default value.
mutating func clearEnumField() {self._enumField = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _intField: Int32? = nil
fileprivate var _enumField: ProtobufUnittest_V1EnumLite? = nil
}
struct ProtobufUnittest_V2MessageLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var intField: Int32 {
get {return _intField ?? 0}
set {_intField = newValue}
}
/// Returns true if `intField` has been explicitly set.
var hasIntField: Bool {return self._intField != nil}
/// Clears the value of `intField`. Subsequent reads from it will return its default value.
mutating func clearIntField() {self._intField = nil}
var enumField: ProtobufUnittest_V2EnumLite {
get {return _enumField ?? .v2First}
set {_enumField = newValue}
}
/// Returns true if `enumField` has been explicitly set.
var hasEnumField: Bool {return self._enumField != nil}
/// Clears the value of `enumField`. Subsequent reads from it will return its default value.
mutating func clearEnumField() {self._enumField = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _intField: Int32? = nil
fileprivate var _enumField: ProtobufUnittest_V2EnumLite? = nil
}
struct ProtobufUnittest_TestHugeFieldNumbersLite: SwiftProtobuf.ExtensibleMessage {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var optionalInt32: Int32 {
get {return _storage._optionalInt32 ?? 0}
set {_uniqueStorage()._optionalInt32 = newValue}
}
/// Returns true if `optionalInt32` has been explicitly set.
var hasOptionalInt32: Bool {return _storage._optionalInt32 != nil}
/// Clears the value of `optionalInt32`. Subsequent reads from it will return its default value.
mutating func clearOptionalInt32() {_uniqueStorage()._optionalInt32 = nil}
var fixed32: Int32 {
get {return _storage._fixed32 ?? 0}
set {_uniqueStorage()._fixed32 = newValue}
}
/// Returns true if `fixed32` has been explicitly set.
var hasFixed32: Bool {return _storage._fixed32 != nil}
/// Clears the value of `fixed32`. Subsequent reads from it will return its default value.
mutating func clearFixed32() {_uniqueStorage()._fixed32 = nil}
var repeatedInt32: [Int32] {
get {return _storage._repeatedInt32}
set {_uniqueStorage()._repeatedInt32 = newValue}
}
var packedInt32: [Int32] {
get {return _storage._packedInt32}
set {_uniqueStorage()._packedInt32 = newValue}
}
var optionalEnum: ProtobufUnittest_ForeignEnumLite {
get {return _storage._optionalEnum ?? .foreignLiteFoo}
set {_uniqueStorage()._optionalEnum = newValue}
}
/// Returns true if `optionalEnum` has been explicitly set.
var hasOptionalEnum: Bool {return _storage._optionalEnum != nil}
/// Clears the value of `optionalEnum`. Subsequent reads from it will return its default value.
mutating func clearOptionalEnum() {_uniqueStorage()._optionalEnum = nil}
var optionalString: String {
get {return _storage._optionalString ?? String()}
set {_uniqueStorage()._optionalString = newValue}
}
/// Returns true if `optionalString` has been explicitly set.
var hasOptionalString: Bool {return _storage._optionalString != nil}
/// Clears the value of `optionalString`. Subsequent reads from it will return its default value.
mutating func clearOptionalString() {_uniqueStorage()._optionalString = nil}
var optionalBytes: Data {
get {return _storage._optionalBytes ?? SwiftProtobuf.Internal.emptyData}
set {_uniqueStorage()._optionalBytes = newValue}
}
/// Returns true if `optionalBytes` has been explicitly set.
var hasOptionalBytes: Bool {return _storage._optionalBytes != nil}
/// Clears the value of `optionalBytes`. Subsequent reads from it will return its default value.
mutating func clearOptionalBytes() {_uniqueStorage()._optionalBytes = nil}
var optionalMessage: ProtobufUnittest_ForeignMessageLite {
get {return _storage._optionalMessage ?? ProtobufUnittest_ForeignMessageLite()}
set {_uniqueStorage()._optionalMessage = newValue}
}
/// Returns true if `optionalMessage` has been explicitly set.
var hasOptionalMessage: Bool {return _storage._optionalMessage != nil}
/// Clears the value of `optionalMessage`. Subsequent reads from it will return its default value.
mutating func clearOptionalMessage() {_uniqueStorage()._optionalMessage = nil}
var optionalGroup: ProtobufUnittest_TestHugeFieldNumbersLite.OptionalGroup {
get {return _storage._optionalGroup ?? ProtobufUnittest_TestHugeFieldNumbersLite.OptionalGroup()}
set {_uniqueStorage()._optionalGroup = newValue}
}
/// Returns true if `optionalGroup` has been explicitly set.
var hasOptionalGroup: Bool {return _storage._optionalGroup != nil}
/// Clears the value of `optionalGroup`. Subsequent reads from it will return its default value.
mutating func clearOptionalGroup() {_uniqueStorage()._optionalGroup = nil}
var stringStringMap: Dictionary<String,String> {
get {return _storage._stringStringMap}
set {_uniqueStorage()._stringStringMap = newValue}
}
var oneofField: OneOf_OneofField? {
get {return _storage._oneofField}
set {_uniqueStorage()._oneofField = newValue}
}
var oneofUint32: UInt32 {
get {
if case .oneofUint32(let v)? = _storage._oneofField {return v}
return 0
}
set {_uniqueStorage()._oneofField = .oneofUint32(newValue)}
}
var oneofTestAllTypes: ProtobufUnittest_TestAllTypesLite {
get {
if case .oneofTestAllTypes(let v)? = _storage._oneofField {return v}
return ProtobufUnittest_TestAllTypesLite()
}
set {_uniqueStorage()._oneofField = .oneofTestAllTypes(newValue)}
}
var oneofString: String {
get {
if case .oneofString(let v)? = _storage._oneofField {return v}
return String()
}
set {_uniqueStorage()._oneofField = .oneofString(newValue)}
}
var oneofBytes: Data {
get {
if case .oneofBytes(let v)? = _storage._oneofField {return v}
return SwiftProtobuf.Internal.emptyData
}
set {_uniqueStorage()._oneofField = .oneofBytes(newValue)}
}
var unknownFields = SwiftProtobuf.UnknownStorage()
enum OneOf_OneofField: Equatable {
case oneofUint32(UInt32)
case oneofTestAllTypes(ProtobufUnittest_TestAllTypesLite)
case oneofString(String)
case oneofBytes(Data)
#if !swift(>=4.1)
static func ==(lhs: ProtobufUnittest_TestHugeFieldNumbersLite.OneOf_OneofField, rhs: ProtobufUnittest_TestHugeFieldNumbersLite.OneOf_OneofField) -> Bool {
switch (lhs, rhs) {
case (.oneofUint32(let l), .oneofUint32(let r)): return l == r
case (.oneofTestAllTypes(let l), .oneofTestAllTypes(let r)): return l == r
case (.oneofString(let l), .oneofString(let r)): return l == r
case (.oneofBytes(let l), .oneofBytes(let r)): return l == r
default: return false
}
}
#endif
}
struct OptionalGroup {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var groupA: Int32 {
get {return _groupA ?? 0}
set {_groupA = newValue}
}
/// Returns true if `groupA` has been explicitly set.
var hasGroupA: Bool {return self._groupA != nil}
/// Clears the value of `groupA`. Subsequent reads from it will return its default value.
mutating func clearGroupA() {self._groupA = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _groupA: Int32? = nil
}
init() {}
var _protobuf_extensionFieldValues = SwiftProtobuf.ExtensionFieldValueSet()
fileprivate var _storage = _StorageClass.defaultInstance
}
struct ProtobufUnittest_TestOneofParsingLite {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var oneofField: OneOf_OneofField? {
get {return _storage._oneofField}
set {_uniqueStorage()._oneofField = newValue}
}
var oneofInt32: Int32 {
get {
if case .oneofInt32(let v)? = _storage._oneofField {return v}
return 0
}
set {_uniqueStorage()._oneofField = .oneofInt32(newValue)}
}
var oneofSubmessage: ProtobufUnittest_TestAllTypesLite {
get {
if case .oneofSubmessage(let v)? = _storage._oneofField {return v}
return ProtobufUnittest_TestAllTypesLite()
}
set {_uniqueStorage()._oneofField = .oneofSubmessage(newValue)}
}
var oneofString: String {
get {
if case .oneofString(let v)? = _storage._oneofField {return v}
return String()
}
set {_uniqueStorage()._oneofField = .oneofString(newValue)}
}
var oneofBytes: Data {
get {
if case .oneofBytes(let v)? = _storage._oneofField {return v}
return Data(bytes: [100, 101, 102, 97, 117, 108, 116, 32, 98, 121, 116, 101, 115])
}
set {_uniqueStorage()._oneofField = .oneofBytes(newValue)}
}
var oneofStringCord: String {
get {
if case .oneofStringCord(let v)? = _storage._oneofField {return v}
return "default Cord"
}
set {_uniqueStorage()._oneofField = .oneofStringCord(newValue)}
}
var oneofBytesCord: Data {
get {
if case .oneofBytesCord(let v)? = _storage._oneofField {return v}
return SwiftProtobuf.Internal.emptyData
}
set {_uniqueStorage()._oneofField = .oneofBytesCord(newValue)}
}
var oneofStringStringPiece: String {
get {
if case .oneofStringStringPiece(let v)? = _storage._oneofField {return v}
return String()
}
set {_uniqueStorage()._oneofField = .oneofStringStringPiece(newValue)}
}
var oneofBytesStringPiece: Data {
get {
if case .oneofBytesStringPiece(let v)? = _storage._oneofField {return v}
return Data(bytes: [100, 101, 102, 97, 117, 108, 116, 32, 83, 116, 114, 105, 110, 103, 80, 105, 101, 99, 101])
}
set {_uniqueStorage()._oneofField = .oneofBytesStringPiece(newValue)}
}
var oneofEnum: ProtobufUnittest_V2EnumLite {
get {
if case .oneofEnum(let v)? = _storage._oneofField {return v}
return .v2First
}
set {_uniqueStorage()._oneofField = .oneofEnum(newValue)}
}
var unknownFields = SwiftProtobuf.UnknownStorage()
enum OneOf_OneofField: Equatable {
case oneofInt32(Int32)
case oneofSubmessage(ProtobufUnittest_TestAllTypesLite)
case oneofString(String)
case oneofBytes(Data)
case oneofStringCord(String)
case oneofBytesCord(Data)
case oneofStringStringPiece(String)
case oneofBytesStringPiece(Data)
case oneofEnum(ProtobufUnittest_V2EnumLite)
#if !swift(>=4.1)
static func ==(lhs: ProtobufUnittest_TestOneofParsingLite.OneOf_OneofField, rhs: ProtobufUnittest_TestOneofParsingLite.OneOf_OneofField) -> Bool {
switch (lhs, rhs) {
case (.oneofInt32(let l), .oneofInt32(let r)): return l == r
case (.oneofSubmessage(let l), .oneofSubmessage(let r)): return l == r
case (.oneofString(let l), .oneofString(let r)): return l == r
case (.oneofBytes(let l), .oneofBytes(let r)): return l == r
case (.oneofStringCord(let l), .oneofStringCord(let r)): return l == r
case (.oneofBytesCord(let l), .oneofBytesCord(let r)): return l == r
case (.oneofStringStringPiece(let l), .oneofStringStringPiece(let r)): return l == r
case (.oneofBytesStringPiece(let l), .oneofBytesStringPiece(let r)): return l == r
case (.oneofEnum(let l), .oneofEnum(let r)): return l == r
default: return false
}
}
#endif
}
init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
/// The following four messages are set up to test for wire compatibility between
/// packed and non-packed repeated fields. We use the field number 2048, because
/// that is large enough to require a 3-byte varint for the tag.
struct ProtobufUnittest_PackedInt32 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var repeatedInt32: [Int32] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct ProtobufUnittest_NonPackedInt32 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var repeatedInt32: [Int32] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct ProtobufUnittest_PackedFixed32 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var repeatedFixed32: [UInt32] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct ProtobufUnittest_NonPackedFixed32 {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var repeatedFixed32: [UInt32] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Extension support defined in unittest_lite.proto.
extension ProtobufUnittest_TestAllExtensionsLite {
/// Singular
var ProtobufUnittest_optionalInt32ExtensionLite: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_int32_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_int32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_int32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalInt32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_int32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_int32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalInt32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_int32_extension_lite)
}
var ProtobufUnittest_optionalInt64ExtensionLite: Int64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_int64_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_int64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_int64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalInt64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_int64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_int64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalInt64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_int64_extension_lite)
}
var ProtobufUnittest_optionalUint32ExtensionLite: UInt32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint32_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_uint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalUint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_uint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalUint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint32_extension_lite)
}
var ProtobufUnittest_optionalUint64ExtensionLite: UInt64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint64_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_uint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalUint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_uint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalUint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_uint64_extension_lite)
}
var ProtobufUnittest_optionalSint32ExtensionLite: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint32_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_sint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalSint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_sint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalSint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint32_extension_lite)
}
var ProtobufUnittest_optionalSint64ExtensionLite: Int64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint64_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_sint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalSint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_sint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalSint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_sint64_extension_lite)
}
var ProtobufUnittest_optionalFixed32ExtensionLite: UInt32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed32_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_fixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalFixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_fixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalFixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed32_extension_lite)
}
var ProtobufUnittest_optionalFixed64ExtensionLite: UInt64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed64_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_fixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalFixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_fixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalFixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_fixed64_extension_lite)
}
var ProtobufUnittest_optionalSfixed32ExtensionLite: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed32_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_sfixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalSfixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_sfixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalSfixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed32_extension_lite)
}
var ProtobufUnittest_optionalSfixed64ExtensionLite: Int64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed64_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_sfixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalSfixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_sfixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalSfixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_sfixed64_extension_lite)
}
var ProtobufUnittest_optionalFloatExtensionLite: Float {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_float_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_float_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_float_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalFloatExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_float_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_float_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalFloatExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_float_extension_lite)
}
var ProtobufUnittest_optionalDoubleExtensionLite: Double {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_double_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_double_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_double_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalDoubleExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_double_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_double_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalDoubleExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_double_extension_lite)
}
var ProtobufUnittest_optionalBoolExtensionLite: Bool {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_bool_extension_lite) ?? false}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_bool_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_bool_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalBoolExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_bool_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_bool_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalBoolExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_bool_extension_lite)
}
var ProtobufUnittest_optionalStringExtensionLite: String {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_extension_lite) ?? String()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_string_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalStringExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_string_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalStringExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_extension_lite)
}
var ProtobufUnittest_optionalBytesExtensionLite: Data {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_bytes_extension_lite) ?? SwiftProtobuf.Internal.emptyData}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_bytes_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_bytes_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalBytesExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_bytes_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_bytes_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalBytesExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_bytes_extension_lite)
}
var ProtobufUnittest_optionalGroupExtensionLite: ProtobufUnittest_OptionalGroup_extension_lite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_OptionalGroup_extension_lite) ?? ProtobufUnittest_OptionalGroup_extension_lite()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_OptionalGroup_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_OptionalGroup_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalGroupExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_OptionalGroup_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_OptionalGroup_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalGroupExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_OptionalGroup_extension_lite)
}
var ProtobufUnittest_optionalNestedMessageExtensionLite: ProtobufUnittest_TestAllTypesLite.NestedMessage {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_message_extension_lite) ?? ProtobufUnittest_TestAllTypesLite.NestedMessage()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_nested_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalNestedMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_nested_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalNestedMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_message_extension_lite)
}
var ProtobufUnittest_optionalForeignMessageExtensionLite: ProtobufUnittest_ForeignMessageLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_message_extension_lite) ?? ProtobufUnittest_ForeignMessageLite()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_foreign_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalForeignMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_foreign_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalForeignMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_message_extension_lite)
}
var ProtobufUnittest_optionalImportMessageExtensionLite: ProtobufUnittestImport_ImportMessageLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_message_extension_lite) ?? ProtobufUnittestImport_ImportMessageLite()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_import_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalImportMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_import_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalImportMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_message_extension_lite)
}
var ProtobufUnittest_optionalNestedEnumExtensionLite: ProtobufUnittest_TestAllTypesLite.NestedEnum {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_enum_extension_lite) ?? .foo}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_nested_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalNestedEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_nested_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalNestedEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_nested_enum_extension_lite)
}
var ProtobufUnittest_optionalForeignEnumExtensionLite: ProtobufUnittest_ForeignEnumLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite) ?? .foreignLiteFoo}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalForeignEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalForeignEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite)
}
var ProtobufUnittest_optionalImportEnumExtensionLite: ProtobufUnittestImport_ImportEnumLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_enum_extension_lite) ?? .importLiteFoo}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_import_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalImportEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_import_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalImportEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_import_enum_extension_lite)
}
var ProtobufUnittest_optionalStringPieceExtensionLite: String {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_piece_extension_lite) ?? String()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_piece_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_string_piece_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalStringPieceExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_piece_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_string_piece_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalStringPieceExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_string_piece_extension_lite)
}
var ProtobufUnittest_optionalCordExtensionLite: String {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_cord_extension_lite) ?? String()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_cord_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_cord_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalCordExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_cord_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_cord_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalCordExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_cord_extension_lite)
}
var ProtobufUnittest_optionalPublicImportMessageExtensionLite: ProtobufUnittestImport_PublicImportMessageLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_public_import_message_extension_lite) ?? ProtobufUnittestImport_PublicImportMessageLite()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_public_import_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_public_import_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalPublicImportMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_public_import_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_public_import_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalPublicImportMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_public_import_message_extension_lite)
}
var ProtobufUnittest_optionalLazyMessageExtensionLite: ProtobufUnittest_TestAllTypesLite.NestedMessage {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_optional_lazy_message_extension_lite) ?? ProtobufUnittest_TestAllTypesLite.NestedMessage()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_optional_lazy_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_optional_lazy_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_optionalLazyMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_optional_lazy_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_optional_lazy_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_optionalLazyMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_optional_lazy_message_extension_lite)
}
/// Repeated
var ProtobufUnittest_repeatedInt32ExtensionLite: [Int32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_int32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedInt32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_int32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedInt32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int32_extension_lite)
}
var ProtobufUnittest_repeatedInt64ExtensionLite: [Int64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_int64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedInt64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_int64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedInt64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_int64_extension_lite)
}
var ProtobufUnittest_repeatedUint32ExtensionLite: [UInt32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_uint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedUint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_uint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedUint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint32_extension_lite)
}
var ProtobufUnittest_repeatedUint64ExtensionLite: [UInt64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_uint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedUint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_uint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedUint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_uint64_extension_lite)
}
var ProtobufUnittest_repeatedSint32ExtensionLite: [Int32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_sint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedSint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_sint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedSint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint32_extension_lite)
}
var ProtobufUnittest_repeatedSint64ExtensionLite: [Int64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_sint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedSint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_sint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedSint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sint64_extension_lite)
}
var ProtobufUnittest_repeatedFixed32ExtensionLite: [UInt32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_fixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedFixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_fixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedFixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed32_extension_lite)
}
var ProtobufUnittest_repeatedFixed64ExtensionLite: [UInt64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_fixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedFixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_fixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedFixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_fixed64_extension_lite)
}
var ProtobufUnittest_repeatedSfixed32ExtensionLite: [Int32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedSfixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedSfixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite)
}
var ProtobufUnittest_repeatedSfixed64ExtensionLite: [Int64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedSfixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedSfixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite)
}
var ProtobufUnittest_repeatedFloatExtensionLite: [Float] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_float_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_float_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_float_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedFloatExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_float_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_float_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedFloatExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_float_extension_lite)
}
var ProtobufUnittest_repeatedDoubleExtensionLite: [Double] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_double_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_double_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_double_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedDoubleExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_double_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_double_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedDoubleExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_double_extension_lite)
}
var ProtobufUnittest_repeatedBoolExtensionLite: [Bool] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bool_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bool_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_bool_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedBoolExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bool_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_bool_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedBoolExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bool_extension_lite)
}
var ProtobufUnittest_repeatedStringExtensionLite: [String] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_string_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedStringExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_string_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedStringExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_extension_lite)
}
var ProtobufUnittest_repeatedBytesExtensionLite: [Data] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bytes_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bytes_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_bytes_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedBytesExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bytes_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_bytes_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedBytesExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_bytes_extension_lite)
}
var ProtobufUnittest_repeatedGroupExtensionLite: [ProtobufUnittest_RepeatedGroup_extension_lite] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_RepeatedGroup_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_RepeatedGroup_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_RepeatedGroup_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedGroupExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_RepeatedGroup_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_RepeatedGroup_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedGroupExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_RepeatedGroup_extension_lite)
}
var ProtobufUnittest_repeatedNestedMessageExtensionLite: [ProtobufUnittest_TestAllTypesLite.NestedMessage] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_message_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_nested_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedNestedMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_nested_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedNestedMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_message_extension_lite)
}
var ProtobufUnittest_repeatedForeignMessageExtensionLite: [ProtobufUnittest_ForeignMessageLite] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedForeignMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedForeignMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite)
}
var ProtobufUnittest_repeatedImportMessageExtensionLite: [ProtobufUnittestImport_ImportMessageLite] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_message_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_import_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedImportMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_import_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedImportMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_message_extension_lite)
}
var ProtobufUnittest_repeatedNestedEnumExtensionLite: [ProtobufUnittest_TestAllTypesLite.NestedEnum] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedNestedEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedNestedEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite)
}
var ProtobufUnittest_repeatedForeignEnumExtensionLite: [ProtobufUnittest_ForeignEnumLite] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedForeignEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedForeignEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite)
}
var ProtobufUnittest_repeatedImportEnumExtensionLite: [ProtobufUnittestImport_ImportEnumLite] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_enum_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_import_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedImportEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_import_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedImportEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_import_enum_extension_lite)
}
var ProtobufUnittest_repeatedStringPieceExtensionLite: [String] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_piece_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_piece_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_string_piece_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedStringPieceExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_piece_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_string_piece_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedStringPieceExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_string_piece_extension_lite)
}
var ProtobufUnittest_repeatedCordExtensionLite: [String] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_cord_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_cord_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_cord_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedCordExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_cord_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_cord_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedCordExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_cord_extension_lite)
}
var ProtobufUnittest_repeatedLazyMessageExtensionLite: [ProtobufUnittest_TestAllTypesLite.NestedMessage] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_repeatedLazyMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_repeatedLazyMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite)
}
/// Singular with defaults
var ProtobufUnittest_defaultInt32ExtensionLite: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_int32_extension_lite) ?? 41}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_int32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_int32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultInt32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_int32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_int32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultInt32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_int32_extension_lite)
}
var ProtobufUnittest_defaultInt64ExtensionLite: Int64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_int64_extension_lite) ?? 42}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_int64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_int64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultInt64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_int64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_int64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultInt64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_int64_extension_lite)
}
var ProtobufUnittest_defaultUint32ExtensionLite: UInt32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_uint32_extension_lite) ?? 43}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_uint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_uint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultUint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_uint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_uint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultUint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_uint32_extension_lite)
}
var ProtobufUnittest_defaultUint64ExtensionLite: UInt64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_uint64_extension_lite) ?? 44}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_uint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_uint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultUint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_uint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_uint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultUint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_uint64_extension_lite)
}
var ProtobufUnittest_defaultSint32ExtensionLite: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_sint32_extension_lite) ?? -45}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_sint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_sint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultSint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_sint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_sint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultSint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_sint32_extension_lite)
}
var ProtobufUnittest_defaultSint64ExtensionLite: Int64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_sint64_extension_lite) ?? 46}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_sint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_sint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultSint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_sint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_sint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultSint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_sint64_extension_lite)
}
var ProtobufUnittest_defaultFixed32ExtensionLite: UInt32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed32_extension_lite) ?? 47}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_fixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultFixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_fixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultFixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed32_extension_lite)
}
var ProtobufUnittest_defaultFixed64ExtensionLite: UInt64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed64_extension_lite) ?? 48}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_fixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultFixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_fixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultFixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_fixed64_extension_lite)
}
var ProtobufUnittest_defaultSfixed32ExtensionLite: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed32_extension_lite) ?? 49}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_sfixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultSfixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_sfixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultSfixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed32_extension_lite)
}
var ProtobufUnittest_defaultSfixed64ExtensionLite: Int64 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed64_extension_lite) ?? -50}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_sfixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultSfixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_sfixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultSfixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_sfixed64_extension_lite)
}
var ProtobufUnittest_defaultFloatExtensionLite: Float {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_float_extension_lite) ?? 51.5}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_float_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_float_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultFloatExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_float_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_float_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultFloatExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_float_extension_lite)
}
var ProtobufUnittest_defaultDoubleExtensionLite: Double {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_double_extension_lite) ?? 52000}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_double_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_double_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultDoubleExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_double_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_double_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultDoubleExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_double_extension_lite)
}
var ProtobufUnittest_defaultBoolExtensionLite: Bool {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_bool_extension_lite) ?? true}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_bool_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_bool_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultBoolExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_bool_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_bool_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultBoolExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_bool_extension_lite)
}
var ProtobufUnittest_defaultStringExtensionLite: String {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_string_extension_lite) ?? "hello"}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_string_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_string_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultStringExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_string_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_string_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultStringExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_string_extension_lite)
}
var ProtobufUnittest_defaultBytesExtensionLite: Data {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_bytes_extension_lite) ?? Data(bytes: [119, 111, 114, 108, 100])}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_bytes_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_bytes_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultBytesExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_bytes_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_bytes_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultBytesExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_bytes_extension_lite)
}
var ProtobufUnittest_defaultNestedEnumExtensionLite: ProtobufUnittest_TestAllTypesLite.NestedEnum {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_nested_enum_extension_lite) ?? .bar}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_nested_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_nested_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultNestedEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_nested_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_nested_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultNestedEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_nested_enum_extension_lite)
}
var ProtobufUnittest_defaultForeignEnumExtensionLite: ProtobufUnittest_ForeignEnumLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_foreign_enum_extension_lite) ?? .foreignLiteBar}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_foreign_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_foreign_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultForeignEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_foreign_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_foreign_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultForeignEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_foreign_enum_extension_lite)
}
var ProtobufUnittest_defaultImportEnumExtensionLite: ProtobufUnittestImport_ImportEnumLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_import_enum_extension_lite) ?? .importLiteBar}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_import_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_import_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultImportEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_import_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_import_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultImportEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_import_enum_extension_lite)
}
var ProtobufUnittest_defaultStringPieceExtensionLite: String {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_string_piece_extension_lite) ?? "abc"}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_string_piece_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_string_piece_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultStringPieceExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_string_piece_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_string_piece_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultStringPieceExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_string_piece_extension_lite)
}
var ProtobufUnittest_defaultCordExtensionLite: String {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_default_cord_extension_lite) ?? "123"}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_default_cord_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_default_cord_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_defaultCordExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_default_cord_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_default_cord_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_defaultCordExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_default_cord_extension_lite)
}
/// For oneof test
var ProtobufUnittest_oneofUint32ExtensionLite: UInt32 {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_oneof_uint32_extension_lite) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_oneof_uint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_oneof_uint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_oneofUint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_oneof_uint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_oneof_uint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_oneofUint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_oneof_uint32_extension_lite)
}
var ProtobufUnittest_oneofNestedMessageExtensionLite: ProtobufUnittest_TestAllTypesLite.NestedMessage {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_oneof_nested_message_extension_lite) ?? ProtobufUnittest_TestAllTypesLite.NestedMessage()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_oneof_nested_message_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_oneof_nested_message_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_oneofNestedMessageExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_oneof_nested_message_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_oneof_nested_message_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_oneofNestedMessageExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_oneof_nested_message_extension_lite)
}
var ProtobufUnittest_oneofStringExtensionLite: String {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_oneof_string_extension_lite) ?? String()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_oneof_string_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_oneof_string_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_oneofStringExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_oneof_string_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_oneof_string_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_oneofStringExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_oneof_string_extension_lite)
}
var ProtobufUnittest_oneofBytesExtensionLite: Data {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_oneof_bytes_extension_lite) ?? SwiftProtobuf.Internal.emptyData}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_oneof_bytes_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_oneof_bytes_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_oneofBytesExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_oneof_bytes_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_oneof_bytes_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_oneofBytesExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_oneof_bytes_extension_lite)
}
var ProtobufUnittest_TestNestedExtensionLite_nestedExtension: Int32 {
get {return getExtensionValue(ext: ProtobufUnittest_TestNestedExtensionLite.Extensions.nested_extension) ?? 0}
set {setExtensionValue(ext: ProtobufUnittest_TestNestedExtensionLite.Extensions.nested_extension, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_TestNestedExtensionLite.Extensions.nested_extension`
/// has been explicitly set.
var hasProtobufUnittest_TestNestedExtensionLite_nestedExtension: Bool {
return hasExtensionValue(ext: ProtobufUnittest_TestNestedExtensionLite.Extensions.nested_extension)
}
/// Clears the value of extension `ProtobufUnittest_TestNestedExtensionLite.Extensions.nested_extension`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_TestNestedExtensionLite_nestedExtension() {
clearExtensionValue(ext: ProtobufUnittest_TestNestedExtensionLite.Extensions.nested_extension)
}
}
extension ProtobufUnittest_TestHugeFieldNumbersLite {
var ProtobufUnittest_testAllTypesLite: ProtobufUnittest_TestAllTypesLite {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_test_all_types_lite) ?? ProtobufUnittest_TestAllTypesLite()}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_test_all_types_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_test_all_types_lite`
/// has been explicitly set.
var hasProtobufUnittest_testAllTypesLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_test_all_types_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_test_all_types_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_testAllTypesLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_test_all_types_lite)
}
}
extension ProtobufUnittest_TestPackedExtensionsLite {
var ProtobufUnittest_packedInt32ExtensionLite: [Int32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_int32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_int32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_int32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedInt32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_int32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_int32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedInt32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_int32_extension_lite)
}
var ProtobufUnittest_packedInt64ExtensionLite: [Int64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_int64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_int64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_int64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedInt64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_int64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_int64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedInt64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_int64_extension_lite)
}
var ProtobufUnittest_packedUint32ExtensionLite: [UInt32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_uint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedUint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_uint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedUint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint32_extension_lite)
}
var ProtobufUnittest_packedUint64ExtensionLite: [UInt64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_uint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedUint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_uint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedUint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_uint64_extension_lite)
}
var ProtobufUnittest_packedSint32ExtensionLite: [Int32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_sint32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedSint32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_sint32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedSint32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint32_extension_lite)
}
var ProtobufUnittest_packedSint64ExtensionLite: [Int64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_sint64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedSint64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_sint64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedSint64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_sint64_extension_lite)
}
var ProtobufUnittest_packedFixed32ExtensionLite: [UInt32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_fixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedFixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_fixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedFixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed32_extension_lite)
}
var ProtobufUnittest_packedFixed64ExtensionLite: [UInt64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_fixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedFixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_fixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedFixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_fixed64_extension_lite)
}
var ProtobufUnittest_packedSfixed32ExtensionLite: [Int32] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed32_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed32_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_sfixed32_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedSfixed32ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed32_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_sfixed32_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedSfixed32ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed32_extension_lite)
}
var ProtobufUnittest_packedSfixed64ExtensionLite: [Int64] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed64_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed64_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_sfixed64_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedSfixed64ExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed64_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_sfixed64_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedSfixed64ExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_sfixed64_extension_lite)
}
var ProtobufUnittest_packedFloatExtensionLite: [Float] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_float_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_float_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_float_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedFloatExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_float_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_float_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedFloatExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_float_extension_lite)
}
var ProtobufUnittest_packedDoubleExtensionLite: [Double] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_double_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_double_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_double_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedDoubleExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_double_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_double_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedDoubleExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_double_extension_lite)
}
var ProtobufUnittest_packedBoolExtensionLite: [Bool] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_bool_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_bool_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_bool_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedBoolExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_bool_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_bool_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedBoolExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_bool_extension_lite)
}
var ProtobufUnittest_packedEnumExtensionLite: [ProtobufUnittest_ForeignEnumLite] {
get {return getExtensionValue(ext: ProtobufUnittest_Extensions_packed_enum_extension_lite) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_Extensions_packed_enum_extension_lite, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_Extensions_packed_enum_extension_lite`
/// has been explicitly set.
var hasProtobufUnittest_packedEnumExtensionLite: Bool {
return hasExtensionValue(ext: ProtobufUnittest_Extensions_packed_enum_extension_lite)
}
/// Clears the value of extension `ProtobufUnittest_Extensions_packed_enum_extension_lite`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_packedEnumExtensionLite() {
clearExtensionValue(ext: ProtobufUnittest_Extensions_packed_enum_extension_lite)
}
}
extension ProtobufUnittest_TestParsingMergeLite {
var ProtobufUnittest_TestParsingMergeLite_optionalExt: ProtobufUnittest_TestAllTypesLite {
get {return getExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.optional_ext) ?? ProtobufUnittest_TestAllTypesLite()}
set {setExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.optional_ext, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_TestParsingMergeLite.Extensions.optional_ext`
/// has been explicitly set.
var hasProtobufUnittest_TestParsingMergeLite_optionalExt: Bool {
return hasExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.optional_ext)
}
/// Clears the value of extension `ProtobufUnittest_TestParsingMergeLite.Extensions.optional_ext`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_TestParsingMergeLite_optionalExt() {
clearExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.optional_ext)
}
var ProtobufUnittest_TestParsingMergeLite_repeatedExt: [ProtobufUnittest_TestAllTypesLite] {
get {return getExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.repeated_ext) ?? []}
set {setExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.repeated_ext, value: newValue)}
}
/// Returns true if extension `ProtobufUnittest_TestParsingMergeLite.Extensions.repeated_ext`
/// has been explicitly set.
var hasProtobufUnittest_TestParsingMergeLite_repeatedExt: Bool {
return hasExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.repeated_ext)
}
/// Clears the value of extension `ProtobufUnittest_TestParsingMergeLite.Extensions.repeated_ext`.
/// Subsequent reads from it will return its default value.
mutating func clearProtobufUnittest_TestParsingMergeLite_repeatedExt() {
clearExtensionValue(ext: ProtobufUnittest_TestParsingMergeLite.Extensions.repeated_ext)
}
}
/// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by
/// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed
/// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create
/// a larger `SwiftProtobuf.SimpleExtensionMap`.
let ProtobufUnittest_UnittestLite_Extensions: SwiftProtobuf.SimpleExtensionMap = [
ProtobufUnittest_Extensions_optional_int32_extension_lite,
ProtobufUnittest_Extensions_optional_int64_extension_lite,
ProtobufUnittest_Extensions_optional_uint32_extension_lite,
ProtobufUnittest_Extensions_optional_uint64_extension_lite,
ProtobufUnittest_Extensions_optional_sint32_extension_lite,
ProtobufUnittest_Extensions_optional_sint64_extension_lite,
ProtobufUnittest_Extensions_optional_fixed32_extension_lite,
ProtobufUnittest_Extensions_optional_fixed64_extension_lite,
ProtobufUnittest_Extensions_optional_sfixed32_extension_lite,
ProtobufUnittest_Extensions_optional_sfixed64_extension_lite,
ProtobufUnittest_Extensions_optional_float_extension_lite,
ProtobufUnittest_Extensions_optional_double_extension_lite,
ProtobufUnittest_Extensions_optional_bool_extension_lite,
ProtobufUnittest_Extensions_optional_string_extension_lite,
ProtobufUnittest_Extensions_optional_bytes_extension_lite,
ProtobufUnittest_Extensions_OptionalGroup_extension_lite,
ProtobufUnittest_Extensions_optional_nested_message_extension_lite,
ProtobufUnittest_Extensions_optional_foreign_message_extension_lite,
ProtobufUnittest_Extensions_optional_import_message_extension_lite,
ProtobufUnittest_Extensions_optional_nested_enum_extension_lite,
ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite,
ProtobufUnittest_Extensions_optional_import_enum_extension_lite,
ProtobufUnittest_Extensions_optional_string_piece_extension_lite,
ProtobufUnittest_Extensions_optional_cord_extension_lite,
ProtobufUnittest_Extensions_optional_public_import_message_extension_lite,
ProtobufUnittest_Extensions_optional_lazy_message_extension_lite,
ProtobufUnittest_Extensions_repeated_int32_extension_lite,
ProtobufUnittest_Extensions_repeated_int64_extension_lite,
ProtobufUnittest_Extensions_repeated_uint32_extension_lite,
ProtobufUnittest_Extensions_repeated_uint64_extension_lite,
ProtobufUnittest_Extensions_repeated_sint32_extension_lite,
ProtobufUnittest_Extensions_repeated_sint64_extension_lite,
ProtobufUnittest_Extensions_repeated_fixed32_extension_lite,
ProtobufUnittest_Extensions_repeated_fixed64_extension_lite,
ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite,
ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite,
ProtobufUnittest_Extensions_repeated_float_extension_lite,
ProtobufUnittest_Extensions_repeated_double_extension_lite,
ProtobufUnittest_Extensions_repeated_bool_extension_lite,
ProtobufUnittest_Extensions_repeated_string_extension_lite,
ProtobufUnittest_Extensions_repeated_bytes_extension_lite,
ProtobufUnittest_Extensions_RepeatedGroup_extension_lite,
ProtobufUnittest_Extensions_repeated_nested_message_extension_lite,
ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite,
ProtobufUnittest_Extensions_repeated_import_message_extension_lite,
ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite,
ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite,
ProtobufUnittest_Extensions_repeated_import_enum_extension_lite,
ProtobufUnittest_Extensions_repeated_string_piece_extension_lite,
ProtobufUnittest_Extensions_repeated_cord_extension_lite,
ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite,
ProtobufUnittest_Extensions_default_int32_extension_lite,
ProtobufUnittest_Extensions_default_int64_extension_lite,
ProtobufUnittest_Extensions_default_uint32_extension_lite,
ProtobufUnittest_Extensions_default_uint64_extension_lite,
ProtobufUnittest_Extensions_default_sint32_extension_lite,
ProtobufUnittest_Extensions_default_sint64_extension_lite,
ProtobufUnittest_Extensions_default_fixed32_extension_lite,
ProtobufUnittest_Extensions_default_fixed64_extension_lite,
ProtobufUnittest_Extensions_default_sfixed32_extension_lite,
ProtobufUnittest_Extensions_default_sfixed64_extension_lite,
ProtobufUnittest_Extensions_default_float_extension_lite,
ProtobufUnittest_Extensions_default_double_extension_lite,
ProtobufUnittest_Extensions_default_bool_extension_lite,
ProtobufUnittest_Extensions_default_string_extension_lite,
ProtobufUnittest_Extensions_default_bytes_extension_lite,
ProtobufUnittest_Extensions_default_nested_enum_extension_lite,
ProtobufUnittest_Extensions_default_foreign_enum_extension_lite,
ProtobufUnittest_Extensions_default_import_enum_extension_lite,
ProtobufUnittest_Extensions_default_string_piece_extension_lite,
ProtobufUnittest_Extensions_default_cord_extension_lite,
ProtobufUnittest_Extensions_oneof_uint32_extension_lite,
ProtobufUnittest_Extensions_oneof_nested_message_extension_lite,
ProtobufUnittest_Extensions_oneof_string_extension_lite,
ProtobufUnittest_Extensions_oneof_bytes_extension_lite,
ProtobufUnittest_Extensions_packed_int32_extension_lite,
ProtobufUnittest_Extensions_packed_int64_extension_lite,
ProtobufUnittest_Extensions_packed_uint32_extension_lite,
ProtobufUnittest_Extensions_packed_uint64_extension_lite,
ProtobufUnittest_Extensions_packed_sint32_extension_lite,
ProtobufUnittest_Extensions_packed_sint64_extension_lite,
ProtobufUnittest_Extensions_packed_fixed32_extension_lite,
ProtobufUnittest_Extensions_packed_fixed64_extension_lite,
ProtobufUnittest_Extensions_packed_sfixed32_extension_lite,
ProtobufUnittest_Extensions_packed_sfixed64_extension_lite,
ProtobufUnittest_Extensions_packed_float_extension_lite,
ProtobufUnittest_Extensions_packed_double_extension_lite,
ProtobufUnittest_Extensions_packed_bool_extension_lite,
ProtobufUnittest_Extensions_packed_enum_extension_lite,
ProtobufUnittest_Extensions_test_all_types_lite,
ProtobufUnittest_TestNestedExtensionLite.Extensions.nested_extension,
ProtobufUnittest_TestParsingMergeLite.Extensions.optional_ext,
ProtobufUnittest_TestParsingMergeLite.Extensions.repeated_ext
]
/// Singular
let ProtobufUnittest_Extensions_optional_int32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 1,
fieldName: "protobuf_unittest.optional_int32_extension_lite"
)
let ProtobufUnittest_Extensions_optional_int64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 2,
fieldName: "protobuf_unittest.optional_int64_extension_lite"
)
let ProtobufUnittest_Extensions_optional_uint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufUInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 3,
fieldName: "protobuf_unittest.optional_uint32_extension_lite"
)
let ProtobufUnittest_Extensions_optional_uint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufUInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 4,
fieldName: "protobuf_unittest.optional_uint64_extension_lite"
)
let ProtobufUnittest_Extensions_optional_sint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 5,
fieldName: "protobuf_unittest.optional_sint32_extension_lite"
)
let ProtobufUnittest_Extensions_optional_sint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 6,
fieldName: "protobuf_unittest.optional_sint64_extension_lite"
)
let ProtobufUnittest_Extensions_optional_fixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufFixed32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 7,
fieldName: "protobuf_unittest.optional_fixed32_extension_lite"
)
let ProtobufUnittest_Extensions_optional_fixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufFixed64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 8,
fieldName: "protobuf_unittest.optional_fixed64_extension_lite"
)
let ProtobufUnittest_Extensions_optional_sfixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSFixed32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 9,
fieldName: "protobuf_unittest.optional_sfixed32_extension_lite"
)
let ProtobufUnittest_Extensions_optional_sfixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSFixed64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 10,
fieldName: "protobuf_unittest.optional_sfixed64_extension_lite"
)
let ProtobufUnittest_Extensions_optional_float_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufFloat>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 11,
fieldName: "protobuf_unittest.optional_float_extension_lite"
)
let ProtobufUnittest_Extensions_optional_double_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufDouble>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 12,
fieldName: "protobuf_unittest.optional_double_extension_lite"
)
let ProtobufUnittest_Extensions_optional_bool_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 13,
fieldName: "protobuf_unittest.optional_bool_extension_lite"
)
let ProtobufUnittest_Extensions_optional_string_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 14,
fieldName: "protobuf_unittest.optional_string_extension_lite"
)
let ProtobufUnittest_Extensions_optional_bytes_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBytes>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 15,
fieldName: "protobuf_unittest.optional_bytes_extension_lite"
)
let ProtobufUnittest_Extensions_OptionalGroup_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalGroupExtensionField<ProtobufUnittest_OptionalGroup_extension_lite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 16,
fieldName: "protobuf_unittest.optionalgroup_extension_lite"
)
let ProtobufUnittest_Extensions_optional_nested_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittest_TestAllTypesLite.NestedMessage>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 18,
fieldName: "protobuf_unittest.optional_nested_message_extension_lite"
)
let ProtobufUnittest_Extensions_optional_foreign_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittest_ForeignMessageLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 19,
fieldName: "protobuf_unittest.optional_foreign_message_extension_lite"
)
let ProtobufUnittest_Extensions_optional_import_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittestImport_ImportMessageLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 20,
fieldName: "protobuf_unittest.optional_import_message_extension_lite"
)
let ProtobufUnittest_Extensions_optional_nested_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalEnumExtensionField<ProtobufUnittest_TestAllTypesLite.NestedEnum>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 21,
fieldName: "protobuf_unittest.optional_nested_enum_extension_lite"
)
let ProtobufUnittest_Extensions_optional_foreign_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalEnumExtensionField<ProtobufUnittest_ForeignEnumLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 22,
fieldName: "protobuf_unittest.optional_foreign_enum_extension_lite"
)
let ProtobufUnittest_Extensions_optional_import_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalEnumExtensionField<ProtobufUnittestImport_ImportEnumLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 23,
fieldName: "protobuf_unittest.optional_import_enum_extension_lite"
)
let ProtobufUnittest_Extensions_optional_string_piece_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 24,
fieldName: "protobuf_unittest.optional_string_piece_extension_lite"
)
let ProtobufUnittest_Extensions_optional_cord_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 25,
fieldName: "protobuf_unittest.optional_cord_extension_lite"
)
let ProtobufUnittest_Extensions_optional_public_import_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittestImport_PublicImportMessageLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 26,
fieldName: "protobuf_unittest.optional_public_import_message_extension_lite"
)
let ProtobufUnittest_Extensions_optional_lazy_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittest_TestAllTypesLite.NestedMessage>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 27,
fieldName: "protobuf_unittest.optional_lazy_message_extension_lite"
)
/// Repeated
let ProtobufUnittest_Extensions_repeated_int32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 31,
fieldName: "protobuf_unittest.repeated_int32_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_int64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 32,
fieldName: "protobuf_unittest.repeated_int64_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_uint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufUInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 33,
fieldName: "protobuf_unittest.repeated_uint32_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_uint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufUInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 34,
fieldName: "protobuf_unittest.repeated_uint64_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_sint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufSInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 35,
fieldName: "protobuf_unittest.repeated_sint32_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_sint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufSInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 36,
fieldName: "protobuf_unittest.repeated_sint64_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_fixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufFixed32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 37,
fieldName: "protobuf_unittest.repeated_fixed32_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_fixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufFixed64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 38,
fieldName: "protobuf_unittest.repeated_fixed64_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_sfixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufSFixed32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 39,
fieldName: "protobuf_unittest.repeated_sfixed32_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_sfixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufSFixed64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 40,
fieldName: "protobuf_unittest.repeated_sfixed64_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_float_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufFloat>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 41,
fieldName: "protobuf_unittest.repeated_float_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_double_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufDouble>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 42,
fieldName: "protobuf_unittest.repeated_double_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_bool_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 43,
fieldName: "protobuf_unittest.repeated_bool_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_string_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 44,
fieldName: "protobuf_unittest.repeated_string_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_bytes_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufBytes>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 45,
fieldName: "protobuf_unittest.repeated_bytes_extension_lite"
)
let ProtobufUnittest_Extensions_RepeatedGroup_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedGroupExtensionField<ProtobufUnittest_RepeatedGroup_extension_lite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 46,
fieldName: "protobuf_unittest.repeatedgroup_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_nested_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedMessageExtensionField<ProtobufUnittest_TestAllTypesLite.NestedMessage>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 48,
fieldName: "protobuf_unittest.repeated_nested_message_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_foreign_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedMessageExtensionField<ProtobufUnittest_ForeignMessageLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 49,
fieldName: "protobuf_unittest.repeated_foreign_message_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_import_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedMessageExtensionField<ProtobufUnittestImport_ImportMessageLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 50,
fieldName: "protobuf_unittest.repeated_import_message_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_nested_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedEnumExtensionField<ProtobufUnittest_TestAllTypesLite.NestedEnum>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 51,
fieldName: "protobuf_unittest.repeated_nested_enum_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_foreign_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedEnumExtensionField<ProtobufUnittest_ForeignEnumLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 52,
fieldName: "protobuf_unittest.repeated_foreign_enum_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_import_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedEnumExtensionField<ProtobufUnittestImport_ImportEnumLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 53,
fieldName: "protobuf_unittest.repeated_import_enum_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_string_piece_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 54,
fieldName: "protobuf_unittest.repeated_string_piece_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_cord_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 55,
fieldName: "protobuf_unittest.repeated_cord_extension_lite"
)
let ProtobufUnittest_Extensions_repeated_lazy_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedMessageExtensionField<ProtobufUnittest_TestAllTypesLite.NestedMessage>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 57,
fieldName: "protobuf_unittest.repeated_lazy_message_extension_lite"
)
/// Singular with defaults
let ProtobufUnittest_Extensions_default_int32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 61,
fieldName: "protobuf_unittest.default_int32_extension_lite"
)
let ProtobufUnittest_Extensions_default_int64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 62,
fieldName: "protobuf_unittest.default_int64_extension_lite"
)
let ProtobufUnittest_Extensions_default_uint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufUInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 63,
fieldName: "protobuf_unittest.default_uint32_extension_lite"
)
let ProtobufUnittest_Extensions_default_uint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufUInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 64,
fieldName: "protobuf_unittest.default_uint64_extension_lite"
)
let ProtobufUnittest_Extensions_default_sint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 65,
fieldName: "protobuf_unittest.default_sint32_extension_lite"
)
let ProtobufUnittest_Extensions_default_sint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSInt64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 66,
fieldName: "protobuf_unittest.default_sint64_extension_lite"
)
let ProtobufUnittest_Extensions_default_fixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufFixed32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 67,
fieldName: "protobuf_unittest.default_fixed32_extension_lite"
)
let ProtobufUnittest_Extensions_default_fixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufFixed64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 68,
fieldName: "protobuf_unittest.default_fixed64_extension_lite"
)
let ProtobufUnittest_Extensions_default_sfixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSFixed32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 69,
fieldName: "protobuf_unittest.default_sfixed32_extension_lite"
)
let ProtobufUnittest_Extensions_default_sfixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufSFixed64>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 70,
fieldName: "protobuf_unittest.default_sfixed64_extension_lite"
)
let ProtobufUnittest_Extensions_default_float_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufFloat>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 71,
fieldName: "protobuf_unittest.default_float_extension_lite"
)
let ProtobufUnittest_Extensions_default_double_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufDouble>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 72,
fieldName: "protobuf_unittest.default_double_extension_lite"
)
let ProtobufUnittest_Extensions_default_bool_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 73,
fieldName: "protobuf_unittest.default_bool_extension_lite"
)
let ProtobufUnittest_Extensions_default_string_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 74,
fieldName: "protobuf_unittest.default_string_extension_lite"
)
let ProtobufUnittest_Extensions_default_bytes_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBytes>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 75,
fieldName: "protobuf_unittest.default_bytes_extension_lite"
)
let ProtobufUnittest_Extensions_default_nested_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalEnumExtensionField<ProtobufUnittest_TestAllTypesLite.NestedEnum>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 81,
fieldName: "protobuf_unittest.default_nested_enum_extension_lite"
)
let ProtobufUnittest_Extensions_default_foreign_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalEnumExtensionField<ProtobufUnittest_ForeignEnumLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 82,
fieldName: "protobuf_unittest.default_foreign_enum_extension_lite"
)
let ProtobufUnittest_Extensions_default_import_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalEnumExtensionField<ProtobufUnittestImport_ImportEnumLite>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 83,
fieldName: "protobuf_unittest.default_import_enum_extension_lite"
)
let ProtobufUnittest_Extensions_default_string_piece_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 84,
fieldName: "protobuf_unittest.default_string_piece_extension_lite"
)
let ProtobufUnittest_Extensions_default_cord_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 85,
fieldName: "protobuf_unittest.default_cord_extension_lite"
)
/// For oneof test
let ProtobufUnittest_Extensions_oneof_uint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufUInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 111,
fieldName: "protobuf_unittest.oneof_uint32_extension_lite"
)
let ProtobufUnittest_Extensions_oneof_nested_message_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittest_TestAllTypesLite.NestedMessage>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 112,
fieldName: "protobuf_unittest.oneof_nested_message_extension_lite"
)
let ProtobufUnittest_Extensions_oneof_string_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufString>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 113,
fieldName: "protobuf_unittest.oneof_string_extension_lite"
)
let ProtobufUnittest_Extensions_oneof_bytes_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufBytes>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 114,
fieldName: "protobuf_unittest.oneof_bytes_extension_lite"
)
let ProtobufUnittest_Extensions_packed_int32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufInt32>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 90,
fieldName: "protobuf_unittest.packed_int32_extension_lite"
)
let ProtobufUnittest_Extensions_packed_int64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufInt64>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 91,
fieldName: "protobuf_unittest.packed_int64_extension_lite"
)
let ProtobufUnittest_Extensions_packed_uint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufUInt32>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 92,
fieldName: "protobuf_unittest.packed_uint32_extension_lite"
)
let ProtobufUnittest_Extensions_packed_uint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufUInt64>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 93,
fieldName: "protobuf_unittest.packed_uint64_extension_lite"
)
let ProtobufUnittest_Extensions_packed_sint32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufSInt32>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 94,
fieldName: "protobuf_unittest.packed_sint32_extension_lite"
)
let ProtobufUnittest_Extensions_packed_sint64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufSInt64>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 95,
fieldName: "protobuf_unittest.packed_sint64_extension_lite"
)
let ProtobufUnittest_Extensions_packed_fixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufFixed32>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 96,
fieldName: "protobuf_unittest.packed_fixed32_extension_lite"
)
let ProtobufUnittest_Extensions_packed_fixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufFixed64>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 97,
fieldName: "protobuf_unittest.packed_fixed64_extension_lite"
)
let ProtobufUnittest_Extensions_packed_sfixed32_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufSFixed32>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 98,
fieldName: "protobuf_unittest.packed_sfixed32_extension_lite"
)
let ProtobufUnittest_Extensions_packed_sfixed64_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufSFixed64>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 99,
fieldName: "protobuf_unittest.packed_sfixed64_extension_lite"
)
let ProtobufUnittest_Extensions_packed_float_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufFloat>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 100,
fieldName: "protobuf_unittest.packed_float_extension_lite"
)
let ProtobufUnittest_Extensions_packed_double_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufDouble>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 101,
fieldName: "protobuf_unittest.packed_double_extension_lite"
)
let ProtobufUnittest_Extensions_packed_bool_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedExtensionField<SwiftProtobuf.ProtobufBool>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 102,
fieldName: "protobuf_unittest.packed_bool_extension_lite"
)
let ProtobufUnittest_Extensions_packed_enum_extension_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.PackedEnumExtensionField<ProtobufUnittest_ForeignEnumLite>, ProtobufUnittest_TestPackedExtensionsLite>(
_protobuf_fieldNumber: 103,
fieldName: "protobuf_unittest.packed_enum_extension_lite"
)
let ProtobufUnittest_Extensions_test_all_types_lite = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittest_TestAllTypesLite>, ProtobufUnittest_TestHugeFieldNumbersLite>(
_protobuf_fieldNumber: 536860000,
fieldName: "protobuf_unittest.test_all_types_lite"
)
extension ProtobufUnittest_TestNestedExtensionLite {
enum Extensions {
static let nested_extension = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt32>, ProtobufUnittest_TestAllExtensionsLite>(
_protobuf_fieldNumber: 12345,
fieldName: "protobuf_unittest.TestNestedExtensionLite.nested_extension"
)
}
}
extension ProtobufUnittest_TestParsingMergeLite {
enum Extensions {
static let optional_ext = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalMessageExtensionField<ProtobufUnittest_TestAllTypesLite>, ProtobufUnittest_TestParsingMergeLite>(
_protobuf_fieldNumber: 1000,
fieldName: "protobuf_unittest.TestParsingMergeLite.optional_ext"
)
static let repeated_ext = SwiftProtobuf.MessageExtension<SwiftProtobuf.RepeatedMessageExtensionField<ProtobufUnittest_TestAllTypesLite>, ProtobufUnittest_TestParsingMergeLite>(
_protobuf_fieldNumber: 1001,
fieldName: "protobuf_unittest.TestParsingMergeLite.repeated_ext"
)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest"
extension ProtobufUnittest_ForeignEnumLite: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
4: .same(proto: "FOREIGN_LITE_FOO"),
5: .same(proto: "FOREIGN_LITE_BAR"),
6: .same(proto: "FOREIGN_LITE_BAZ"),
]
}
extension ProtobufUnittest_V1EnumLite: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "V1_FIRST"),
]
}
extension ProtobufUnittest_V2EnumLite: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "V2_FIRST"),
2: .same(proto: "V2_SECOND"),
]
}
extension ProtobufUnittest_TestAllTypesLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestAllTypesLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "optional_int32"),
2: .standard(proto: "optional_int64"),
3: .standard(proto: "optional_uint32"),
4: .standard(proto: "optional_uint64"),
5: .standard(proto: "optional_sint32"),
6: .standard(proto: "optional_sint64"),
7: .standard(proto: "optional_fixed32"),
8: .standard(proto: "optional_fixed64"),
9: .standard(proto: "optional_sfixed32"),
10: .standard(proto: "optional_sfixed64"),
11: .standard(proto: "optional_float"),
12: .standard(proto: "optional_double"),
13: .standard(proto: "optional_bool"),
14: .standard(proto: "optional_string"),
15: .standard(proto: "optional_bytes"),
16: .unique(proto: "OptionalGroup", json: "optionalgroup"),
18: .standard(proto: "optional_nested_message"),
19: .standard(proto: "optional_foreign_message"),
20: .standard(proto: "optional_import_message"),
21: .standard(proto: "optional_nested_enum"),
22: .standard(proto: "optional_foreign_enum"),
23: .standard(proto: "optional_import_enum"),
24: .standard(proto: "optional_string_piece"),
25: .standard(proto: "optional_cord"),
26: .standard(proto: "optional_public_import_message"),
27: .standard(proto: "optional_lazy_message"),
31: .standard(proto: "repeated_int32"),
32: .standard(proto: "repeated_int64"),
33: .standard(proto: "repeated_uint32"),
34: .standard(proto: "repeated_uint64"),
35: .standard(proto: "repeated_sint32"),
36: .standard(proto: "repeated_sint64"),
37: .standard(proto: "repeated_fixed32"),
38: .standard(proto: "repeated_fixed64"),
39: .standard(proto: "repeated_sfixed32"),
40: .standard(proto: "repeated_sfixed64"),
41: .standard(proto: "repeated_float"),
42: .standard(proto: "repeated_double"),
43: .standard(proto: "repeated_bool"),
44: .standard(proto: "repeated_string"),
45: .standard(proto: "repeated_bytes"),
46: .unique(proto: "RepeatedGroup", json: "repeatedgroup"),
48: .standard(proto: "repeated_nested_message"),
49: .standard(proto: "repeated_foreign_message"),
50: .standard(proto: "repeated_import_message"),
51: .standard(proto: "repeated_nested_enum"),
52: .standard(proto: "repeated_foreign_enum"),
53: .standard(proto: "repeated_import_enum"),
54: .standard(proto: "repeated_string_piece"),
55: .standard(proto: "repeated_cord"),
57: .standard(proto: "repeated_lazy_message"),
61: .standard(proto: "default_int32"),
62: .standard(proto: "default_int64"),
63: .standard(proto: "default_uint32"),
64: .standard(proto: "default_uint64"),
65: .standard(proto: "default_sint32"),
66: .standard(proto: "default_sint64"),
67: .standard(proto: "default_fixed32"),
68: .standard(proto: "default_fixed64"),
69: .standard(proto: "default_sfixed32"),
70: .standard(proto: "default_sfixed64"),
71: .standard(proto: "default_float"),
72: .standard(proto: "default_double"),
73: .standard(proto: "default_bool"),
74: .standard(proto: "default_string"),
75: .standard(proto: "default_bytes"),
81: .standard(proto: "default_nested_enum"),
82: .standard(proto: "default_foreign_enum"),
83: .standard(proto: "default_import_enum"),
84: .standard(proto: "default_string_piece"),
85: .standard(proto: "default_cord"),
111: .standard(proto: "oneof_uint32"),
112: .standard(proto: "oneof_nested_message"),
113: .standard(proto: "oneof_string"),
114: .standard(proto: "oneof_bytes"),
115: .standard(proto: "oneof_lazy_nested_message"),
116: .standard(proto: "deceptively_named_list"),
]
fileprivate class _StorageClass {
var _optionalInt32: Int32? = nil
var _optionalInt64: Int64? = nil
var _optionalUint32: UInt32? = nil
var _optionalUint64: UInt64? = nil
var _optionalSint32: Int32? = nil
var _optionalSint64: Int64? = nil
var _optionalFixed32: UInt32? = nil
var _optionalFixed64: UInt64? = nil
var _optionalSfixed32: Int32? = nil
var _optionalSfixed64: Int64? = nil
var _optionalFloat: Float? = nil
var _optionalDouble: Double? = nil
var _optionalBool: Bool? = nil
var _optionalString: String? = nil
var _optionalBytes: Data? = nil
var _optionalGroup: ProtobufUnittest_TestAllTypesLite.OptionalGroup? = nil
var _optionalNestedMessage: ProtobufUnittest_TestAllTypesLite.NestedMessage? = nil
var _optionalForeignMessage: ProtobufUnittest_ForeignMessageLite? = nil
var _optionalImportMessage: ProtobufUnittestImport_ImportMessageLite? = nil
var _optionalNestedEnum: ProtobufUnittest_TestAllTypesLite.NestedEnum? = nil
var _optionalForeignEnum: ProtobufUnittest_ForeignEnumLite? = nil
var _optionalImportEnum: ProtobufUnittestImport_ImportEnumLite? = nil
var _optionalStringPiece: String? = nil
var _optionalCord: String? = nil
var _optionalPublicImportMessage: ProtobufUnittestImport_PublicImportMessageLite? = nil
var _optionalLazyMessage: ProtobufUnittest_TestAllTypesLite.NestedMessage? = nil
var _repeatedInt32: [Int32] = []
var _repeatedInt64: [Int64] = []
var _repeatedUint32: [UInt32] = []
var _repeatedUint64: [UInt64] = []
var _repeatedSint32: [Int32] = []
var _repeatedSint64: [Int64] = []
var _repeatedFixed32: [UInt32] = []
var _repeatedFixed64: [UInt64] = []
var _repeatedSfixed32: [Int32] = []
var _repeatedSfixed64: [Int64] = []
var _repeatedFloat: [Float] = []
var _repeatedDouble: [Double] = []
var _repeatedBool: [Bool] = []
var _repeatedString: [String] = []
var _repeatedBytes: [Data] = []
var _repeatedGroup: [ProtobufUnittest_TestAllTypesLite.RepeatedGroup] = []
var _repeatedNestedMessage: [ProtobufUnittest_TestAllTypesLite.NestedMessage] = []
var _repeatedForeignMessage: [ProtobufUnittest_ForeignMessageLite] = []
var _repeatedImportMessage: [ProtobufUnittestImport_ImportMessageLite] = []
var _repeatedNestedEnum: [ProtobufUnittest_TestAllTypesLite.NestedEnum] = []
var _repeatedForeignEnum: [ProtobufUnittest_ForeignEnumLite] = []
var _repeatedImportEnum: [ProtobufUnittestImport_ImportEnumLite] = []
var _repeatedStringPiece: [String] = []
var _repeatedCord: [String] = []
var _repeatedLazyMessage: [ProtobufUnittest_TestAllTypesLite.NestedMessage] = []
var _defaultInt32: Int32? = nil
var _defaultInt64: Int64? = nil
var _defaultUint32: UInt32? = nil
var _defaultUint64: UInt64? = nil
var _defaultSint32: Int32? = nil
var _defaultSint64: Int64? = nil
var _defaultFixed32: UInt32? = nil
var _defaultFixed64: UInt64? = nil
var _defaultSfixed32: Int32? = nil
var _defaultSfixed64: Int64? = nil
var _defaultFloat: Float? = nil
var _defaultDouble: Double? = nil
var _defaultBool: Bool? = nil
var _defaultString: String? = nil
var _defaultBytes: Data? = nil
var _defaultNestedEnum: ProtobufUnittest_TestAllTypesLite.NestedEnum? = nil
var _defaultForeignEnum: ProtobufUnittest_ForeignEnumLite? = nil
var _defaultImportEnum: ProtobufUnittestImport_ImportEnumLite? = nil
var _defaultStringPiece: String? = nil
var _defaultCord: String? = nil
var _oneofField: ProtobufUnittest_TestAllTypesLite.OneOf_OneofField?
var _deceptivelyNamedList: Int32? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_optionalInt32 = source._optionalInt32
_optionalInt64 = source._optionalInt64
_optionalUint32 = source._optionalUint32
_optionalUint64 = source._optionalUint64
_optionalSint32 = source._optionalSint32
_optionalSint64 = source._optionalSint64
_optionalFixed32 = source._optionalFixed32
_optionalFixed64 = source._optionalFixed64
_optionalSfixed32 = source._optionalSfixed32
_optionalSfixed64 = source._optionalSfixed64
_optionalFloat = source._optionalFloat
_optionalDouble = source._optionalDouble
_optionalBool = source._optionalBool
_optionalString = source._optionalString
_optionalBytes = source._optionalBytes
_optionalGroup = source._optionalGroup
_optionalNestedMessage = source._optionalNestedMessage
_optionalForeignMessage = source._optionalForeignMessage
_optionalImportMessage = source._optionalImportMessage
_optionalNestedEnum = source._optionalNestedEnum
_optionalForeignEnum = source._optionalForeignEnum
_optionalImportEnum = source._optionalImportEnum
_optionalStringPiece = source._optionalStringPiece
_optionalCord = source._optionalCord
_optionalPublicImportMessage = source._optionalPublicImportMessage
_optionalLazyMessage = source._optionalLazyMessage
_repeatedInt32 = source._repeatedInt32
_repeatedInt64 = source._repeatedInt64
_repeatedUint32 = source._repeatedUint32
_repeatedUint64 = source._repeatedUint64
_repeatedSint32 = source._repeatedSint32
_repeatedSint64 = source._repeatedSint64
_repeatedFixed32 = source._repeatedFixed32
_repeatedFixed64 = source._repeatedFixed64
_repeatedSfixed32 = source._repeatedSfixed32
_repeatedSfixed64 = source._repeatedSfixed64
_repeatedFloat = source._repeatedFloat
_repeatedDouble = source._repeatedDouble
_repeatedBool = source._repeatedBool
_repeatedString = source._repeatedString
_repeatedBytes = source._repeatedBytes
_repeatedGroup = source._repeatedGroup
_repeatedNestedMessage = source._repeatedNestedMessage
_repeatedForeignMessage = source._repeatedForeignMessage
_repeatedImportMessage = source._repeatedImportMessage
_repeatedNestedEnum = source._repeatedNestedEnum
_repeatedForeignEnum = source._repeatedForeignEnum
_repeatedImportEnum = source._repeatedImportEnum
_repeatedStringPiece = source._repeatedStringPiece
_repeatedCord = source._repeatedCord
_repeatedLazyMessage = source._repeatedLazyMessage
_defaultInt32 = source._defaultInt32
_defaultInt64 = source._defaultInt64
_defaultUint32 = source._defaultUint32
_defaultUint64 = source._defaultUint64
_defaultSint32 = source._defaultSint32
_defaultSint64 = source._defaultSint64
_defaultFixed32 = source._defaultFixed32
_defaultFixed64 = source._defaultFixed64
_defaultSfixed32 = source._defaultSfixed32
_defaultSfixed64 = source._defaultSfixed64
_defaultFloat = source._defaultFloat
_defaultDouble = source._defaultDouble
_defaultBool = source._defaultBool
_defaultString = source._defaultString
_defaultBytes = source._defaultBytes
_defaultNestedEnum = source._defaultNestedEnum
_defaultForeignEnum = source._defaultForeignEnum
_defaultImportEnum = source._defaultImportEnum
_defaultStringPiece = source._defaultStringPiece
_defaultCord = source._defaultCord
_oneofField = source._oneofField
_deceptivelyNamedList = source._deceptivelyNamedList
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &_storage._optionalInt32)
case 2: try decoder.decodeSingularInt64Field(value: &_storage._optionalInt64)
case 3: try decoder.decodeSingularUInt32Field(value: &_storage._optionalUint32)
case 4: try decoder.decodeSingularUInt64Field(value: &_storage._optionalUint64)
case 5: try decoder.decodeSingularSInt32Field(value: &_storage._optionalSint32)
case 6: try decoder.decodeSingularSInt64Field(value: &_storage._optionalSint64)
case 7: try decoder.decodeSingularFixed32Field(value: &_storage._optionalFixed32)
case 8: try decoder.decodeSingularFixed64Field(value: &_storage._optionalFixed64)
case 9: try decoder.decodeSingularSFixed32Field(value: &_storage._optionalSfixed32)
case 10: try decoder.decodeSingularSFixed64Field(value: &_storage._optionalSfixed64)
case 11: try decoder.decodeSingularFloatField(value: &_storage._optionalFloat)
case 12: try decoder.decodeSingularDoubleField(value: &_storage._optionalDouble)
case 13: try decoder.decodeSingularBoolField(value: &_storage._optionalBool)
case 14: try decoder.decodeSingularStringField(value: &_storage._optionalString)
case 15: try decoder.decodeSingularBytesField(value: &_storage._optionalBytes)
case 16: try decoder.decodeSingularGroupField(value: &_storage._optionalGroup)
case 18: try decoder.decodeSingularMessageField(value: &_storage._optionalNestedMessage)
case 19: try decoder.decodeSingularMessageField(value: &_storage._optionalForeignMessage)
case 20: try decoder.decodeSingularMessageField(value: &_storage._optionalImportMessage)
case 21: try decoder.decodeSingularEnumField(value: &_storage._optionalNestedEnum)
case 22: try decoder.decodeSingularEnumField(value: &_storage._optionalForeignEnum)
case 23: try decoder.decodeSingularEnumField(value: &_storage._optionalImportEnum)
case 24: try decoder.decodeSingularStringField(value: &_storage._optionalStringPiece)
case 25: try decoder.decodeSingularStringField(value: &_storage._optionalCord)
case 26: try decoder.decodeSingularMessageField(value: &_storage._optionalPublicImportMessage)
case 27: try decoder.decodeSingularMessageField(value: &_storage._optionalLazyMessage)
case 31: try decoder.decodeRepeatedInt32Field(value: &_storage._repeatedInt32)
case 32: try decoder.decodeRepeatedInt64Field(value: &_storage._repeatedInt64)
case 33: try decoder.decodeRepeatedUInt32Field(value: &_storage._repeatedUint32)
case 34: try decoder.decodeRepeatedUInt64Field(value: &_storage._repeatedUint64)
case 35: try decoder.decodeRepeatedSInt32Field(value: &_storage._repeatedSint32)
case 36: try decoder.decodeRepeatedSInt64Field(value: &_storage._repeatedSint64)
case 37: try decoder.decodeRepeatedFixed32Field(value: &_storage._repeatedFixed32)
case 38: try decoder.decodeRepeatedFixed64Field(value: &_storage._repeatedFixed64)
case 39: try decoder.decodeRepeatedSFixed32Field(value: &_storage._repeatedSfixed32)
case 40: try decoder.decodeRepeatedSFixed64Field(value: &_storage._repeatedSfixed64)
case 41: try decoder.decodeRepeatedFloatField(value: &_storage._repeatedFloat)
case 42: try decoder.decodeRepeatedDoubleField(value: &_storage._repeatedDouble)
case 43: try decoder.decodeRepeatedBoolField(value: &_storage._repeatedBool)
case 44: try decoder.decodeRepeatedStringField(value: &_storage._repeatedString)
case 45: try decoder.decodeRepeatedBytesField(value: &_storage._repeatedBytes)
case 46: try decoder.decodeRepeatedGroupField(value: &_storage._repeatedGroup)
case 48: try decoder.decodeRepeatedMessageField(value: &_storage._repeatedNestedMessage)
case 49: try decoder.decodeRepeatedMessageField(value: &_storage._repeatedForeignMessage)
case 50: try decoder.decodeRepeatedMessageField(value: &_storage._repeatedImportMessage)
case 51: try decoder.decodeRepeatedEnumField(value: &_storage._repeatedNestedEnum)
case 52: try decoder.decodeRepeatedEnumField(value: &_storage._repeatedForeignEnum)
case 53: try decoder.decodeRepeatedEnumField(value: &_storage._repeatedImportEnum)
case 54: try decoder.decodeRepeatedStringField(value: &_storage._repeatedStringPiece)
case 55: try decoder.decodeRepeatedStringField(value: &_storage._repeatedCord)
case 57: try decoder.decodeRepeatedMessageField(value: &_storage._repeatedLazyMessage)
case 61: try decoder.decodeSingularInt32Field(value: &_storage._defaultInt32)
case 62: try decoder.decodeSingularInt64Field(value: &_storage._defaultInt64)
case 63: try decoder.decodeSingularUInt32Field(value: &_storage._defaultUint32)
case 64: try decoder.decodeSingularUInt64Field(value: &_storage._defaultUint64)
case 65: try decoder.decodeSingularSInt32Field(value: &_storage._defaultSint32)
case 66: try decoder.decodeSingularSInt64Field(value: &_storage._defaultSint64)
case 67: try decoder.decodeSingularFixed32Field(value: &_storage._defaultFixed32)
case 68: try decoder.decodeSingularFixed64Field(value: &_storage._defaultFixed64)
case 69: try decoder.decodeSingularSFixed32Field(value: &_storage._defaultSfixed32)
case 70: try decoder.decodeSingularSFixed64Field(value: &_storage._defaultSfixed64)
case 71: try decoder.decodeSingularFloatField(value: &_storage._defaultFloat)
case 72: try decoder.decodeSingularDoubleField(value: &_storage._defaultDouble)
case 73: try decoder.decodeSingularBoolField(value: &_storage._defaultBool)
case 74: try decoder.decodeSingularStringField(value: &_storage._defaultString)
case 75: try decoder.decodeSingularBytesField(value: &_storage._defaultBytes)
case 81: try decoder.decodeSingularEnumField(value: &_storage._defaultNestedEnum)
case 82: try decoder.decodeSingularEnumField(value: &_storage._defaultForeignEnum)
case 83: try decoder.decodeSingularEnumField(value: &_storage._defaultImportEnum)
case 84: try decoder.decodeSingularStringField(value: &_storage._defaultStringPiece)
case 85: try decoder.decodeSingularStringField(value: &_storage._defaultCord)
case 111:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: UInt32?
try decoder.decodeSingularUInt32Field(value: &v)
if let v = v {_storage._oneofField = .oneofUint32(v)}
case 112:
var v: ProtobufUnittest_TestAllTypesLite.NestedMessage?
if let current = _storage._oneofField {
try decoder.handleConflictingOneOf()
if case .oneofNestedMessage(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {_storage._oneofField = .oneofNestedMessage(v)}
case 113:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {_storage._oneofField = .oneofString(v)}
case 114:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: Data?
try decoder.decodeSingularBytesField(value: &v)
if let v = v {_storage._oneofField = .oneofBytes(v)}
case 115:
var v: ProtobufUnittest_TestAllTypesLite.NestedMessage?
if let current = _storage._oneofField {
try decoder.handleConflictingOneOf()
if case .oneofLazyNestedMessage(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {_storage._oneofField = .oneofLazyNestedMessage(v)}
case 116: try decoder.decodeSingularInt32Field(value: &_storage._deceptivelyNamedList)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._optionalInt32 {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
if let v = _storage._optionalInt64 {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 2)
}
if let v = _storage._optionalUint32 {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 3)
}
if let v = _storage._optionalUint64 {
try visitor.visitSingularUInt64Field(value: v, fieldNumber: 4)
}
if let v = _storage._optionalSint32 {
try visitor.visitSingularSInt32Field(value: v, fieldNumber: 5)
}
if let v = _storage._optionalSint64 {
try visitor.visitSingularSInt64Field(value: v, fieldNumber: 6)
}
if let v = _storage._optionalFixed32 {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 7)
}
if let v = _storage._optionalFixed64 {
try visitor.visitSingularFixed64Field(value: v, fieldNumber: 8)
}
if let v = _storage._optionalSfixed32 {
try visitor.visitSingularSFixed32Field(value: v, fieldNumber: 9)
}
if let v = _storage._optionalSfixed64 {
try visitor.visitSingularSFixed64Field(value: v, fieldNumber: 10)
}
if let v = _storage._optionalFloat {
try visitor.visitSingularFloatField(value: v, fieldNumber: 11)
}
if let v = _storage._optionalDouble {
try visitor.visitSingularDoubleField(value: v, fieldNumber: 12)
}
if let v = _storage._optionalBool {
try visitor.visitSingularBoolField(value: v, fieldNumber: 13)
}
if let v = _storage._optionalString {
try visitor.visitSingularStringField(value: v, fieldNumber: 14)
}
if let v = _storage._optionalBytes {
try visitor.visitSingularBytesField(value: v, fieldNumber: 15)
}
if let v = _storage._optionalGroup {
try visitor.visitSingularGroupField(value: v, fieldNumber: 16)
}
if let v = _storage._optionalNestedMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 18)
}
if let v = _storage._optionalForeignMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 19)
}
if let v = _storage._optionalImportMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 20)
}
if let v = _storage._optionalNestedEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 21)
}
if let v = _storage._optionalForeignEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 22)
}
if let v = _storage._optionalImportEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 23)
}
if let v = _storage._optionalStringPiece {
try visitor.visitSingularStringField(value: v, fieldNumber: 24)
}
if let v = _storage._optionalCord {
try visitor.visitSingularStringField(value: v, fieldNumber: 25)
}
if let v = _storage._optionalPublicImportMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 26)
}
if let v = _storage._optionalLazyMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 27)
}
if !_storage._repeatedInt32.isEmpty {
try visitor.visitRepeatedInt32Field(value: _storage._repeatedInt32, fieldNumber: 31)
}
if !_storage._repeatedInt64.isEmpty {
try visitor.visitRepeatedInt64Field(value: _storage._repeatedInt64, fieldNumber: 32)
}
if !_storage._repeatedUint32.isEmpty {
try visitor.visitRepeatedUInt32Field(value: _storage._repeatedUint32, fieldNumber: 33)
}
if !_storage._repeatedUint64.isEmpty {
try visitor.visitRepeatedUInt64Field(value: _storage._repeatedUint64, fieldNumber: 34)
}
if !_storage._repeatedSint32.isEmpty {
try visitor.visitRepeatedSInt32Field(value: _storage._repeatedSint32, fieldNumber: 35)
}
if !_storage._repeatedSint64.isEmpty {
try visitor.visitRepeatedSInt64Field(value: _storage._repeatedSint64, fieldNumber: 36)
}
if !_storage._repeatedFixed32.isEmpty {
try visitor.visitRepeatedFixed32Field(value: _storage._repeatedFixed32, fieldNumber: 37)
}
if !_storage._repeatedFixed64.isEmpty {
try visitor.visitRepeatedFixed64Field(value: _storage._repeatedFixed64, fieldNumber: 38)
}
if !_storage._repeatedSfixed32.isEmpty {
try visitor.visitRepeatedSFixed32Field(value: _storage._repeatedSfixed32, fieldNumber: 39)
}
if !_storage._repeatedSfixed64.isEmpty {
try visitor.visitRepeatedSFixed64Field(value: _storage._repeatedSfixed64, fieldNumber: 40)
}
if !_storage._repeatedFloat.isEmpty {
try visitor.visitRepeatedFloatField(value: _storage._repeatedFloat, fieldNumber: 41)
}
if !_storage._repeatedDouble.isEmpty {
try visitor.visitRepeatedDoubleField(value: _storage._repeatedDouble, fieldNumber: 42)
}
if !_storage._repeatedBool.isEmpty {
try visitor.visitRepeatedBoolField(value: _storage._repeatedBool, fieldNumber: 43)
}
if !_storage._repeatedString.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._repeatedString, fieldNumber: 44)
}
if !_storage._repeatedBytes.isEmpty {
try visitor.visitRepeatedBytesField(value: _storage._repeatedBytes, fieldNumber: 45)
}
if !_storage._repeatedGroup.isEmpty {
try visitor.visitRepeatedGroupField(value: _storage._repeatedGroup, fieldNumber: 46)
}
if !_storage._repeatedNestedMessage.isEmpty {
try visitor.visitRepeatedMessageField(value: _storage._repeatedNestedMessage, fieldNumber: 48)
}
if !_storage._repeatedForeignMessage.isEmpty {
try visitor.visitRepeatedMessageField(value: _storage._repeatedForeignMessage, fieldNumber: 49)
}
if !_storage._repeatedImportMessage.isEmpty {
try visitor.visitRepeatedMessageField(value: _storage._repeatedImportMessage, fieldNumber: 50)
}
if !_storage._repeatedNestedEnum.isEmpty {
try visitor.visitRepeatedEnumField(value: _storage._repeatedNestedEnum, fieldNumber: 51)
}
if !_storage._repeatedForeignEnum.isEmpty {
try visitor.visitRepeatedEnumField(value: _storage._repeatedForeignEnum, fieldNumber: 52)
}
if !_storage._repeatedImportEnum.isEmpty {
try visitor.visitRepeatedEnumField(value: _storage._repeatedImportEnum, fieldNumber: 53)
}
if !_storage._repeatedStringPiece.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._repeatedStringPiece, fieldNumber: 54)
}
if !_storage._repeatedCord.isEmpty {
try visitor.visitRepeatedStringField(value: _storage._repeatedCord, fieldNumber: 55)
}
if !_storage._repeatedLazyMessage.isEmpty {
try visitor.visitRepeatedMessageField(value: _storage._repeatedLazyMessage, fieldNumber: 57)
}
if let v = _storage._defaultInt32 {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 61)
}
if let v = _storage._defaultInt64 {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 62)
}
if let v = _storage._defaultUint32 {
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 63)
}
if let v = _storage._defaultUint64 {
try visitor.visitSingularUInt64Field(value: v, fieldNumber: 64)
}
if let v = _storage._defaultSint32 {
try visitor.visitSingularSInt32Field(value: v, fieldNumber: 65)
}
if let v = _storage._defaultSint64 {
try visitor.visitSingularSInt64Field(value: v, fieldNumber: 66)
}
if let v = _storage._defaultFixed32 {
try visitor.visitSingularFixed32Field(value: v, fieldNumber: 67)
}
if let v = _storage._defaultFixed64 {
try visitor.visitSingularFixed64Field(value: v, fieldNumber: 68)
}
if let v = _storage._defaultSfixed32 {
try visitor.visitSingularSFixed32Field(value: v, fieldNumber: 69)
}
if let v = _storage._defaultSfixed64 {
try visitor.visitSingularSFixed64Field(value: v, fieldNumber: 70)
}
if let v = _storage._defaultFloat {
try visitor.visitSingularFloatField(value: v, fieldNumber: 71)
}
if let v = _storage._defaultDouble {
try visitor.visitSingularDoubleField(value: v, fieldNumber: 72)
}
if let v = _storage._defaultBool {
try visitor.visitSingularBoolField(value: v, fieldNumber: 73)
}
if let v = _storage._defaultString {
try visitor.visitSingularStringField(value: v, fieldNumber: 74)
}
if let v = _storage._defaultBytes {
try visitor.visitSingularBytesField(value: v, fieldNumber: 75)
}
if let v = _storage._defaultNestedEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 81)
}
if let v = _storage._defaultForeignEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 82)
}
if let v = _storage._defaultImportEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 83)
}
if let v = _storage._defaultStringPiece {
try visitor.visitSingularStringField(value: v, fieldNumber: 84)
}
if let v = _storage._defaultCord {
try visitor.visitSingularStringField(value: v, fieldNumber: 85)
}
switch _storage._oneofField {
case .oneofUint32(let v)?:
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 111)
case .oneofNestedMessage(let v)?:
try visitor.visitSingularMessageField(value: v, fieldNumber: 112)
case .oneofString(let v)?:
try visitor.visitSingularStringField(value: v, fieldNumber: 113)
case .oneofBytes(let v)?:
try visitor.visitSingularBytesField(value: v, fieldNumber: 114)
case .oneofLazyNestedMessage(let v)?:
try visitor.visitSingularMessageField(value: v, fieldNumber: 115)
case nil: break
}
if let v = _storage._deceptivelyNamedList {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 116)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestAllTypesLite, rhs: ProtobufUnittest_TestAllTypesLite) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._optionalInt32 != rhs_storage._optionalInt32 {return false}
if _storage._optionalInt64 != rhs_storage._optionalInt64 {return false}
if _storage._optionalUint32 != rhs_storage._optionalUint32 {return false}
if _storage._optionalUint64 != rhs_storage._optionalUint64 {return false}
if _storage._optionalSint32 != rhs_storage._optionalSint32 {return false}
if _storage._optionalSint64 != rhs_storage._optionalSint64 {return false}
if _storage._optionalFixed32 != rhs_storage._optionalFixed32 {return false}
if _storage._optionalFixed64 != rhs_storage._optionalFixed64 {return false}
if _storage._optionalSfixed32 != rhs_storage._optionalSfixed32 {return false}
if _storage._optionalSfixed64 != rhs_storage._optionalSfixed64 {return false}
if _storage._optionalFloat != rhs_storage._optionalFloat {return false}
if _storage._optionalDouble != rhs_storage._optionalDouble {return false}
if _storage._optionalBool != rhs_storage._optionalBool {return false}
if _storage._optionalString != rhs_storage._optionalString {return false}
if _storage._optionalBytes != rhs_storage._optionalBytes {return false}
if _storage._optionalGroup != rhs_storage._optionalGroup {return false}
if _storage._optionalNestedMessage != rhs_storage._optionalNestedMessage {return false}
if _storage._optionalForeignMessage != rhs_storage._optionalForeignMessage {return false}
if _storage._optionalImportMessage != rhs_storage._optionalImportMessage {return false}
if _storage._optionalNestedEnum != rhs_storage._optionalNestedEnum {return false}
if _storage._optionalForeignEnum != rhs_storage._optionalForeignEnum {return false}
if _storage._optionalImportEnum != rhs_storage._optionalImportEnum {return false}
if _storage._optionalStringPiece != rhs_storage._optionalStringPiece {return false}
if _storage._optionalCord != rhs_storage._optionalCord {return false}
if _storage._optionalPublicImportMessage != rhs_storage._optionalPublicImportMessage {return false}
if _storage._optionalLazyMessage != rhs_storage._optionalLazyMessage {return false}
if _storage._repeatedInt32 != rhs_storage._repeatedInt32 {return false}
if _storage._repeatedInt64 != rhs_storage._repeatedInt64 {return false}
if _storage._repeatedUint32 != rhs_storage._repeatedUint32 {return false}
if _storage._repeatedUint64 != rhs_storage._repeatedUint64 {return false}
if _storage._repeatedSint32 != rhs_storage._repeatedSint32 {return false}
if _storage._repeatedSint64 != rhs_storage._repeatedSint64 {return false}
if _storage._repeatedFixed32 != rhs_storage._repeatedFixed32 {return false}
if _storage._repeatedFixed64 != rhs_storage._repeatedFixed64 {return false}
if _storage._repeatedSfixed32 != rhs_storage._repeatedSfixed32 {return false}
if _storage._repeatedSfixed64 != rhs_storage._repeatedSfixed64 {return false}
if _storage._repeatedFloat != rhs_storage._repeatedFloat {return false}
if _storage._repeatedDouble != rhs_storage._repeatedDouble {return false}
if _storage._repeatedBool != rhs_storage._repeatedBool {return false}
if _storage._repeatedString != rhs_storage._repeatedString {return false}
if _storage._repeatedBytes != rhs_storage._repeatedBytes {return false}
if _storage._repeatedGroup != rhs_storage._repeatedGroup {return false}
if _storage._repeatedNestedMessage != rhs_storage._repeatedNestedMessage {return false}
if _storage._repeatedForeignMessage != rhs_storage._repeatedForeignMessage {return false}
if _storage._repeatedImportMessage != rhs_storage._repeatedImportMessage {return false}
if _storage._repeatedNestedEnum != rhs_storage._repeatedNestedEnum {return false}
if _storage._repeatedForeignEnum != rhs_storage._repeatedForeignEnum {return false}
if _storage._repeatedImportEnum != rhs_storage._repeatedImportEnum {return false}
if _storage._repeatedStringPiece != rhs_storage._repeatedStringPiece {return false}
if _storage._repeatedCord != rhs_storage._repeatedCord {return false}
if _storage._repeatedLazyMessage != rhs_storage._repeatedLazyMessage {return false}
if _storage._defaultInt32 != rhs_storage._defaultInt32 {return false}
if _storage._defaultInt64 != rhs_storage._defaultInt64 {return false}
if _storage._defaultUint32 != rhs_storage._defaultUint32 {return false}
if _storage._defaultUint64 != rhs_storage._defaultUint64 {return false}
if _storage._defaultSint32 != rhs_storage._defaultSint32 {return false}
if _storage._defaultSint64 != rhs_storage._defaultSint64 {return false}
if _storage._defaultFixed32 != rhs_storage._defaultFixed32 {return false}
if _storage._defaultFixed64 != rhs_storage._defaultFixed64 {return false}
if _storage._defaultSfixed32 != rhs_storage._defaultSfixed32 {return false}
if _storage._defaultSfixed64 != rhs_storage._defaultSfixed64 {return false}
if _storage._defaultFloat != rhs_storage._defaultFloat {return false}
if _storage._defaultDouble != rhs_storage._defaultDouble {return false}
if _storage._defaultBool != rhs_storage._defaultBool {return false}
if _storage._defaultString != rhs_storage._defaultString {return false}
if _storage._defaultBytes != rhs_storage._defaultBytes {return false}
if _storage._defaultNestedEnum != rhs_storage._defaultNestedEnum {return false}
if _storage._defaultForeignEnum != rhs_storage._defaultForeignEnum {return false}
if _storage._defaultImportEnum != rhs_storage._defaultImportEnum {return false}
if _storage._defaultStringPiece != rhs_storage._defaultStringPiece {return false}
if _storage._defaultCord != rhs_storage._defaultCord {return false}
if _storage._oneofField != rhs_storage._oneofField {return false}
if _storage._deceptivelyNamedList != rhs_storage._deceptivelyNamedList {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestAllTypesLite.NestedEnum: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "FOO"),
2: .same(proto: "BAR"),
3: .same(proto: "BAZ"),
]
}
extension ProtobufUnittest_TestAllTypesLite.NestedMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestAllTypesLite.protoMessageName + ".NestedMessage"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "bb"),
2: .same(proto: "cc"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self._bb)
case 2: try decoder.decodeSingularInt64Field(value: &self._cc)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._bb {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
if let v = self._cc {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestAllTypesLite.NestedMessage, rhs: ProtobufUnittest_TestAllTypesLite.NestedMessage) -> Bool {
if lhs._bb != rhs._bb {return false}
if lhs._cc != rhs._cc {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestAllTypesLite.OptionalGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestAllTypesLite.protoMessageName + ".OptionalGroup"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
17: .same(proto: "a"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 17: try decoder.decodeSingularInt32Field(value: &self._a)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._a {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 17)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestAllTypesLite.OptionalGroup, rhs: ProtobufUnittest_TestAllTypesLite.OptionalGroup) -> Bool {
if lhs._a != rhs._a {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestAllTypesLite.RepeatedGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestAllTypesLite.protoMessageName + ".RepeatedGroup"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
47: .same(proto: "a"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 47: try decoder.decodeSingularInt32Field(value: &self._a)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._a {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 47)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestAllTypesLite.RepeatedGroup, rhs: ProtobufUnittest_TestAllTypesLite.RepeatedGroup) -> Bool {
if lhs._a != rhs._a {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_ForeignMessageLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".ForeignMessageLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "c"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self._c)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._c {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_ForeignMessageLite, rhs: ProtobufUnittest_ForeignMessageLite) -> Bool {
if lhs._c != rhs._c {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestPackedTypesLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestPackedTypesLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
90: .standard(proto: "packed_int32"),
91: .standard(proto: "packed_int64"),
92: .standard(proto: "packed_uint32"),
93: .standard(proto: "packed_uint64"),
94: .standard(proto: "packed_sint32"),
95: .standard(proto: "packed_sint64"),
96: .standard(proto: "packed_fixed32"),
97: .standard(proto: "packed_fixed64"),
98: .standard(proto: "packed_sfixed32"),
99: .standard(proto: "packed_sfixed64"),
100: .standard(proto: "packed_float"),
101: .standard(proto: "packed_double"),
102: .standard(proto: "packed_bool"),
103: .standard(proto: "packed_enum"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 90: try decoder.decodeRepeatedInt32Field(value: &self.packedInt32)
case 91: try decoder.decodeRepeatedInt64Field(value: &self.packedInt64)
case 92: try decoder.decodeRepeatedUInt32Field(value: &self.packedUint32)
case 93: try decoder.decodeRepeatedUInt64Field(value: &self.packedUint64)
case 94: try decoder.decodeRepeatedSInt32Field(value: &self.packedSint32)
case 95: try decoder.decodeRepeatedSInt64Field(value: &self.packedSint64)
case 96: try decoder.decodeRepeatedFixed32Field(value: &self.packedFixed32)
case 97: try decoder.decodeRepeatedFixed64Field(value: &self.packedFixed64)
case 98: try decoder.decodeRepeatedSFixed32Field(value: &self.packedSfixed32)
case 99: try decoder.decodeRepeatedSFixed64Field(value: &self.packedSfixed64)
case 100: try decoder.decodeRepeatedFloatField(value: &self.packedFloat)
case 101: try decoder.decodeRepeatedDoubleField(value: &self.packedDouble)
case 102: try decoder.decodeRepeatedBoolField(value: &self.packedBool)
case 103: try decoder.decodeRepeatedEnumField(value: &self.packedEnum)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.packedInt32.isEmpty {
try visitor.visitPackedInt32Field(value: self.packedInt32, fieldNumber: 90)
}
if !self.packedInt64.isEmpty {
try visitor.visitPackedInt64Field(value: self.packedInt64, fieldNumber: 91)
}
if !self.packedUint32.isEmpty {
try visitor.visitPackedUInt32Field(value: self.packedUint32, fieldNumber: 92)
}
if !self.packedUint64.isEmpty {
try visitor.visitPackedUInt64Field(value: self.packedUint64, fieldNumber: 93)
}
if !self.packedSint32.isEmpty {
try visitor.visitPackedSInt32Field(value: self.packedSint32, fieldNumber: 94)
}
if !self.packedSint64.isEmpty {
try visitor.visitPackedSInt64Field(value: self.packedSint64, fieldNumber: 95)
}
if !self.packedFixed32.isEmpty {
try visitor.visitPackedFixed32Field(value: self.packedFixed32, fieldNumber: 96)
}
if !self.packedFixed64.isEmpty {
try visitor.visitPackedFixed64Field(value: self.packedFixed64, fieldNumber: 97)
}
if !self.packedSfixed32.isEmpty {
try visitor.visitPackedSFixed32Field(value: self.packedSfixed32, fieldNumber: 98)
}
if !self.packedSfixed64.isEmpty {
try visitor.visitPackedSFixed64Field(value: self.packedSfixed64, fieldNumber: 99)
}
if !self.packedFloat.isEmpty {
try visitor.visitPackedFloatField(value: self.packedFloat, fieldNumber: 100)
}
if !self.packedDouble.isEmpty {
try visitor.visitPackedDoubleField(value: self.packedDouble, fieldNumber: 101)
}
if !self.packedBool.isEmpty {
try visitor.visitPackedBoolField(value: self.packedBool, fieldNumber: 102)
}
if !self.packedEnum.isEmpty {
try visitor.visitPackedEnumField(value: self.packedEnum, fieldNumber: 103)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestPackedTypesLite, rhs: ProtobufUnittest_TestPackedTypesLite) -> Bool {
if lhs.packedInt32 != rhs.packedInt32 {return false}
if lhs.packedInt64 != rhs.packedInt64 {return false}
if lhs.packedUint32 != rhs.packedUint32 {return false}
if lhs.packedUint64 != rhs.packedUint64 {return false}
if lhs.packedSint32 != rhs.packedSint32 {return false}
if lhs.packedSint64 != rhs.packedSint64 {return false}
if lhs.packedFixed32 != rhs.packedFixed32 {return false}
if lhs.packedFixed64 != rhs.packedFixed64 {return false}
if lhs.packedSfixed32 != rhs.packedSfixed32 {return false}
if lhs.packedSfixed64 != rhs.packedSfixed64 {return false}
if lhs.packedFloat != rhs.packedFloat {return false}
if lhs.packedDouble != rhs.packedDouble {return false}
if lhs.packedBool != rhs.packedBool {return false}
if lhs.packedEnum != rhs.packedEnum {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestAllExtensionsLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestAllExtensionsLite"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
public var isInitialized: Bool {
if !_protobuf_extensionFieldValues.isInitialized {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
if (1 <= fieldNumber && fieldNumber < 536870912) {
try decoder.decodeExtensionField(values: &_protobuf_extensionFieldValues, messageType: ProtobufUnittest_TestAllExtensionsLite.self, fieldNumber: fieldNumber)
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try visitor.visitExtensionFields(fields: _protobuf_extensionFieldValues, start: 1, end: 536870912)
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestAllExtensionsLite, rhs: ProtobufUnittest_TestAllExtensionsLite) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
if lhs._protobuf_extensionFieldValues != rhs._protobuf_extensionFieldValues {return false}
return true
}
}
extension ProtobufUnittest_OptionalGroup_extension_lite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".OptionalGroup_extension_lite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
17: .same(proto: "a"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 17: try decoder.decodeSingularInt32Field(value: &self._a)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._a {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 17)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_OptionalGroup_extension_lite, rhs: ProtobufUnittest_OptionalGroup_extension_lite) -> Bool {
if lhs._a != rhs._a {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_RepeatedGroup_extension_lite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".RepeatedGroup_extension_lite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
47: .same(proto: "a"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 47: try decoder.decodeSingularInt32Field(value: &self._a)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._a {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 47)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_RepeatedGroup_extension_lite, rhs: ProtobufUnittest_RepeatedGroup_extension_lite) -> Bool {
if lhs._a != rhs._a {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestPackedExtensionsLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestPackedExtensionsLite"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
public var isInitialized: Bool {
if !_protobuf_extensionFieldValues.isInitialized {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
if (1 <= fieldNumber && fieldNumber < 536870912) {
try decoder.decodeExtensionField(values: &_protobuf_extensionFieldValues, messageType: ProtobufUnittest_TestPackedExtensionsLite.self, fieldNumber: fieldNumber)
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try visitor.visitExtensionFields(fields: _protobuf_extensionFieldValues, start: 1, end: 536870912)
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestPackedExtensionsLite, rhs: ProtobufUnittest_TestPackedExtensionsLite) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
if lhs._protobuf_extensionFieldValues != rhs._protobuf_extensionFieldValues {return false}
return true
}
}
extension ProtobufUnittest_TestNestedExtensionLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestNestedExtensionLite"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestNestedExtensionLite, rhs: ProtobufUnittest_TestNestedExtensionLite) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestDeprecatedLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestDeprecatedLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "deprecated_field"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self._deprecatedField)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._deprecatedField {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestDeprecatedLite, rhs: ProtobufUnittest_TestDeprecatedLite) -> Bool {
if lhs._deprecatedField != rhs._deprecatedField {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestParsingMergeLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestParsingMergeLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "required_all_types"),
2: .standard(proto: "optional_all_types"),
3: .standard(proto: "repeated_all_types"),
10: .unique(proto: "OptionalGroup", json: "optionalgroup"),
20: .unique(proto: "RepeatedGroup", json: "repeatedgroup"),
]
fileprivate class _StorageClass {
var _requiredAllTypes: ProtobufUnittest_TestAllTypesLite? = nil
var _optionalAllTypes: ProtobufUnittest_TestAllTypesLite? = nil
var _repeatedAllTypes: [ProtobufUnittest_TestAllTypesLite] = []
var _optionalGroup: ProtobufUnittest_TestParsingMergeLite.OptionalGroup? = nil
var _repeatedGroup: [ProtobufUnittest_TestParsingMergeLite.RepeatedGroup] = []
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_requiredAllTypes = source._requiredAllTypes
_optionalAllTypes = source._optionalAllTypes
_repeatedAllTypes = source._repeatedAllTypes
_optionalGroup = source._optionalGroup
_repeatedGroup = source._repeatedGroup
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
if !_protobuf_extensionFieldValues.isInitialized {return false}
return withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._requiredAllTypes == nil {return false}
return true
}
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &_storage._requiredAllTypes)
case 2: try decoder.decodeSingularMessageField(value: &_storage._optionalAllTypes)
case 3: try decoder.decodeRepeatedMessageField(value: &_storage._repeatedAllTypes)
case 10: try decoder.decodeSingularGroupField(value: &_storage._optionalGroup)
case 20: try decoder.decodeRepeatedGroupField(value: &_storage._repeatedGroup)
case 1000..<536870912:
try decoder.decodeExtensionField(values: &_protobuf_extensionFieldValues, messageType: ProtobufUnittest_TestParsingMergeLite.self, fieldNumber: fieldNumber)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._requiredAllTypes {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if let v = _storage._optionalAllTypes {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
if !_storage._repeatedAllTypes.isEmpty {
try visitor.visitRepeatedMessageField(value: _storage._repeatedAllTypes, fieldNumber: 3)
}
if let v = _storage._optionalGroup {
try visitor.visitSingularGroupField(value: v, fieldNumber: 10)
}
if !_storage._repeatedGroup.isEmpty {
try visitor.visitRepeatedGroupField(value: _storage._repeatedGroup, fieldNumber: 20)
}
try visitor.visitExtensionFields(fields: _protobuf_extensionFieldValues, start: 1000, end: 536870912)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestParsingMergeLite, rhs: ProtobufUnittest_TestParsingMergeLite) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._requiredAllTypes != rhs_storage._requiredAllTypes {return false}
if _storage._optionalAllTypes != rhs_storage._optionalAllTypes {return false}
if _storage._repeatedAllTypes != rhs_storage._repeatedAllTypes {return false}
if _storage._optionalGroup != rhs_storage._optionalGroup {return false}
if _storage._repeatedGroup != rhs_storage._repeatedGroup {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
if lhs._protobuf_extensionFieldValues != rhs._protobuf_extensionFieldValues {return false}
return true
}
}
extension ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestParsingMergeLite.protoMessageName + ".RepeatedFieldsGenerator"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "field1"),
2: .same(proto: "field2"),
3: .same(proto: "field3"),
10: .unique(proto: "Group1", json: "group1"),
20: .unique(proto: "Group2", json: "group2"),
1000: .same(proto: "ext1"),
1001: .same(proto: "ext2"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedMessageField(value: &self.field1)
case 2: try decoder.decodeRepeatedMessageField(value: &self.field2)
case 3: try decoder.decodeRepeatedMessageField(value: &self.field3)
case 10: try decoder.decodeRepeatedGroupField(value: &self.group1)
case 20: try decoder.decodeRepeatedGroupField(value: &self.group2)
case 1000: try decoder.decodeRepeatedMessageField(value: &self.ext1)
case 1001: try decoder.decodeRepeatedMessageField(value: &self.ext2)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.field1.isEmpty {
try visitor.visitRepeatedMessageField(value: self.field1, fieldNumber: 1)
}
if !self.field2.isEmpty {
try visitor.visitRepeatedMessageField(value: self.field2, fieldNumber: 2)
}
if !self.field3.isEmpty {
try visitor.visitRepeatedMessageField(value: self.field3, fieldNumber: 3)
}
if !self.group1.isEmpty {
try visitor.visitRepeatedGroupField(value: self.group1, fieldNumber: 10)
}
if !self.group2.isEmpty {
try visitor.visitRepeatedGroupField(value: self.group2, fieldNumber: 20)
}
if !self.ext1.isEmpty {
try visitor.visitRepeatedMessageField(value: self.ext1, fieldNumber: 1000)
}
if !self.ext2.isEmpty {
try visitor.visitRepeatedMessageField(value: self.ext2, fieldNumber: 1001)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator, rhs: ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator) -> Bool {
if lhs.field1 != rhs.field1 {return false}
if lhs.field2 != rhs.field2 {return false}
if lhs.field3 != rhs.field3 {return false}
if lhs.group1 != rhs.group1 {return false}
if lhs.group2 != rhs.group2 {return false}
if lhs.ext1 != rhs.ext1 {return false}
if lhs.ext2 != rhs.ext2 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group1: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.protoMessageName + ".Group1"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
11: .same(proto: "field1"),
]
fileprivate class _StorageClass {
var _field1: ProtobufUnittest_TestAllTypesLite? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_field1 = source._field1
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 11: try decoder.decodeSingularMessageField(value: &_storage._field1)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._field1 {
try visitor.visitSingularMessageField(value: v, fieldNumber: 11)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group1, rhs: ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group1) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._field1 != rhs_storage._field1 {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group2: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.protoMessageName + ".Group2"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
21: .same(proto: "field1"),
]
fileprivate class _StorageClass {
var _field1: ProtobufUnittest_TestAllTypesLite? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_field1 = source._field1
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 21: try decoder.decodeSingularMessageField(value: &_storage._field1)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._field1 {
try visitor.visitSingularMessageField(value: v, fieldNumber: 21)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group2, rhs: ProtobufUnittest_TestParsingMergeLite.RepeatedFieldsGenerator.Group2) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._field1 != rhs_storage._field1 {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestParsingMergeLite.OptionalGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestParsingMergeLite.protoMessageName + ".OptionalGroup"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
11: .standard(proto: "optional_group_all_types"),
]
fileprivate class _StorageClass {
var _optionalGroupAllTypes: ProtobufUnittest_TestAllTypesLite? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_optionalGroupAllTypes = source._optionalGroupAllTypes
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 11: try decoder.decodeSingularMessageField(value: &_storage._optionalGroupAllTypes)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._optionalGroupAllTypes {
try visitor.visitSingularMessageField(value: v, fieldNumber: 11)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestParsingMergeLite.OptionalGroup, rhs: ProtobufUnittest_TestParsingMergeLite.OptionalGroup) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._optionalGroupAllTypes != rhs_storage._optionalGroupAllTypes {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestParsingMergeLite.RepeatedGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestParsingMergeLite.protoMessageName + ".RepeatedGroup"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
21: .standard(proto: "repeated_group_all_types"),
]
fileprivate class _StorageClass {
var _repeatedGroupAllTypes: ProtobufUnittest_TestAllTypesLite? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_repeatedGroupAllTypes = source._repeatedGroupAllTypes
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 21: try decoder.decodeSingularMessageField(value: &_storage._repeatedGroupAllTypes)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if let v = _storage._repeatedGroupAllTypes {
try visitor.visitSingularMessageField(value: v, fieldNumber: 21)
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestParsingMergeLite.RepeatedGroup, rhs: ProtobufUnittest_TestParsingMergeLite.RepeatedGroup) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._repeatedGroupAllTypes != rhs_storage._repeatedGroupAllTypes {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestEmptyMessageLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestEmptyMessageLite"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestEmptyMessageLite, rhs: ProtobufUnittest_TestEmptyMessageLite) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestEmptyMessageWithExtensionsLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestEmptyMessageWithExtensionsLite"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
public var isInitialized: Bool {
if !_protobuf_extensionFieldValues.isInitialized {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
if (1 <= fieldNumber && fieldNumber < 536870912) {
try decoder.decodeExtensionField(values: &_protobuf_extensionFieldValues, messageType: ProtobufUnittest_TestEmptyMessageWithExtensionsLite.self, fieldNumber: fieldNumber)
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try visitor.visitExtensionFields(fields: _protobuf_extensionFieldValues, start: 1, end: 536870912)
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestEmptyMessageWithExtensionsLite, rhs: ProtobufUnittest_TestEmptyMessageWithExtensionsLite) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
if lhs._protobuf_extensionFieldValues != rhs._protobuf_extensionFieldValues {return false}
return true
}
}
extension ProtobufUnittest_V1MessageLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".V1MessageLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "int_field"),
2: .standard(proto: "enum_field"),
]
public var isInitialized: Bool {
if self._intField == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self._intField)
case 2: try decoder.decodeSingularEnumField(value: &self._enumField)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._intField {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
if let v = self._enumField {
try visitor.visitSingularEnumField(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_V1MessageLite, rhs: ProtobufUnittest_V1MessageLite) -> Bool {
if lhs._intField != rhs._intField {return false}
if lhs._enumField != rhs._enumField {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_V2MessageLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".V2MessageLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "int_field"),
2: .standard(proto: "enum_field"),
]
public var isInitialized: Bool {
if self._intField == nil {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self._intField)
case 2: try decoder.decodeSingularEnumField(value: &self._enumField)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._intField {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
}
if let v = self._enumField {
try visitor.visitSingularEnumField(value: v, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_V2MessageLite, rhs: ProtobufUnittest_V2MessageLite) -> Bool {
if lhs._intField != rhs._intField {return false}
if lhs._enumField != rhs._enumField {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestHugeFieldNumbersLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestHugeFieldNumbersLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
536870000: .standard(proto: "optional_int32"),
536870001: .standard(proto: "fixed_32"),
536870002: .standard(proto: "repeated_int32"),
536870003: .standard(proto: "packed_int32"),
536870004: .standard(proto: "optional_enum"),
536870005: .standard(proto: "optional_string"),
536870006: .standard(proto: "optional_bytes"),
536870007: .standard(proto: "optional_message"),
536870008: .unique(proto: "OptionalGroup", json: "optionalgroup"),
536870010: .standard(proto: "string_string_map"),
536870011: .standard(proto: "oneof_uint32"),
536870012: .standard(proto: "oneof_test_all_types"),
536870013: .standard(proto: "oneof_string"),
536870014: .standard(proto: "oneof_bytes"),
]
fileprivate class _StorageClass {
var _optionalInt32: Int32? = nil
var _fixed32: Int32? = nil
var _repeatedInt32: [Int32] = []
var _packedInt32: [Int32] = []
var _optionalEnum: ProtobufUnittest_ForeignEnumLite? = nil
var _optionalString: String? = nil
var _optionalBytes: Data? = nil
var _optionalMessage: ProtobufUnittest_ForeignMessageLite? = nil
var _optionalGroup: ProtobufUnittest_TestHugeFieldNumbersLite.OptionalGroup? = nil
var _stringStringMap: Dictionary<String,String> = [:]
var _oneofField: ProtobufUnittest_TestHugeFieldNumbersLite.OneOf_OneofField?
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_optionalInt32 = source._optionalInt32
_fixed32 = source._fixed32
_repeatedInt32 = source._repeatedInt32
_packedInt32 = source._packedInt32
_optionalEnum = source._optionalEnum
_optionalString = source._optionalString
_optionalBytes = source._optionalBytes
_optionalMessage = source._optionalMessage
_optionalGroup = source._optionalGroup
_stringStringMap = source._stringStringMap
_oneofField = source._oneofField
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public var isInitialized: Bool {
if !_protobuf_extensionFieldValues.isInitialized {return false}
return true
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 536870000: try decoder.decodeSingularInt32Field(value: &_storage._optionalInt32)
case 536870001: try decoder.decodeSingularInt32Field(value: &_storage._fixed32)
case 536870002: try decoder.decodeRepeatedInt32Field(value: &_storage._repeatedInt32)
case 536870003: try decoder.decodeRepeatedInt32Field(value: &_storage._packedInt32)
case 536870004: try decoder.decodeSingularEnumField(value: &_storage._optionalEnum)
case 536870005: try decoder.decodeSingularStringField(value: &_storage._optionalString)
case 536870006: try decoder.decodeSingularBytesField(value: &_storage._optionalBytes)
case 536870007: try decoder.decodeSingularMessageField(value: &_storage._optionalMessage)
case 536870008: try decoder.decodeSingularGroupField(value: &_storage._optionalGroup)
case 536870010: try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: &_storage._stringStringMap)
case 536870011:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: UInt32?
try decoder.decodeSingularUInt32Field(value: &v)
if let v = v {_storage._oneofField = .oneofUint32(v)}
case 536870012:
var v: ProtobufUnittest_TestAllTypesLite?
if let current = _storage._oneofField {
try decoder.handleConflictingOneOf()
if case .oneofTestAllTypes(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {_storage._oneofField = .oneofTestAllTypes(v)}
case 536870013:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {_storage._oneofField = .oneofString(v)}
case 536870014:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: Data?
try decoder.decodeSingularBytesField(value: &v)
if let v = v {_storage._oneofField = .oneofBytes(v)}
case 536860000..<536870000:
try decoder.decodeExtensionField(values: &_protobuf_extensionFieldValues, messageType: ProtobufUnittest_TestHugeFieldNumbersLite.self, fieldNumber: fieldNumber)
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
try visitor.visitExtensionFields(fields: _protobuf_extensionFieldValues, start: 536860000, end: 536870000)
if let v = _storage._optionalInt32 {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 536870000)
}
if let v = _storage._fixed32 {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 536870001)
}
if !_storage._repeatedInt32.isEmpty {
try visitor.visitRepeatedInt32Field(value: _storage._repeatedInt32, fieldNumber: 536870002)
}
if !_storage._packedInt32.isEmpty {
try visitor.visitPackedInt32Field(value: _storage._packedInt32, fieldNumber: 536870003)
}
if let v = _storage._optionalEnum {
try visitor.visitSingularEnumField(value: v, fieldNumber: 536870004)
}
if let v = _storage._optionalString {
try visitor.visitSingularStringField(value: v, fieldNumber: 536870005)
}
if let v = _storage._optionalBytes {
try visitor.visitSingularBytesField(value: v, fieldNumber: 536870006)
}
if let v = _storage._optionalMessage {
try visitor.visitSingularMessageField(value: v, fieldNumber: 536870007)
}
if let v = _storage._optionalGroup {
try visitor.visitSingularGroupField(value: v, fieldNumber: 536870008)
}
if !_storage._stringStringMap.isEmpty {
try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap<SwiftProtobuf.ProtobufString,SwiftProtobuf.ProtobufString>.self, value: _storage._stringStringMap, fieldNumber: 536870010)
}
switch _storage._oneofField {
case .oneofUint32(let v)?:
try visitor.visitSingularUInt32Field(value: v, fieldNumber: 536870011)
case .oneofTestAllTypes(let v)?:
try visitor.visitSingularMessageField(value: v, fieldNumber: 536870012)
case .oneofString(let v)?:
try visitor.visitSingularStringField(value: v, fieldNumber: 536870013)
case .oneofBytes(let v)?:
try visitor.visitSingularBytesField(value: v, fieldNumber: 536870014)
case nil: break
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestHugeFieldNumbersLite, rhs: ProtobufUnittest_TestHugeFieldNumbersLite) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._optionalInt32 != rhs_storage._optionalInt32 {return false}
if _storage._fixed32 != rhs_storage._fixed32 {return false}
if _storage._repeatedInt32 != rhs_storage._repeatedInt32 {return false}
if _storage._packedInt32 != rhs_storage._packedInt32 {return false}
if _storage._optionalEnum != rhs_storage._optionalEnum {return false}
if _storage._optionalString != rhs_storage._optionalString {return false}
if _storage._optionalBytes != rhs_storage._optionalBytes {return false}
if _storage._optionalMessage != rhs_storage._optionalMessage {return false}
if _storage._optionalGroup != rhs_storage._optionalGroup {return false}
if _storage._stringStringMap != rhs_storage._stringStringMap {return false}
if _storage._oneofField != rhs_storage._oneofField {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
if lhs._protobuf_extensionFieldValues != rhs._protobuf_extensionFieldValues {return false}
return true
}
}
extension ProtobufUnittest_TestHugeFieldNumbersLite.OptionalGroup: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = ProtobufUnittest_TestHugeFieldNumbersLite.protoMessageName + ".OptionalGroup"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
536870009: .standard(proto: "group_a"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 536870009: try decoder.decodeSingularInt32Field(value: &self._groupA)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._groupA {
try visitor.visitSingularInt32Field(value: v, fieldNumber: 536870009)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestHugeFieldNumbersLite.OptionalGroup, rhs: ProtobufUnittest_TestHugeFieldNumbersLite.OptionalGroup) -> Bool {
if lhs._groupA != rhs._groupA {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_TestOneofParsingLite: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestOneofParsingLite"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "oneof_int32"),
2: .standard(proto: "oneof_submessage"),
3: .standard(proto: "oneof_string"),
4: .standard(proto: "oneof_bytes"),
5: .standard(proto: "oneof_string_cord"),
6: .standard(proto: "oneof_bytes_cord"),
7: .standard(proto: "oneof_string_string_piece"),
8: .standard(proto: "oneof_bytes_string_piece"),
9: .standard(proto: "oneof_enum"),
]
fileprivate class _StorageClass {
var _oneofField: ProtobufUnittest_TestOneofParsingLite.OneOf_OneofField?
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_oneofField = source._oneofField
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: Int32?
try decoder.decodeSingularInt32Field(value: &v)
if let v = v {_storage._oneofField = .oneofInt32(v)}
case 2:
var v: ProtobufUnittest_TestAllTypesLite?
if let current = _storage._oneofField {
try decoder.handleConflictingOneOf()
if case .oneofSubmessage(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {_storage._oneofField = .oneofSubmessage(v)}
case 3:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {_storage._oneofField = .oneofString(v)}
case 4:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: Data?
try decoder.decodeSingularBytesField(value: &v)
if let v = v {_storage._oneofField = .oneofBytes(v)}
case 5:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {_storage._oneofField = .oneofStringCord(v)}
case 6:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: Data?
try decoder.decodeSingularBytesField(value: &v)
if let v = v {_storage._oneofField = .oneofBytesCord(v)}
case 7:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {_storage._oneofField = .oneofStringStringPiece(v)}
case 8:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: Data?
try decoder.decodeSingularBytesField(value: &v)
if let v = v {_storage._oneofField = .oneofBytesStringPiece(v)}
case 9:
if _storage._oneofField != nil {try decoder.handleConflictingOneOf()}
var v: ProtobufUnittest_V2EnumLite?
try decoder.decodeSingularEnumField(value: &v)
if let v = v {_storage._oneofField = .oneofEnum(v)}
default: break
}
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
switch _storage._oneofField {
case .oneofInt32(let v)?:
try visitor.visitSingularInt32Field(value: v, fieldNumber: 1)
case .oneofSubmessage(let v)?:
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
case .oneofString(let v)?:
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
case .oneofBytes(let v)?:
try visitor.visitSingularBytesField(value: v, fieldNumber: 4)
case .oneofStringCord(let v)?:
try visitor.visitSingularStringField(value: v, fieldNumber: 5)
case .oneofBytesCord(let v)?:
try visitor.visitSingularBytesField(value: v, fieldNumber: 6)
case .oneofStringStringPiece(let v)?:
try visitor.visitSingularStringField(value: v, fieldNumber: 7)
case .oneofBytesStringPiece(let v)?:
try visitor.visitSingularBytesField(value: v, fieldNumber: 8)
case .oneofEnum(let v)?:
try visitor.visitSingularEnumField(value: v, fieldNumber: 9)
case nil: break
}
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_TestOneofParsingLite, rhs: ProtobufUnittest_TestOneofParsingLite) -> Bool {
if lhs._storage !== rhs._storage {
let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let rhs_storage = _args.1
if _storage._oneofField != rhs_storage._oneofField {return false}
return true
}
if !storagesAreEqual {return false}
}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_PackedInt32: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PackedInt32"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
2048: .standard(proto: "repeated_int32"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 2048: try decoder.decodeRepeatedInt32Field(value: &self.repeatedInt32)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.repeatedInt32.isEmpty {
try visitor.visitPackedInt32Field(value: self.repeatedInt32, fieldNumber: 2048)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_PackedInt32, rhs: ProtobufUnittest_PackedInt32) -> Bool {
if lhs.repeatedInt32 != rhs.repeatedInt32 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_NonPackedInt32: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".NonPackedInt32"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
2048: .standard(proto: "repeated_int32"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 2048: try decoder.decodeRepeatedInt32Field(value: &self.repeatedInt32)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.repeatedInt32.isEmpty {
try visitor.visitRepeatedInt32Field(value: self.repeatedInt32, fieldNumber: 2048)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_NonPackedInt32, rhs: ProtobufUnittest_NonPackedInt32) -> Bool {
if lhs.repeatedInt32 != rhs.repeatedInt32 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_PackedFixed32: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PackedFixed32"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
2048: .standard(proto: "repeated_fixed32"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 2048: try decoder.decodeRepeatedFixed32Field(value: &self.repeatedFixed32)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.repeatedFixed32.isEmpty {
try visitor.visitPackedFixed32Field(value: self.repeatedFixed32, fieldNumber: 2048)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_PackedFixed32, rhs: ProtobufUnittest_PackedFixed32) -> Bool {
if lhs.repeatedFixed32 != rhs.repeatedFixed32 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_NonPackedFixed32: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".NonPackedFixed32"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
2048: .standard(proto: "repeated_fixed32"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 2048: try decoder.decodeRepeatedFixed32Field(value: &self.repeatedFixed32)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.repeatedFixed32.isEmpty {
try visitor.visitRepeatedFixed32Field(value: self.repeatedFixed32, fieldNumber: 2048)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: ProtobufUnittest_NonPackedFixed32, rhs: ProtobufUnittest_NonPackedFixed32) -> Bool {
if lhs.repeatedFixed32 != rhs.repeatedFixed32 {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| bsd-2-clause |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/User/RealmOwnedGear.swift | 1 | 802 | //
// RealmOwnedGear.swift
// Habitica Database
//
// Created by Phillip Thelen on 12.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import RealmSwift
import Habitica_Models
@objc
class RealmOwnedGear: Object, OwnedGearProtocol {
@objc dynamic var combinedKey: String?
@objc dynamic var key: String?
@objc dynamic var userID: String?
@objc dynamic var isOwned: Bool = false
override static func primaryKey() -> String {
return "combinedKey"
}
convenience init(userID: String?, gearProtocol: OwnedGearProtocol) {
self.init()
combinedKey = (userID ?? "") + (gearProtocol.key ?? "")
self.userID = userID
key = gearProtocol.key
isOwned = gearProtocol.isOwned
}
}
| gpl-3.0 |
TelerikAcademy/Mobile-Applications-with-iOS | demos/StoryboardsAndViewControllers/StoryboardsAndViewControllers/DetailsViewController.swift | 1 | 1809 | //
// DetailsViewController.swift
// StoryboardsAndViewControllers
//
// Created by Doncho Minkov on 3/17/17.
// Copyright © 2017 Doncho Minkov. All rights reserved.
//
import UIKit
class DetailsViewController: UIViewController {
var name: String = ""
var labelName: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
let topOffeset = self.navigationController?.navigationBar.bounds.size.height
let origin = CGPoint(x: self.view.bounds.origin.x, y: self.view.bounds.origin.y + topOffeset!)
self.labelName = UILabel(frame: CGRect(origin: origin,
size: CGSize(width: 100, height: 50)))
self.labelName?.text = self.name
self.labelName?.backgroundColor = .purple
self.labelName?.textColor = .yellow
self.view.addSubview(self.labelName!)
print(self.name)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func unwindToMainTableViewController(segue: UIStoryboardSegue) {
print("fired!");
}
@IBAction func goBacl(_ sender: UIButton) {
print("Tapped")
self.performSegue(withIdentifier: "unwind", sender: self)
}
/*
// 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.
}
*/
}
| mit |
milseman/swift | test/expr/dynamic_lookup.swift | 19 | 204 | // RUN: %target-typecheck-verify-swift
@objc class HasStaticProperties {
@objc class var staticVar1: Int { return 4 }
}
func testStaticProperty(classObj: AnyObject.Type) {
_ = classObj.staticVar1
}
| apache-2.0 |
toshiapp/toshi-ios-client | Toshi/Views/TintColorChangingButton.swift | 1 | 3015 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import UIKit
/// A button which automatically updates its tint color based on the button's current state.
final class TintColorChangingButton: UIButton {
private let normalTintColor: UIColor
private let disabledTintColor: UIColor
private let selectedTintColor: UIColor
private let highlightedTintColor: UIColor
/// Designated initializer.
///
/// - Parameters:
/// - normalTintColor: The color the button should be when enabled. Defaults to the theme color.
/// - disabledTintColor: The color the button should be when disabled. Defaults to a gray color.
/// - selectedTintColor: [Optional] The color the button should be when selected.
/// If nil, the `normalTintColor` will be used. Defaults to nil.
/// - highlightedTintColor: [Optional] The color the button should be when highlighted.
/// If nil, the `normalTintColor` will be use. Defaults to nil.
init(normalTintColor: UIColor = Theme.tintColor,
disabledTintColor: UIColor = Theme.greyTextColor,
selectedTintColor: UIColor? = nil,
highlightedTintColor: UIColor? = nil) {
self.normalTintColor = normalTintColor
self.disabledTintColor = disabledTintColor
self.selectedTintColor = selectedTintColor ?? normalTintColor
self.highlightedTintColor = highlightedTintColor ?? normalTintColor
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isEnabled: Bool {
didSet {
updateTintColor()
}
}
override var isHighlighted: Bool {
didSet {
updateTintColor()
}
}
override var isSelected: Bool {
didSet {
updateTintColor()
}
}
private func updateTintColor() {
switch state {
case .normal:
tintColor = normalTintColor
case .disabled:
tintColor = disabledTintColor
case .selected:
tintColor = selectedTintColor
case .highlighted:
tintColor = highlightedTintColor
default:
// some state combo is happening, leave things where they are
break
}
}
}
| gpl-3.0 |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Pods/PDFReader/Sources/Classes/PDFPageView.swift | 1 | 8908 | //
// PDFPageView.swift
// PDFReader
//
// Created by ALUA KINZHEBAYEVA on 4/23/15.
// Copyright (c) 2015 AK. All rights reserved.
//
import UIKit
/// Delegate that is informed of important interaction events with the current `PDFPageView`
protocol PDFPageViewDelegate: class {
/// User has tapped on the page view
func handleSingleTap(_ pdfPageView: PDFPageView)
}
/// An interactable page of a document
internal final class PDFPageView: UIScrollView {
/// The TiledPDFView that is currently front most.
private var tiledPDFView: TiledView
/// Current scale of the scrolling view
private var scale: CGFloat
/// Number of zoom levels possible when double tapping
private let zoomLevels: CGFloat = 2
/// View which contains all of our content
private var contentView: UIView
/// A low resolution image of the PDF page that is displayed until the TiledPDFView renders its content.
private let backgroundImageView: UIImageView
/// Page reference being displayed
private let pdfPage: CGPDFPage
/// Current amount being zoomed
private var zoomAmount: CGFloat?
/// Delegate that is informed of important interaction events
private weak var pageViewDelegate: PDFPageViewDelegate?
/// Instantiates a scrollable page view
///
/// - parameter frame: frame of the view
/// - parameter document: document to be displayed
/// - parameter pageNumber: specific page number of the document to display
/// - parameter backgroundImage: background image of the page to display while rendering
/// - parameter pageViewDelegate: delegate notified of any important interaction events
///
/// - returns: a freshly initialized page view
init(frame: CGRect, document: PDFDocument, pageNumber: Int, backgroundImage: UIImage?, pageViewDelegate: PDFPageViewDelegate?) {
guard let pageRef = document.coreDocument.page(at: pageNumber + 1) else { fatalError() }
pdfPage = pageRef
self.pageViewDelegate = pageViewDelegate
let originalPageRect = pageRef.originalPageRect
scale = min(frame.width/originalPageRect.width, frame.height/originalPageRect.height)
let scaledPageRectSize = CGSize(width: originalPageRect.width * scale, height: originalPageRect.height * scale)
let scaledPageRect = CGRect(origin: originalPageRect.origin, size: scaledPageRectSize)
guard !scaledPageRect.isEmpty else { fatalError() }
// Create our content view based on the size of the PDF page
contentView = UIView(frame: scaledPageRect)
backgroundImageView = UIImageView(image: backgroundImage)
backgroundImageView.frame = contentView.bounds
// Create the TiledPDFView and scale it to fit the content view.
tiledPDFView = TiledView(frame: contentView.bounds, scale: scale, newPage: pdfPage)
super.init(frame: frame)
let targetRect = bounds.insetBy(dx: 0, dy: 0)
var zoomScale = zoomScaleThatFits(targetRect.size, source: bounds.size)
minimumZoomScale = zoomScale // Set the minimum and maximum zoom scales
maximumZoomScale = zoomScale * (zoomLevels * zoomLevels) // Max number of zoom levels
zoomAmount = (maximumZoomScale - minimumZoomScale) / zoomLevels
scale = 1
if zoomScale > minimumZoomScale {
zoomScale = minimumZoomScale
}
contentView.addSubview(backgroundImageView)
contentView.sendSubview(toBack: backgroundImageView)
contentView.addSubview(tiledPDFView)
addSubview(contentView)
let doubleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleDoubleTap))
doubleTapOne.numberOfTapsRequired = 2
doubleTapOne.cancelsTouchesInView = false
addGestureRecognizer(doubleTapOne)
let singleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleSingleTap))
singleTapOne.numberOfTapsRequired = 1
singleTapOne.cancelsTouchesInView = false
addGestureRecognizer(singleTapOne)
singleTapOne.require(toFail: doubleTapOne)
bouncesZoom = false
decelerationRate = UIScrollViewDecelerationRateFast
delegate = self
autoresizesSubviews = true
autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Use layoutSubviews to center the PDF page in the view.
override func layoutSubviews() {
super.layoutSubviews()
// Center the image as it becomes smaller than the size of the screen.
let contentViewSize = contentView.frame.size
// Center horizontally.
let xOffset: CGFloat
if contentViewSize.width < bounds.width {
xOffset = (bounds.width - contentViewSize.width) / 2
} else {
xOffset = 0
}
// Center vertically.
let yOffset: CGFloat
if contentViewSize.height < bounds.height {
yOffset = (bounds.height - contentViewSize.height) / 2
} else {
yOffset = 0
}
contentView.frame = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: contentViewSize)
// To handle the interaction between CATiledLayer and high resolution screens, set the
// tiling view's contentScaleFactor to 1.0. If this step were omitted, the content scale factor
// would be 2.0 on high resolution screens, which would cause the CATiledLayer to ask for tiles of the wrong scale.
tiledPDFView.contentScaleFactor = 1
}
/// Notifies the delegate that a single tap was performed
@objc func handleSingleTap(_ tapRecognizer: UITapGestureRecognizer) {
pageViewDelegate?.handleSingleTap(self)
}
/// Zooms in and out accordingly, based on the current zoom level
@objc func handleDoubleTap(_ tapRecognizer: UITapGestureRecognizer) {
var newScale = zoomScale * zoomLevels
if newScale >= maximumZoomScale {
newScale = minimumZoomScale
}
let zoomRect = zoomRectForScale(newScale, zoomPoint: tapRecognizer.location(in: tapRecognizer.view))
zoom(to: zoomRect, animated: true)
}
/// Calculates the zoom scale given a target size and a source size
///
/// - parameter target: size of the target rect
/// - parameter source: size of the source rect
///
/// - returns: the zoom scale of the target in relation to the source
private func zoomScaleThatFits(_ target: CGSize, source: CGSize) -> CGFloat {
let widthScale = target.width / source.width
let heightScale = target.height / source.height
return (widthScale < heightScale) ? widthScale : heightScale
}
/// Calculates the new zoom rect given a desired scale and a point to zoom on
///
/// - parameter scale: desired scale to zoom to
/// - parameter zoomPoint: the reference point to zoom on
///
/// - returns: a new zoom rect
private func zoomRectForScale(_ scale: CGFloat, zoomPoint: CGPoint) -> CGRect {
// Normalize current content size back to content scale of 1.0f
let updatedContentSize = CGSize(width: contentSize.width/zoomScale, height: contentSize.height/zoomScale)
let translatedZoomPoint = CGPoint(x: (zoomPoint.x / bounds.width) * updatedContentSize.width,
y: (zoomPoint.y / bounds.height) * updatedContentSize.height)
// derive the size of the region to zoom to
let zoomSize = CGSize(width: bounds.width / scale, height: bounds.height / scale)
// offset the zoom rect so the actual zoom point is in the middle of the rectangle
return CGRect(x: translatedZoomPoint.x - zoomSize.width / 2.0,
y: translatedZoomPoint.y - zoomSize.height / 2.0,
width: zoomSize.width,
height: zoomSize.height)
}
}
extension PDFPageView: UIScrollViewDelegate {
/// A UIScrollView delegate callback, called when the user starts zooming.
/// Return the content view
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return contentView
}
/// A UIScrollView delegate callback, called when the user stops zooming.
/// When the user stops zooming, create a new Tiled
/// PDFView based on the new zoom level and draw it on top of the old TiledPDFView.
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.scale = scale
}
}
| mit |
allevato/SwiftCGI | Tests/SwiftCGI/HTTPCookieTest.swift | 1 | 1279 | // Copyright 2015 Tony Allevato
//
// 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.
@testable import SwiftCGI
import XCTest
/// Unit tests for the `HTTPCookie` struct.
class HTTPCookieTest: XCTestCase {
func testInitializer_shouldSetDefaultValues() {
let cookie = HTTPCookie(name: "name", value: "value")
XCTAssertEqual(cookie.name, "name")
XCTAssertEqual(cookie.value, "value")
XCTAssertFalse(cookie.secure)
XCTAssertNil(cookie.domain)
XCTAssertNil(cookie.expirationTime)
XCTAssertNil(cookie.path)
}
func testHeaderString_withNameAndValueOnly() {
let cookie = HTTPCookie(name: "name", value: "value")
XCTAssertEqual(cookie.headerString, "name=value")
}
// TODO: Add a test for all values once time zones are working.
}
| apache-2.0 |
AdaptiveMe/adaptive-arp-darwin | adaptive-arp-rt/Source/Sources.Common/utils/I18NParser.swift | 1 | 4935 | /*
* =| ADAPTIVE RUNTIME PLATFORM |=======================================================================================
*
* (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by 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.
*
* Original author:
*
* * Carlos Lozano Diez
* <http://github.com/carloslozano>
* <http://twitter.com/adaptivecoder>
* <mailto:carlos@adaptive.me>
*
* Contributors:
*
* * Ferran Vila Conesa
* <http://github.com/fnva>
* <http://twitter.com/ferran_vila>
* <mailto:ferran.vila.conesa@gmail.com>
*
* =====================================================================================================================
*/
import Foundation
import AdaptiveArpApi
public class I18NParser : NSObject, NSXMLParserDelegate {
/// Singleton instance
public class var sharedInstance : I18NParser {
struct Static {
static let instance : I18NParser = I18NParser()
}
return Static.instance
}
/// Logging variable
let logger : ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge()
let loggerTag : String = "I18NParser"
/// Locales supported (filled by the getLocaleSupportedDescriptors method)
var localesArray:[Locale]? = nil
/// Default Locale
var defaultLocale:Locale?
/// i18n config file
public class var I18N_CONFIG_FILE: String {
return "i18n-config.xml";
}
public class var I18N_LANG_FILE: String {
return ".plist";
}
let I18N_SUPLANG_ELEM: String = "supportedLanguage"
let I18N_SUPLANG_DEFAULT: String = "default"
let I18N_SUPLANG_ATTR_LANG: String = "language"
let I18N_SUPLANG_ATTR_CNTR: String = "country"
/**
Class constructor
*/
public override init(){
super.init()
// Read the i18n config file
if let resourceData:ResourceData = AppResourceManager.sharedInstance.retrieveConfigResource(I18NParser.I18N_CONFIG_FILE) {
let xmlParser = NSXMLParser(data: resourceData.data)
xmlParser.delegate = self
localesArray = []
defaultLocale = Locale()
if !xmlParser.parse() {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "Error parsing i18n config file: \(I18NParser.I18N_CONFIG_FILE)")
}
} else {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "Error reading i18n config file: \(I18NParser.I18N_CONFIG_FILE)")
}
}
/**
Method involved in the xml parse response
:param: parser XML parser
:param: elementName name of the element
:param: namespaceURI namespace uri of the element
:param: qName qName of the element
:param: attributeDict dictionary of attributes
*/
public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
// Store
if elementName == I18N_SUPLANG_ELEM {
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Reading language: \(attributeDict[I18N_SUPLANG_ATTR_LANG])")
let locale:Locale = Locale()
locale.setLanguage("\(attributeDict[I18N_SUPLANG_ATTR_LANG]!)")
locale.setCountry("\(attributeDict[I18N_SUPLANG_ATTR_CNTR]!)")
localesArray!.append(locale)
} else if elementName == I18N_SUPLANG_DEFAULT {
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Reading default language: \(attributeDict[I18N_SUPLANG_ATTR_LANG])")
defaultLocale!.setLanguage("\(attributeDict[I18N_SUPLANG_ATTR_LANG]!)")
defaultLocale!.setCountry("\(attributeDict[I18N_SUPLANG_ATTR_CNTR]!)")
}
}
/**
Return the locales parsed
:returns: List of locales
*/
public func getLocales() -> [Locale]? {
return localesArray
}
/**
Returns the deault locale of the application
:returns: Default Locale
*/
public func getDefaultLocale() -> Locale? {
return defaultLocale
}
} | apache-2.0 |
danielsaidi/iExtra | iExtra/Files/FilteredDirectoryFileManager.swift | 1 | 1222 | //
// FilteredDirectoryFileManager.swift
// iExtra
//
// Created by Daniel Saidi on 2016-12-19.
// Copyright © 2016 Daniel Saidi. All rights reserved.
//
import UIKit
open class FilteredDirectoryFileManager: DirectoryFileManagerDefault {
// MARK: - Initialization
public init?(directory: FileManager.SearchPathDirectory, fileExtensions: [String], fileManager: AppFileManager) {
self.fileExtensions = fileExtensions
super.init(directory: directory, fileManager: fileManager)
}
public init(directoryUrl: URL, fileExtensions: [String], fileManager: AppFileManager) {
self.fileExtensions = fileExtensions
super.init(directoryUrl: directoryUrl, fileManager: fileManager)
}
// MARK: - Properties
fileprivate let fileExtensions: [String]
// MARK: - Public Functions
open override func getFileNames() -> [String] {
let fileNames = super.getFileNames()
let fileExtensions = self.fileExtensions.map { $0.lowercased() }
return fileNames.filter {
let fileName = $0.lowercased()
return fileExtensions.filter { fileName.hasSuffix($0) }.first != nil
}
}
}
| mit |
fruitcoder/ReplaceAnimation | ReplaceAnimation/CollectionViewCell.swift | 1 | 533 | //
// CollectionViewCell.swift
// ReplaceAnimation
//
// Created by Alexander Hüllmandel on 07/03/16.
// Copyright © 2016 Alexander Hüllmandel. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var leftImage: UIImageView!
@IBOutlet weak var leftLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| mit |
kaizeiyimi/XLYIDTracker-swift | XLYIDTracker.swift | 1 | 8109 | //
// XLYIDTracker
//
// Created by 王凯 on 14-9-24.
// Copyright (c) 2014年 kaizei. All rights reserved.
//
import Foundation
/*
//create a tracker with a given queue and store it somewhere
var tracker: XLYIDTracker = XLYIDTracker(trackerQueue: dispatch_queue_create("tracker", DISPATCH_QUEUE_SERIAL))
// make a common handler for response
var handler: XLYTrackingHandler = { (trackingInfo, response) -> () in
if let value = response {
println("get response : \(value)")
} else {
println("no response get")
}
}
// must add trackingInfos in tracker's queue
dispatch_async(tracker.trackerQueue) {
//default queue uses tracker's queue
tracker.addTrackingInfo("a", timeOut: 2, queue: nil, handler)
//track in the main queue
tracker.addTrackingInfo("b", timeOut: 2, queue: dispatch_get_main_queue(), handler)
var queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL)
//track in a custom queue
tracker.addTrackingInfo("c", timeOut: 2, queue: queue, handler)
//or you can create a trackingInfo and then add it
var trackingInfo = XLYBasicTrackingInfo(trackID: "d", timeOut: 2, queue: queue, handler)
trackingInfo.autoRemoveFromTracker = true
tracker.addTrackingInfo(trackingInfo)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(3 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
dispatch_async(self.tracker?.trackerQueue) {
let _ = self.tracker?.responseTrackingForID("d", response: "d hello")
}
}
}
*/
/// trackingInfo 的回调方法,传递trackinginfo和回应的数据,如果没有数据则为nil
public typealias XLYTrackingHandler = (trackingInfo: XLYTrackingInfo, response:Any?) -> ()
//MARK: XLYIDTracker
public class XLYIDTracker {
public let trackerQueue: dispatch_queue_t
private var trackingInfos = [String : XLYTrackingInfo]()
private let queueTag = UnsafeMutablePointer<Void>(malloc(1))
public init(trackerQueue:dispatch_queue_t) {
self.trackerQueue = trackerQueue
dispatch_queue_set_specific(trackerQueue, queueTag, queueTag, nil)
}
private let lock = NSLock()
private subscript(trackID: String) -> XLYTrackingInfo? {
get {
assert(queueTag == dispatch_get_specific(queueTag), "must invoke tracker methods in tracker queue")
lock.lock()
let trackingInfo = trackingInfos[trackID]
lock.unlock()
return trackingInfo
}
set {
assert(queueTag == dispatch_get_specific(queueTag), "must invoke tracker methods in tracker queue")
assert(newValue?.tracker == nil, "can not add a trackingInfo which already has a tracker associated")
lock.lock()
if let trackingInfo = trackingInfos.removeValueForKey(trackID) {
trackingInfo.cancelTimer()
}
if var trackingInfo = newValue {
trackingInfos[trackID] = trackingInfo
trackingInfo.tracker = self
trackingInfo.startTimer()
}
lock.unlock()
}
}
///通过trackID和回调方法来创建trackingInfo,会使用默认的trackingInfo实现
public func addTrackingInfo(trackID: String, timeOut: NSTimeInterval, queue: dispatch_queue_t?, handler: XLYTrackingHandler) {
let trackingInfo = XLYBasicTrackingInfo(trackID: trackID, timeOut: timeOut, queue: queue ?? self.trackerQueue, handler: handler)
addTrackingInfo(trackingInfo)
}
///添加一个配置好的trackingInfo,会覆盖已有的trackingInfo
public func addTrackingInfo(var trackingInfo: XLYTrackingInfo) {
self[trackingInfo.trackID] = trackingInfo
}
///响应一个tracking, 如果响应成功返回true,否则返回NO
public func responseTrackingForID(trackID: String, response: Any?) -> Bool {
if let trackingInfo = self[trackID] {
self[trackID] = nil
dispatch_async(trackingInfo.trackQueue, {trackingInfo.response(response)})
return true
}
return false
}
///停止track
public func stopTrackingForID(trackID: String) {
self[trackID] = nil
}
///停止所有的tracking
public func stopAllTracking() {
for trackID in trackingInfos.keys {
self[trackID] = nil
}
}
}
//MARK: - XLYTrackingInfo protocol
/// all properties and functions should not be called directly.
public protocol XLYTrackingInfo {
///标识唯一的track id.
var trackID: String {get}
///track所使用的queue,计时应该在这个queue里面进行
var trackQueue: dispatch_queue_t {get}
///所从属的tracker
weak var tracker: XLYIDTracker! {get set}
init(trackID: String, timeOut: NSTimeInterval, queue :dispatch_queue_t, handler: XLYTrackingHandler)
///开始计时,应该在trackQueue里面进行,超时后需要调用tracker的response方法并传递自定义的错误信息比如nil
func startTimer()
///停止计时,取消掉timer
func cancelTimer()
///响应一个track,可以是任何对象,由tracker在trackQueue中进行调用
func response(response: Any?)
}
//MARK: - XLYBasicTrackingInfo
public class XLYBasicTrackingInfo: XLYTrackingInfo {
public let trackID: String
public let trackQueue: dispatch_queue_t
public var autoRemoveFromTracker = false
public weak var tracker: XLYIDTracker!
private let trackTimeOut: NSTimeInterval = 15
private let trackHandler: XLYTrackingHandler
private var trackTimer: dispatch_source_t?
private let queueTag = UnsafeMutablePointer<Void>(malloc(1))
required public init(trackID: String, timeOut: NSTimeInterval, queue :dispatch_queue_t, handler: XLYTrackingHandler) {
self.trackID = trackID
trackHandler = handler
trackQueue = queue
if timeOut > 0 {
trackTimeOut = timeOut
}
dispatch_queue_set_specific(queue, queueTag, queueTag, nil)
}
deinit {
cancelTimer()
}
///超时后response为nil,意味着没有规定时间内没有得到响应数据
public func startTimer() {
assert(trackTimer == nil, "XLYBasicTrackingInfo class can start counting down only when timer is stoped.")
assert(tracker != nil, "XLYBasicTrackingInfo class must have tracker set to perform response")
trackTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, trackQueue);
dispatch_source_set_event_handler(trackTimer) {
[weak self] in
autoreleasepool(){
if let strongSelf = self {
if let tracker = strongSelf.tracker {
dispatch_async(tracker.trackerQueue) {
if strongSelf.autoRemoveFromTracker {
let _ = tracker.responseTrackingForID(strongSelf.trackID, response: nil)
} else {
dispatch_async(strongSelf.trackQueue) {
strongSelf.response(nil)
}
}
}
}
}
}
}
let tt = dispatch_time(DISPATCH_TIME_NOW, Int64(trackTimeOut * NSTimeInterval(NSEC_PER_SEC)));
dispatch_source_set_timer(trackTimer!, tt, DISPATCH_TIME_FOREVER, 0)
dispatch_resume(trackTimer!);
}
public func cancelTimer() {
if let timer = trackTimer {
dispatch_source_cancel(timer)
trackTimer = nil
}
}
public func response(response: Any?) {
assert(queueTag == dispatch_get_specific(queueTag), "should response in XLYBasicTrackingInfo.trackQueue.")
autoreleasepool() {
self.trackHandler(trackingInfo: self, response: response)
}
}
}
| mit |
aiwalle/LiveProject | macSocket/LJSocket/LJClientManager.swift | 1 | 2925 | //
// LJClientManager.swift
// LiveProject
//
// Created by liang on 2017/8/28.
// Copyright © 2017年 liang. All rights reserved.
//
import Cocoa
protocol LJClientManagerDelegate : class {
func sendMsgToClient(_ data : Data)
func removeClient(client : LJClientManager)
}
class LJClientManager : NSObject {
weak var delegate : LJClientManagerDelegate?
var client : TCPClient
fileprivate var isClientConnecting : Bool = false
fileprivate var heartTimeCount : Int = 0
init(client : TCPClient) {
self.client = client
}
}
extension LJClientManager {
func readMessage() {
isClientConnecting = true
while isClientConnecting {
if let headMsg = client.read(4) {
let timer = Timer(fireAt: Date(), interval: 1, target: self, selector: #selector(checkHeartBeat), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
timer.fire()
let headData = Data(bytes: headMsg, count: 4)
var actualLength = 0
// 给actualLength赋值,获取消息内容长度
(headData as NSData).getBytes(&actualLength, length: 4)
guard let typeMsg = client.read(2) else {
return
}
let typeData = Data(bytes: typeMsg, count: 2)
var type = 0
(typeData as NSData).getBytes(&type, length: 2)
guard let actualMsg = client.read(actualLength) else {
return
}
let actualData = Data(bytes: actualMsg, count: actualLength)
let actualMsgStr = String(data: actualData, encoding: .utf8)
if type == 1 {
removeClient()
} else if type == 100 {
// 客户端在线才会给服务器发送❤️包,所以如果收到了❤️,就一直连接服务器,除非客户端退出或下线
heartTimeCount = 0
// 不读❤️包的消息
continue
}
print(actualMsgStr ?? "解析消息出错")
let totalData = headData + typeData + actualData
delegate?.sendMsgToClient(totalData)
} else {
removeClient()
}
}
}
@objc fileprivate func checkHeartBeat() {
heartTimeCount += 1
if heartTimeCount >= 10 {
removeClient()
}
print("收到了心跳包")
}
private func removeClient() {
delegate?.removeClient(client: self)
isClientConnecting = false
print("客户端断开了连接")
_ = client.close()
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0858-swift-typebase-getcanonicaltype.swift | 13 | 279 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B : c(x() {
let end = [$0.A"
protocol c : d {
typealias d
| apache-2.0 |
corey-lin/PlayMarvelAPI | NameSHero/QuizViewController.swift | 1 | 2922 | //
// QuizViewController.swift
// NameSHero
//
// Created by coreylin on 3/2/16.
// Copyright © 2016 coreylin. All rights reserved.
//
import UIKit
//import ReactiveCocoa
import Kingfisher
import SwiftSpinner
import TAOverlay
class QuizViewController: UIViewController {
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var pictureImageView: UIImageView!
@IBOutlet var choiceButtons: [UIButton]!
@IBOutlet weak var quizPlayView: UIView!
var viewModel = QuizViewModel()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.pictureURL.producer.startWithNext {
print("\($0)")
if let imageURL = $0 {
self.pictureImageView.kf_setImageWithURL(imageURL)
}
}
viewModel.choices.producer.startWithNext {
if let choices = $0 {
for index in 0..<choices.count {
self.choiceButtons[index].setTitle(choices[index], forState: UIControlState.Normal)
}
}
}
viewModel.numberOfQuests.producer.startWithNext {
if $0 > 0 {
let score = ($0 - 1) * 10
self.scoreLabel.text = "Score:\(score)"
if score == 100 {
self.performSegueWithIdentifier("toResult", sender: nil)
}
}
}
viewModel.quizViewStateInfo.producer.startWithNext {
if $0.curState == QuizViewState.GameOver {
self.performSegueWithIdentifier("toResult", sender: nil)
} else if $0.curState == QuizViewState.Loading {
SwiftSpinner.show("Loading Data From Server...")
self.quizPlayView.hidden = true
} else if $0.curState == QuizViewState.UserPlay {
SwiftSpinner.hide()
self.quizPlayView.hidden = false
}
}
viewModel.notifyAnswerCorrect.producer.startWithNext {
if $0 && self.viewModel.numberOfQuests.value > 0 {
TAOverlay.showOverlayWithLabel(nil, options:[
TAOverlayOptions.OverlayTypeSuccess,
TAOverlayOptions.AutoHide,
TAOverlayOptions.OverlaySizeFullScreen])
}
}
viewModel.notifyAnswerWrong.producer.startWithNext {
if $0 && self.viewModel.numberOfQuests.value > 0 {
TAOverlay.showOverlayWithLabel(nil, options:[
TAOverlayOptions.OverlayTypeError,
TAOverlayOptions.AutoHide,
TAOverlayOptions.OverlaySizeFullScreen
])
}
}
}
override func viewWillAppear(animated: Bool) {
viewModel.resetQuiz()
viewModel.fetchCharacterPicture()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toResult" {
let resultVC = segue.destinationViewController as! ResultViewController
let vm = ResultViewModel((viewModel.numberOfQuests.value - 1) * 10)
resultVC.bindViewModel(vm)
}
}
@IBAction func selectButtonPressed(sender: AnyObject) {
let button = sender as! UIButton
viewModel.checkAnswer(button.titleLabel?.text)
}
} | mit |
MingLeiVV/MLEmoticon | test/test/ViewController.swift | 1 | 736 | //
// ViewController.swift
// test
//
// Created by 吴明磊 on 15/5/6.
// Copyright © 2015年 wuminglei. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private lazy var emoticonVC: MLEmoticonController = MLEmoticonController {[weak self] (emoticon) -> () in
if emoticon != nil {
self?.selectEmoticon(emoticon!)
}
}
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.inputView = emoticonVC.view
}
private func selectEmoticon (emoticon : Emoticons) {
textView.insertEmoticon(emoticon)
}
}
| apache-2.0 |
Zewo/TCPIP | Sources/TCPIP/TCPError.swift | 1 | 1571 | // TCPError.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 CTide
public struct TCPError : ErrorProtocol, CustomStringConvertible {
public let description: String
public let bytesProcessed: Int?
init(description: String, bytesProcessed: Int? = nil) {
self.description = description
self.bytesProcessed = bytesProcessed
}
static var lastSystemErrorDescription: String {
return String(validatingUTF8: strerror(errno))!
}
}
| mit |
czechboy0/BuildaUtils | Source/Server.swift | 2 | 325 | //
// Server.swift
// Buildasaur
//
// Created by Honza Dvorsky on 14/12/2014.
// Copyright (c) 2014 Honza Dvorsky. All rights reserved.
//
import Foundation
open class HTTPServer : NSObject {
open let http: HTTP
public init(http: HTTP? = nil) {
self.http = http ?? HTTP(session: nil)
}
}
| mit |
nitrado/NitrAPI-Swift | Pod/Classes/customer/SSHKeys.swift | 1 | 1199 | import ObjectMapper
/// This class represents a SSHKeys.
open class SSHKeys: Mappable {
fileprivate var nitrapi: Nitrapi!
/// Returns keys.
open fileprivate(set) var keys: [SSHKey]?
init() {
}
required public init?(map: Map) {
}
public func mapping(map: Map) {
keys <- map["keys"]
}
/// Upload a SSH key.
/// - parameter key: key
open func uploadKey(_ key: String) throws {
_ = try nitrapi.client.dataPost("user/ssh_keys/", parameters: [
"key": key
])
}
/// Updates a SSH public key.
/// - parameter id: id
/// - parameter key: key
/// - parameter enabled: enabled
open func updateKey(_ id: Int, key: String, enabled: Bool) throws {
_ = try nitrapi.client.dataPost("user/ssh_keys/\(id)", parameters: [
"key": key,
"enabled": enabled
])
}
/// Deletes a SSH public key.
/// - parameter id: id
open func deleteKey(_ id: Int) throws {
_ = try nitrapi.client.dataDelete("user/ssh_keys/\(id)", parameters: [:])
}
// MARK: - Internally used
func postInit(_ nitrapi: Nitrapi) {
self.nitrapi = nitrapi
}
}
| mit |
nalexn/ViewInspector | Sources/ViewInspector/SwiftUI/TextField.swift | 1 | 3543 | import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct TextField: KnownViewType {
public static var typePrefix: String = "TextField"
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: SingleViewContent {
func textField() throws -> InspectableView<ViewType.TextField> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: MultipleViewContent {
func textField(_ index: Int) throws -> InspectableView<ViewType.TextField> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Non Standard Children
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.TextField: SupplementaryChildrenLabelView { }
// MARK: - Custom Attributes
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View == ViewType.TextField {
func labelView() throws -> InspectableView<ViewType.ClassifiedView> {
return try View.supplementaryChildren(self).element(at: 0)
.asInspectableView(ofType: ViewType.ClassifiedView.self)
}
func callOnEditingChanged() throws {
try guardIsResponsive()
typealias Callback = (Bool) -> Void
let callback: Callback = try {
if let value = try? Inspector
.attribute(label: "onEditingChanged", value: content.view, type: Callback.self) {
return value
}
return try Inspector
.attribute(path: deprecatedActionsPath("editingChanged"), value: content.view, type: Callback.self)
}()
callback(false)
}
func callOnCommit() throws {
try guardIsResponsive()
typealias Callback = () -> Void
let callback: Callback = try {
if let value = try? Inspector
.attribute(label: "onCommit", value: content.view, type: Callback.self) {
return value
}
return try Inspector
.attribute(path: deprecatedActionsPath("commit"), value: content.view, type: Callback.self)
}()
callback()
}
private func deprecatedActionsPath(_ action: String) -> String {
return "_state|state|_value|deprecatedActions|some|\(action)"
}
func input() throws -> String {
return try inputBinding().wrappedValue
}
func setInput(_ value: String) throws {
try guardIsResponsive()
try inputBinding().wrappedValue = value
}
private func inputBinding() throws -> Binding<String> {
let label: String
if #available(iOS 13.2, macOS 10.17, tvOS 13.2, *) {
label = "_text"
} else {
label = "text"
}
return try Inspector.attribute(label: label, value: content.view, type: Binding<String>.self)
}
}
// MARK: - Global View Modifiers
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func textFieldStyle() throws -> Any {
let modifier = try self.modifier({ modifier -> Bool in
return modifier.modifierType.hasPrefix("TextFieldStyleModifier")
}, call: "textFieldStyle")
return try Inspector.attribute(path: "modifier|style", value: modifier)
}
}
| mit |
asurinsaka/swift_examples_2.1 | MemLeak/MemLeak/ViewController.swift | 1 | 792 | //
// ViewController.swift
// MemLeak
//
// Created by doudou on 10/3/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
class Client
{
var name:String
var account:Account!
init(name:String)
{
self.name = name
self.account = Account(client: self)
}
deinit
{
println("Client::deinit")
}
}
class Account
{
var client:Client
var balance:Int
init(client:Client)
{
self.client = client
self.balance = 0
}
deinit
{
println("Account::deinit")
}
}
override func viewDidLoad()
{
super.viewDidLoad()
var client:Client! = Client(name: "larryhou")
client = nil
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
}
| mit |
Brightify/ReactantUI | Sources/Tokenizer/Properties/Types/SupportedPropertyType.swift | 1 | 1647 | //
// SupportedPropertyType.swift
// ReactantUI
//
// Created by Tadeas Kriz.
// Copyright © 2017 Brightify. All rights reserved.
//
import Foundation
public protocol SupportedPropertyType {
var requiresTheme: Bool { get }
func generate(context: SupportedPropertyTypeContext) -> String
#if SanAndreas
func dematerialize(context: SupportedPropertyTypeContext) -> String
#endif
#if canImport(UIKit)
func runtimeValue(context: SupportedPropertyTypeContext) -> Any?
#endif
// FIXME Although it's not needed for POC of Themes, it should be implemented so that more things can be themed.
// We would then use this to know how is the type called for generating.
// static var runtimeType: String { get }
// FIXME Has to be put into `AttributeSupportedPropertyType`
static var xsdType: XSDType { get }
}
public extension SupportedPropertyType {
var requiresTheme: Bool {
return false
}
}
public protocol AttributeSupportedPropertyType: SupportedPropertyType {
static func materialize(from value: String) throws -> Self
}
public protocol ElementSupportedPropertyType: SupportedPropertyType {
static func materialize(from element: XMLElement) throws -> Self
}
public protocol MultipleAttributeSupportedPropertyType: SupportedPropertyType {
static func materialize(from attributes: [String: String]) throws -> Self
}
extension ElementSupportedPropertyType where Self: AttributeSupportedPropertyType {
static func materialize(from element: XMLElement) throws -> Self {
let text = element.text ?? ""
return try materialize(from: text)
}
}
| mit |
feighter09/Cloud9 | SoundCloud Pro/MusicPlayerView.swift | 1 | 541 | //
// MusicPlayerView.swift
// SoundCloud Pro
//
// Created by Austin Feight on 8/10/15.
// Copyright © 2015 Lost in Flight. All rights reserved.
//
import UIKit
class MusicPlayerView: UIView {
@IBOutlet private weak var expandContractButton: UIButton!
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView?
{
if let view = super.hitTest(point, withEvent: event) { return view }
else if CGRectContainsPoint(expandContractButton.frame, point) { return expandContractButton }
return nil
}
}
| lgpl-3.0 |
xedin/swift | test/SILGen/switch_debuginfo.swift | 14 | 2857 | // RUN: %target-swift-emit-silgen -g -Xllvm -sil-print-debuginfo %s | %FileCheck %s
func nop1() {}
func nop2() {}
enum Binary {
case On
case Off
}
func isOn(_ b: Binary) -> Bool {
return b == .On
}
// CHECK: [[LOC:loc "[^"]+"]]
// First, check that we don't assign fresh locations to each case statement,
// except for any relevant debug value instructions.
// CHECK-LABEL: sil hidden [ossa] @$s16switch_debuginfo5test11iySi_tF
func test1(i: Int) {
switch i {
// CHECK-NOT: [[LOC]]:[[@LINE+1]]
case 0: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]]
// CHECK-NOT: [[LOC]]:[[@LINE-1]]
nop1()
// CHECK-NOT: [[LOC]]:[[@LINE+1]]
case 1: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]]
// CHECK-NOT: [[LOC]]:[[@LINE-1]]
nop1()
default: // CHECK-NOT: [[LOC]]:[[@LINE]]
nop1()
}
}
// Next, check that case statements and switch subjects have the same locations.
// CHECK-LABEL: sil hidden [ossa] @$s16switch_debuginfo5test21sySS_tF
func test2(s: String) {
switch s {
case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10
nop1()
case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10
nop2()
default:
nop1()
}
}
// Fallthrough shouldn't affect case statement locations.
// CHECK-LABEL: sil hidden [ossa] @$s16switch_debuginfo5test31sySS_tF
func test3(s: String) {
switch s {
case "a", "b":
// CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-2]]:10
// CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10
nop1()
fallthrough
case "b", "c":
// CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-7]]:10
// CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE-8]]:10
nop2()
fallthrough
default:
nop1()
}
}
// It should be possible to set breakpoints on where clauses.
// CHECK-LABEL: sil hidden [ossa] @$s16switch_debuginfo5test41byAA6BinaryO_tF
func test4(b: Binary) {
switch b {
case let _ // CHECK-NOT: [[LOC]]:[[@LINE]]
where isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11
nop1()
case let _ // CHECK-NOT: [[LOC]]:[[@LINE]]
where !isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11
nop2()
default:
nop1()
}
}
// Check that we set the right locations before/after nested switches.
// CHECK-LABEL: sil hidden [ossa] @$s16switch_debuginfo5test51sySS_tF
func test5(s: String) {
switch s {
case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10
switch "b" {
case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-1]]:12
nop1()
default:
nop2()
}
if "c" == "c" { // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE]]
nop1()
}
default:
nop1()
}
if "d" == "d" { // CHECK: string_literal utf8 "d", [[LOC]]:[[@LINE]]
nop1()
}
}
| apache-2.0 |
shajrawi/swift | test/stdlib/StringCompatibility.swift | 1 | 8336 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-codesign %t/a.out4 && %target-run %t/a.out4
// Requires swift-version 4
// UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic
// REQUIRES: executable_test
import StdlibUnittest
//===--- MyString ---------------------------------------------------------===//
/// A simple StringProtocol with a wacky .description that proves
/// LosslessStringConvertible is not infecting ordinary constructions by using
/// .description as the content of a copied string.
struct MyString {
var base: String
}
extension MyString : BidirectionalCollection {
typealias Iterator = String.Iterator
typealias Index = String.Index
typealias SubSequence = MyString
func makeIterator() -> Iterator { return base.makeIterator() }
var startIndex: String.Index { return base.startIndex }
var endIndex: String.Index { return base.startIndex }
subscript(i: Index) -> Character { return base[i] }
subscript(indices: Range<Index>) -> MyString {
return MyString(base: String(self.base[indices]))
}
func index(after i: Index) -> Index { return base.index(after: i) }
func index(before i: Index) -> Index { return base.index(before: i) }
func index(_ i: Index, offsetBy n: Int) -> Index {
return base.index(i, offsetBy: n)
}
func distance(from i: Index, to j: Index) -> Int {
return base.distance(from: i, to: j)
}
}
extension MyString : RangeReplaceableCollection {
init() { base = "" }
mutating func append<S: Sequence>(contentsOf s: S)
where S.Element == Character {
base.append(contentsOf: s)
}
mutating func replaceSubrange<C: Collection>(_ r: Range<Index>, with c: C)
where C.Element == Character {
base.replaceSubrange(r, with: c)
}
}
extension MyString : CustomStringConvertible {
var description: String { return "***MyString***" }
}
extension MyString : TextOutputStream {
public mutating func write(_ other: String) {
append(contentsOf: other)
}
}
extension MyString : TextOutputStreamable {
public func write<Target : TextOutputStream>(to target: inout Target) {
target.write(base)
}
}
extension MyString : ExpressibleByUnicodeScalarLiteral {
public init(unicodeScalarLiteral value: String) {
base = .init(unicodeScalarLiteral: value)
}
}
extension MyString : ExpressibleByExtendedGraphemeClusterLiteral {
public init(extendedGraphemeClusterLiteral value: String) {
base = .init(extendedGraphemeClusterLiteral: value)
}
}
extension MyString : ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
base = .init(stringLiteral: value)
}
}
extension MyString : CustomReflectable {
public var customMirror: Mirror {
return base.customMirror
}
}
extension MyString : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return base.customPlaygroundQuickLook
}
}
extension MyString : CustomDebugStringConvertible {
public var debugDescription: String {
return "(***MyString***)"
}
}
extension MyString : Equatable {
public static func ==(lhs: MyString, rhs: MyString) -> Bool {
return lhs.base == rhs.base
}
}
extension MyString : Comparable {
public static func <(lhs: MyString, rhs: MyString) -> Bool {
return lhs.base < rhs.base
}
}
extension MyString : Hashable {
public var hashValue : Int {
return base.hashValue
}
}
extension MyString {
public func hasPrefix(_ prefix: String) -> Bool {
return self.base.hasPrefix(prefix)
}
public func hasSuffix(_ suffix: String) -> Bool {
return self.base.hasSuffix(suffix)
}
}
extension MyString : StringProtocol {
var utf8: String.UTF8View { return base.utf8 }
var utf16: String.UTF16View { return base.utf16 }
var unicodeScalars: String.UnicodeScalarView { return base.unicodeScalars }
var characters: String.CharacterView { return base.characters }
func lowercased() -> String {
return base.lowercased()
}
func uppercased() -> String {
return base.uppercased()
}
init<C: Collection, Encoding: Unicode.Encoding>(
decoding codeUnits: C, as sourceEncoding: Encoding.Type
)
where C.Iterator.Element == Encoding.CodeUnit {
base = .init(decoding: codeUnits, as: sourceEncoding)
}
init(cString nullTerminatedUTF8: UnsafePointer<CChar>) {
base = .init(cString: nullTerminatedUTF8)
}
init<Encoding: Unicode.Encoding>(
decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>,
as sourceEncoding: Encoding.Type) {
base = .init(decodingCString: nullTerminatedCodeUnits, as: sourceEncoding)
}
func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result {
return try base.withCString(body)
}
func withCString<Result, Encoding: Unicode.Encoding>(
encodedAs targetEncoding: Encoding.Type,
_ body: (UnsafePointer<Encoding.CodeUnit>) throws -> Result
) rethrows -> Result {
return try base.withCString(encodedAs: targetEncoding, body)
}
}
//===----------------------------------------------------------------------===//
public typealias ExpectedConcreteSlice = Substring
public typealias ExpectedStringFromString = String
let swift = 4
var Tests = TestSuite("StringCompatibility")
Tests.test("String/Range/Slice/ExpectedType/\(swift)") {
var s = "hello world"
var sub = s[s.startIndex ..< s.endIndex]
var subsub = sub[s.startIndex ..< s.endIndex]
expectType(String.self, &s)
expectType(ExpectedConcreteSlice.self, &sub)
expectType(ExpectedConcreteSlice.self, &subsub)
}
Tests.test("String/ClosedRange/Slice/ExpectedType/\(swift)") {
var s = "hello world"
let lastIndex = s.index(before:s.endIndex)
var sub = s[s.startIndex ... lastIndex]
var subsub = sub[s.startIndex ... lastIndex]
expectType(String.self, &s)
expectType(ExpectedConcreteSlice.self, &sub)
expectType(ExpectedConcreteSlice.self, &subsub)
}
Tests.test("Substring/Range/Slice/ExpectedType/\(swift)") {
let s = "hello world" as Substring
var sub = s[s.startIndex ..< s.endIndex]
var subsub = sub[s.startIndex ..< s.endIndex]
// slicing a String in Swift 3 produces a String
// but slicing a Substring should still produce a Substring
expectType(Substring.self, &sub)
expectType(Substring.self, &subsub)
}
Tests.test("Substring/ClosedRange/Slice/ExpectedType/\(swift)") {
let s = "hello world" as Substring
let lastIndex = s.index(before:s.endIndex)
var sub = s[s.startIndex ... lastIndex]
var subsub = sub[s.startIndex ... lastIndex]
expectType(ExpectedConcreteSlice.self, &sub)
expectType(ExpectedConcreteSlice.self, &subsub)
}
Tests.test("RangeReplaceable.init/generic/\(swift)") {
func check<
T: RangeReplaceableCollection, S: Collection
>(_: T.Type, from source: S)
where T.Element : Equatable, T.Element == S.Element
{
var r = T(source)
expectType(T.self, &r)
expectEqualSequence(Array(source), Array(r))
}
check(String.self, from: "a" as String)
check(Substring.self, from: "b" as String)
// FIXME: Why isn't this working?
// check(MyString.self, from: "c" as String)
check(String.self, from: "d" as Substring)
check(Substring.self, from: "e" as Substring)
// FIXME: Why isn't this working?
// check(MyString.self, from: "f" as Substring)
// FIXME: Why isn't this working?
// check(String.self, from: "g" as MyString)
// check(Substring.self, from: "h" as MyString)
check(MyString.self, from: "i" as MyString)
}
Tests.test("String.init(someString)/default type/\(swift)") {
var s = String("" as String)
expectType(ExpectedStringFromString.self, &s)
}
Tests.test("Substring.init(someString)/default type/\(swift)") {
var s = Substring("" as Substring)
expectType(Substring.self, &s)
}
Tests.test("LosslessStringConvertible/generic/\(swift)") {
func f<T : LosslessStringConvertible>(_ x: T.Type) {
_ = T("")! // unwrapping optional should work in generic context
}
f(String.self)
}
public typealias ExpectedUTF8ViewSlice = String.UTF8View.SubSequence
Tests.test("UTF8ViewSlicing") {
let s = "Hello, String.UTF8View slicing world!".utf8
var slice = s[s.startIndex..<s.endIndex]
expectType(ExpectedUTF8ViewSlice.self, &slice)
_ = s[s.startIndex..<s.endIndex] as String.UTF8View.SubSequence
}
runAllTests()
| apache-2.0 |
crazypoo/PTools | Pods/UIColor_Hex_Swift/HEXColor/StringExtension.swift | 5 | 877 | //
// StringExtension.swift
// HEXColor-iOS
//
// Created by Sergey Pugach on 2/2/18.
// Copyright © 2018 P.D.Q. All rights reserved.
//
import Foundation
extension String {
/**
Convert argb string to rgba string.
*/
public var argb2rgba: String? {
guard self.hasPrefix("#") else {
return nil
}
let hexString: String = String(self[self.index(self.startIndex, offsetBy: 1)...])
switch hexString.count {
case 4:
return "#\(String(hexString[self.index(self.startIndex, offsetBy: 1)...]))\(String(hexString[..<self.index(self.startIndex, offsetBy: 1)]))"
case 8:
return "#\(String(hexString[self.index(self.startIndex, offsetBy: 2)...]))\(String(hexString[..<self.index(self.startIndex, offsetBy: 2)]))"
default:
return nil
}
}
}
| mit |
brbulic/fastlane | fastlane/swift/ScanfileProtocol.swift | 1 | 11053 | // ScanfileProtocol.swift
// Copyright (c) 2020 FastlaneTools
public protocol ScanfileProtocol: class {
/// Path to the workspace file
var workspace: String? { get }
/// Path to the project file
var project: String? { get }
/// The project's scheme. Make sure it's marked as `Shared`
var scheme: String? { get }
/// The name of the simulator type you want to run tests on (e.g. 'iPhone 6')
var device: String? { get }
/// Array of devices to run the tests on (e.g. ['iPhone 6', 'iPad Air'])
var devices: [String]? { get }
/// Should skip auto detecting of devices if none were specified
var skipDetectDevices: Bool { get }
/// Enabling this option will automatically killall Simulator processes before the run
var forceQuitSimulator: Bool { get }
/// Enabling this option will automatically erase the simulator before running the application
var resetSimulator: Bool { get }
/// Enabling this option will disable the simulator from showing the 'Slide to type' prompt
var disableSlideToType: Bool { get }
/// Enabling this option will launch the first simulator prior to calling any xcodebuild command
var prelaunchSimulator: Bool? { get }
/// Enabling this option will automatically uninstall the application before running it
var reinstallApp: Bool { get }
/// The bundle identifier of the app to uninstall (only needed when enabling reinstall_app)
var appIdentifier: String? { get }
/// Array of strings matching Test Bundle/Test Suite/Test Cases to run
var onlyTesting: String? { get }
/// Array of strings matching Test Bundle/Test Suite/Test Cases to skip
var skipTesting: String? { get }
/// The testplan associated with the scheme that should be used for testing
var testplan: String? { get }
/// Array of strings matching test plan configurations to run
var onlyTestConfigurations: String? { get }
/// Array of strings matching test plan configurations to skip
var skipTestConfigurations: String? { get }
/// Run tests using the provided `.xctestrun` file
var xctestrun: String? { get }
/// The toolchain that should be used for building the application (e.g. `com.apple.dt.toolchain.Swift_2_3, org.swift.30p620160816a`)
var toolchain: String? { get }
/// Should the project be cleaned before building it?
var clean: Bool { get }
/// Should code coverage be generated? (Xcode 7 and up)
var codeCoverage: Bool? { get }
/// Should the address sanitizer be turned on?
var addressSanitizer: Bool? { get }
/// Should the thread sanitizer be turned on?
var threadSanitizer: Bool? { get }
/// Should the HTML report be opened when tests are completed?
var openReport: Bool { get }
/// Disable xcpretty formatting of build, similar to `output_style='raw'` but this will also skip the test results table
var disableXcpretty: Bool? { get }
/// The directory in which all reports will be stored
var outputDirectory: String { get }
/// Define how the output should look like. Valid values are: standard, basic, rspec, or raw (disables xcpretty during xcodebuild)
var outputStyle: String? { get }
/// Comma separated list of the output types (e.g. html, junit, json-compilation-database)
var outputTypes: String { get }
/// Comma separated list of the output files, corresponding to the types provided by :output_types (order should match). If specifying an output type of json-compilation-database with :use_clang_report_name enabled, that option will take precedence
var outputFiles: String? { get }
/// The directory where to store the raw log
var buildlogPath: String { get }
/// If the logs generated by the app (e.g. using NSLog, perror, etc.) in the Simulator should be written to the output_directory
var includeSimulatorLogs: Bool { get }
/// Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path
var suppressXcodeOutput: Bool? { get }
/// A custom xcpretty formatter to use
var formatter: String? { get }
/// Pass in xcpretty additional command line arguments (e.g. '--test --no-color' or '--tap --no-utf')
var xcprettyArgs: String? { get }
/// The directory where build products and other derived data will go
var derivedDataPath: String? { get }
/// Should zip the derived data build products and place in output path?
var shouldZipBuildProducts: Bool { get }
/// Should an Xcode result bundle be generated in the output directory
var resultBundle: Bool { get }
/// Generate the json compilation database with clang naming convention (compile_commands.json)
var useClangReportName: Bool { get }
/// Specify the exact number of test runners that will be spawned during parallel testing. Equivalent to -parallel-testing-worker-count
var concurrentWorkers: Int? { get }
/// Constrain the number of simulator devices on which to test concurrently. Equivalent to -maximum-concurrent-test-simulator-destinations
var maxConcurrentSimulators: Int? { get }
/// Do not run test bundles in parallel on the specified destinations. Testing will occur on each destination serially. Equivalent to -disable-concurrent-testing
var disableConcurrentTesting: Bool { get }
/// Should debug build be skipped before test build?
var skipBuild: Bool { get }
/// Test without building, requires a derived data path
var testWithoutBuilding: Bool? { get }
/// Build for testing only, does not run tests
var buildForTesting: Bool? { get }
/// The SDK that should be used for building the application
var sdk: String? { get }
/// The configuration to use when building the app. Defaults to 'Release'
var configuration: String? { get }
/// Pass additional arguments to xcodebuild. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++"
var xcargs: String? { get }
/// Use an extra XCCONFIG file to build your app
var xcconfig: String? { get }
/// App name to use in slack message and logfile name
var appName: String? { get }
/// Target version of the app being build or tested. Used to filter out simulator version
var deploymentTargetVersion: String? { get }
/// Create an Incoming WebHook for your Slack group to post results there
var slackUrl: String? { get }
/// #channel or @username
var slackChannel: String? { get }
/// The message included with each message posted to slack
var slackMessage: String? { get }
/// Use webhook's default username and icon settings? (true/false)
var slackUseWebhookConfiguredUsernameAndIcon: Bool { get }
/// Overrides the webhook's username property if slack_use_webhook_configured_username_and_icon is false
var slackUsername: String { get }
/// Overrides the webhook's image property if slack_use_webhook_configured_username_and_icon is false
var slackIconUrl: String { get }
/// Don't publish to slack, even when an URL is given
var skipSlack: Bool { get }
/// Only post on Slack if the tests fail
var slackOnlyOnFailure: Bool { get }
/// Use only if you're a pro, use the other options instead
var destination: String? { get }
/// **DEPRECATED!** Use `--output_files` instead - Sets custom full report file name when generating a single report
var customReportFileName: String? { get }
/// Allows for override of the default `xcodebuild` command
var xcodebuildCommand: String { get }
/// Sets a custom path for Swift Package Manager dependencies
var clonedSourcePackagesPath: String? { get }
/// Should this step stop the build if the tests fail? Set this to false if you're using trainer
var failBuild: Bool { get }
}
public extension ScanfileProtocol {
var workspace: String? { return nil }
var project: String? { return nil }
var scheme: String? { return nil }
var device: String? { return nil }
var devices: [String]? { return nil }
var skipDetectDevices: Bool { return false }
var forceQuitSimulator: Bool { return false }
var resetSimulator: Bool { return false }
var disableSlideToType: Bool { return true }
var prelaunchSimulator: Bool? { return nil }
var reinstallApp: Bool { return false }
var appIdentifier: String? { return nil }
var onlyTesting: String? { return nil }
var skipTesting: String? { return nil }
var testplan: String? { return nil }
var onlyTestConfigurations: String? { return nil }
var skipTestConfigurations: String? { return nil }
var xctestrun: String? { return nil }
var toolchain: String? { return nil }
var clean: Bool { return false }
var codeCoverage: Bool? { return nil }
var addressSanitizer: Bool? { return nil }
var threadSanitizer: Bool? { return nil }
var openReport: Bool { return false }
var disableXcpretty: Bool? { return nil }
var outputDirectory: String { return "./test_output" }
var outputStyle: String? { return nil }
var outputTypes: String { return "html,junit" }
var outputFiles: String? { return nil }
var buildlogPath: String { return "~/Library/Logs/scan" }
var includeSimulatorLogs: Bool { return false }
var suppressXcodeOutput: Bool? { return nil }
var formatter: String? { return nil }
var xcprettyArgs: String? { return nil }
var derivedDataPath: String? { return nil }
var shouldZipBuildProducts: Bool { return false }
var resultBundle: Bool { return false }
var useClangReportName: Bool { return false }
var concurrentWorkers: Int? { return nil }
var maxConcurrentSimulators: Int? { return nil }
var disableConcurrentTesting: Bool { return false }
var skipBuild: Bool { return false }
var testWithoutBuilding: Bool? { return nil }
var buildForTesting: Bool? { return nil }
var sdk: String? { return nil }
var configuration: String? { return nil }
var xcargs: String? { return nil }
var xcconfig: String? { return nil }
var appName: String? { return nil }
var deploymentTargetVersion: String? { return nil }
var slackUrl: String? { return nil }
var slackChannel: String? { return nil }
var slackMessage: String? { return nil }
var slackUseWebhookConfiguredUsernameAndIcon: Bool { return false }
var slackUsername: String { return "fastlane" }
var slackIconUrl: String { return "https://fastlane.tools/assets/img/fastlane_icon.png" }
var skipSlack: Bool { return false }
var slackOnlyOnFailure: Bool { return false }
var destination: String? { return nil }
var customReportFileName: String? { return nil }
var xcodebuildCommand: String { return "env NSUnbufferedIO=YES xcodebuild" }
var clonedSourcePackagesPath: String? { return nil }
var failBuild: Bool { return true }
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.51]
| mit |
MattMcEachern/CustomLoadingIndicator | CustomLoadingIndicatorDemo/ViewController.swift | 1 | 1076 | //
// ViewController.swift
// CustomLoadingIndicatorDemo
//
// Created by Matt McEachern on 8/16/15.
// Copyright (c) 2015 Matt McEachern. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
let loadingLabel = UILabel(frame: CGRect(x: 0,y: 0,width: self.view.bounds.width, height: 100.0))
loadingLabel.text = "LOADING"
loadingLabel.textColor = UIColor.blackColor()
loadingLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(loadingLabel)
loadingLabel.center = CGPoint(x: self.view.center.x, y: self.view.center.y + 55.0);
let customLoadingIndicator = CustomLoadingIndicator()
self.view.addSubview(customLoadingIndicator)
customLoadingIndicator.center = self.view.center
customLoadingIndicator.startAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
Motsai/neblina-swift | NebCtrlMultiSync/iOS/NebCtrlMultiSync/ViewController.swift | 2 | 59274 | //
// ViewController.swift
// BauerPanel
//
// Created by Hoan Hoang on 2017-02-23.
// Copyright © 2017 Hoan Hoang. All rights reserved.
//
import UIKit
import CoreBluetooth
import QuartzCore
import SceneKit
let CmdMotionDataStream = Int32(1)
let CmdHeading = Int32(2)
let NebCmdList = [NebCmdItem] (arrayLiteral:
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, ActiveStatus: UInt32(NEBLINA_INTERFACE_STATUS_BLE.rawValue),
Name: "BLE Data Port", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, ActiveStatus: UInt32(NEBLINA_INTERFACE_STATUS_UART.rawValue),
Name: "UART Data Port", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, ActiveStatus: 0,
Name: "Calibrate Forward Pos", Actuator : 2, Text: "Calib Fwrd"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, ActiveStatus: 0,
Name: "Calibrate Down Pos", Actuator : 2, Text: "Calib Dwn"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_FUSION_TYPE, ActiveStatus: 0,
Name: "Fusion 9 axis", Actuator : 1, Text:""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, ActiveStatus: 0,
Name: "Reset timestamp", Actuator : 2, Text: "Reset"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_QUATERNION.rawValue),
Name: "Quaternion Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER.rawValue),
Name: "Accelerometer Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_GYROSCOPE.rawValue),
Name: "Gyroscope Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_MAGNETOMETER.rawValue),
Name: "Magnetometer Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER_GYROSCOPE.rawValue),
Name: "Accel & Gyro Stream", Actuator : 1, Text:""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_PRESSURE.rawValue),
Name: "Pressure Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_TEMPERATURE.rawValue),
Name: "Temperature Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_HUMIDITY.rawValue),
Name: "Humidity Sensor Stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, ActiveStatus: 0,
Name: "Lock Heading Ref.", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: UInt32(NEBLINA_RECORDER_STATUS_RECORD.rawValue),
Name: "Flash Record", Actuator : 2, Text: "Start"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: 0,
Name: "Flash Record", Actuator : 2, Text: "Stop"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK, ActiveStatus: 0,
Name: "Flash Playback", Actuator : 4, Text: "Play"),
// NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD, ActiveStatus: 0,
// Name: "Flash Download", Actuator : 2, Text: "Start"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED0 level", Actuator : 3, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED1 level", Actuator : 3, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0,
Name: "Set LED2", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_EEPROM, CmdId: NEBLINA_COMMAND_EEPROM_READ, ActiveStatus: 0,
Name: "EEPROM Read", Actuator : 2, Text: "Read"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_POWER, CmdId: NEBLINA_COMMAND_POWER_CHARGE_CURRENT, ActiveStatus: 0,
Name: "Charge Current in mA", Actuator : 3, Text: ""),
NebCmdItem(SubSysId: 0xf, CmdId: CmdMotionDataStream, ActiveStatus: 0,
Name: "Motion data stream", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: 0xf, CmdId: CmdHeading, ActiveStatus: 0,
Name: "Heading", Actuator : 1, Text: ""),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_ERASE_ALL, ActiveStatus: 0,
Name: "Flash Erase All", Actuator : 2, Text: "Erase"),
NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, ActiveStatus: 0,
Name: "Firmware Update", Actuator : 2, Text: "DFU")
// Baromter, pressure
)
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, SCNSceneRendererDelegate, CBCentralManagerDelegate, NeblinaDelegate {
//, CBPeripheralDelegate {
let scene = SCNScene(named: "art.scnassets/ship.scn")!
let scene2 = SCNScene(named: "art.scnassets/ship.scn")!
var ship = [SCNNode]() //= scene.rootNode.childNodeWithName("ship", recursively: true)!
let max_count = Int16(15)
var prevTimeStamp : [UInt32] = Array(repeating: 0, count: 8)//[UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0)]
var cnt = Int16(15)
var xf = Int16(0)
var yf = Int16(0)
var zf = Int16(0)
var heading = Bool(false)
//var flashEraseProgress = Bool(false)
var PaketCnt : [UInt32] = Array(repeating: 0, count: 8)//[UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0)]
var dropCnt : [UInt32] = Array(repeating: 0, count: 8)//[UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0)]
var bleCentralManager : CBCentralManager!
var foundDevices = [Neblina]()
var connectedDevices = [Neblina]()
//var nebdev = Neblina(devid: 0, peripheral: nil)
var selectedDevices = [Neblina]()
var curSessionId = UInt16(0)
var curSessionOffset = UInt32(0)
var sessionCount = UInt8(0)
var startDownload = Bool(false)
var filepath = String()
var file : FileHandle?
var downloadRecovering = Bool(false)
var playback = Bool(false)
var packetCnt = Int(0)
var graphDisplay = Bool(false)
@IBOutlet weak var cmdView: UITableView!
@IBOutlet weak var devscanView : UITableView!
@IBOutlet weak var selectedView : UITableView!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var flashLabel: UILabel!
//@IBOutlet weak var dumpLabel: UILabel!
@IBOutlet weak var logView: UITextView!
@IBOutlet weak var sceneView : SCNView!
@IBOutlet weak var sceneView2 : SCNView!
@IBAction func doubleTap(_ sender: UITapGestureRecognizer) {
let idx = selectedView.indexPathForSelectedRow! as IndexPath
if idx.row > 0 {
let dev = connectedDevices.remove(at: idx.row - 1)
if connectedDevices.count > 0 {
if selectedDevices.count > 2 {
selectedDevices.remove(at: 0)
}
selectedDevices.append(connectedDevices[0])
}
else {
selectedDevices.removeAll()
// nebdev = Neblina(devid: 0, peripheral: nil)
}
bleCentralManager.cancelPeripheralConnection(dev.device)
//foundDevices.append(dev)
foundDevices.removeAll()
devscanView.reloadData()
selectedView.reloadData()
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
}
}
func getCmdIdx(_ subsysId : Int32, cmdId : Int32) -> Int {
for (idx, item) in NebCmdList.enumerated() {
if (item.SubSysId == subsysId && item.CmdId == cmdId) {
return idx
}
}
return -1
}
override func viewDidLoad() {
super.viewDidLoad()
devscanView.dataSource = self
selectedView.dataSource = self
cmdView.dataSource = self
bleCentralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
// Do any additional setup after loading the view, typically from a nib.
cnt = max_count
//textview = self.view.viewWithTag(3) as! UITextView
// create a new scene
//scene = SCNScene(named: "art.scnassets/ship.scn")!
//scene = SCNScene(named: "art.scnassets/Arc-170_ship/Obj_Shaded/Arc170.obj")
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
let cameraNode2 = SCNNode()
cameraNode2.camera = SCNCamera()
scene2.rootNode.addChildNode(cameraNode2)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
cameraNode2.position = SCNVector3(x: 0, y: 0, z: 15)
//cameraNode.position = SCNVector3(x: 0, y: 15, z: 0)
//cameraNode.rotation = SCNVector4(0, 0, 1, GLKMathDegreesToRadians(-180))
//cameraNode.rotation = SCNVector3(x:
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLight.LightType.omni
lightNode.position = SCNVector3(x: 0, y: 10, z: 50)
scene.rootNode.addChildNode(lightNode)
let lightNode2 = SCNNode()
lightNode2.light = SCNLight()
lightNode2.light!.type = SCNLight.LightType.omni
lightNode2.position = SCNVector3(x: 0, y: 10, z: 50)
scene2.rootNode.addChildNode(lightNode2)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLight.LightType.ambient
ambientLightNode.light!.color = UIColor.darkGray
scene.rootNode.addChildNode(ambientLightNode)
let ambientLightNode2 = SCNNode()
ambientLightNode2.light = SCNLight()
ambientLightNode2.light!.type = SCNLight.LightType.ambient
ambientLightNode2.light!.color = UIColor.darkGray
scene2.rootNode.addChildNode(ambientLightNode)
// retrieve the ship node
// ship = scene.rootNode.childNodeWithName("MillenniumFalconTop", recursively: true)!
// ship = scene.rootNode.childNodeWithName("ARC_170_LEE_RAY_polySurface1394376_2_2", recursively: true)!
var sh = scene.rootNode.childNode(withName: "ship", recursively: true)!
ship.append(sh)
// ship = scene.rootNode.childNodeWithName("MDL Obj", recursively: true)!
ship[0].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180))
//ship.rotation = SCNVector4(1, 0, 0, GLKMathDegreesToRadians(90))
//print("1 - \(ship)")
// animate the 3d object
//ship.runAction(SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 2, z: 0, duration: 1)))
//ship.runAction(SCNAction.rotateToX(CGFloat(eulerAngles.x), y: CGFloat(eulerAngles.y), z: CGFloat(eulerAngles.z), duration:1 ))// 10, y: 0.0, z: 0.0, duration: 1))
let sh1 = scene2.rootNode.childNode(withName: "ship", recursively: true)!
ship.append(sh1)
// ship = scene.rootNode.childNodeWithName("MDL Obj", recursively: true)!
ship[1].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180))
// retrieve the SCNView
let scnView = self.view.subviews[0] as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.black
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:)))
scnView.addGestureRecognizer(tapGesture)
//scnView.preferredFramesPerSecond = 60
// let scnView2 = self.view.subviews[1] as! SCNView
// set the scene to the view
sceneView2.scene = scene2
// allows the user to manipulate the camera
sceneView2.allowsCameraControl = true
// show statistics such as fps and timing information
sceneView2.showsStatistics = true
// configure the view
sceneView2.backgroundColor = UIColor.black
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func handleTap(_ gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let scnView = self.view.subviews[0] as! SCNView
// check what nodes are tapped
let p = gestureRecognize.location(in: scnView)
let hitResults = scnView.hitTest(p, options: nil)
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: AnyObject! = hitResults[0]
// get its material
let material = result.node!.geometry!.firstMaterial!
// highlight it
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
// on completion - unhighlight
/*SCNTransaction.completionBlock {
SCNTransaction.begin()
SCNTransaction.animationDuration = 0.5
material.emission.contents = UIColor.black
SCNTransaction.commit()
}
*/
material.emission.contents = UIColor.red
SCNTransaction.commit()
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField.resignFirstResponder()
var value = UInt16(textField.text!)
let idx = cmdView.indexPath(for: textField.superview!.superview as! UITableViewCell)
let row = ((idx as NSIndexPath?)?.row)! as Int
if (value == nil) {
value = 0
}
switch (NebCmdList[row].SubSysId) {
case NEBLINA_SUBSYSTEM_LED:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATE)
for item in connectedDevices {
item.setLed(UInt8(row - i), Value: UInt8(value!))
}
break
case NEBLINA_SUBSYSTEM_POWER:
for item in connectedDevices {
item.setBatteryChargeCurrent(value!)
}
break
default:
break
}
return true;
}
@IBAction func didSelectDevice(sender : UITableViewCell) {
}
@IBAction func buttonAction(_ sender:UIButton)
{
let idx = cmdView.indexPath(for: sender.superview!.superview as! UITableViewCell)
let row = ((idx as NSIndexPath?)?.row)! as Int
if connectedDevices.count <= 0 {
return
}
if (row < NebCmdList.count) {
switch (NebCmdList[row].SubSysId)
{
case NEBLINA_SUBSYSTEM_GENERAL:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE:
for item in connectedDevices {
item.firmwareUpdate()
}
//nebdev.firmwareUpdate()
print("DFU Command")
break
case NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP:
for item in connectedDevices {
item.resetTimeStamp(Delayed: true)
}
// nebdev.resetTimeStamp(Delayed: true)
print("Reset timestamp")
default:
break
}
break
case NEBLINA_SUBSYSTEM_EEPROM:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_EEPROM_READ:
selectedDevices[0].eepromRead(0)
break
case NEBLINA_COMMAND_EEPROM_WRITE:
//UInt8_t eepdata[8]
//nebdev.SendCmdEepromWrite(0, eepdata)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_FUSION:
switch (NebCmdList[row].CmdId) {
case NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION:
for item in connectedDevices {
item.calibrateForwardPosition()
}
break
case NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION:
for item in connectedDevices {
item.calibrateDownPosition()
}
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (NebCmdList[row].CmdId) {
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
//if flashEraseProgress == false {
// flashEraseProgress = true;
for item in connectedDevices {
item.eraseStorage(false)
logView.text = logView.text + String(format: "%@ - Erase command sent\n", item.device.name!)
}
//}
case NEBLINA_COMMAND_RECORDER_RECORD:
if NebCmdList[row].ActiveStatus == 0 {
for item in connectedDevices {
item.sessionRecord(false, info: "")
}
//nebdev.sessionRecord(false)
}
else {
for item in connectedDevices {
item.sessionRecord(true, info: "")
}
//nebdev.sessionRecord(true)
}
break
case NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD:
/* let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if (cell != nil) {
//let control = cell!.viewWithTag(4) as! UITextField
//let but = cell!.viewWithTag(2) as! UIButton
//but.isEnabled = false
curSessionId = 0//UInt16(control.text!)!
startDownload = true
curSessionOffset = 0
//let filename = String(format:"NeblinaRecord_%d.dat", curSessionId)
let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask, true)
if dirPaths != nil {
filepath = dirPaths[0]// as! String
filepath.append(String(format:"/%@/", (nebdev?.device.name!)!))
do {
try FileManager.default.createDirectory(atPath: filepath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
filepath.append(String(format:"%@_%d.dat", (nebdev?.device.name!)!, curSessionId))
FileManager.default.createFile(atPath: filepath, contents: nil, attributes: nil)
do {
try file = FileHandle(forWritingAtPath: filepath)
} catch { print("file failed \(filepath)")}
nebdev?.sessionDownload(true, SessionId : curSessionId, Len: 16, Offset: 0)
}
}*/
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if cell != nil {
let tf = cell?.viewWithTag(4) as! UITextField
let bt = cell?.viewWithTag(2) as! UIButton
if playback == true {
bt.setTitle("Play", for: .normal)
playback = false
}
else {
bt.setTitle("Stop", for: .normal)
var n = UInt16(0)
if UInt16(tf.text!)! != nil {
n = UInt16(tf.text!)!
}
for item in connectedDevices {
item.sessionPlayback(true, sessionId : n)
}
//selectedDevices[1].sessionPlayback(true, sessionId : n)
//nebdev.sessionPlayback(true, sessionId : n)
packetCnt = 0
playback = true
}
}
break
default:
break
}
default:
break
}
}
}
@IBAction func switchAction(_ sender:UISegmentedControl)
{
//let tableView = sender.superview?.superview?.superview?.superview as! UITableView
let idx = cmdView.indexPath(for: sender.superview!.superview as! UITableViewCell)
let row = ((idx as NSIndexPath?)?.row)! as Int
if (selectedDevices.count <= 0) {
return
}
if (row < NebCmdList.count) {
switch (NebCmdList[row].SubSysId)
{
case NEBLINA_SUBSYSTEM_GENERAL:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS:
//nebdev!.setInterface(sender.selectedSegmentIndex)
break
case NEBLINA_COMMAND_GENERAL_INTERFACE_STATE:
for item in connectedDevices {
item.setDataPort(row, Ctrl:UInt8(sender.selectedSegmentIndex))
}
break;
default:
break
}
break
case NEBLINA_SUBSYSTEM_FUSION:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM:
for item in connectedDevices {
item.streamMotionState(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_FUSION_FUSION_TYPE:
for item in connectedDevices {
item.setFusionType(UInt8(sender.selectedSegmentIndex))
}
break
//case IMU_Data:
// nebdev!.streamIMU(sender.selectedSegmentIndex == 1)
// break
case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM:
for item in connectedDevices {
item.streamQuaternion(sender.selectedSegmentIndex == 1)
}
/*
nebdev.streamEulerAngle(false)
heading = false
prevTimeStamp = 0
nebdev.streamQuaternion(sender.selectedSegmentIndex == 1)*/
let i = getCmdIdx(0xf, cmdId: 1)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = 0
}
break
case NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM:
for item in connectedDevices {
item.streamQuaternion(false)
item.streamEulerAngle(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM:
for item in connectedDevices {
item.streamExternalForce(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM:
for item in connectedDevices {
item.streamPedometer(sender.selectedSegmentIndex == 1)
}
break;
case NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD:
for item in connectedDevices {
item.recordTrajectory(sender.selectedSegmentIndex == 1)
}
break;
case NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM:
for item in connectedDevices {
item.streamTrajectoryInfo(sender.selectedSegmentIndex == 1)
}
break;
/* case NEBLINA_COMMAND_FUSION_MAG_STATE:
nebdev.streamMAG(sender.selectedSegmentIndex == 1)
break;*/
case NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE:
for item in connectedDevices {
item.lockHeadingReference()
}
let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = 0
}
break
default:
break
}
case NEBLINA_SUBSYSTEM_LED:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATE)
for item in connectedDevices {
if sender.selectedSegmentIndex == 1 {
item.setLed(UInt8(row - i), Value: 255)
}
else {
item.setLed(UInt8(row - i), Value: 0)
}
}
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
if (sender.selectedSegmentIndex == 1) {
// flashEraseProgress = true;
}
for item in connectedDevices {
item.eraseStorage(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_RECORDER_RECORD:
for item in connectedDevices {
item.sessionRecord(sender.selectedSegmentIndex == 1, info: "")
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
for item in connectedDevices {
item.sessionPlayback(sender.selectedSegmentIndex == 1, sessionId : 0xffff)
}
if (sender.selectedSegmentIndex == 1) {
packetCnt = 0
}
break
case NEBLINA_COMMAND_RECORDER_SESSION_READ:
// curDownloadSession = 0xFFFF
// curDownloadOffset = 0
// nebdev!.sessionRead(curDownloadSession, Len: 32, Offset: curDownloadOffset)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_EEPROM:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_EEPROM_READ:
for item in connectedDevices {
item.eepromRead(0)
}
break
case NEBLINA_COMMAND_EEPROM_WRITE:
//UInt8_t eepdata[8]
//nebdev.SendCmdEepromWrite(0, eepdata)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_SENSOR:
switch (NebCmdList[row].CmdId)
{
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM:
for item in connectedDevices {
item.sensorStreamAccelData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM:
for item in connectedDevices {
item.sensorStreamGyroData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM:
for item in connectedDevices {
item.sensorStreamMagData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM:
for item in connectedDevices {
item.sensorStreamPressureData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM:
for item in connectedDevices {
item.sensorStreamTemperatureData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM:
for item in connectedDevices {
item.sensorStreamHumidityData(sender.selectedSegmentIndex == 1)
}
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM:
for item in connectedDevices {
item.sensorStreamAccelGyroData(sender.selectedSegmentIndex == 1)
}
//nebdev.streamAccelGyroSensorData(sender.selectedSegmentIndex == 1)
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM:
for item in connectedDevices {
item.sensorStreamAccelMagData(sender.selectedSegmentIndex == 1)
}
// nebdev.streamAccelMagSensorData(sender.selectedSegmentIndex == 1)
break
default:
break
}
break
case 0xf:
switch (NebCmdList[row].CmdId) {
case CmdHeading:
for item in connectedDevices {
item.streamQuaternion(false)
item.streamEulerAngle(sender.selectedSegmentIndex == 1)
}
// Heading = sender.selectedSegmentIndex == 1
var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
i = getCmdIdx(0xF, cmdId: CmdMotionDataStream)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
break
case CmdMotionDataStream:
if sender.selectedSegmentIndex == 0 {
for item in connectedDevices {
item.disableStreaming()
}
break
}
for item in connectedDevices {
item.streamQuaternion(sender.selectedSegmentIndex == 1)
}
var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.sensorStreamMagData(sender.selectedSegmentIndex == 1)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_SENSOR, cmdId: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.streamExternalForce(sender.selectedSegmentIndex == 1)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.streamPedometer(sender.selectedSegmentIndex == 1)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
for item in connectedDevices {
item.streamRotationInfo(sender.selectedSegmentIndex == 1, Type: 2)
}
i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = sender.selectedSegmentIndex
}
i = getCmdIdx(0xF, cmdId: CmdHeading)
cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(1) as! UISegmentedControl
control.selectedSegmentIndex = 0
}
break
default:
break
}
break
default:
break
}
}
/* else {
switch (row - NebCmdList.count) {
case 0:
nebdev.streamQuaternion(false)
nebdev.streamEulerAngle(true)
heading = sender.selectedSegmentIndex == 1
let i = getCmdIdx(NEB_CTRL_SUBSYS_MOTION_ENG, cmdId: Quaternion)
let cell = cmdView.cellForRowAtIndexPath( NSIndexPath(forRow: i, inSection: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = 0
}
break
default:
break
}
}*/
}
func updateUI(status : NeblinaSystemStatus_t) {
for idx in 0...NebCmdList.count - 1 {
switch (NebCmdList[idx].SubSysId) {
case NEBLINA_SUBSYSTEM_GENERAL:
switch (NebCmdList[idx].CmdId) {
case NEBLINA_COMMAND_GENERAL_INTERFACE_STATE:
//let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView
let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0))
if cell != nil {
let control = cell?.viewWithTag(1) as! UISegmentedControl
if NebCmdList[idx].ActiveStatus & UInt32(status.interface) == 0 {
control.selectedSegmentIndex = 0
}
else {
control.selectedSegmentIndex = 1
}
}
default:
break
}
case NEBLINA_SUBSYSTEM_FUSION:
//let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView
let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0))
if cell != nil {
let control = cell?.viewWithTag(1) as! UISegmentedControl
if NebCmdList[idx].ActiveStatus & status.fusion == 0 {
control.selectedSegmentIndex = 0
}
else {
control.selectedSegmentIndex = 1
}
}
case NEBLINA_SUBSYSTEM_SENSOR:
let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0))
if cell != nil {
//let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView
let control = cell?.viewWithTag(1) as! UISegmentedControl
if NebCmdList[idx].ActiveStatus & UInt32(status.sensor) == 0 {
control.selectedSegmentIndex = 0
}
else {
control.selectedSegmentIndex = 1
}
}
default:
break
}
}
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == devscanView {
return foundDevices.count + 1
}
else if tableView == selectedView {
return connectedDevices.count + 1
}
else if tableView == cmdView {
return NebCmdList.count
}
return 1
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if tableView == devscanView {
if indexPath.row == 0 {
cell.textLabel!.text = String("Devices Found")
cell.selectionStyle = UITableViewCell.SelectionStyle.none
}
else {
let object = foundDevices[(indexPath as NSIndexPath).row - 1]
// cell.textLabel!.text = object.device.name
// print("\(cell.textLabel!.text)")
cell.textLabel!.text = object.device.name! + String(format: "_%lX", object.id)
}
}
else if tableView == selectedView {
if indexPath.row == 0 {
//cell.textLabel!.text = String("Connected")
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let label = cell.contentView.subviews[1] as! UILabel
label.text = String("Connected")
}
else {
let object = connectedDevices[(indexPath as NSIndexPath).row - 1]
//cell.textLabel!.text = object.device.name
let label = cell.contentView.subviews[1] as! UILabel
label.text = object.device.name! + String(format: "_%lX", object.id)
let label1 = cell.contentView.subviews[0] as! UILabel
if object == selectedDevices[0] {
label1.text = "T"
}
else if object == selectedDevices[1] {
label1.text = "B"
}
else {
label1.text?.removeAll()
}
}
}
else if tableView == cmdView {
if indexPath.row < NebCmdList.count {
let labelView = cell.viewWithTag(255) as! UILabel
labelView.text = NebCmdList[indexPath.row].Name// - FusionCmdList.count].Name
switch (NebCmdList[indexPath.row].Actuator)
{
case 1:
let control = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UISegmentedControl
control.isHidden = false
let b = cell.viewWithTag(2) as! UIButton
b.isHidden = true
let t = cell.viewWithTag(3) as! UITextField
t.isHidden = true
break
case 2:
let control = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UIButton
control.isHidden = false
if !NebCmdList[indexPath.row].Text.isEmpty
{
control.setTitle(NebCmdList[indexPath.row].Text, for: UIControl.State())
}
let s = cell.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let t = cell.viewWithTag(3) as! UITextField
t.isHidden = true
break
case 3:
let control = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UITextField
control.isHidden = false
if !NebCmdList[indexPath.row].Text.isEmpty
{
control.text = NebCmdList[indexPath.row].Text
}
let s = cell.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let b = cell.viewWithTag(2) as! UIButton
b.isHidden = true
break
case 4:
let tfcontrol = cell.viewWithTag(NebCmdList[indexPath.row].Actuator) as! UITextField
tfcontrol.isHidden = false
/* if !NebCmdList[(indexPath! as NSIndexPath).row].Text.isEmpty
{
tfcontrol.text = NebCmdList[(indexPath! as NSIndexPath).row].Text
}*/
let bucontrol = cell.viewWithTag(2) as! UIButton
bucontrol.isHidden = false
if !NebCmdList[indexPath.row].Text.isEmpty
{
bucontrol.setTitle(NebCmdList[indexPath.row].Text, for: UIControl.State())
}
let s = cell.viewWithTag(1) as! UISegmentedControl
s.isHidden = true
let t = cell.viewWithTag(3) as! UITextField
t.isHidden = true
break
default:
//switchCtrl.enabled = false
// switchCtrl.hidden = true
// buttonCtrl.hidden = true
break
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == devscanView && indexPath.row > 0 {
let dev = foundDevices.remove(at: indexPath.row - 1)
dev.device.delegate = dev
bleCentralManager.connect(dev.device, options: nil)
connectedDevices.append(dev)
//nebdev.delegate = nil
if selectedDevices.count > 1 {
selectedDevices.remove(at: 0)
}
dev.delegate = self
selectedDevices.append(dev)
for (idx, item)in selectedDevices.enumerated() {
if item == dev {
prevTimeStamp[idx] = 0
dropCnt[idx] = 0;
}
}
//nebdev = dev
//nebdev.delegate = self
devscanView.reloadData()
selectedView.reloadData()
}
else if tableView == selectedView && indexPath.row > 0 {
// Switch device to view
//nebdev.delegate = nil
let dev = connectedDevices[indexPath.row - 1]
for item in selectedDevices {
if item == dev {
return
}
}
if selectedDevices.count > 1 {
selectedDevices.remove(at: 0)
}
dev.delegate = self
selectedDevices.append(dev)
// get update status
dev.getSystemStatus()
dev.getFirmwareVersion()
}
}
// MARK: - Bluetooth
func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData : [String : Any],
rssi RSSI: NSNumber) {
print("PERIPHERAL NAME: \(peripheral)\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n")
print("UUID DESCRIPTION: \(peripheral.identifier.uuidString)\n")
print("IDENTIFIER: \(peripheral.identifier)\n")
if advertisementData[CBAdvertisementDataManufacturerDataKey] == nil {
return
}
let mdata = advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData
if mdata.length < 8 {
return
}
var id : UInt64 = 0
(advertisementData[CBAdvertisementDataManufacturerDataKey] as! NSData).getBytes(&id, range: NSMakeRange(2, 8))
if (id == 0) {
return
}
var name : String? = nil
if advertisementData[CBAdvertisementDataLocalNameKey] == nil {
print("bad, no name")
name = peripheral.name
}
else {
name = advertisementData[CBAdvertisementDataLocalNameKey] as! String
}
let device = Neblina(devName: name!, devid: id, peripheral: peripheral)
for dev in foundDevices
{
if (dev.id == id)
{
return;
}
}
foundDevices.insert(device, at: 0)
devscanView.reloadData();
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
central.stopScan()
peripheral.discoverServices(nil)
print("Connected to peripheral")
}
func centralManager(_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?) {
for i in 0..<connectedDevices.count {
if connectedDevices[i].device == peripheral {
connectedDevices.remove(at: i)
selectedView.reloadData()
break
}
}
print("disconnected from peripheral \(error)")
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
}
func scanPeripheral(_ sender: CBCentralManager)
{
print("Scan for peripherals")
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
}
@objc func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOff:
print("CoreBluetooth BLE hardware is powered off")
//self.sensorData.text = "CoreBluetooth BLE hardware is powered off\n"
break
case .poweredOn:
print("CoreBluetooth BLE hardware is powered on and ready")
//self.sensorData.text = "CoreBluetooth BLE hardware is powered on and ready\n"
// We can now call scanForBeacons
let lastPeripherals = central.retrieveConnectedPeripherals(withServices: [NEB_SERVICE_UUID])
if lastPeripherals.count > 0 {
// let device = lastPeripherals.last as CBPeripheral;
//connectingPeripheral = device;
//centralManager.connectPeripheral(connectingPeripheral, options: nil)
}
//scanPeripheral(central)
bleCentralManager.scanForPeripherals(withServices: [NEB_SERVICE_UUID], options: nil)
break
case .resetting:
print("CoreBluetooth BLE hardware is resetting")
//self.sensorData.text = "CoreBluetooth BLE hardware is resetting\n"
break
case .unauthorized:
print("CoreBluetooth BLE state is unauthorized")
//self.sensorData.text = "CoreBluetooth BLE state is unauthorized\n"
break
case .unknown:
print("CoreBluetooth BLE state is unknown")
//self.sensorData.text = "CoreBluetooth BLE state is unknown\n"
break
case .unsupported:
print("CoreBluetooth BLE hardware is unsupported on this platform")
//self.sensorData.text = "CoreBluetooth BLE hardware is unsupported on this platform\n"
break
default:
break
}
}
//
// MARK: Neblina delegate
//
func didConnectNeblina(sender : Neblina) {
// prevTimeStamp[0] = 0
// prevTimeStamp[1] = 0
sender.getSystemStatus()
sender.getFirmwareVersion()
}
func didReceiveResponsePacket(sender: Neblina, subsystem: Int32, cmdRspId: Int32, data: UnsafePointer<UInt8>, dataLen: Int) {
print("didReceiveResponsePacket : \(subsystem) \(cmdRspId)")
switch subsystem {
case NEBLINA_SUBSYSTEM_GENERAL:
switch (cmdRspId) {
case NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS:
let d = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaSystemStatus_t.self)// UnsafeBufferPointer<NeblinaSystemStatus_t>(data))
print(" \(d)")
updateUI(status: d)
break
case NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION:
let vers = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaFirmwareVersion_t.self)
let b = (UInt32(vers.firmware_build.0) & 0xFF) | ((UInt32(vers.firmware_build.1) & 0xFF) << 8) | ((UInt32(vers.firmware_build.2) & 0xFF) << 16)
print("\(vers) ")
versionLabel.text = String(format: "API:%d, Firm. Ver.:%d.%d.%d-%d", vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b
)
logView.text = logView.text + String(format: "%@ - API:%d, Firm. Ver.:%d.%d.%d-%d", sender.device.name!, vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b)
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_FUSION:
switch cmdRspId {
case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM:
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_RECORDER:
switch (cmdRspId) {
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
flashLabel.text = String(format: "%@ - Flash erased\n", sender.device.name!)
logView.text = logView.text + String(format: "%@ - Flash erased\n", sender.device.name!)
// flashLabel.text = "Flash erased"
//flashEraseProgress = false
break
case NEBLINA_COMMAND_RECORDER_RECORD:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
// if (nebdev == sender) {
flashLabel.text = String(format: "%@ - Recording session %d", sender.device.name!, session)
// }
logView.text = logView.text + String(format: "%@ - Recording session %d\n", sender.device.name!, session)
}
else {
// if (nebdev == sender) {
flashLabel.text = String(format: "Recorded session %d", session)
// }
logView.text = logView.text + String(format: "%@ - Recorded session %d\n", sender.device.name!, session)
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "Playing session %d", session)
}
}
else {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "End session %d, %u", session, sender.getPacketCount())
playback = false
let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(2) as! UIButton
sw.setTitle("Play", for: .normal)
}
}
}
break
default:
break
}
break
case NEBLINA_SUBSYSTEM_SENSOR:
//nebdev?.getFirmwareVersion()
break
default:
break
}
}
func didReceiveRSSI(sender : Neblina, rssi : NSNumber) {
}
func didReceiveBatteryLevel(sender: Neblina, level: UInt8) {
}
func didReceiveGeneralData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafeRawPointer, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS:
var myStruct = NeblinaSystemStatus_t()
let status = withUnsafeMutablePointer(to: &myStruct) {_ in UnsafeMutableRawPointer(mutating: data)}
//print("Status \(status)")
let d = data.load(as: NeblinaSystemStatus_t.self)// UnsafeBufferPointer<NeblinaSystemStatus_t>(data)
//print(" \(d)")
updateUI(status: d)
break
/* case NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION:
let vers = data.load(as: NeblinaFirmwareVersion_t.self)
let b = (UInt32(vers.firmware_build.0) & 0xFF) | ((UInt32(vers.firmware_build.1) & 0xFF) << 8) | ((UInt32(vers.firmware_build.2) & 0xFF) << 16)
if selectedDevices[0] == sender {
//let vers = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaFirmwareVersion_t.self)
print("\(vers) ")
versionLabel.text = String(format: "API:%d, Firm. Ver.:%d.%d.%d-%d", vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b
)
//versionLabel.text = String(format: "API:%d, FEN:%d.%d.%d, BLE:%d.%d.%d", d.apiVersion,
// d.coreVersion.major, d.coreVersion.minor, d.coreVersion.build,
// d.bleVersion.major, d.bleVersion.minor, d.bleVersion.build)
}
logView.text = logView.text + String(format: "%@ - API:%d, Firm. Ver.:%d.%d.%d-%d", sender.device.name!, vers.api,
vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b)
break*/
/*case NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS:
let i = getCmdIdx(NEBLINA_SUBSYSTEM_GENERAL, cmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE)
var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = Int(data[0])
}
cell = cmdView.cellForRow( at: IndexPath(row: i + 1, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(1) as! UISegmentedControl
sw.selectedSegmentIndex = Int(data[1])
}
break*/
default:
break
}
}
func didReceiveFusionData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : NeblinaFusionPacket_t, errFlag : Bool) {
//let errflag = Bool(type.rawValue & 0x80 == 0x80)
//let id = FusionId(rawValue: type.rawValue & 0x7F)! as FusionId
if selectedDevices[0] == sender {
//logView.text = logView.text + String(format: "Total packet %u @ %0.2f pps\n", nebdev.getPacketCount(), nebdev.getDataRate())
}
switch (cmdRspId) {
case NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM:
break
// case NEBLINA_COMMAND_FUSION_IMU_STATE:
// break
case NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM:
//
// Process Euler Angle
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xrot = Float(x) / 10.0
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yrot = Float(y) / 10.0
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zrot = Float(z) / 10.0
if selectedDevices[0] == sender {
if (heading) {
ship[0].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(xrot))
}
else {
ship[0].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(yrot), GLKMathDegreesToRadians(xrot), GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(zrot))
}
label.text = String("Euler - Yaw:\(xrot), Pitch:\(yrot), Roll:\(zrot)")
}
if selectedDevices[1] == sender {
if (heading) {
ship[1].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(xrot))
}
else {
ship[1].eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(yrot), GLKMathDegreesToRadians(xrot), GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(zrot))
}
}
break
case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM:
//
// Process Quaternion
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xq = Float(x) / 32768.0
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yq = Float(y) / 32768.0
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zq = Float(z) / 32768.0
let w = (Int16(data.data.6) & 0xff) | (Int16(data.data.7) << 8)
let wq = Float(w) / 32768.0
for (idx, item) in selectedDevices.enumerated() {
if item == sender {
ship[idx].orientation = SCNQuaternion(yq, xq, zq, wq)
label.text = String("Quat - x:\(xq), y:\(yq), z:\(zq), w:\(wq)")
}
}
for (idx, item) in connectedDevices.enumerated() {
if (prevTimeStamp[idx] == 0 || data.timestamp <= prevTimeStamp[idx])
{
prevTimeStamp[idx] = data.timestamp;
}
else
{
let tdiff = data.timestamp - prevTimeStamp[idx];
if (tdiff > 49000)
{
dropCnt[idx] += 1
//logView.text = logView.text + String("\(dropCnt) Drop : \(tdiff)\n")
}
prevTimeStamp[idx] = data.timestamp
}
}
break
case NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM:
//
// Process External Force
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xq = x / 1600
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yq = y / 1600
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zq = z / 1600
cnt -= 1
if (cnt <= 0) {
cnt = max_count
//if (xf != xq || yf != yq || zf != zq) {
let pos = SCNVector3(CGFloat(xf/cnt), CGFloat(yf/cnt), CGFloat(zf/cnt))
ship[0].position = pos
xf = xq
yf = yq
zf = zq
//}
}
else {
//if (abs(xf) <= abs(xq)) {
xf += xq
//}
//if (abs(yf) <= abs(yq)) {
yf += yq
//}
//if (abs(xf) <= abs(xq)) {
zf += zq
//}
}
if selectedDevices[0] == sender {
label.text = String("Extrn Force - x:\(xq), y:\(yq), z:\(zq)")
}
//print("Extrn Force - x:\(xq), y:\(yq), z:\(zq)")
break
/* case NEBLINA_COMMAND_FUSION_MAG_ST:
//
// Mag data
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)
let xq = x
let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)
let yq = y
let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)
let zq = z
if nebdev == sender {
label.text = String("Mag - x:\(xq), y:\(yq), z:\(zq)")
}
//ship.rotation = SCNVector4(Float(xq), Float(yq), 0, GLKMathDegreesToRadians(90))
break
*/
default:
break
}
}
func didReceivePmgntData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
let value = UInt16(data[0]) | (UInt16(data[1]) << 8)
if (cmdRspId == NEBLINA_COMMAND_POWER_CHARGE_CURRENT && selectedDevices[0] == sender)
{
let i = getCmdIdx(NEBLINA_SUBSYSTEM_POWER, cmdId: NEBLINA_COMMAND_POWER_CHARGE_CURRENT)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let control = cell!.viewWithTag(3) as! UITextField
control.text = String(value)
}
}
}
func didReceiveLedData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
}
func didReceiveDebugData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
//print("Debug \(type) data \(data)")
switch (cmdRspId) {
case NEBLINA_COMMAND_DEBUG_DUMP_DATA:
if selectedDevices[0] == sender {
logView.text = logView.text + String(format: "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9],
data[10], data[11], data[12], data[13], data[14], data[15])
}
break
default:
break
}
}
func didReceiveRecorderData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_RECORDER_ERASE_ALL:
// if nebdev == sender {
// flashLabel.text = "Flash erased"
// }
flashLabel.text = String(format: "%@ - Flash erased\n", sender.device.name!)
logView.text = logView.text + String(format: "%@ - Flash erased\n", sender.device.name!)
break
case NEBLINA_COMMAND_RECORDER_RECORD:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
// if (nebdev == sender) {
flashLabel.text = String(format: "%@ - Recording session %d", sender.device.name!, session)
// }
logView.text = logView.text + String(format: "%@ - Recording session %d\n", sender.device.name!, session)
}
else {
// if (nebdev == sender) {
flashLabel.text = String(format: "Recorded session %d", session)
// }
logView.text = logView.text + String(format: "%@ - Recorded session %d\n", sender.device.name!, session)
}
break
case NEBLINA_COMMAND_RECORDER_PLAYBACK:
let session = Int16(data[1]) | (Int16(data[2]) << 8)
if (data[0] != 0) {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "Playing session %d", session)
}
}
else {
if selectedDevices[0] == sender {
flashLabel.text = String(format: "End session %d, %u", session, sender.getPacketCount())
playback = false
let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK)
let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0))
if (cell != nil) {
let sw = cell!.viewWithTag(2) as! UIButton
sw.setTitle("Play", for: .normal)
}
}
}
break
/* case NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD:
if (errFlag == false && dataLen > 0) {
if dataLen < 4 {
break
}
let offset = UInt32(UInt32(data[0]) | (UInt32(data[1]) << 8) | (UInt32(data[2]) << 16) | (UInt32(data[3]) << 24))
if curSessionOffset != offset {
// packet loss
print("SessionDownload \(curSessionOffset), \(offset), \(data) \(dataLen)")
if downloadRecovering == false {
nebdev?.sessionDownload(false, SessionId: curSessionId, Len: 12, Offset: curSessionOffset)
downloadRecovering = true
}
}
else {
downloadRecovering = false
let d = NSData(bytes: data + 4, length: dataLen - 4)
//writing
if file != nil {
file?.write(d as Data)
}
curSessionOffset += UInt32(dataLen-4)
flashLabel.text = String(format: "Downloading session %d : %u", curSessionId, curSessionOffset)
}
//print("\(curSessionOffset), \(data)")
}
else {
print("End session \(filepath)")
print(" Download End session errflag")
flashLabel.text = String(format: "Downloaded session %d : %u", curSessionId, curSessionOffset)
if (dataLen > 0) {
let d = NSData(bytes: data, length: dataLen)
//writing
if file != nil {
file?.write(d as Data)
}
}
file?.closeFile()
let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD)
if i < 0 {
break
}
// let cell = cmdView.view(atColumn: 0, row: i, makeIfNecessary: false)! as NSView // cellForRowAtIndexPath( NSIndexPath(forRow: i, inSection: 0))
// let sw = cell.viewWithTag(2) as! NSButton
// sw.isEnabled = true
}
break*/
default:
break
}
}
func didReceiveEepromData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_EEPROM_READ:
let pageno = UInt16(data[0]) | (UInt16(data[1]) << 8)
logView.text = logView.text + String(format: "%@ EEP page [%d] : %02x %02x %02x %02x %02x %02x %02x %02x\n", sender.device.name!,
pageno, data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9])
break
case NEBLINA_COMMAND_EEPROM_WRITE:
break;
default:
break
}
}
func didReceiveSensorData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) {
switch (cmdRspId) {
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("Accel - x:\(xq), y:\(yq), z:\(zq)")
}
// rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("Gyro - x:\(xq), y:\(yq), z:\(zq)")
}
//rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM:
break
case NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM:
//
// Mag data
//
//let ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("Mag - x:\(xq), y:\(yq), z:\(zq)")
}
//rxCount += 1
//ship.rotation = SCNVector4(Float(xq), Float(yq), 0, GLKMathDegreesToRadians(90))
break
case NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM:
break
case NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM:
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM:
let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8)
let xq = x
let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8)
let yq = y
let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8)
let zq = z
if selectedDevices[0] == sender {
label.text = String("IMU - x:\(xq), y:\(yq), z:\(zq)")
}
//rxCount += 1
break
case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM:
break
default:
break
}
cmdView.setNeedsDisplay()
}
}
| mit |
eljeff/AudioKit | Sources/AudioKit/Nodes/Node.swift | 1 | 8897 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// AudioKIt connection point
open class Node {
/// Nodes providing input to this node.
open var connections: [Node] = []
/// The internal AVAudioEngine AVAudioNode
open var avAudioNode: AVAudioNode
/// The internal AVAudioUnit, which is a subclass of AVAudioNode with more capabilities
open var avAudioUnit: AVAudioUnit? {
didSet {
guard let avAudioUnit = avAudioUnit else { return }
let mirror = Mirror(reflecting: self)
for child in mirror.children {
if let param = child.value as? ParameterBase, let label = child.label {
// Property wrappers create a variable with an underscore
// prepended. Drop the underscore to look up the parameter.
let name = String(label.dropFirst())
param.projectedValue.associate(with: avAudioUnit,
identifier: name)
}
}
}
}
/// Returns either the avAudioUnit or avAudioNode (prefers the avAudioUnit if it exists)
open var avAudioUnitOrNode: AVAudioNode {
return avAudioUnit ?? avAudioNode
}
/// Initialize the node from an AVAudioUnit
/// - Parameter avAudioUnit: AVAudioUnit to initialize with
public init(avAudioUnit: AVAudioUnit) {
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
}
/// Initialize the node from an AVAudioNode
/// - Parameter avAudioNode: AVAudioNode to initialize with
public init(avAudioNode: AVAudioNode) {
self.avAudioNode = avAudioNode
}
/// Reset the internal state of the unit
/// Fixes issues such as https://github.com/AudioKit/AudioKit/issues/2046
public func reset() {
if let avAudioUnit = self.avAudioUnit {
AudioUnitReset(avAudioUnit.audioUnit, kAudioUnitScope_Global, 0)
}
}
func detach() {
if let engine = avAudioNode.engine {
engine.detach(avAudioNode)
}
for connection in connections {
connection.detach()
}
}
func makeAVConnections() {
// Are we attached?
if let engine = avAudioNode.engine {
for (bus, connection) in connections.enumerated() {
if let sourceEngine = connection.avAudioNode.engine {
if sourceEngine != avAudioNode.engine {
Log("🛑 Error: Attempt to connect nodes from different engines.")
return
}
}
engine.attach(connection.avAudioNode)
// Mixers will decide which input bus to use.
if let mixer = avAudioNode as? AVAudioMixerNode {
mixer.connect(input: connection.avAudioNode, bus: mixer.nextAvailableInputBus)
} else {
avAudioNode.connect(input: connection.avAudioNode, bus: bus)
}
connection.makeAVConnections()
}
}
}
/// Work-around for an AVAudioEngine bug.
func initLastRenderTime() {
// We don't have a valid lastRenderTime until we query it.
_ = avAudioNode.lastRenderTime
for connection in connections {
connection.initLastRenderTime()
}
}
}
/// Protocol for responding to play and stop of MIDI notes
public protocol Polyphonic {
/// Play a sound corresponding to a MIDI note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
/// - frequency: Play this frequency
func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, frequency: AUValue, channel: MIDIChannel)
/// Play a sound corresponding to a MIDI note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
///
func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel)
/// Stop a sound corresponding to a MIDI note
///
/// - parameter noteNumber: MIDI Note Number
///
func stop(noteNumber: MIDINoteNumber)
}
/// Bare bones implementation of Polyphonic protocol
open class PolyphonicNode: Node, Polyphonic {
/// Global tuning table used by PolyphonicNode (Node classes adopting Polyphonic protocol)
@objc public static var tuningTable = TuningTable()
/// MIDI Instrument
open var midiInstrument: AVAudioUnitMIDIInstrument?
/// Play a sound corresponding to a MIDI note with frequency
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
/// - frequency: Play this frequency
///
open func play(noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
frequency: AUValue,
channel: MIDIChannel = 0) {
Log("Playing note: \(noteNumber), velocity: \(velocity), frequency: \(frequency), channel: \(channel), " +
"override in subclass")
}
/// Play a sound corresponding to a MIDI note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number
/// - velocity: MIDI Velocity
///
open func play(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel = 0) {
// Microtonal pitch lookup
// default implementation is 12 ET
let frequency = PolyphonicNode.tuningTable.frequency(forNoteNumber: noteNumber)
play(noteNumber: noteNumber, velocity: velocity, frequency: AUValue(frequency), channel: channel)
}
/// Stop a sound corresponding to a MIDI note
///
/// - parameter noteNumber: MIDI Note Number
///
open func stop(noteNumber: MIDINoteNumber) {
Log("Stopping note \(noteNumber), override in subclass")
}
}
/// Protocol to allow nodes to be tapped using AudioKit's tapping system (not AVAudioEngine's installTap)
public protocol Tappable {
/// Install tap on this node
func installTap()
/// Remove tap on this node
func removeTap()
/// Get the latest data for this node
/// - Parameter sampleCount: Number of samples to retrieve
/// - Returns: Float channel data for two channels
func getTapData(sampleCount: Int) -> FloatChannelData
}
/// Default functions for nodes that conform to Tappable
extension Tappable where Self: AudioUnitContainer {
/// Install tap on this node
public func installTap() {
akInstallTap(internalAU?.dsp)
}
/// Remove tap on this node
public func removeTap() {
akRemoveTap(internalAU?.dsp)
}
/// Get the latest data for this node
/// - Parameter sampleCount: Number of samples to retrieve
/// - Returns: Float channel data for two channels
public func getTapData(sampleCount: Int) -> FloatChannelData {
var leftData = [Float](repeating: 0, count: sampleCount)
var rightData = [Float](repeating: 0, count: sampleCount)
var success = false
leftData.withUnsafeMutableBufferPointer { leftPtr in
rightData.withUnsafeMutableBufferPointer { rightPtr in
success = akGetTapData(internalAU?.dsp, sampleCount, leftPtr.baseAddress!, rightPtr.baseAddress!)
}
}
if !success { return [] }
return [leftData, rightData]
}
}
/// Protocol for dictating that a node can be in a started or stopped state
public protocol Toggleable {
/// Tells whether the node is processing (ie. started, playing, or active)
var isStarted: Bool { get }
/// Function to start, play, or activate the node, all do the same thing
func start()
/// Function to stop or bypass the node, both are equivalent
func stop()
}
/// Default functions for nodes that conform to Toggleable
public extension Toggleable {
/// Synonym for isStarted that may make more sense with musical instruments
var isPlaying: Bool {
return isStarted
}
/// Antonym for isStarted
var isStopped: Bool {
return !isStarted
}
/// Antonym for isStarted that may make more sense with effects
var isBypassed: Bool {
return !isStarted
}
/// Synonym to start that may more more sense with musical instruments
func play() {
start()
}
/// Synonym for stop that may make more sense with effects
func bypass() {
stop()
}
}
public extension Toggleable where Self: AudioUnitContainer {
/// Is node started?
var isStarted: Bool {
return internalAU?.isStarted ?? false
}
/// Start node
func start() {
internalAU?.start()
}
/// Stop node
func stop() {
internalAU?.stop()
}
}
| mit |
eocleo/AlbumCore | AlbumDemo/AlbumDemo/AlbumViews/views/OverlayerView.swift | 1 | 808 | //
// OverlayerView.swift
// FileMail
//
// Created by leo on 2017/5/27.
// Copyright © 2017年 leo. All rights reserved.
//
import UIKit
class OverlayerView: UIView {
var showFrame: CGRect?
func showOn(view: UIView) -> Void {
if self.showFrame != nil {
self.frame = self.showFrame!
} else {
self.frame = view.bounds
}
self.isOpaque = false
runInMain {
view.addSubview(self)
}
// self.alpha = 0.1
// UIView.animate(withDuration: 0.3) {
// self.alpha = 1.0
// }
AlbumDebug("showOn: \(self)")
}
func dismiss() -> Void {
DispatchQueue.main.async {
AlbumDebug("dismiss: \(self)")
self.removeFromSuperview()
}
}
}
| mit |
jannainm/wingman | Wingman_MAIN/Wingman_MAIN/AppDelegate.swift | 1 | 2156 | //
// AppDelegate.swift
// Wingman_MAIN
//
// Created by Michael Jannain on 10/3/15.
// Copyright (c) 2015 Michael Jannain. 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:.
}
}
| gpl-2.0 |
wikimedia/wikipedia-ios | Wikipedia/Code/TableOfContentsViewController.swift | 1 | 11754 | import UIKit
import WMF
enum TableOfContentsDisplayMode {
case inline
case modal
}
enum TableOfContentsDisplaySide {
case left
case right
}
protocol TableOfContentsViewControllerDelegate : UIViewController {
/**
Notifies the delegate that the controller will display
Use this to update the ToC if needed
*/
func tableOfContentsControllerWillDisplay(_ controller: TableOfContentsViewController)
/**
The delegate is responsible for dismissing the view controller
*/
func tableOfContentsController(_ controller: TableOfContentsViewController,
didSelectItem item: TableOfContentsItem)
/**
The delegate is responsible for dismissing the view controller
*/
func tableOfContentsControllerDidCancel(_ controller: TableOfContentsViewController)
var tableOfContentsArticleLanguageURL: URL? { get }
var tableOfContentsSemanticContentAttribute: UISemanticContentAttribute { get }
var tableOfContentsItems: [TableOfContentsItem] { get }
}
class TableOfContentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TableOfContentsAnimatorDelegate, Themeable {
fileprivate var theme = Theme.standard
let tableOfContentsFunnel: ToCInteractionFunnel
var semanticContentAttributeOverride: UISemanticContentAttribute {
return delegate?.tableOfContentsSemanticContentAttribute ?? .unspecified
}
let displaySide: TableOfContentsDisplaySide
var displayMode = TableOfContentsDisplayMode.modal {
didSet {
animator?.displayMode = displayMode
closeGestureRecognizer?.isEnabled = displayMode == .inline
apply(theme: theme)
}
}
var isVisible: Bool = false
var closeGestureRecognizer: UISwipeGestureRecognizer?
@objc func handleTableOfContentsCloseGesture(_ swipeGestureRecoginzer: UIGestureRecognizer) {
guard swipeGestureRecoginzer.state == .ended, isVisible else {
return
}
delegate?.tableOfContentsControllerDidCancel(self)
}
let tableView: UITableView = UITableView(frame: .zero, style: .grouped)
lazy var animator: TableOfContentsAnimator? = {
guard let delegate = delegate else {
return nil
}
let animator = TableOfContentsAnimator(presentingViewController: delegate, presentedViewController: self)
animator.apply(theme: theme)
animator.delegate = self
animator.displaySide = displaySide
animator.displayMode = displayMode
return animator
}()
weak var delegate: TableOfContentsViewControllerDelegate?
var items: [TableOfContentsItem] {
return delegate?.tableOfContentsItems ?? []
}
func reload() {
tableView.reloadData()
selectInitialItemIfNecessary()
}
// MARK: - Init
required init(delegate: TableOfContentsViewControllerDelegate?, theme: Theme, displaySide: TableOfContentsDisplaySide) {
self.theme = theme
self.delegate = delegate
self.displaySide = displaySide
tableOfContentsFunnel = ToCInteractionFunnel()
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .custom
transitioningDelegate = animator
edgesForExtendedLayout = .all
extendedLayoutIncludesOpaqueBars = true
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Sections
var indexOfSelectedItem: Int = -1
var indiciesOfHighlightedItems: Set<Int> = []
func selectInitialItemIfNecessary() {
guard indexOfSelectedItem == -1, !items.isEmpty else {
return
}
selectItem(at: 0)
}
func selectItem(at index: Int) {
guard index < items.count else {
assertionFailure("Trying to select an item out of range")
return
}
guard indexOfSelectedItem != index else {
return
}
indexOfSelectedItem = index
var newIndicies: Set<Int> = [index]
let item = items[index]
for (index, relatedItem) in items.enumerated() {
guard item.shouldBeHighlightedAlongWithItem(relatedItem) else {
continue
}
newIndicies.insert(index)
}
guard newIndicies != indiciesOfHighlightedItems else {
return
}
let indiciesToReload = newIndicies.union(indiciesOfHighlightedItems)
let indexPathsToReload = indiciesToReload.map { IndexPath(row: $0, section: 0) }
indiciesOfHighlightedItems = newIndicies
guard viewIfLoaded != nil else {
return
}
tableView.reloadRows(at: indexPathsToReload, with: .none)
}
func scrollToItem(at index: Int) {
guard index < items.count else {
assertionFailure("Trying to scroll to an item put of range")
return
}
guard viewIfLoaded != nil, index < tableView.numberOfRows(inSection: 0) else {
return
}
let indexPath = IndexPath(row: index, section: 0)
guard !(tableView.indexPathsForVisibleRows?.contains(indexPath) ?? true) else {
return
}
let shouldAnimate = (displayMode == .inline)
tableView.scrollToRow(at: indexPath, at: .top, animated: shouldAnimate)
}
// MARK: - Selection
private func didRequestClose(_ controller: TableOfContentsAnimator?) -> Bool {
tableOfContentsFunnel.logClose()
delegate?.tableOfContentsControllerDidCancel(self)
return delegate != nil
}
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
assert(tableView.style == .grouped, "Use grouped UITableView layout so our TableOfContentsHeader's autolayout works properly. Formerly we used a .Plain table style and set self.tableView.tableHeaderView to our TableOfContentsHeader, but doing so caused autolayout issues for unknown reasons. Instead, we now use a grouped layout and use TableOfContentsHeader with viewForHeaderInSection, which plays nicely with autolayout. (grouped layouts also used because they allow the header to scroll *with* the section cells rather than floating)")
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundView = nil
tableView.register(TableOfContentsCell.wmf_classNib(),
forCellReuseIdentifier: TableOfContentsCell.reuseIdentifier())
tableView.estimatedRowHeight = 41
tableView.rowHeight = UITableView.automaticDimension
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 32
tableView.separatorStyle = .none
view.wmf_addSubviewWithConstraintsToEdges(tableView)
tableView.contentInsetAdjustmentBehavior = .never
tableView.allowsMultipleSelection = false
tableView.semanticContentAttribute = delegate?.tableOfContentsSemanticContentAttribute ?? .unspecified
view.semanticContentAttribute = delegate?.tableOfContentsSemanticContentAttribute ?? .unspecified
let closeGR = UISwipeGestureRecognizer(target: self, action: #selector(handleTableOfContentsCloseGesture))
switch displaySide {
case .left:
closeGR.direction = .left
case .right:
closeGR.direction = .right
}
view.addGestureRecognizer(closeGR)
closeGestureRecognizer = closeGR
apply(theme: theme)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.delegate?.tableOfContentsControllerWillDisplay(self)
tableOfContentsFunnel.logOpen()
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableOfContentsCell.reuseIdentifier(), for: indexPath) as! TableOfContentsCell
let index = indexPath.row
let item = items[index]
let shouldHighlight = indiciesOfHighlightedItems.contains(index)
cell.backgroundColor = tableView.backgroundColor
cell.contentView.backgroundColor = tableView.backgroundColor
cell.titleIndentationLevel = item.indentationLevel
let color = item.itemType == .primary ? theme.colors.primaryText : theme.colors.secondaryText
let selectionColor = theme.colors.link
let isHighlighted = index == indexOfSelectedItem
cell.setTitleHTML(item.titleHTML, with: item.itemType.titleTextStyle, highlighted: isHighlighted, color: color, selectionColor: selectionColor)
if isHighlighted {
// This makes no difference to sighted users; it allows VoiceOver to read highlighted cell as selected.
cell.accessibilityTraits = .selected
}
cell.setNeedsLayout()
cell.setSectionSelected(shouldHighlight, animated: false)
cell.contentView.semanticContentAttribute = semanticContentAttributeOverride
cell.titleLabel.semanticContentAttribute = semanticContentAttributeOverride
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let delegate = delegate {
let header = TableOfContentsHeader.wmf_viewFromClassNib()
header?.articleURL = delegate.tableOfContentsArticleLanguageURL
header?.backgroundColor = tableView.backgroundColor
header?.semanticContentAttribute = semanticContentAttributeOverride
header?.contentsLabel.semanticContentAttribute = semanticContentAttributeOverride
header?.contentsLabel.textColor = theme.colors.secondaryText
return header
} else {
return nil
}
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
tableOfContentsFunnel.logClick()
let index = indexPath.row
selectItem(at: index)
delegate?.tableOfContentsController(self, didSelectItem: items[index])
}
func tableOfContentsAnimatorDidTapBackground(_ controller: TableOfContentsAnimator) {
_ = didRequestClose(controller)
}
// MARK: - UIAccessibilityAction
override func accessibilityPerformEscape() -> Bool {
return didRequestClose(nil)
}
// MARK: - UIAccessibilityAction
override func accessibilityPerformMagicTap() -> Bool {
return didRequestClose(nil)
}
public func apply(theme: Theme) {
self.theme = theme
self.animator?.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
if displayMode == .modal {
tableView.backgroundColor = theme.colors.paperBackground
} else {
tableView.backgroundColor = theme.colors.midBackground
}
tableView.reloadData()
}
}
| mit |
Sebastian-Hojas/BetterGCD | Source/GCD.swift | 1 | 7986 | //
// GCDPipePipe.swift
// BetterGCDPipe
//
// MIT License
//
// Copyright (c) 2016 Sebastian Hojas
//
// 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
private enum BlockType<T>
{
case AdvancedExecutionBlock(GCDPipe<T>.AdvancedExecutionBlock)
case SimpleExecutionBlock(GCDPipe<T>.SimpleExecutionBlock)
case CatchBlock(GCDPipe<T>.CatchBlock)
}
public class GCD: GCDPipe<Any>{
public override init()
{
super.init()
}
private init(previous: GCD)
{
super.init(previous: previous)
}
public func async(execution: SimpleExecutionBlock) -> GCD
{
self.execution = BlockType<Any>.SimpleExecutionBlock(execution)
if self.previous?.executed == true {
self.fire(cachedReturnValue)
}
self.next = GCD(previous: self)
return self.next as! GCD
}
public override func main() -> GCD
{
super.main()
return self
}
public override func low(flags: UInt = 0) -> GCD
{
super.low(flags)
return self
}
public override func high(flags: UInt = 0) -> GCD
{
super.high(flags)
return self
}
public override func after(time: NSTimeInterval) -> GCD
{
super.after(time)
return self
}
public override func cycle(times: Int) -> GCD
{
super.cycle(times)
return self
}
public override func priority(priority: dispatch_queue_priority_t, flags: UInt = 0) -> GCD
{
super.priority(priority, flags: flags)
return self
}
}
public class GCDPipe<T> {
public typealias CatchBlock = (ErrorType) -> ()
public typealias AdvancedExecutionBlock = (T?) throws ->(T?)
public typealias SimpleExecutionBlock = () throws -> ()
private var previous: GCDPipe?
private var next: GCDPipe?
private var queue: dispatch_queue_t = dispatch_get_main_queue()
private var after: NSTimeInterval?
private var repetition: Int = 1
private var execution: BlockType<T>?
private var executed: Bool = false
private var cachedReturnValue: T? = nil
//var queue: dispatch_queue_t?
//var after: NSTimeInterval?
/**
Initiation of first chain element
- returns: initiated GCDPipe block
*/
public init()
{
self.fire(nil)
}
/**
Initiates element in execution chain
- parameter previous: Link to previous element of linked list
- returns: initiated GCDPipe block
*/
private init(previous: GCDPipe<T>)
{
self.previous = previous
// stay on the same queue by default
self.queue = previous.queue
}
/**
Starts the dispatch
- parameter chainValue: value that should be passed on to the block
*/
private func fire(chainValue: T?) {
let block: dispatch_block_t = {
guard let execution = self.execution else {
// no block available, save return value, for later
self.cachedReturnValue = chainValue
return
}
self.repetition -= 1
switch execution {
case .AdvancedExecutionBlock(let _exec):
do {
let retValue = try _exec(chainValue)
if self.repetition > 0
{
self.fire(retValue)
}
else{
self.next?.fire(retValue)
}
}
catch{
self.unwindError(error)
}
break
case .SimpleExecutionBlock(let _exec):
do {
try _exec()
if self.repetition > 0
{
self.fire(nil)
}
else{
self.next?.fire(nil)
}
}
catch{
self.unwindError(error)
}
break
case .CatchBlock:
// no need to call catch block
break
}
self.executed = true
}
guard let after = after else {
dispatch_async(queue, block)
return
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(after*Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block)
}
/**
Unwinds linked list to find catch block and raise error
- parameter error: risen error
*/
private func unwindError(error: ErrorType)
{
// find last element
if let next = next {
next.unwindError(error)
return
}
guard let exec = execution else {
// Do we ignore error?
print("Ignored error \(error)")
return
}
switch exec {
case .CatchBlock(let catchBlock):
// should we do that on the main thread?
catchBlock(error)
default:
print("Should not never happen")
}
}
/**
Adds a new block to the chains
- parameter execution: block that should be dispatched
- returns: next possible block
*/
public func async(execution: AdvancedExecutionBlock) -> GCDPipe<T>
{
self.execution = BlockType<T>.AdvancedExecutionBlock(execution)
if self.previous?.executed == true {
self.fire(cachedReturnValue)
}
self.next = GCDPipe<T>(previous: self)
return self.next!
}
public func catching(catchBlock: CatchBlock)
{
self.execution = BlockType<T>.CatchBlock(catchBlock)
}
public func main() -> GCDPipe<T>
{
queue = dispatch_get_main_queue()
return self
}
public func priority(priority: dispatch_queue_priority_t, flags: UInt = 0) -> GCDPipe<T>
{
queue = dispatch_get_global_queue(priority, flags)
return self
}
public func low(flags: UInt = 0) -> GCDPipe<T>
{
self.priority(DISPATCH_QUEUE_PRIORITY_LOW, flags: flags)
return self
}
public func high(flags: UInt = 0) -> GCDPipe<T>
{
self.priority(DISPATCH_QUEUE_PRIORITY_HIGH, flags: flags)
return self
}
public func after(time: NSTimeInterval) -> GCDPipe<T>
{
after = time
return self
}
public func cycle(times: Int) -> GCDPipe<T>
{
repetition = times
return self
}
}
| mit |
rentpath/RPValidationKit | RPValidationKit/RPValidationKit/Validators/RPRequiredValidator.swift | 1 | 1730 | /*
* Copyright (c) 2016 RentPath, LLC
*
* 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
open class RPRequiredValidator: RPValidator {
open override func getType() -> String {
return "required"
}
open override func validate(_ value: String) -> Bool {
let trimmedString = value.trimmingCharacters(in: CharacterSet.whitespaces)
return !trimmedString.isEmpty
}
open override func validateField(_ fieldName: String, value: String) -> RPValidation {
if validate(value) {
return RPValidation.valid
} else {
return RPValidation.error(message: "\(fieldName) is required")
}
}
}
| mit |
mihaicris/digi-cloud | Digi Cloud/Controller/Views/URLHashTextField.swift | 1 | 1415 | //
// URLHashTextField.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 23/02/2017.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import UIKit
final class URLHashTextField: UITextField {
// MARK: - Initializers and Deinitializers
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overridden Methods and Properties
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0)
layer.cornerRadius = 8
translatesAutoresizingMaskIntoConstraints = false
autocapitalizationType = .none
autocorrectionType = .no
spellCheckingType = .no
keyboardType = .alphabet
clearButtonMode = .whileEditing
font = UIFont.boldSystemFont(ofSize: 16)
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
let padLeft: CGFloat = 5
let padRight: CGFloat = 20
let inset = CGRect(x: bounds.origin.x + padLeft,
y: bounds.origin.y,
width: bounds.width - padLeft - padRight,
height: bounds.height)
return inset
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}
| mit |
remlostime/one | one/one/ViewControllers/EditUserInfoViewController.swift | 1 | 8529 | //
// EditUserInfoViewController.swift
// one
//
// Created by Kai Chen on 12/30/16.
// Copyright © 2016 Kai Chen. All rights reserved.
//
import UIKit
import Parse
import SCLAlertView
class EditUserInfoViewController: UITableViewController {
fileprivate var profileImageCell: ProfileUserImageViewCell?
fileprivate var genderPickerView: UIPickerView!
let genders = ["Male", "Female"]
var genderCell: UserInfoViewCell?
let userInfo = UserInfo.init(nil)
fileprivate var profileImage: UIImage?
fileprivate var username: String?
fileprivate var fullname: String?
fileprivate var bio: String?
fileprivate var website: String?
fileprivate var email: String?
fileprivate var mobile: String?
fileprivate var gender: String?
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
genderPickerView = UIPickerView()
genderPickerView.dataSource = self
genderPickerView.delegate = self
genderPickerView.backgroundColor = UIColor.groupTableViewBackground
genderPickerView.showsSelectionIndicator = true
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "Cancel", style: .plain, target: self, action: #selector(cancelButtonTapped))
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "Done", style: .done, target: self, action: #selector(doneButtonTapped))
}
// MARK: Action
func cancelButtonTapped() {
self.dismiss(animated: true, completion: nil)
}
func doneButtonTapped() {
// TODO: We should setup listener in email field to get email when user is done with it
let emailIndexPath = IndexPath(row: 0, section: 1)
let emailCell = tableView.cellForRow(at: emailIndexPath) as? UserInfoViewCell
let email = emailCell?.contentTextField.text
if let email = email {
if !email.isValidEmail() {
SCLAlertView().showError("Incorrect Email", subTitle: "Please provoide correct email.")
return
}
}
let websiteIndexPath = IndexPath(row: 3, section: 0)
let websiteCell = tableView.cellForRow(at: websiteIndexPath) as? UserInfoViewCell
let website = websiteCell?.contentTextField.text
if let website = website {
if !website.isValidWebsite() {
SCLAlertView().showError("Incorrect Website", subTitle: "Please provide correct website")
return
}
}
let user = PFUser.current()
let usernameIndexPath = IndexPath(row: 2, section: 0)
let usernameCell = tableView.cellForRow(at: usernameIndexPath) as? UserInfoViewCell
user?.username = usernameCell?.contentTextField.text
user?.email = emailCell?.contentTextField.text
user?[User.website.rawValue] = websiteCell?.contentTextField.text
let fullnameIndexPath = IndexPath(row: 1, section: 0)
let fullnameCell = tableView.cellForRow(at: fullnameIndexPath) as? UserInfoViewCell
user?[User.fullname.rawValue] = fullnameCell?.contentTextField.text
let bioIndexPath = IndexPath(row: 4, section: 0)
let bioCell = tableView.cellForRow(at: bioIndexPath) as? UserInfoViewCell
user?[User.bio.rawValue] = bioCell?.contentTextField.text
let mobileIndexPath = IndexPath(row: 1, section: 1)
let mobileCell = tableView.cellForRow(at: mobileIndexPath) as? UserInfoViewCell
user?[User.mobile.rawValue] = mobileCell?.contentTextField.text
let genderIndexPath = IndexPath(row: 2, section: 0)
let genderCell = tableView.cellForRow(at: genderIndexPath) as? UserInfoViewCell
user?[User.gender.rawValue] = genderCell?.contentTextField.text
let profileImageData = UIImagePNGRepresentation((profileImageCell?.profileImageView.image)!)
let profileImageFile = PFFile(name: "profile_image.png", data: profileImageData!)
user?[User.profileImage.rawValue] = profileImageFile
user?.saveInBackground(block: { (success: Bool, error: Error?) in
guard !success else {
SCLAlertView().showError("Save Error", subTitle: "Can not save, please try again!")
return
}
NotificationCenter.default.post(name: .updateUserInfo, object: nil)
})
dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 5
} else {
return 3
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0 && indexPath.row == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.profileUserImageViewCell.rawValue, for: indexPath) as? ProfileUserImageViewCell
// setup user image
cell?.delegate = self
profileImageCell = cell
let profileImageFile = userInfo.profileImageFile
profileImageFile?.getDataInBackground(block: { [weak cell](data: Data?, error: Error?) in
guard let strongCell = cell else {
return
}
strongCell.profileImageView?.image = UIImage(data: data!)
})
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.userInfoViewCell.rawValue, for: indexPath) as? UserInfoViewCell
cell?.config(indexPath, userInfo: userInfo)
if (indexPath.section == 1 && indexPath.row == 2) {
cell?.contentTextField.inputView = genderPickerView
genderCell = cell
}
return cell!
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return nil
} else {
return "Private Information"
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
return 150.0
} else {
return 46.0
}
}
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
}
extension EditUserInfoViewController: ProfileUserImageViewCellDelegate {
func showImagePicker(_ profileImageCell: ProfileUserImageViewCell) {
let imagePickerVC = UIImagePickerController()
imagePickerVC.delegate = self
imagePickerVC.sourceType = .photoLibrary
imagePickerVC.allowsEditing = true
present(imagePickerVC, animated: true, completion: nil)
}
}
extension EditUserInfoViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
profileImageCell?.profileImageView.image = info[UIImagePickerControllerEditedImage] as? UIImage
dismiss(animated: true, completion: nil)
}
}
extension EditUserInfoViewController: UINavigationControllerDelegate {
}
extension EditUserInfoViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let genderCell = genderCell {
genderCell.contentTextField.text = genders[row]
genderCell.endEditing(true)
}
}
}
extension EditUserInfoViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return genders.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return genders[row]
}
}
| gpl-3.0 |
pasmall/WeTeam | WeTools/WeTools/ViewController/Login/RegistViewController.swift | 1 | 2703 | //
// RegistViewController.swift
// WeTools
//
// Created by lhtb on 2016/11/17.
// Copyright © 2016年 lhtb. All rights reserved.
//
import UIKit
import Alamofire
class RegistViewController: BaseViewController {
let accTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 140, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入手机号码")
let psdTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入密码")
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "注册"
setUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.navigationBar.isHidden = false
}
func setUI () {
view.addSubview(accTF)
view.addSubview(psdTF)
let line = UIView.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 0.4))
line.backgroundColor = backColor
view.addSubview(line)
psdTF.isSecureTextEntry = true
//登录
let logBtn = UIButton()
logBtn.frame = CGRect.init(x: 10, y: 248, width: SCREEN_WIDTH - 20, height: 44)
logBtn.backgroundColor = blueColor
logBtn.setTitle("注册", for: .normal)
logBtn.layer.cornerRadius = 4
logBtn.layer.masksToBounds = true
logBtn.addTarget(self, action: #selector(LoginViewController.tapLoginBtn), for: .touchUpInside)
view.addSubview(logBtn)
}
func tapLoginBtn() {
self.showSimpleHUD()
Alamofire.request( IP + "regist.php", method: .post, parameters: ["name":accTF.text!,"psd":psdTF.text!]).responseJSON { (data) in
if let json = data.result.value as? [String:Any]{
print(json)
if json["code"] as! Int == 200{
self.hidSimpleHUD()
_ = self.alert.showAlert("", subTitle: "注册成功", style: AlertStyle.success, buttonTitle: "返回登录", action: { (true) in
_ = self.navigationController?.popViewController(animated: true)
})
} else if json["code"] as! Int == 202{
_ = self.alert.showAlert("该账号已被注册")
}
}
}
}
}
| apache-2.0 |
ascode/pmn | AnimationDemo/Controller/ImageViewAnimationViewController.swift | 1 | 4830 | //
// testViewController.swift
// AnimationDemo
//
// Created by 金飞 on 2016/10/17.
// Copyright © 2016年 JL. All rights reserved.
//
import UIKit
class ImageViewAnimationViewController: UIViewController {
var img: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
img = UIImageView()
img.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 50)
img.animationImages = [
UIImage(named: "1")!,
UIImage(named: "2")!,
UIImage(named: "3")!,
UIImage(named: "4")!,
UIImage(named: "5")!,
UIImage(named: "6")!,
UIImage(named: "7")!,
UIImage(named: "8")!,
UIImage(named: "9")!,
UIImage(named: "10")!,
UIImage(named: "11")!,
UIImage(named: "12")!,
UIImage(named: "13")!,
UIImage(named: "14")!,
UIImage(named: "15")!,
UIImage(named: "16")!,
UIImage(named: "17")!,
UIImage(named: "18")!,
UIImage(named: "19")!,
UIImage(named: "20")!,
UIImage(named: "21")!,
UIImage(named: "22")!,
UIImage(named: "23")!,
UIImage(named: "24")!,
UIImage(named: "25")!
]
img.animationDuration = 50
img.animationRepeatCount = 0
self.view.addSubview(img)
let btnStart: UIButton = UIButton()
btnStart.frame = CGRect(x: UIScreen.main.bounds.width * 0/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnStart.setTitle("播放", for: UIControlState.normal)
btnStart.layer.borderColor = UIColor.white.cgColor
btnStart.layer.borderWidth = 3
btnStart.layer.cornerRadius = 3
btnStart.layer.masksToBounds = true
btnStart.backgroundColor = UIColor.blue
btnStart.addTarget(self, action: #selector(ImageViewAnimationViewController.btnStartPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnStart)
let btnStop: UIButton = UIButton()
btnStop.frame = CGRect(x: UIScreen.main.bounds.width * 1/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnStop.setTitle("停止", for: UIControlState.normal)
btnStop.layer.borderColor = UIColor.white.cgColor
btnStop.layer.borderWidth = 3
btnStop.layer.cornerRadius = 3
btnStop.layer.masksToBounds = true
btnStop.backgroundColor = UIColor.blue
btnStop.addTarget(self, action: #selector(ImageViewAnimationViewController.btnStopPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnStop)
let btnBack: UIButton = UIButton()
btnBack.frame = CGRect(x: UIScreen.main.bounds.width * 2/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnBack.setTitle("返回", for: UIControlState.normal)
btnBack.layer.borderColor = UIColor.white.cgColor
btnBack.layer.borderWidth = 3
btnBack.layer.cornerRadius = 3
btnBack.layer.masksToBounds = true
btnBack.backgroundColor = UIColor.blue
btnBack.addTarget(self, action: #selector(ImageViewAnimationViewController.btnBackPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnBack)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func btnBackPressed(){
self.dismiss(animated: true) {
}
}
func btnStartPressed(){
img.startAnimating()
}
func btnStopPressed(){
img.stopAnimating()
}
/*
// 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.
}
*/
}
| mit |
ustwo/mockingbird | Sources/SwaggerKit/Model/HTTPMethod.swift | 1 | 582 | //
// HTTPMethod.swift
// Mockingbird
//
// Created by Aaron McTavish on 20/12/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
enum HTTPMethod: String {
case connect = "CONNECT"
case delete = "DELETE"
case get = "GET"
case head = "HEAD"
case options = "OPTIONS"
case patch = "PATCH"
case post = "POST"
case put = "PUT"
case trace = "TRACE"
static let allValues: [HTTPMethod] = [.connect, .delete, .get, .head, .options,
.patch, .post, .put, .trace]
}
| mit |
UyumazHakan/iBuzzer | App/App/Restaurant.swift | 1 | 432 | //
// Restaurant.swift
// App
//
// Created by student1 on 05/01/15.
// Copyright (c) 2015 Hakan Uyumaz. All rights reserved.
//
import Foundation
class Restaurant {
let id: Int
let name: String
let type: String
init(json: JSON){
id = json["ID"].asInt!
name = json["NAME"].asString!
type = json["TYPE"].asString!
println("Restauran Created: " + name + ", " + type )
}
} | gpl-2.0 |
morizotter/BrightFutures | BrightFutures/FutureUtils.swift | 1 | 6921 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Result
//// The free functions in this file operate on sequences of Futures
/// Performs the fold operation over a sequence of futures. The folding is performed
/// on `Queue.global`.
/// (The Swift compiler does not allow a context parameter with a default value
/// so we define some functions twice)
public func fold<S: SequenceType, T, R, E where S.Generator.Element == Future<T, E>>(seq: S, zero: R, f: (R, T) -> R) -> Future<R, E> {
return fold(seq, context: Queue.global.context, zero: zero, f: f)
}
/// Performs the fold operation over a sequence of futures. The folding is performed
/// in the given context.
public func fold<S: SequenceType, T, R, E where S.Generator.Element == Future<T, E>>(seq: S, context c: ExecutionContext, zero: R, f: (R, T) -> R) -> Future<R, E> {
return seq.reduce(Future<R, E>(successValue: zero)) { zero, elem in
return zero.flatMap { zeroVal in
elem.map(context: c) { elemVal in
return f(zeroVal, elemVal)
}
}
}
}
/// Turns a sequence of T's into an array of `Future<U>`'s by calling the given closure for each element in the sequence.
/// If no context is provided, the given closure is executed on `Queue.global`
public func traverse<S: SequenceType, T, U, E where S.Generator.Element == T>(seq: S, context c: ExecutionContext = Queue.global.context, f: T -> Future<U, E>) -> Future<[U], E> {
return fold(seq.map(f), context: c, zero: [U]()) { (list: [U], elem: U) -> [U] in
return list + [elem]
}
}
/// Turns a sequence of `Future<T>`'s into a future with an array of T's (Future<[T]>)
/// If one of the futures in the given sequence fails, the returned future will fail
/// with the error of the first future that comes first in the list.
public func sequence<S: SequenceType, T, E where S.Generator.Element == Future<T, E>>(seq: S) -> Future<[T], E> {
return traverse(seq) { (fut: Future<T, E>) -> Future<T, E> in
return fut
}
}
/// See `find<S: SequenceType, T where S.Generator.Element == Future<T>>(seq: S, context c: ExecutionContext, p: T -> Bool) -> Future<T>`
public func find<S: SequenceType, T, E: ErrorType where S.Generator.Element == Future<T, E>>(seq: S, p: T -> Bool) -> Future<T, BrightFuturesError<E>> {
return find(seq, context: Queue.global.context, p: p)
}
/// Returns a future that succeeds with the value from the first future in the given
/// sequence that passes the test `p`.
/// If any of the futures in the given sequence fail, the returned future fails with the
/// error of the first failed future in the sequence.
/// If no futures in the sequence pass the test, a future with an error with NoSuchElement is returned.
public func find<S: SequenceType, T, E: ErrorType where S.Generator.Element == Future<T, E>>(seq: S, context c: ExecutionContext, p: T -> Bool) -> Future<T, BrightFuturesError<E>> {
return sequence(seq).mapError { error in
return BrightFuturesError(external: error)
}.flatMap(context: c) { val -> Result<T, BrightFuturesError<E>> in
for elem in val {
if (p(elem)) {
return Result(value: elem)
}
}
return Result(error: .NoSuchElement)
}
}
/// Returns a future that returns with the first future from the given sequence that completes
/// (regardless of whether that future succeeds or fails)
public func firstCompletedOf<S: SequenceType, T, E where S.Generator.Element == Future<T, E>>(seq: S) -> Future<T, E> {
let p = Promise<T, E>()
for fut in seq {
fut.onComplete(context: Queue.global.context) { res in
p.tryComplete(res)
return
}
}
return p.future
}
/// Enables the chaining of two failable operations where the second operation is asynchronous and
/// represented by a future.
/// Like map, the given closure (that performs the second operation) is only executed
/// if the first operation result is a .Success
/// If a regular `map` was used, the result would be `Result<Future<U>>`.
/// The implementation of this function uses `map`, but then flattens the result before returning it.
public func flatMap<T,U, E>(result: Result<T,E>, @noescape f: T -> Future<U, E>) -> Future<U, E> {
return flatten(result.map(f))
}
/// Returns a .Failure with the error from the outer or inner result if either of the two failed
/// or a .Success with the success value from the inner Result
public func flatten<T, E>(result: Result<Result<T,E>,E>) -> Result<T,E> {
return result.analysis(ifSuccess: { $0 }, ifFailure: { Result(error: $0) })
}
/// Returns the inner future if the outer result succeeded or a failed future
/// with the error from the outer result otherwise
public func flatten<T, E>(result: Result<Future<T, E>,E>) -> Future<T, E> {
return result.analysis(ifSuccess: { $0 }, ifFailure: { Future(error: $0) })
}
/// Turns a sequence of `Result<T>`'s into a Result with an array of T's (`Result<[T]>`)
/// If one of the results in the given sequence is a .Failure, the returned result is a .Failure with the
/// error from the first failed result from the sequence.
public func sequence<S: SequenceType, T, E where S.Generator.Element == Result<T, E>>(seq: S) -> Result<[T], E> {
return seq.reduce(Result(value: [])) { (res, elem) -> Result<[T], E> in
switch res {
case .Success(let resultSequence):
switch elem {
case .Success(let elemValue):
let newSeq = resultSequence + [elemValue]
return Result<[T], E>(value: newSeq)
case .Failure(let elemError):
return Result<[T], E>(error: elemError)
}
case .Failure(_):
return res
}
}
}
| mit |
andykkt/BFWControls | BFWControls/Modules/Transition/Controller/SegueHandlerType.swift | 1 | 3065 | //
// SegueHandlerType.swift
//
// Created by Tom Brodhurst-Hill on 7/12/16.
// Copyright © 2016 BareFeetWare.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
/*
Inspired by:
https://www.bignerdranch.com/blog/using-swift-enumerations-makes-segues-safer/
https://developer.apple.com/library/content/samplecode/Lister/Listings/Lister_SegueHandlerTypeType_swift.html
https://www.natashatherobot.com/protocol-oriented-segue-identifiers-swift/
but changed to allow (ie not crash) blank segue identifiers with no code handling.
Example usage:
class RootViewController: UITableViewController, SegueHandlerType {
enum SegueIdentifier: String {
case account, products, recentProducts, contacts, login
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
guard let segueIdentifier = segueIdentifier(forIdentifier: identifier)
else { return true }
let should: Bool
switch segueIdentifier {
case .account:
should = isLoggedIn
if !should {
performSegue(.login, sender: sender)
}
default:
should = true
}
return should
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let segueIdentifier = segueIdentifier(forIdentifier: segue.identifier)
else { return }
switch segueIdentifier {
case .account:
if let accountViewController = segue.destination as? AccountViewController {
accountViewController.account = account
}
case .products, .recentProducts:
if let productsViewController = segue.destination as? ProductsViewController {
productsViewController.products = ??
}
case .contacts:
if let contactsViewController = segue.destination as? ContactsViewController {
contactsViewController.contacts = [String]()
}
case .login:
break
}
}
}
*/
import UIKit
public protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
public extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String {
public func performSegue(_ segueIdentifier: SegueIdentifier, sender: Any?) {
performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
}
/// To perform the segue after already queued UI actions. For instance, use in an unwind segue to perform a forward segue after viewDidAppear has finished.
public func performOnMainQueueSegue(_ segueIdentifier: SegueIdentifier, sender: Any?) {
DispatchQueue.main.async { [weak self] in
self?.performSegue(segueIdentifier, sender: sender)
}
}
public func segueIdentifier(forIdentifier identifier: String?) -> SegueIdentifier? {
return identifier.flatMap { SegueIdentifier(rawValue: $0) }
}
}
| mit |
MTR2D2/TIY-Assignments | ToDo/ToDoCore+CoreDataProperties.swift | 1 | 445 | //
// ToDoCore+CoreDataProperties.swift
// ToDo
//
// Created by Michael Reynolds on 10/20/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension ToDoCore {
@NSManaged var something: String?
@NSManaged var done: Bool
}
| cc0-1.0 |
Josscii/iOS-Demos | AnimateNavigationBarDemo/AnimateNavigationBarDemo/AppDelegate.swift | 1 | 2184 | //
// AppDelegate.swift
// AnimateNavigationBarDemo
//
// Created by josscii on 2018/2/6.
// Copyright © 2018年 josscii. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
tonystone/geofeatures2 | Sources/GeoFeatures/Bounds.swift | 1 | 2550 | ///
/// Bounds.swift
///
/// Copyright (c) 2018 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 3/24/18.
///
import Swift
///
/// Represents the min and max X Y coordinates of a collection of Coordinates (any geometry).
///
/// This object can be thought of as the bounding box and represents the lower right and upper left coordinates of a Ractangle.
///
public struct Bounds {
///
/// Min X Y values
///
public let min: (x: Double, y: Double)
///
/// Max X Y values
///
public let max: (x: Double, y: Double)
///
/// Mid X Y values
///
public var mid: (x: Double, y: Double) {
return (x: (min.x + max.x) / 2, y: (min.y + max.y) / 2)
}
///
/// Initialize a Bounds with the min and max coordinates.
///
public init(min: Coordinate, max: Coordinate) {
self.min = (x: min.x, y: min.y)
self.max = (x: max.x, y: max.y)
}
///
/// Initialize a Bounds with the min and max tuples.
///
public init(min: (x: Double, y: Double), max: (x: Double, y: Double)) {
self.min = (x: min.x, y: min.y)
self.max = (x: max.x, y: max.y)
}
}
extension Bounds {
///
/// Returns the minX, minY, maxX, maxY, of 2 `Bounds`s as a `Bounds`.
///
public func expand(other: Bounds) -> Bounds {
return Bounds(min: (x: Swift.min(self.min.x, other.min.x), y: Swift.min(self.min.y, other.min.y)),
max: (x: Swift.max(self.max.x, other.max.x), y: Swift.max(self.max.y, other.max.y)))
}
}
extension Bounds: Equatable {
public static func == (lhs: Bounds, rhs: Bounds) -> Bool {
return lhs.min == rhs.min && lhs.max == rhs.max
}
}
extension Bounds: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "\(type(of: self))(min: \(self.min), max: \(self.max))"
}
public var debugDescription: String {
return self.description
}
}
| apache-2.0 |
64characters/Telephone | Telephone/AsyncFailingProductsFake.swift | 1 | 1185 | //
// AsyncFailingProductsFake.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
final class AsyncFailingProductsFake {
let all: [Product] = []
private let target: ProductsEventTarget
init(target: ProductsEventTarget) {
self.target = target
}
}
extension AsyncFailingProductsFake: Products {
subscript(identifier: String) -> Product? {
return nil
}
func fetch() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: notifyTarget)
}
private func notifyTarget() {
target.didFailFetching(self, error: "Network is unreachable.")
}
}
| gpl-3.0 |
edwinps/CZCustomLayout | CZCustomLayout/controller/ViewController.swift | 1 | 8007 | //
// ViewController.swift
// CZCustomLayout
//
// Created by Edwin Peña on 4/9/17.
// Copyright © 2017 Edwin Peña. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, BaseCollectionViewLayoutProtocol {
//MARK: Outlets
@IBOutlet weak var collectionView: UICollectionView!
//MARK: dataSource
let dataSource = ModelItems()
//number Of Columns we want to display
let numberOfColumns = 2
//hash
private var hashCell : [String : UICollectionViewCell] = [:]
override func viewDidLoad() {
super.viewDidLoad()
dataSource.buildDataSource()
dataSource.buildHeader()
dataSource.buildFooter()
// Attach datasource and delegate
self.collectionView.dataSource = self
self.collectionView.delegate = self
//configure Outlets
configureOutlets()
//Register nibs
registerNibs()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - UI Configuration
private func configureOutlets() {
self.automaticallyAdjustsScrollViewInsets = false
//create the Layout
let layout = BaseCollectionViewLayout()
//config margin
layout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
// The minimum spacing to use between rows.
layout.minimumInteritemSpacing = 10
// The minimum spacing to use between columns
layout.minimumLineSpacing = 10
// Add the waterfall layout to your collection view
self.collectionView.collectionViewLayout = layout
//add delegate
layout.delegate = self
}
// Register CollectionView Nibs
private func registerNibs(){
let viewNib = UINib(nibName: "ItemCollectionViewCell", bundle: nil)
collectionView.register(viewNib, forCellWithReuseIdentifier: "cell")
let headerViewNib = UINib(nibName: "HeaderCollectionViewCell", bundle: nil)
collectionView.register(headerViewNib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
let footerViewNib = UINib(nibName: "FooterCollectionViewCell", bundle: nil)
collectionView.register(footerViewNib, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer")
}
//MARK: - Accessible Methods
func calculateCellHeight(item: ItemViewModel, _ indexPath: IndexPath, _ availableWidth: CGFloat) -> CGFloat {
let bundle = Bundle(for: type(of: self))
//calculate automatic size
let cellNibName = String(describing: ItemCollectionViewCell.self)
/// it should be exits always
guard !cellNibName.isEmpty else {
return 0.0
}
//look it the view is already create to no create always a new one
var existingCell = hashCell[cellNibName]
if existingCell == nil {
let nib = UINib(nibName: cellNibName, bundle: bundle)
existingCell = nib.instantiate(withOwner: nil, options: nil)[0] as? ItemCollectionViewCell
hashCell[cellNibName] = existingCell
}
/// it should be exits always
guard let currentCell = existingCell else {
return 0.0
}
//config the cell with the datasource
if let cell = currentCell as? ItemCollectionViewCell {
cell.configureView(viewModel: item)
}
//use systemLayoutSizeFitting to calculate the height base in the width
let targetSize = CGSize(width: availableWidth, height: 0)
let autoLayoutSize = currentCell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultLow)
return autoLayoutSize.height
}
//MARK: BaseCollectionViewLayoutProtocol
func collectionView (_ collectionView: UICollectionView, availableWidth: CGFloat, heightForItemAtIndexPath indexPath: IndexPath) -> CGFloat {
if let item = dataSource.ds[indexPath.section]?[indexPath.row]{
return calculateCellHeight(item: item, indexPath,availableWidth)
}
return 0
}
func collectionView (_ collectionView: UICollectionView, availableWidth: CGFloat, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? 50 : 0
}
func collectionView (_ collectionView: UICollectionView, availableWidth: CGFloat, heightForFooterInSection section: Int) -> CGFloat {
return section == 0 ? 50 : 0
}
func collectionView (_ collectionView: UICollectionView, columnCountForSection section: Int) -> Int {
return section == 0 ? 2 : 3
}
func collectionViewBiggerCell(_ indexPath: IndexPath) -> Bool {
//make the first item bigger
if(indexPath.row == 0 && indexPath.section == 0){
return true
}
return false
}
//MARK: CollectionView Delegate Methods
//** Number of Cells in the CollectionView */
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let numberOfRow = dataSource.ds[section]?.count {
return numberOfRow
}
return 0
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.ds.count
}
// Create a CollectionView Cell */
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
// Create the cell and return the cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! ItemCollectionViewCell
// confic cell
if let model = dataSource.ds[indexPath.section]?[indexPath.row] {
cell.configureView(viewModel: model)
return cell
}
return collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
/// review when there are not header of footer for section
case UICollectionView.elementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! HeaderCollectionViewCell
if indexPath.section < dataSource.headerViewModel.count {
headerView.configureView(viewModel: dataSource.headerViewModel[indexPath.section])
return headerView
}
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header", for: indexPath as IndexPath)
case UICollectionView.elementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footer", for: indexPath) as! FooterCollectionViewCell
if indexPath.section < dataSource.headerViewModel.count {
footerView.configureView(viewModel: dataSource.footerViewModel[indexPath.section])
return footerView
}
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footer", for: indexPath as IndexPath)
default:
assert(false, "Unexpected element kind")
}
}
}
| mit |
nvh/DataSourceable | DataSourceableTests/SectionableSpec.swift | 1 | 3296 | //
// Sectionable.swift
// DataSourceable
//
// Created by Niels van Hoorn on 13/10/15.
// Copyright © 2015 Zeker Waar. All rights reserved.
//
import Foundation
import DataSourceable
import Quick
import Nimble
struct SingleSectionDataSource: Sectionable, DataContaining {
typealias Data = [Int]
typealias Section = Data
var data: Data? = nil
}
struct SectionableDataSource: Sectionable, DataContaining {
typealias Data = [Section]
typealias Section = [Int]
var data: Data? = nil
}
class SectionableSpec: QuickSpec {
override func spec() {
describe("Sectionable") {
var sectionable: SectionableDataSource!
context("data is nil") {
beforeEach {
sectionable = SectionableDataSource(data: nil)
}
it("sections is nil") {
expect(sectionable.sections).to(beNil())
}
it("numberOfSections to be 0") {
expect(sectionable.numberOfSections).to(equal(0))
}
it("should return an item count of 0") {
expect(sectionable.numberOfItems(inSection: 0)).to(equal(0))
}
}
context("data is set") {
let data = [[3,5,7,9],[2,4,6]]
beforeEach {
sectionable = SectionableDataSource(data: data)
}
it("should return two sections") {
expect(sectionable.numberOfSections).to(equal(data.count))
}
it("should return the right number of items") {
expect(sectionable.numberOfItems(inSection: 0)).to(equal(data[0].count))
}
it("should return the right items") {
for sectionIndex in 0..<sectionable.numberOfSections {
for index in 0..<sectionable.numberOfItems(inSection: sectionIndex) {
expect(sectionable.item(atIndexPath: NSIndexPath(forItem: index, inSection: sectionIndex))).to(equal(data[sectionIndex][index]))
}
}
}
}
context("single section datasource") {
var singleSection: SingleSectionDataSource!
let data = [3,1,4,1,5]
beforeEach {
singleSection = SingleSectionDataSource(data: data)
}
it("should return one section") {
expect(singleSection.numberOfSections).to(equal(1))
}
it("should return the data count for the first section") {
expect(singleSection.numberOfItems(inSection: 0)).to(equal(data.count))
}
it("should return the contents of data for the first section") {
for (index,value) in data.enumerate() {
expect(singleSection.item(atIndexPath: NSIndexPath(forItem: index, inSection: 0))).to(equal(value))
}
}
}
}
}
}
| mit |
rechsteiner/Parchment | ParchmentTests/Mocks/Mock.swift | 1 | 987 | import Foundation
enum Action: Equatable {
case collectionView(MockCollectionView.Action)
case collectionViewLayout(MockCollectionViewLayout.Action)
case delegate(MockPagingControllerDelegate.Action)
}
struct MockCall {
let datetime: Date
let action: Action
}
extension MockCall: Equatable {
static func == (lhs: MockCall, rhs: MockCall) -> Bool {
return lhs.datetime == rhs.datetime && lhs.action == rhs.action
}
}
extension MockCall: Comparable {
static func < (lhs: MockCall, rhs: MockCall) -> Bool {
return lhs.datetime < rhs.datetime
}
}
protocol Mock {
var calls: [MockCall] { get }
}
func actions(_ calls: [MockCall]) -> [Action] {
return calls.map { $0.action }
}
func combinedActions(_ a: [MockCall], _ b: [MockCall]) -> [Action] {
return actions(Array(a + b).sorted())
}
func combinedActions(_ a: [MockCall], _ b: [MockCall], _ c: [MockCall]) -> [Action] {
return actions(Array(a + b + c).sorted())
}
| mit |
codepgq/LearningSwift | TableViewCellEdit/TableViewCellEdit/TBDataSource.swift | 1 | 3220 | //
// TBDataSource.swift
// CustomPullToRefresh
//
// Created by ios on 16/9/26.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
/**
设置Section样式,默认 Single
*/
public enum TBSectionStyle : Int {
///Default 默认没有多个Section
case Section_Single
/// 有多个Section
case Section_Has
}
typealias TBMoveCellBlock = ((item : UITableViewRowAction,index : Int) -> Void)?
class TBDataSource: NSObject,UITableViewDataSource,UITableViewDelegate {
/**
数据类型
*/
private var sectionStyle : TBSectionStyle = .Section_Single
/**
数据源
*/
private var data : NSArray?
/**
标识符
*/
private var identifier : String = "null"
/**
cell回调
*/
private var cellBlock : ((cell : AnyObject, item : AnyObject) -> ())?
private var moveBlock : TBMoveCellBlock?
/**
快速创建一个数据源,需要提前注册,数组和style要对应
- parameter identifier: 标识
- parameter data: 数据
- parameter style: 类型
- parameter cell: 回调
- returns: 数据源对象(dataSource)
*/
class func cellIdentifierWith(identifier : String , data : NSArray , style : TBSectionStyle , cell : ((cell : AnyObject, item : AnyObject) -> Void)) -> TBDataSource {
let source = TBDataSource()
source.sectionStyle = style
source.data = data
source.identifier = identifier
source.cellBlock = cell
return source
}
/**
返回数据
- parameter indexPath: indexPath
- returns: 数据
*/
private func itemWithIndexPath(indexPath : NSIndexPath) -> AnyObject{
if sectionStyle == .Section_Single {
return data![indexPath.row]
}
else{
return data![indexPath.section][indexPath.row]
}
}
/**
返回有多少个Section
- parameter tableView: tableView
- returns: section
*/
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if sectionStyle == .Section_Single {
return 1
}
return (data?.count)!
}
/**
返回对应Section的rows
- parameter tableView: tableView
- parameter section: section
- returns: rows
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if sectionStyle == .Section_Single {
return (data?.count)!
}else{
return (data?[section].count)!
}
}
/**
返回cell,并用闭包把cell封装到外面,提供样式设置
- parameter tableView: tableView
- parameter indexPath: indexPath
- returns: cell
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
if let block = cellBlock {
block(cell: cell, item: itemWithIndexPath(indexPath))
}
return cell
}
}
| apache-2.0 |
swc1098/TIRO | TIRO/TIRO/ExitNode.swift | 1 | 654 | //
// ExitNode.swift
// TIRO
//
// Created by student on 11/9/16.
// Copyright © 2016 swc1098. All rights reserved.
//
import SpriteKit
class ExitNode: SKSpriteNode, EventListenerNode {
func didMoveToScene() {
print("exit added to scene")
// 97 124
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width:97, height: 124))
self.physicsBody!.isDynamic = false
self.physicsBody!.categoryBitMask = PhysicsCategory.Goal
self.physicsBody!.collisionBitMask = PhysicsCategory.None
self.physicsBody!.contactTestBitMask = PhysicsCategory.Ball
}
}
| mit |
wordpress-mobile/WordPress-Aztec-iOS | Aztec/Classes/Extensions/NSAttributedString+Attachments.swift | 2 | 6174 | import Foundation
import UIKit
// MARK: - NSAttributedString Extension for Attachments
//
extension NSAttributedString
{
/// Indicates the Attributed String Length of a single TextAttachment
///
static let lengthOfTextAttachment = NSAttributedString(attachment: NSTextAttachment()).length
// MARK: - Initializers
/// Helper Initializer: returns an Attributed String, with the specified attachment, styled with a given
/// collection of attributes.
///
public convenience init(attachment: NSTextAttachment, attributes: [NSAttributedString.Key: Any]) {
var attributesWithAttachment = attributes
attributesWithAttachment[.attachment] = attachment
self.init(.textAttachment, attributes: attributesWithAttachment)
}
public convenience init(attachment: NSTextAttachment, caption: NSAttributedString, attributes: [NSAttributedString.Key: Any]) {
let figure = Figure()
let figcaption = Figcaption(defaultFont: UIFont.systemFont(ofSize: 14), storing: nil)
let figureAttributes = attributes.appending(figure)
let finalString = NSMutableAttributedString(attachment: attachment, attributes: figureAttributes)
let mutableCaption = NSMutableAttributedString(attributedString: caption)
mutableCaption.append(paragraphProperty: figure)
mutableCaption.append(paragraphProperty: figcaption)
let paragraphSeparator = NSAttributedString(.paragraphSeparator, attributes: [:])
finalString.append(paragraphSeparator)
finalString.append(mutableCaption)
finalString.append(paragraphSeparator)
self.init(attributedString: finalString)
}
/// Loads any NSTextAttachment's lazy file reference, into a UIImage instance, in memory.
///
func loadLazyAttachments() {
enumerateAttachmentsOfType(NSTextAttachment.self) { (attachment, _, _) in
guard let data = attachment.fileWrapper?.regularFileContents else {
return
}
if let mediaAttachment = attachment as? MediaAttachment {
mediaAttachment.refreshIdentifier()
}
let scale = UIScreen.main.scale
let image = UIImage(data: data, scale: scale)
attachment.fileWrapper = nil
attachment.image = image
}
}
/// Enumerates all of the available NSTextAttachment's of the specified kind, in a given range.
/// For each one of those elements, the specified block will be called.
///
/// - Parameters:
/// - range: The range that should be checked. Nil wil cause the whole text to be scanned
/// - type: The kind of Attachment we're after
/// - block: Closure to be executed, for each one of the elements
///
func enumerateAttachmentsOfType<T : NSTextAttachment>(_ type: T.Type, range: NSRange? = nil, block: ((T, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)) {
let range = range ?? NSMakeRange(0, length)
enumerateAttribute(.attachment, in: range, options: []) { (object, range, stop) in
if let object = object as? T {
block(object, range, stop)
}
}
}
/// Determine the character ranges for an attachment
///
/// - Parameters:
/// - attachment: the attachment to search for
///
/// - Returns: an array of ranges where the attachement can be found
///
public func ranges(forAttachment attachment: NSTextAttachment) -> [NSRange] {
let range = NSRange(location: 0, length: length)
var attachmentRanges = [NSRange]()
enumerateAttribute(.attachment, in: range, options: []) { (value, effectiveRange, nil) in
guard let foundAttachment = value as? NSTextAttachment, foundAttachment == attachment else {
return
}
attachmentRanges.append(effectiveRange)
}
return attachmentRanges
}
// MARK: - Captions
open func caption(for attachment: NSTextAttachment) -> NSAttributedString? {
guard let captionRange = self.captionRange(for: attachment) else {
return nil
}
let string = attributedSubstring(from: captionRange).mutableCopy() as! NSMutableAttributedString
for character in Character.paragraphBreakingCharacters {
string.replaceOcurrences(of: String(character), with: "")
}
return NSAttributedString(attributedString: string)
}
public func captionRange(for attachment: NSTextAttachment) -> NSRange? {
guard let figureRange = self.figureRange(for: attachment) else {
return nil
}
return figcaptionRanges(within: figureRange).first
}
// MARK: - Captions: Figure and Figcaption property ranges
private func figcaptionRanges(within range: NSRange) -> [NSRange] {
var ranges = [NSRange]()
enumerateParagraphRanges(spanning: range) { (_, enclosingRange) in
guard let paragraphStyle = attribute(.paragraphStyle, at: enclosingRange.lowerBound, effectiveRange: nil) as? ParagraphStyle else {
return
}
if paragraphStyle.hasProperty(where: { $0 is Figcaption }) {
ranges.append(enclosingRange)
}
}
return ranges
}
private func figureRange(for attachment: NSTextAttachment) -> NSRange? {
guard let attachmentRange = ranges(forAttachment: attachment).first else {
return nil
}
let paragraphRange = self.paragraphRange(for: attachmentRange)
guard let paragraphStyle = self.attribute(.paragraphStyle, at: paragraphRange.lowerBound, effectiveRange: nil) as? ParagraphStyle,
let figure = paragraphStyle.property(where: { $0 is Figure }) as? Figure else {
return nil
}
return self.paragraphRange(around: attachmentRange) { (properties) -> Bool in
return properties.contains { $0 === figure }
}
}
}
| gpl-2.0 |
lojals/semanasanta | Semana Santa/Semana Santa/Classes/ViaCrusisVC2.swift | 1 | 4937 | //
// ViaCrusisVC.swift
// Semana Santa
//
// Created by Jorge Raul Ovalle Zuleta on 3/9/15.
// Copyright (c) 2015 Jorge Ovalle. All rights reserved.
//
import UIKit
class ViaCrusisVC2: GenericContentVC {
var scroll:UIScrollView!
var imgChurch:UIImageView!
var lblTitle:UILabel!
var lblDescription:UILabel!
var lblsemiPray1:UILabel!
var lblPray1:UILabel!
var lblPray2:UILabel!
var lblPray3:UILabel!
var lblText3:UILabel!
var _id:Int!
override func viewDidLoad() {
super.viewDidLoad()
scroll = UIScrollView(frame: self.view.frame)
scroll.backgroundColor = UIColor.clearColor()
scroll.maximumZoomScale = 10
scroll.multipleTouchEnabled = false
self.view.addSubview(scroll)
lblTitle = UILabel(frame: CGRect(x: 15, y: 30, width: self.view.frame.width - 30, height: 45))
lblTitle.text = ((array.objectAtIndex(pageIndex))["TIT"]) as? String
lblTitle.textColor = UIColor.theme2()
lblTitle.textAlignment = NSTextAlignment.Center
lblTitle.font = UIFont.boldFlatFontOfSize(45)
scroll.addSubview(lblTitle)
var txt1 = ((array.objectAtIndex(pageIndex))["ALIAS"]) as? String
lblDescription = UILabel(frame: CGRect(x: 15, y: lblTitle.frame.maxY + 5, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.lightFlatFontOfSize(15), width: self.view.frame.width - 30)))
lblDescription.text = txt1
lblDescription.textColor = UIColor.theme1()
lblDescription.numberOfLines = 0
lblDescription.textAlignment = NSTextAlignment.Center
lblDescription.font = UIFont.lightFlatFontOfSize(15)
scroll.addSubview(lblDescription)
txt1 = ((array.objectAtIndex(pageIndex))["NAME"]) as? String
lblPray1 = UILabel(frame: CGRect(x: 15, y: lblDescription.frame.maxY + 8, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblPray1.text = txt1
lblPray1.textColor = UIColor.themeComplement()
lblPray1.numberOfLines = 0
lblPray1.textAlignment = NSTextAlignment.Center
lblPray1.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblPray1)
lblsemiPray1 = UILabel(frame: CGRect(x: 15, y: lblPray1.frame.maxY + 8, width: self.view.frame.width - 30, height: 45))
lblsemiPray1.text = "Te adoramos, oh Cristo, y te bendecimos. \n Pues por tu santa cruz redimiste al mundo."
lblsemiPray1.textColor = UIColor.theme2()
lblsemiPray1.numberOfLines = 0
lblsemiPray1.textAlignment = NSTextAlignment.Left
lblsemiPray1.font = UIFont.lightFlatFontOfSize(16)
scroll.addSubview(lblsemiPray1)
txt1 = ((array.objectAtIndex(pageIndex))["TEXT1"]) as? String
lblPray2 = UILabel(frame: CGRect(x: 15, y: lblsemiPray1.frame.maxY + 8, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblPray2.text = txt1
lblPray2.textColor = UIColor.theme1()
lblPray2.numberOfLines = 0
lblPray2.textAlignment = NSTextAlignment.Left
lblPray2.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblPray2)
txt1 = ((array.objectAtIndex(pageIndex))["PRAY1"]) as? String
lblPray3 = UILabel(frame: CGRect(x: 15, y: lblPray2.frame.maxY + 10, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblPray3.text = txt1
lblPray3.textColor = UIColor.themeComplement()
lblPray3.numberOfLines = 0
lblPray3.textAlignment = NSTextAlignment.Center
lblPray3.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblPray3)
txt1 = ((array.objectAtIndex(pageIndex))["TEXT2"]) as? String
lblText3 = UILabel(frame: CGRect(x: 15, y: lblPray3.frame.maxY + 10, width: self.view.frame.width - 30, height: heightForView(txt1!, font: UIFont.flatFontOfSize(16), width: self.view.frame.width - 30)))
lblText3.text = txt1
lblText3.textColor = UIColor.theme1()
lblText3.numberOfLines = 0
lblText3.textAlignment = NSTextAlignment.Left
lblText3.font = UIFont.flatFontOfSize(16)
scroll.addSubview(lblText3)
scroll.contentSize = CGSize(width: 320, height: lblText3.frame.maxY + 100)
}
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
| gpl-2.0 |
kuruvilla6970/Zoot | Source/JS API/Dialog.swift | 1 | 974 | //
// Dialog.swift
// THGHybridWeb
//
// Created by Angelo Di Paolo on 7/30/15.
// Copyright (c) 2015 TheHolyGrail. All rights reserved.
//
import JavaScriptCore
@objc class Dialog: NSObject {
var dialogAlert: DialogAlert?
func show(options: [String: AnyObject], callback: JSValue) {
switch DialogOptions.resultOrErrorWithOptions(options) {
case .Success(let box):
dispatch_async(dispatch_get_main_queue()) {
let dialogOptions = box.value
self.dialogAlert = DialogAlert(dialogOptions: dialogOptions)
self.dialogAlert?.show { buttonIndex in
if let action = dialogOptions.actionAtIndex(buttonIndex) {
callback.callWithData(action)
}
}
}
case .Failure(let error):
callback.callWithErrorMessage(error.message)
}
}
}
| mit |
keygx/E2 | E2/E2.Queue.swift | 1 | 240 | //
// E2.Queue.swift
// E2Sample
//
// Created by keygx on 2016/10/10.
// Copyright © 2016年 keygx. All rights reserved.
//
import Foundation
extension E2 {
public enum Queue: Int {
case main
case global
}
}
| mit |
sonsongithub/numsw | Playgrounds/MatrixTextRenderer.swift | 1 | 806 | //
// MatrixTextRenderer.swift
// sandbox
//
// Created by sonson on 2017/03/14.
// Copyright © 2017年 sonson. All rights reserved.
//
import Foundation
import CoreGraphics
#if SANDBOX_APP
import numsw
#endif
#if os(iOS)
public class MatrixTextRenderer: TextRenderer {
let matrix: Matrix<Double>
public init(_ aMatrix: Matrix<Double>) {
matrix = aMatrix
var string = "\(aMatrix.rows)x\(aMatrix.columns)\n"
for i in 0..<aMatrix.rows {
let s: [String] = (0..<aMatrix.columns).map({ aMatrix.elements[i * aMatrix.columns + $0] }).flatMap({ String($0) })
let r = s.joined(separator: ", ")
string += "[ \(r) ]\n"
}
super.init(string)
}
private var compositer: CompositeRenderer?
}
#endif
| mit |
designatednerd/SwiftSnake-tvOS | SwiftSnake/SwiftSnake/GameLogicControllers/PieceToDisplay.swift | 2 | 239 | //
// PieceToDisplay.swift
// SwiftSnake
//
// Created by Ellen Shapiro (Vokal) on 9/24/15.
// Copyright © 2015 Vokal. All rights reserved.
//
import Foundation
enum PieceToDisplay {
case
SnakeHead,
SnakeBody,
Food
} | mit |
volodg/LotterySRV | Sources/App/Models/Lottery.swift | 1 | 3203 | import Vapor
import FluentProvider
import HTTP
import Node
final class Lottery: Model {
static var entity = "lotteries"
let storage = Storage()
/// The content of the lottery
var name: String
var url: String
var path: String
var lastResultsUpdateTime: Date
/// Creates a new Post
init(name: String, url: String, path: String, lastResultsUpdateTime: Date) {
self.name = name
self.url = url
self.path = path
self.lastResultsUpdateTime = lastResultsUpdateTime
}
// MARK: Fluent Serialization
/// Initializes the Post from the
/// database row
init(row: Row) throws {
name = try row.get("name")
url = try row.get("url")
path = try row.get("path")
lastResultsUpdateTime = try row.get("last_results_update_time")
}
// Serializes the Post to the database
func makeRow() throws -> Row {
var row = Row()
try row.set("name", name)
try row.set("url", url)
try row.set("path", path)
try row.set("last_results_update_time", lastResultsUpdateTime)
return row
}
}
// MARK: Fluent Preparation
extension Lottery: Preparation {
/// Prepares a table/collection in the database
/// for storing Posts
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string("name")
builder.string("url")
builder.string("path", length: nil, optional: false, unique: true, default: nil)
builder.date("last_results_update_time", optional: true, unique: false, default: nil)
}
try setupInitialValues(database)
}
private static func setupInitialValues(_ database: Database) throws {
let config = try Config()
struct SetupError: Error {
let description: String
}
let path = config.resourcesDir + "/" + "lotteries.json"
let json = try readJSON(path: path)
guard let lotteries = json["data"]?.array else {
throw SetupError(description: "no lotteries config")
}
let models = try lotteries.map { data -> Lottery in
let json = JSON(data)
let result = try Lottery(json: json)
return result
}
try models.forEach { entity in
try entity.save()
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSON
// How the model converts from / to JSON.
// For example when:
// - Creating a new Post (POST /posts)
// - Fetching a post (GET /posts, GET /posts/:id)
//
extension Lottery: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
name: json.get("name"),
url: json.get("url"),
path: json.get("path"),
lastResultsUpdateTime: Date(timeIntervalSince1970: 0)
)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("name", name)
try json.set("url", url)
try json.set("path", path)
try json.set("last_results_update_time", lastResultsUpdateTime.timeIntervalSince1970)
return json
}
}
// MARK: HTTP
// This allows Post models to be returned
// directly in route closures
extension Lottery: ResponseRepresentable { }
| mit |
slicedev/slice-ios | SliceSDK/Framework/Source/Public/Foundation+Extensions.swift | 1 | 308 | //
// Foundation+Extensions.swift
// SliceSDK
//
import Foundation
public func dispatchMain(delay: Double, block: () -> Void) {
let nanoDelay = delay * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(nanoDelay))
dispatch_after(time, dispatch_get_main_queue(), block)
}
| mit |
awslabs/lambda-refarch-mobilebackend | ios-sample/MobileBackendIOS/AddNoteViewController.swift | 1 | 812 | //
// ViewController.swift
// MobileBackendIOS
//
import Foundation
import UIKit
import MobileCoreServices
class AddNoteViewController: UIViewController {
@IBOutlet weak var headlineTextField: UITextField!
@IBOutlet weak var noteTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
MobileBackendApi.sharedInstance.configureNoteApi()
}
@IBAction func saveNoteButtonPressed(sender: UIButton) {
if(headlineTextField.text != nil && noteTextField.text != nil) {
MobileBackendApi.sharedInstance.postNote(headlineTextField.text!, text: noteTextField.text!)
headlineTextField.text = nil
noteTextField.text = nil
} else {
print("Error text fields are nil")
}
}
}
| apache-2.0 |
carsonmcdonald/TinyPNGForMac | TinyPNG/Config.swift | 1 | 319 | import Foundation
struct Config {
struct Notification {
static let FileDrop = "kFileDropNotification"
static let FileDetailSelected = "kFileDetailSelectedNotification"
}
struct Preferences {
static let MaxConnections = "max_connections"
static let APIKey = "api_key"
}
} | mit |
aotian16/SwiftColor | SwiftColor/SwiftColorTests/SwiftColorTests.swift | 1 | 979 | //
// SwiftColorTests.swift
// SwiftColorTests
//
// Created by 童进 on 15/10/29.
// Copyright © 2015年 qefee. All rights reserved.
//
import XCTest
@testable import SwiftColor
class SwiftColorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/19346-swift-constraints-constraintsystem-simplifyrestrictedconstraint.swift | 11 | 250 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S<d {
{
}
class b
{
}
class n {
func a<T: a {
}
}
var f = b
class b
var b
| mit |
DopamineLabs/DopamineKit-iOS | Example/Tests/Mocks/MockBKRefreshCartridgeContainer.swift | 1 | 507 | //
// MockBKRefreshCartridgeContainer.swift
// BoundlessKit_Example
//
// Created by Akash Desai on 5/2/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
@testable import BoundlessKit
class MockBKRefreshCartridgeContainer : BKRefreshCartridgeContainer {
override init(cartridges: [String : BKRefreshCartridge] = [:]) {
super.init(cartridges: cartridges)
self.cartridges[MockBKRefreshCartridge.actionID] = MockBKRefreshCartridge.allRewards
}
}
| mit |
Fenrikur/ef-app_ios | EurofurenceTests/Presenter Tests/Dealer Detail/Test Doubles/StubDealerDetailSceneFactory.swift | 1 | 281 | @testable import Eurofurence
import EurofurenceModel
import UIKit
class StubDealerDetailSceneFactory: DealerDetailSceneFactory {
let scene = CapturingDealerDetailScene()
func makeDealerDetailScene() -> UIViewController & DealerDetailScene {
return scene
}
}
| mit |
xmartlabs/Swift-Project-Template | Project-iOS/XLProjectName/XLProjectName/Helpers/Helpers.swift | 1 | 719 | //
// Helpers.swift
// XLProjectName
//
// Created by XLAuthorName ( XLAuthorWebsite )
// Copyright © 2016 'XLOrganizationName'. All rights reserved.
//
import Foundation
func DEBUGLog(_ message: String, file: String = #file, line: Int = #line, function: String = #function) {
#if DEBUG
let fileURL = NSURL(fileURLWithPath: file)
let fileName = fileURL.deletingPathExtension?.lastPathComponent ?? ""
print("\(Date().dblog()) \(fileName)::\(function)[L:\(line)] \(message)")
#endif
// Nothing to do if not debugging
}
func DEBUGJson(_ value: AnyObject) {
#if DEBUG
if Constants.Debug.jsonResponse {
// print(JSONStringify(value))
}
#endif
}
| mit |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/UI/AnimatedButton/PXProgressView.swift | 1 | 3197 | import Foundation
protocol ProgressViewDelegate: AnyObject {
func didFinishProgress()
func progressTimeOut()
}
final class ProgressView: UIView {
private var timer: Timer?
private let progressAlpha: CGFloat = 0.35
private var deltaIncrementFraction: CGFloat = 6
private let progressViewHeight: CGFloat
private let progressViewEndX: CGFloat
private var progressViewDeltaIncrement: CGFloat = 0
private let timeOut: TimeInterval
private let timerInterval: TimeInterval = 0.6
private var timerCounter = 0
weak var progressDelegate: ProgressViewDelegate?
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(forView: UIView, loadingColor: UIColor = UIColor.white, timeOut: TimeInterval = 15) {
progressViewHeight = forView.frame.height
progressViewEndX = forView.frame.width
deltaIncrementFraction = CGFloat(timeOut * 0.4)
self.timeOut = timeOut
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: progressViewHeight))
self.backgroundColor = loadingColor
self.layer.cornerRadius = forView.layer.cornerRadius
self.alpha = progressAlpha
forView.layer.masksToBounds = true
forView.addSubview(self)
initTimer(everySecond: timerInterval, customSelector: #selector(ProgressView.increment))
}
@objc fileprivate func increment() {
timerCounter += 1
let incompleteWidth = self.progressViewEndX - self.frame.width
let newWidth = self.frame.width + incompleteWidth / deltaIncrementFraction
let newFrame = CGRect(x: 0, y: 0, width: (newWidth), height: self.frame.height)
UIView.animate(withDuration: 0.3, animations: { [weak self] in
self?.frame = newFrame
}, completion: { [weak self] _ in
guard let self = self else { return }
if Double(self.timerCounter) * self.timerInterval > self.timeOut {
self.stopTimer()
self.progressDelegate?.progressTimeOut()
}
})
}
}
// MARK: Timer.
extension ProgressView {
fileprivate func initTimer(everySecond: TimeInterval = 0.5, customSelector: Selector) {
timer = Timer.scheduledTimer(timeInterval: everySecond, target: self, selector: customSelector, userInfo: nil, repeats: true)
}
func stopTimer() {
timer?.invalidate()
timer = nil
}
}
// MARK: Public methods.
extension ProgressView {
func doReset() {
let newFrame = CGRect(x: 0, y: 0, width: 0, height: self.frame.height)
self.frame = newFrame
}
func doComplete(completion: @escaping (_ finish: Bool) -> Void) {
let newFrame = CGRect(x: 0, y: 0, width: progressViewEndX, height: self.frame.height)
UIView.animate(withDuration: 0.5, animations: { [weak self] in
self?.frame = newFrame
}, completion: { [weak self] _ in
guard let self = self else { return }
self.stopTimer()
self.progressDelegate?.didFinishProgress()
completion(true)
})
}
}
| mit |
leoru/Brainstorage | Brainstorage-iOS/Classes/Controllers/Base/BaseTabBarViewController.swift | 1 | 1023 | //
// BaseTabBarViewController.swift
// Brainstorage-iOS
//
// Created by Kirill Kunst on 04.02.15.
// Copyright (c) 2015 Kirill Kunst. All rights reserved.
//
import UIKit
class BaseTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.tabBar.barTintColor = UIColor.whiteColor();
self.tabBar.tintColor = bs_redColor;
self.tabBar.backgroundColor = UIColor.whiteColor();
self.tabBar.shadowImage = UIImage(named: "tabBar_Border");
self.tabBar.translucent=false;
var offset = UIOffset(horizontal: 0, vertical: -4);
(self.tabBar.items![0] as! UITabBarItem).selectedImage = UIImage(named: "vacancy_active");
(self.tabBar.items![0] as! UITabBarItem).setTitlePositionAdjustment(offset);
(self.tabBar.items![1] as! UITabBarItem).selectedImage = UIImage(named: "about_active");
(self.tabBar.items![1] as! UITabBarItem).setTitlePositionAdjustment(offset);
}
}
| mit |
jorgeluis11/EmbalsesPR | Embalses/DetailViewController.swift | 1 | 3789 | //
// ViewController.swift
// Embalses
//
// Created by Jorge Perez on 9/28/15.
// Copyright © 2015 Jorge Perez. All rights reserved.
//
import UIKit
import Kanna
import Charts
class DetailViewController: UIViewController {
@IBOutlet var barChartView: BarChartView!
var county:String?
var date:String?
var meters:String?
var niveles:[Double]?
@IBOutlet var labelWater: UILabel!
var chartData = [899.56]
@IBOutlet var navigationBar: UINavigationBar!
@IBAction func backButton(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
print("Sdf")
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
override func unwindForSegue(unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {
}
override func viewDidLoad() {
super.viewDidLoad()
// navigationBar.ba = backButton
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]
setChart(months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)
if let niveles = niveles{
var ll = ChartLimitLine(limit: niveles[0], label: "Desborde")
// ll.setLineColor(Color.RED);
//
//
// ll.setLineWidth(4f);
// ll.setTextColor(Color.BLACK);
// ll.setTextSize(12f);
barChartView.rightAxis.addLimitLine(ll)
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[1], label: "Seguridad"))
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[2], label: "Obervación"))
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[3], label: "Ajustes Operacionales"))
barChartView.rightAxis.addLimitLine(ChartLimitLine(limit: niveles[4], label: "Control"))
// var xAxis:ChartYAxis = barChartView.getAxis(ChartYAxis(position: 34.34))
// LimitLine ll = new LimitLine(140f, "Critical Blood Pressure");
// ll.setLineColor(Color.RED);
// ll.setLineWidth(4f);
// ll.setTextColor(Color.BLACK);
// ll.setTextSize(12f);
// .. and more styling options
//
// leftAxis.addLimitLine(ll);
}
barChartView.noDataText = "You need to provide data for the chart."
let meterDouble:Double = Double(self.meters!)!
let dataEntries: [BarChartDataEntry] = [BarChartDataEntry(value: meterDouble, xIndex: 0)]
let dataPoints2 = [self.county]
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Agua en Metros")
let chartData = BarChartData(xVals: dataPoints2, dataSet: chartDataSet)
barChartView.data = chartData
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
var newFrame:CGRect = labelWater.frame;
newFrame.origin.y = newFrame.origin.y - 615;
// newFrame.size.height = 181;
newFrame.size.height = 665;
UIView.animateWithDuration(3, animations: {
self.labelWater.frame = newFrame
})
}
}
| mit |
iluuu1994/2048 | 2048/Classes/GameObject.swift | 1 | 448 | //
// GameObjct.swift
// 2048
//
// Created by Ilija Tovilo on 05/08/14.
// Copyright (c) 2014 Ilija Tovilo. All rights reserved.
//
import Foundation
public class GameObject: CCResponder {
public var view: View!
override init() {
super.init()
loadView()
}
internal func loadView() {
// Implemented in subclasses
assert(false, "The loadView method must be overridden!")
}
}
| bsd-3-clause |
rmclea21/Flappy-Santa | FlappyBird/AppDelegate.swift | 1 | 2136 | //
// AppDelegate.swift
// Flappy Santa
//
// Created by pmst on 15/10/4.
// Copyright © 2015年 pmst. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
ChrisAU/CardinalHashMap | CardinalHashMap/CardinalHashMap/CardinalHashMap+Collector.swift | 1 | 2807 | //
// CardinalHashMap+Collector.swift
// CardinalHashMap
//
// Created by Chris Nevin on 1/04/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import Foundation
extension CardinalHashMap {
private func loop(start: T, directions: [CardinalDirection], seeded: Bool, `while`: ((T) -> Bool)? = nil) -> [T] {
var buffer = [T]()
if self[start] == nil {
return buffer
}
if `while` == nil || `while`?(start) == true {
buffer.append(start)
}
for direction in directions {
if let nextObject = self[start, direction] {
buffer += loop(nextObject, directions: seeded ? directions : [direction], seeded: seeded, while: `while`)
}
}
return Array(Set(buffer))
}
/// Perform the seed fill (or flood fill) algorithm in a given number of directions.
/// - parameter start: Object to start from.
/// - parameter directions: `CardinalDirection` array, each item that is found will fill in these directions as well.
/// - parameter while (Optional): Only iterate while this function is true.
/// - returns: Unsorted items that were found.
public func seedFill(start: T, directions: [CardinalDirection], `while`: ((T) -> Bool)? = nil) -> [T] {
return loop(start, directions: directions, seeded: true, while: `while`)
}
/// Iterate in direction as long as `while` passes and it is possible to navigate in that direction.
/// - parameter start: First object to validate and iterate from.
/// - parameter direction: `CardinalDirection` to travel in.
/// - parameter while (Optional): Validate `object`, if `false` is returned function will exit and return. If not specified or nil is specified it will assume `true`.
/// - returns: `object` and all other objects in that direction that pass `while` validation.
public func collect(start: T, direction: CardinalDirection, `while`: ((T) -> Bool)? = nil) -> [T] {
return collect(start, directions: [direction], while: `while`)
}
/// Iterate in direction as long as `while` passes and it is possible to navigate in each direction given.
/// - parameter start: First object to validate and iterate from.
/// - parameter directions: `CardinalDirection` array.
/// - parameter while (Optional): Validate `object`, if `false` is returned function will exit and return. If not specified or nil is specified it will assume `true`.
/// - returns: `object` and all other objects in given directions that pass `while` validation.
public func collect(start: T, directions: [CardinalDirection], `while`: ((T) -> Bool)? = nil) -> [T] {
return loop(start, directions: directions, seeded: false, while: `while`)
}
} | mit |
NunoAlexandre/broccoli_mobile | ios/Carthage/Checkouts/Eureka/Tests/HiddenRowsTests.swift | 2 | 13121 | // HiddenRowsTests.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Eureka
class HiddenRowsTests: BaseEurekaTests {
var form : Form!
let row10 = IntRow("int1_hrt"){
$0.hidden = "$IntRow_s1 > 23"
}
let row11 = TextRow("txt1_hrt"){
$0.hidden = .function(["NameRow_s1"], { form in
if let r1 : NameRow = form.rowBy(tag: "NameRow_s1") {
return r1.value?.contains(" is ") ?? false
}
return false
})
}
let sec2 = Section("Whatsoever") {
$0.tag = "s3_hrt"
$0.hidden = "$NameRow_s1 contains 'God'"
}
let row20 = TextRow("txt2_hrt"){
$0.hidden = .function(["IntRow_s1", "NameRow_s1"], { form in
if let r1 : IntRow = form.rowBy(tag: "IntRow_s1"), let r2 : NameRow = form.rowBy(tag: "NameRow_s1") {
return r1.value == 88 || r2.value?.hasSuffix("real") ?? false
}
return false
})
}
let inlineDateRow21 = DateInlineRow() {
$0.hidden = "$IntRow_s1 > 23"
}
override func setUp() {
super.setUp()
form = shortForm
+++ row10
<<< row11
+++ sec2
<<< row20
<<< inlineDateRow21
}
func testAddRowToObserver(){
let intDep = form.rowObservers["IntRow_s1"]?[.hidden]
let nameDep = form.rowObservers["NameRow_s1"]?[.hidden]
// make sure we can unwrap
XCTAssertNotNil(intDep)
XCTAssertNotNil(nameDep)
// test rowObservers
XCTAssertEqual(intDep!.count, 3)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains(where: { $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains(where: { $0.tag == "int1_hrt" }))
//This should not change when some rows hide ...
form[0][0].baseValue = "God is real"
form[0][1].baseValue = 88
//check everything is still the same
XCTAssertEqual(intDep!.count, 3)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains(where: { $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains(where: { $0.tag == "int1_hrt" }))
// ...nor if they reappear
form[0][0].baseValue = "blah blah blah"
form[0][1].baseValue = 1
//check everything is still the same
XCTAssertEqual(intDep!.count, 3)
XCTAssertEqual(nameDep!.count, 3)
XCTAssertTrue(intDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(intDep!.contains(where: { $0.tag == "int1_hrt" }))
XCTAssertFalse(intDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt2_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "s3_hrt" }))
XCTAssertTrue(nameDep!.contains(where: { $0.tag == "txt1_hrt" }))
XCTAssertFalse(nameDep!.contains(where: { $0.tag == "int1_hrt" }))
// Test a condition with nil
let newRow = TextRow("new_row") {
$0.hidden = "$txt1_hrt == nil"
}
form.last! <<< newRow
XCTAssertTrue(newRow.hiddenCache)
}
func testItemsByTag(){
// test that all rows and sections with tag are there
XCTAssertEqual(form.rowBy(tag: "NameRow_s1"), form[0][0])
XCTAssertEqual(form.rowBy(tag: "IntRow_s1"), form[0][1])
XCTAssertEqual(form.rowBy(tag: "int1_hrt"), row10)
XCTAssertEqual(form.rowBy(tag: "txt1_hrt"), row11)
XCTAssertEqual(form.sectionBy(tag: "s3_hrt"), sec2)
XCTAssertEqual(form.rowBy(tag: "txt2_hrt"), row20)
// check that these are all in there
XCTAssertEqual(form.rowsByTag.count, 5)
// what happens after hiding the rows? Let's cause havoc
form[0][0].baseValue = "God is real"
form[0][1].baseValue = 88
// we still want the same results here
XCTAssertEqual(form.rowBy(tag: "NameRow_s1"), form[0][0])
XCTAssertEqual(form.rowBy(tag: "IntRow_s1"), form[0][1])
XCTAssertEqual(form.rowBy(tag: "int1_hrt"), row10)
XCTAssertEqual(form.rowBy(tag: "txt1_hrt"), row11)
XCTAssertEqual(form.sectionBy(tag: "s3_hrt"), sec2)
XCTAssertEqual(form.rowBy(tag: "txt2_hrt"), row20)
XCTAssertEqual(form.rowsByTag.count, 5)
// and let them come up again
form[0][0].baseValue = "blah blah"
form[0][1].baseValue = 1
// we still want the same results here
XCTAssertEqual(form.rowsByTag["NameRow_s1"], form[0][0])
XCTAssertEqual(form.rowsByTag["IntRow_s1"], form[0][1])
XCTAssertEqual(form.rowsByTag["int1_hrt"], row10)
XCTAssertEqual(form.rowsByTag["txt1_hrt"], row11)
XCTAssertEqual(form.sectionBy(tag: "s3_hrt"), sec2)
XCTAssertEqual(form.rowsByTag["txt2_hrt"], row20)
XCTAssertEqual(form.rowsByTag.count, 5)
}
func testCorrectValues(){
//initial empty values (none is hidden)
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 2)
// false values
form[0][0].baseValue = "Hi there"
form[0][1].baseValue = 15
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 2)
// hide 'int1_hrt' row
form[0][1].baseValue = 24
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 1)
XCTAssertEqual(sec2.count, 1)
XCTAssertEqual(form[1][0].tag, "txt1_hrt")
// hide 'txt1_hrt' and 'txt2_hrt'
form[0][0].baseValue = " is real"
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
XCTAssertEqual(sec2.count, 0)
// let the last section disappear
form[0][0].baseValue = "God is real"
XCTAssertEqual(form.count, 2)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
// and see if they come back to live
form[0][0].baseValue = "blah"
form[0][1].baseValue = 2
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(sec2.count, 2)
}
func testInlineRows(){
//initial empty values (none is hidden)
XCTAssertEqual(sec2.count, 2)
// change dependency value
form[0][1].baseValue = 25
XCTAssertEqual(sec2.count, 1)
// change dependency value
form[0][1].baseValue = 10
XCTAssertEqual(sec2.count, 2)
//hide inline row when expanded
inlineDateRow21.expandInlineRow()
// check that the row is expanded
XCTAssertEqual(sec2.count, 3)
// hide expanded inline row
form[0][1].baseValue = 25
XCTAssertEqual(sec2.count, 1)
// make inline row visible again
form[0][1].baseValue = 10
XCTAssertEqual(sec2.count, 2)
}
func testHiddenSections(){
let s1 = Section(){
$0.hidden = "$NameRow_s1 contains 'hello'"
$0.tag = "s1_ths"
}
let s2 = Section(){
$0.hidden = "$NameRow_s1 contains 'morning'"
$0.tag = "s2_ths"
}
form.insert(s1, at: 1)
form.insert(s2, at: 3)
/* what we should have here
shortForm (1 section)
s1
{ row10, row11 }
s2
sec2 (2 rows)
*/
XCTAssertEqual(form.count, 5)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 0)
XCTAssertEqual(form[2].count, 2)
XCTAssertEqual(form[3].count, 0)
XCTAssertEqual(form[4].count, 2)
form[0][0].baseValue = "hello, good morning!"
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(form[2].count, 2)
form[0][0].baseValue = "whatever"
XCTAssertEqual(form.count, 5)
XCTAssertEqual(form[1].tag, "s1_ths")
XCTAssertEqual(form[3].tag, "s2_ths")
XCTAssertEqual(form[4].tag, "s3_hrt")
}
func testInsertionIndex(){
let r1 = CheckRow("check1_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'morning'" }
let r2 = CheckRow("check2_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'morning'" }
let r3 = CheckRow("check3_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'good'" }
let r4 = CheckRow("check4_tii_hrt"){ $0.hidden = "$NameRow_s1 contains 'good'" }
form[0].insert(r1, at: 1)
form[1].insert(contentsOf: [r2,r3], at: 0)
//test correct insert
XCTAssertEqual(form[0].count, 3)
XCTAssertEqual(form[0][1].tag, "check1_tii_hrt")
XCTAssertEqual(form[1].count, 4)
XCTAssertEqual(form[1][0].tag, "check2_tii_hrt")
XCTAssertEqual(form[1][1].tag, "check3_tii_hrt")
// hide these rows
form[0][0].baseValue = "hello, good morning!"
// insert another row
form[1].insert(r4, at: 1)
XCTAssertEqual(form[1].count, 2) // all inserted rows should be hidden
XCTAssertEqual(form[1][0].tag, "int1_hrt")
XCTAssertEqual(form[1][1].tag, "txt1_hrt")
form[0][0].baseValue = "whatever"
// we inserted r4 at index 1 but there were two rows hidden before it as well so it shall be at index 3
XCTAssertEqual(form[1].count, 5)
XCTAssertEqual(form[1][0].tag, "check2_tii_hrt")
XCTAssertEqual(form[1][1].tag, "check3_tii_hrt")
XCTAssertEqual(form[1][2].tag, "int1_hrt")
XCTAssertEqual(form[1][3].tag, "check4_tii_hrt")
XCTAssertEqual(form[1][4].tag, "txt1_hrt")
form[0][0].baseValue = "hello, good morning!"
//check that hidden rows get removed as well
form[1].removeAll()
//inserting 2 rows at the end, deleting 1
form[2].replaceSubrange(1..<2, with: [r2, r4])
XCTAssertEqual(form[1].count, 0)
XCTAssertEqual(form[2].count, 1)
XCTAssertEqual(form[2][0].tag, "txt2_hrt")
form[0][0].baseValue = "whatever"
XCTAssertEqual(form[2].count, 3)
XCTAssertEqual(form[2][0].tag, "txt2_hrt")
XCTAssertEqual(form[2][1].tag, "check2_tii_hrt")
XCTAssertEqual(form[2][2].tag, "check4_tii_hrt")
}
}
| mit |
glassonion1/RxStoreKit | Sources/RxStoreKit/SKReceiptRefreshRequestDelegateProxy.swift | 1 | 1478 | //
// SKReceiptRefreshRequestDelegateProxy.swift
// Pods-Example
//
// Created by François Boulais on 16/12/2017.
//
import StoreKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
public class SKReceiptRefreshRequestDelegateProxy
: DelegateProxy<SKReceiptRefreshRequest, SKRequestDelegate>
, DelegateProxyType
, SKRequestDelegate {
public init(parentObject: SKReceiptRefreshRequest) {
super.init(parentObject: parentObject, delegateProxy: SKReceiptRefreshRequestDelegateProxy.self)
}
public static func registerKnownImplementations() {
self.register { SKReceiptRefreshRequestDelegateProxy(parentObject: $0) }
}
public static func currentDelegate(for object: SKReceiptRefreshRequest) -> SKRequestDelegate? {
return object.delegate
}
public static func setCurrentDelegate(_ delegate: SKRequestDelegate?, to object: SKReceiptRefreshRequest) {
object.delegate = delegate
}
let responseSubject = PublishSubject<SKProductsResponse>()
public func requestDidFinish(_ request: SKRequest) {
_forwardToDelegate?.requestDidFinish?(request)
responseSubject.onCompleted()
}
public func request(_ request: SKRequest, didFailWithError error: Error) {
_forwardToDelegate?.request?(request, didFailWithError: error)
responseSubject.onError(error)
}
deinit {
responseSubject.on(.completed)
}
}
| mit |
ahoppen/swift | test/SILGen/objc_imported_generic.swift | 2 | 7899 |
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic %s | %FileCheck %s
// For integration testing, ensure we get through IRGen too.
// RUN: %target-swift-emit-ir(mock-sdk: %clang-importer-sdk) -module-name objc_imported_generic -verify -DIRGEN_INTEGRATION_TEST %s
// REQUIRES: objc_interop
import objc_generics
func callInitializer() {
_ = GenericClass(thing: NSObject())
}
// CHECK-LABEL: sil shared [serialized] [ossa] @$sSo12GenericClassC5thingAByxGSgxSg_tcfC
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
return o.thing!()!
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C17MethodOnAnyObject{{[_0-9a-zA-Z]*}}F
// CHECK: objc_method {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!foreign : <T where T : AnyObject> (GenericClass<T>) -> () -> T?, $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>
public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? {
return o.thing?()
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF
// CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '$s21objc_imported_generic0C24MethodOnAnyObjectChained1o1byXlSgyXl_SbtF'
public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
return o[0 as UInt16]
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF
// CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]] : $AnyObject to $@opened([[TAG:.*]]) AnyObject
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG]]) AnyObject, #GenericClass.subscript!getter.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
// CHECK: } // end sil function '$s21objc_imported_generic0C20SubscriptOnAnyObject1o1byXlSgyXl_SbtF'
public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
return o.propertyThing
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF
// CHECK: bb0([[ANY:%.*]] : @guaranteed $AnyObject, [[BOOL:%.*]] : $Bool):
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.foreign, bb1
// CHECK: bb1({{%.*}} : $@convention(objc_method) (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '$s21objc_imported_generic0C19PropertyOnAnyObject1o1byXlSgSgyXl_SbtF'
public protocol ThingHolder {
associatedtype Thing
init!(thing: Thing!)
func thing() -> Thing?
func arrayOfThings() -> [Thing]
func setArrayOfThings(_: [Thing])
static func classThing() -> Thing?
var propertyThing: Thing? { get set }
var propertyArrayOfThings: [Thing]? { get set }
}
public protocol Ansible: class {
associatedtype Anser: ThingHolder
}
public func genericBlockBridging<T: Ansible>(x: GenericClass<T>) {
let block = x.blockForPerformingOnThings()
x.performBlock(onThings: block)
}
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic0C13BlockBridging{{[_0-9a-zA-Z]*}}F
// CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @$sxxIeyBya_xxIeggo_21objc_imported_generic7AnsibleRzlTR
// CHECK: partial_apply [callee_guaranteed] [[BLOCK_TO_FUNC]]<T>
// CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @$sxxIeggo_xxIeyBya_21objc_imported_generic7AnsibleRzlTR
// CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T>
// CHECK-LABEL: sil [ossa] @$s21objc_imported_generic20arraysOfGenericParam{{[_0-9a-zA-Z]*}}F
public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
// CHECK: function_ref @$sSo12GenericClassC13arrayOfThingsAByxGSgSayxG_tcfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>>
let x = GenericClass<T>(arrayOfThings: y)!
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
x.setArrayOfThings(y)
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray>
_ = x.propertyArrayOfThings
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> ()
x.propertyArrayOfThings = y
}
// CHECK-LABEL: sil private [ossa] @$s21objc_imported_generic0C4FuncyyxmRlzClFyycfU_ : $@convention(thin) <V where V : AnyObject> () -> () {
// CHECK: [[META:%.*]] = metatype $@thick GenericClass<V>.Type
// CHECK: [[INIT:%.*]] = function_ref @$sSo12GenericClassCAByxGycfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@thick GenericClass<τ_0_0>.Type) -> @owned GenericClass<τ_0_0>
// CHECK: apply [[INIT]]<V>([[META]])
// CHECK: return
func genericFunc<V: AnyObject>(_ v: V.Type) {
let _ = {
var _ = GenericClass<V>()
}
}
// CHECK-LABEL: sil hidden [ossa] @$s21objc_imported_generic23configureWithoutOptionsyyF : $@convention(thin) () -> ()
// CHECK: enum $Optional<Dictionary<GenericOption, Any>>, #Optional.none!enumelt
// CHECK: return
func configureWithoutOptions() {
_ = GenericClass<NSObject>(options: nil)
}
// CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$sSo12GenericClassC13arrayOfThingsAByxGSgSayxG_tcfcTO
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>>
// foreign to native thunk for init(options:), uses GenericOption : Hashable
// conformance
// CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$sSo12GenericClassC7optionsAByxGSgSDySo0A6OptionaypGSg_tcfcTO : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>>
// CHECK: [[FN:%.*]] = function_ref @$sSD10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: apply [[FN]]<GenericOption, Any>({{.*}}) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: return
// Make sure we emitted the witness table for the above conformance
// CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
// CHECK: method #Hashable.hashValue!getter: {{.*}}: @$sSo13GenericOptionaSHSCSH9hashValueSivgTW
// CHECK: }
| apache-2.0 |
KeithPiTsui/Pavers | Pavers/Sources/FRP/ReactiveSwift/Scheduler.swift | 2 | 19521 | //
// Scheduler.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Dispatch
import Foundation
#if os(Linux)
import let CDispatch.NSEC_PER_SEC
#endif
/// Represents a serial queue of work items.
public protocol Scheduler: class {
/// Enqueues an action on the scheduler.
///
/// When the work is executed depends on the scheduler in use.
///
/// - parameters:
/// - action: The action to be scheduled.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(_ action: @escaping () -> Void) -> Disposable?
}
/// A particular kind of scheduler that supports enqueuing actions at future
/// dates.
public protocol DateScheduler: Scheduler {
/// The current date, as determined by this scheduler.
///
/// This can be implemented to deterministically return a known date (e.g.,
/// for testing purposes).
var currentDate: Date { get }
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: The start date.
/// - action: A closure of the action to be performed.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, action: @escaping () -> Void) -> Disposable?
/// Schedules a recurring action at the given interval, beginning at the
/// given date.
///
/// - parameters:
/// - date: The start date.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition.
/// - action: A closure of the action to be performed.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable?
}
/// A scheduler that performs all work synchronously.
public final class ImmediateScheduler: Scheduler {
public init() {}
/// Immediately calls passed in `action`.
///
/// - parameters:
/// - action: A closure of the action to be performed.
///
/// - returns: `nil`.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
action()
return nil
}
}
/// A scheduler that performs all work on the main queue, as soon as possible.
///
/// If the caller is already running on the main queue when an action is
/// scheduled, it may be run synchronously. However, ordering between actions
/// will always be preserved.
public final class UIScheduler: Scheduler {
private static let dispatchSpecificKey = DispatchSpecificKey<UInt8>()
private static let dispatchSpecificValue = UInt8.max
private static var __once: () = {
DispatchQueue.main.setSpecific(key: UIScheduler.dispatchSpecificKey,
value: dispatchSpecificValue)
}()
#if os(Linux)
private var queueLength: Atomic<Int32> = Atomic(0)
#else
// `inout` references do not guarantee atomicity. Use `UnsafeMutablePointer`
// instead.
//
// https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161205/004147.html
private let queueLength: UnsafeMutablePointer<Int32> = {
let memory = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
memory.initialize(to: 0)
return memory
}()
deinit {
queueLength.deinitialize(count: 1)
queueLength.deallocate()
}
#endif
/// Initializes `UIScheduler`
public init() {
/// This call is to ensure the main queue has been setup appropriately
/// for `UIScheduler`. It is only called once during the application
/// lifetime, since Swift has a `dispatch_once` like mechanism to
/// lazily initialize global variables and static variables.
_ = UIScheduler.__once
}
/// Queues an action to be performed on main queue. If the action is called
/// on the main thread and no work is queued, no scheduling takes place and
/// the action is called instantly.
///
/// - parameters:
/// - action: A closure of the action to be performed on the main thread.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let positionInQueue = enqueue()
// If we're already running on the main queue, and there isn't work
// already enqueued, we can skip scheduling and just execute directly.
if positionInQueue == 1 && DispatchQueue.getSpecific(key: UIScheduler.dispatchSpecificKey) == UIScheduler.dispatchSpecificValue {
action()
dequeue()
return nil
} else {
let disposable = AnyDisposable()
DispatchQueue.main.async {
defer { self.dequeue() }
guard !disposable.isDisposed else { return }
action()
}
return disposable
}
}
private func dequeue() {
#if os(Linux)
queueLength.modify { $0 -= 1 }
#else
OSAtomicDecrement32(queueLength)
#endif
}
private func enqueue() -> Int32 {
#if os(Linux)
return queueLength.modify { value -> Int32 in
value += 1
return value
}
#else
return OSAtomicIncrement32(queueLength)
#endif
}
}
/// A `Hashable` wrapper for `DispatchSourceTimer`. `Hashable` conformance is
/// based on the identity of the wrapper object rather than the wrapped
/// `DispatchSourceTimer`, so two wrappers wrapping the same timer will *not*
/// be equal.
private final class DispatchSourceTimerWrapper: Hashable {
private let value: DispatchSourceTimer
#if swift(>=4.1.50)
fileprivate func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
#else
fileprivate var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
#endif
fileprivate init(_ value: DispatchSourceTimer) {
self.value = value
}
fileprivate static func ==(lhs: DispatchSourceTimerWrapper, rhs: DispatchSourceTimerWrapper) -> Bool {
// Note that this isn't infinite recursion thanks to `===`.
return lhs === rhs
}
}
/// A scheduler backed by a serial GCD queue.
public final class QueueScheduler: DateScheduler {
/// A singleton `QueueScheduler` that always targets the main thread's GCD
/// queue.
///
/// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a
/// future date, and will always schedule asynchronously (even if
/// already running on the main thread).
public static let main = QueueScheduler(internalQueue: DispatchQueue.main)
public var currentDate: Date {
return Date()
}
public let queue: DispatchQueue
private var timers: Atomic<Set<DispatchSourceTimerWrapper>>
internal init(internalQueue: DispatchQueue) {
queue = internalQueue
timers = Atomic(Set())
}
/// Initializes a scheduler that will target the given queue with its
/// work.
///
/// - note: Even if the queue is concurrent, all work items enqueued with
/// the `QueueScheduler` will be serial with respect to each other.
///
/// - warning: Obsoleted in OS X 10.11
@available(OSX, deprecated:10.10, obsoleted:10.11, message:"Use init(qos:name:targeting:) instead")
@available(iOS, deprecated:8.0, obsoleted:9.0, message:"Use init(qos:name:targeting:) instead.")
public convenience init(queue: DispatchQueue, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler") {
self.init(internalQueue: DispatchQueue(label: name, target: queue))
}
/// Initializes a scheduler that creates a new serial queue with the
/// given quality of service class.
///
/// - parameters:
/// - qos: Dispatch queue's QoS value.
/// - name: A name for the queue in the form of reverse domain.
/// - targeting: (Optional) The queue on which this scheduler's work is
/// targeted
@available(OSX 10.10, *)
public convenience init(
qos: DispatchQoS = .default,
name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler",
targeting targetQueue: DispatchQueue? = nil
) {
self.init(internalQueue: DispatchQueue(
label: name,
qos: qos,
target: targetQueue
))
}
/// Schedules action for dispatch on internal queue
///
/// - parameters:
/// - action: A closure of the action to be scheduled.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let d = AnyDisposable()
queue.async {
if !d.isDisposed {
action()
}
}
return d
}
private func wallTime(with date: Date) -> DispatchWallTime {
let (seconds, frac) = modf(date.timeIntervalSince1970)
let nsec: Double = frac * Double(NSEC_PER_SEC)
let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec))
return DispatchWallTime(timespec: walltime)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: The start date.
/// - action: A closure of the action to be performed.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
let d = AnyDisposable()
queue.asyncAfter(wallDeadline: wallTime(with: date)) {
if !d.isDisposed {
action()
}
}
return d
}
/// Schedules a recurring action at the given interval and beginning at the
/// given start date. A reasonable default timer interval leeway is
/// provided.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - action: Closure of the action to repeat.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return schedule(after: date, interval: interval, leeway: interval * 0.1, action: action)
}
/// Schedules a recurring action at the given interval with provided leeway,
/// beginning at the given start time.
///
/// - precondition: `interval` must be non-negative number.
/// - precondition: `leeway` must be non-negative number.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
precondition(interval.timeInterval >= 0)
precondition(leeway.timeInterval >= 0)
let timer = DispatchSource.makeTimerSource(
flags: DispatchSource.TimerFlags(rawValue: UInt(0)),
queue: queue
)
#if swift(>=4.0)
timer.schedule(wallDeadline: wallTime(with: date),
repeating: interval,
leeway: leeway)
#else
timer.scheduleRepeating(wallDeadline: wallTime(with: date),
interval: interval,
leeway: leeway)
#endif
timer.setEventHandler(handler: action)
timer.resume()
let wrappedTimer = DispatchSourceTimerWrapper(timer)
timers.modify { timers in
timers.insert(wrappedTimer)
}
return AnyDisposable { [weak self] in
timer.cancel()
if let scheduler = self {
scheduler.timers.modify { timers in
timers.remove(wrappedTimer)
}
}
}
}
}
/// A scheduler that implements virtualized time, for use in testing.
public final class TestScheduler: DateScheduler {
private final class ScheduledAction {
let date: Date
let action: () -> Void
init(date: Date, action: @escaping () -> Void) {
self.date = date
self.action = action
}
func less(_ rhs: ScheduledAction) -> Bool {
return date < rhs.date
}
}
private let lock = NSRecursiveLock()
private var _currentDate: Date
/// The virtual date that the scheduler is currently at.
public var currentDate: Date {
let d: Date
lock.lock()
d = _currentDate
lock.unlock()
return d
}
private var scheduledActions: [ScheduledAction] = []
/// Initializes a TestScheduler with the given start date.
///
/// - parameters:
/// - startDate: The start date of the scheduler.
public init(startDate: Date = Date(timeIntervalSinceReferenceDate: 0)) {
lock.name = "org.reactivecocoa.ReactiveSwift.TestScheduler"
_currentDate = startDate
}
private func schedule(_ action: ScheduledAction) -> Disposable {
lock.lock()
scheduledActions.append(action)
scheduledActions.sort { $0.less($1) }
lock.unlock()
return AnyDisposable {
self.lock.lock()
self.scheduledActions = self.scheduledActions.filter { $0 !== action }
self.lock.unlock()
}
}
/// Enqueues an action on the scheduler.
///
/// - note: The work is executed on `currentDate` as it is understood by the
/// scheduler.
///
/// - parameters:
/// - action: An action that will be performed on scheduler's
/// `currentDate`.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: currentDate, action: action))
}
/// Schedules an action for execution after some delay.
///
/// - parameters:
/// - delay: A delay for execution.
/// - action: A closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), action: action)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: A starting date.
/// - action: A closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: date, action: action))
}
/// Schedules a recurring action at the given interval, beginning at the
/// given start date.
///
/// - precondition: `interval` must be non-negative.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - disposable: A disposable.
/// - action: A closure of the action to repeat.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
private func schedule(after date: Date, interval: DispatchTimeInterval, disposable: SerialDisposable, action: @escaping () -> Void) {
precondition(interval.timeInterval >= 0)
disposable.inner = schedule(after: date) { [unowned self] in
action()
self.schedule(after: date.addingTimeInterval(interval), interval: interval, disposable: disposable, action: action)
}
}
/// Schedules a recurring action after given delay repeated at the given,
/// interval, beginning at the given interval counted from `currentDate`.
///
/// - parameters:
/// - delay: A delay for action's dispatch.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: DispatchTimeInterval, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), interval: interval, leeway: leeway, action: action)
}
/// Schedules a recurring action at the given interval with
/// provided leeway, beginning at the given start date.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? {
let disposable = SerialDisposable()
schedule(after: date, interval: interval, disposable: disposable, action: action)
return disposable
}
/// Advances the virtualized clock by an extremely tiny interval, dequeuing
/// and executing any actions along the way.
///
/// This is intended to be used as a way to execute actions that have been
/// scheduled to run as soon as possible.
public func advance() {
advance(by: .nanoseconds(1))
}
/// Advances the virtualized clock by the given interval, dequeuing and
/// executing any actions along the way.
///
/// - parameters:
/// - interval: Interval by which the current date will be advanced.
public func advance(by interval: DispatchTimeInterval) {
lock.lock()
advance(to: currentDate.addingTimeInterval(interval))
lock.unlock()
}
/// Advances the virtualized clock to the given future date, dequeuing and
/// executing any actions up until that point.
///
/// - parameters:
/// - newDate: Future date to which the virtual clock will be advanced.
public func advance(to newDate: Date) {
lock.lock()
assert(currentDate <= newDate)
while scheduledActions.count > 0 {
if newDate < scheduledActions[0].date {
break
}
_currentDate = scheduledActions[0].date
let scheduledAction = scheduledActions.remove(at: 0)
scheduledAction.action()
}
_currentDate = newDate
lock.unlock()
}
/// Dequeues and executes all scheduled actions, leaving the scheduler's
/// date at `Date.distantFuture()`.
public func run() {
advance(to: Date.distantFuture)
}
/// Rewinds the virtualized clock by the given interval.
/// This simulates that user changes device date.
///
/// - parameters:
/// - interval: An interval by which the current date will be retreated.
public func rewind(by interval: DispatchTimeInterval) {
lock.lock()
let newDate = currentDate.addingTimeInterval(-interval)
assert(currentDate >= newDate)
_currentDate = newDate
lock.unlock()
}
}
| mit |
eoger/firefox-ios | Shared/AlertController.swift | 13 | 1002 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
// Subclassed to support accessibility identifiers
public class AlertController: UIAlertController {
private var accessibilityIdentifiers = [UIAlertAction: String]()
public func addAction(_ action: UIAlertAction, accessibilityIdentifier: String) {
super.addAction(action)
accessibilityIdentifiers[action] = accessibilityIdentifier
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// From https://stackoverflow.com/questions/38117410/how-can-i-set-accessibilityidentifier-to-uialertcontroller
for action in actions {
let item = action.value(forKey: "__representer") as? UIView
item?.accessibilityIdentifier = accessibilityIdentifiers[action]
}
}
}
| mpl-2.0 |
cenfoiOS/ImpesaiOSCourse | NewsWithRealm/News/NewsTableViewCell.swift | 2 | 1088 | //
// NewsTableViewCell.swift
// News
//
// Created by Cesar Brenes on 5/23/17.
// Copyright © 2017 César Brenes Solano. All rights reserved.
//
import UIKit
class NewsTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setupCell(news: News){
titleLabel.text = news.titleNews
descriptionLabel.text = news.descriptionNews
dateLabel.text = news.createdAt.toString(dateFormat: "yyyy-MM-dd HH:mm:ss")
}
}
extension Date{
func toString(dateFormat: String ) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: self)
}
}
| mit |
emilstahl/swift | validation-test/compiler_crashers_fixed/0578-swift-type-walk.swift | 13 | 248 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S<T.E == {
class B<I : B<T>
| apache-2.0 |
SquidKit/SquidKit | Examples/SquidKitExample/SquidKitExampleTests/SquidKitExampleTests.swift | 1 | 1997 | //
// SquidKitExampleTests.swift
// SquidKitExampleTests
//
// Created by Mike Leavy on 8/21/14.
// Copyright (c) 2014 SquidKit. All rights reserved.
//
import UIKit
import XCTest
import SquidKit
class SquidKitExampleTests: 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.
}
}
func testCache() {
let stringCache = Cache<NSString, NSString>()
stringCache.insert("foo", key: "a")
stringCache.insert("bar", key: "b")
let a = stringCache.get("a")
let b = stringCache.get("b")
XCTAssertEqual(a, "foo", "key a is not \"foo\"")
XCTAssertEqual(b, "bar", "key b is not \"bar\"")
// test that all caches of type NSString, NSString are the same
let anotherStringCache = Cache<NSString, NSString>()
let anotherA = anotherStringCache["a"]
XCTAssertEqual(anotherA, "foo", "key a is not \"foo\"")
let numberCache = Cache<NSString, NSNumber>()
numberCache.insert(12, key: "12")
numberCache.insert(24, key: "24")
var twelve = numberCache.get("12")
XCTAssertEqual(12, twelve, "cache entry for \"12\" is not 12")
numberCache.remove(forKey: "12")
twelve = numberCache["12"]
XCTAssertNil(twelve, "expected nil result for key \"12\"")
}
}
| mit |
dockwa/EmailPicker | Sources/EmailPicker/EmailPickerCell.swift | 1 | 3777 | import UIKit
class EmailPickerCell: UITableViewCell {
@objc static let height: CGFloat = 60
static var reuseIdentifier: String {
String(describing: self)
}
lazy var thumbnailImageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 20
imageView.layer.masksToBounds = true
return imageView
}()
lazy var label: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 18)
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(thumbnailImageView)
contentView.addSubview(label)
imageViewConstraints()
labelConstraints()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func imageViewConstraints() {
thumbnailImageView.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: thumbnailImageView,
attribute: .top,
relatedBy: .equal,
toItem: contentView,
attribute: .top,
multiplier: 1,
constant: 10)
let leading = NSLayoutConstraint(item: thumbnailImageView,
attribute: .leading,
relatedBy: .equal,
toItem: contentView,
attribute: .leading,
multiplier: 1,
constant: 10)
let centerY = NSLayoutConstraint(item: thumbnailImageView,
attribute: .centerY,
relatedBy: .equal,
toItem: contentView,
attribute: .centerY,
multiplier: 1,
constant: 0)
let width = NSLayoutConstraint(item: thumbnailImageView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 40)
thumbnailImageView.addConstraint(width)
contentView.addConstraints([top, leading, centerY])
}
private func labelConstraints() {
label.translatesAutoresizingMaskIntoConstraints = false
let leading = NSLayoutConstraint(item: label,
attribute: .leading,
relatedBy: .equal,
toItem: thumbnailImageView,
attribute: .trailing,
multiplier: 1,
constant: 10)
let centerY = NSLayoutConstraint(item: label,
attribute: .centerY,
relatedBy: .equal,
toItem: contentView,
attribute: .centerY,
multiplier: 1,
constant: 0)
contentView.addConstraints([leading, centerY])
}
}
| mit |
naoto0822/try-reactive-swift | TrySwiftBond/TrySwiftBond/User.swift | 1 | 599 | //
// User.swift
// TrySwiftBond
//
// Created by naoto yamaguchi on 2016/04/13.
// Copyright © 2016年 naoto yamaguchi. All rights reserved.
//
import UIKit
import Bond
public class User {
// MARK: - Property
public let id: String
public let profileImageURL: String
// MARK: - LifeCycle
init() {
self.id = ""
self.profileImageURL = ""
}
init(dictionary: [String: AnyObject]) {
self.id = dictionary["id"] as? String ?? ""
self.profileImageURL = dictionary["profile_image_url"] as? String ?? ""
}
}
| mit |
FotiosTragopoulos/Anemos | Anemos/ViewController.swift | 1 | 2503 | //
// ViewController.swift
// Anemos
//
// Created by Fotios Tragopoulos on 01/02/2018.
// Copyright © 2018 Fotios Tragopoulos. All rights reserved.
//
import UIKit
import WebKit
import SafariServices
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var backButton: UIBarButtonItem!
@IBOutlet weak var frontButton: UIBarButtonItem!
@IBOutlet weak var searchButton: UIBarButtonItem!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var stopButton: UIBarButtonItem!
var timeBool: Bool!
var timer: Timer!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let url: URL = URL(string: "https://duckduckgo.com")!
let urlRequest: URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
@IBAction func backButtonTapped(_ sender: Any) {
if webView.canGoBack {
webView.goBack()
}
}
@IBAction func frontButtonTapped(_ sender: Any) {
if webView.canGoForward {
webView.goForward()
}
}
@IBAction func searchPage(_ sender: Any) {
viewDidAppear(true)
}
@IBAction func reloadPage(_ sender: Any) {
webView.reload()
}
@IBAction func stopLoading(_ sender: Any) {
webView.stopLoading()
progressBar.isHidden = true
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
backButton.isEnabled = webView.canGoBack
frontButton.isEnabled = webView.canGoForward
progressBar.isHidden = false
progressBar.progress = 0.0
timeBool = false
timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(ViewController.timerCallBack), userInfo: nil, repeats: true)
}
@objc func timerCallBack() {
if timeBool != nil {
if progressBar.progress >= 1 {
progressBar.isHidden = true
timer.invalidate()
} else {
progressBar.progress += 0.1
}
} else {
progressBar.progress += 0.01
if progressBar.progress >= 0.95 {
progressBar.progress = 0.95
}
}
}
}
| mit |
Bartlebys/Bartleby | Inspector/Inspector/InspectorViewController.swift | 1 | 19735 | //
// InspectorViewController.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 15/07/2016.
//
//
import Cocoa
import BartlebyKit
protocol FilterPredicateDelegate {
func filterSelectedIndex()->Int
func filterExpression()->String
}
class InspectorViewController: NSViewController,DocumentDependent,FilterPredicateDelegate{
override var nibName : NSNib.Name { return NSNib.Name("InspectorViewController") }
@IBOutlet var listOutlineView: NSOutlineView!
@IBOutlet var topBox: NSBox!
@IBOutlet var bottomBox: NSBox!
// Provisionned View controllers
@IBOutlet var sourceEditor: SourceEditor!
@IBOutlet var operationViewController: OperationViewController!
@IBOutlet var changesViewController: ChangesViewController!
@IBOutlet var metadataViewController: MetadataDetails!
@IBOutlet var contextualMenu: NSMenu!
@IBOutlet weak var filterPopUp: NSPopUpButton!
@IBOutlet weak var filterField: NSSearchField!
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
return true
}
// The currently associated View Controller
fileprivate var _topViewController:NSViewController?
fileprivate var _bottomViewController:NSViewController?
//MARK:- Menu Actions
@IBAction func resetAllSupervisionCounter(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
documentReference.metadata.currentUser?.changedKeys.removeAll()
documentReference.iterateOnCollections({ (collection) in
if let o = collection as? ManagedModel{
o.changedKeys.removeAll()
}
})
documentReference.superIterate({ (element) in
if let o = element as? ManagedModel{
o.changedKeys.removeAll()
}
})
}
NotificationCenter.default.post(name: Notification.Name(rawValue: DocumentInspector.CHANGES_HAS_BEEN_RESET_NOTIFICATION), object: nil)
}
@IBAction func commitChanges(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
do {
try documentReference.commitPendingChanges()
} catch {
}
}
}
@IBAction func openWebStack(_ sender: AnyObject) {
if let document=self.documentProvider?.getDocument() {
if let url=document.metadata.currentUser?.signInURL(for:document){
NSWorkspace.shared.open(url)
}
}
}
@IBAction func saveDocument(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
documentReference.save(sender)
}
}
@IBAction func deleteOperations(_ sender: AnyObject) {
if let documentReference=self.documentProvider?.getDocument(){
for operation in documentReference.pushOperations.reversed(){
documentReference.pushOperations.removeObject(operation, commit: false)
}
NotificationCenter.default.post(name: Notification.Name(rawValue: REFRESH_METADATA_INFOS_NOTIFICATION_NAME), object: nil)
}
}
@IBAction func cleanupOperationQuarantine(_ sender: AnyObject) {
if let document=self.documentProvider?.getDocument() {
document.metadata.operationsQuarantine.removeAll()
NotificationCenter.default.post(name: Notification.Name(rawValue: REFRESH_METADATA_INFOS_NOTIFICATION_NAME), object: nil)
}
}
@IBAction func forceDataIntegration(_ sender: AnyObject) {
if let document=self.documentProvider?.getDocument(){
document.forceDataIntegration()
NotificationCenter.default.post(name: Notification.Name(rawValue: REFRESH_METADATA_INFOS_NOTIFICATION_NAME), object: nil)
}
}
@IBAction func deleteBSFSOrpheans(_ sender: NSMenuItem) {
if let document=self.documentProvider?.getDocument(){
document.blocks.reversed().forEach({ (block) in
if block.ownedBy.count == 0{
try? block.erase()
}
})
document.nodes.reversed().forEach({ (node) in
if node.ownedBy.count == 0{
try? node.erase()
}
})
document.boxes.reversed().forEach({ (box) in
if box.ownedBy.count == 0{
try? box.erase()
}
})
}
}
@IBAction func deleteSelectedEntity(_ sender: NSMenuItem) {
if let item = self.listOutlineView.item(atRow: self.listOutlineView.selectedRow) as? ManagedModel{
try? item.erase()
}
}
//MARK:- Collections
fileprivate var _collectionListDelegate:CollectionListDelegate?
// MARK - DocumentDependent
internal var documentProvider: DocumentProvider?{
didSet{
if let documentReference=self.documentProvider?.getDocument(){
self._collectionListDelegate=CollectionListDelegate(documentReference:documentReference,filterDelegate:self,outlineView:self.listOutlineView,onSelection: {(selected) in
self.updateRepresentedObject(selected)
})
self._topViewController=self.sourceEditor
self._bottomViewController=self.changesViewController
self.topBox.contentView=self._topViewController!.view
self.bottomBox.contentView=self._bottomViewController!.view
self.listOutlineView.delegate = self._collectionListDelegate
self.listOutlineView.dataSource = self._collectionListDelegate
self._collectionListDelegate?.reloadData()
self.metadataViewController.documentProvider=self.documentProvider
}
}
}
func providerHasADocument() {}
//MARK: - initialization
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidAppear() {
super.viewDidAppear()
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: DocumentInspector.CHANGES_HAS_BEEN_RESET_NOTIFICATION), object: nil, queue: nil) {(notification) in
self._collectionListDelegate?.reloadData()
}
}
override func viewWillDisappear() {
super.viewWillDisappear()
NotificationCenter.default.removeObserver(self)
}
/**
Updates and adapts the children viewControllers to the Represented Object
- parameter selected: the outline selected Object
*/
func updateRepresentedObject(_ selected:Any?) -> () {
if let document=self.documentProvider?.getDocument(){
if selected==nil {
document.log("Represented object is nil", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}else{
glog("Document provider fault", file: #file, function: #function, line: #line, category: Default.LOG_FAULT, decorative: false)
}
if let object=selected as? ManagedModel{
// Did the type of represented object changed.
if object.runTimeTypeName() != (self._bottomViewController?.representedObject as? Collectible)?.runTimeTypeName(){
switch object {
case _ where object is PushOperation :
self._topViewController=self.sourceEditor
self._bottomViewController=self.operationViewController
break
default:
self._topViewController=self.sourceEditor
self._bottomViewController=self.changesViewController
}
}
}else{
// It a UnManagedModel
if let _ = selected as? DocumentMetadata{
self._topViewController=self.sourceEditor
self._bottomViewController=self.metadataViewController
}
}
if let object = selected as? NSObject{
if self.topBox.contentView != self._topViewController!.view{
self.topBox.contentView=self._topViewController!.view
}
if self.bottomBox.contentView != self._bottomViewController!.view{
self.bottomBox.contentView=self._bottomViewController!.view
}
if (self._topViewController?.representedObject as? NSObject) != object{
self._topViewController?.representedObject=object
}
if (self._bottomViewController?.representedObject as? NSObject) != object {
self._bottomViewController?.representedObject=object
}
}
}
// MARK - Filtering
@IBAction func firstPartOfPredicateDidChange(_ sender: Any) {
let idx=self.filterPopUp.indexOfSelectedItem
if idx==0{
self.filterField.isEnabled=false
}else{
self.filterField.isEnabled=true
}
self._collectionListDelegate?.updateFilter()
}
@IBAction func filterOperandDidChange(_ sender: Any) {
self._collectionListDelegate?.updateFilter()
}
// MARK - FilterPredicateDelegate
public func filterSelectedIndex()->Int{
return self.filterPopUp.indexOfSelectedItem
}
public func filterExpression()->String{
return PString.trim(self.filterField.stringValue)
}
}
// MARK: - CollectionListDelegate
class CollectionListDelegate:NSObject,NSOutlineViewDelegate,NSOutlineViewDataSource,Identifiable{
fileprivate var _filterPredicateDelegate:FilterPredicateDelegate
fileprivate var _documentReference:BartlebyDocument
fileprivate var _outlineView:NSOutlineView!
fileprivate var _selectionHandler:((_ selected:Any)->())
fileprivate var _collections:[BartlebyCollection]=[BartlebyCollection]()
fileprivate var _filteredCollections:[BartlebyCollection]=[BartlebyCollection]()
var UID: String = Bartleby.createUID()
required init(documentReference:BartlebyDocument,filterDelegate:FilterPredicateDelegate,outlineView:NSOutlineView,onSelection:@escaping ((_ selected:Any)->())) {
self._documentReference=documentReference
self._outlineView=outlineView
self._selectionHandler=onSelection
self._filterPredicateDelegate=filterDelegate
super.init()
self._documentReference.iterateOnCollections { (collection) in
self._collections.append(collection)
collection.addChangesSuperviser(self, closure: { (key, oldValue, newValue) in
self.reloadData()
})
}
// No Filter by default
self._filteredCollections=self._collections
}
public func updateFilter(){
let idx=self._filterPredicateDelegate.filterSelectedIndex()
let expression=self._filterPredicateDelegate.filterExpression()
if (idx == 0 || expression=="" && idx < 8){
self._filteredCollections=self._collections
}else{
self._filteredCollections=[BartlebyCollection]()
for collection in self._collections {
let filteredCollection=collection.filteredCopy({ (instance) -> Bool in
if let o=instance as? ManagedModel{
if idx==1{
// UID contains
return o.UID.contains(expression, compareOptions: NSString.CompareOptions.caseInsensitive)
}else if idx==2{
// ExternalId contains
return o.externalID.contains(expression, compareOptions: NSString.CompareOptions.caseInsensitive)
}else if idx==4{
// ---------
// Is owned by <UID>
return o.ownedBy.contains(expression)
}else if idx==5{
// Owns <UID>
return o.owns.contains(expression)
}else if idx==6{
//Is related to <UID>
return o.freeRelations.contains(expression)
}else if idx==8{
// --------- NO Expression required after this separator
//Changes Count > 0
return o.changedKeys.count > 0
}
}
return false
})
if filteredCollection.count>0{
if let casted=filteredCollection as? BartlebyCollection{
self._filteredCollections.append(casted)
}
}
}
}
self.reloadData()
}
func reloadData(){
// Data reload must be async to support deletions.
Async.main{
var selectedIndexes=self._outlineView.selectedRowIndexes
self._outlineView.reloadData()
if selectedIndexes.count==0 && self._outlineView.numberOfRows > 0 {
selectedIndexes=IndexSet(integer: 0)
}
self._outlineView.selectRowIndexes(selectedIndexes, byExtendingSelection: false)
}
}
//MARK: - NSOutlineViewDataSource
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item==nil{
return self._filteredCollections.count + 1
}
if let object=item as? ManagedModel{
if let collection = object as? BartlebyCollection {
return collection.count
}
}
return 0
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item==nil{
// Root of the tree
// Return the Metadata
if index==0{
return self._documentReference.metadata
}else{
// Return the collections with a shifted index
return self._filteredCollections[index-1]
}
}
if let object=item as? ManagedModel{
if let collection = object as? BartlebyCollection {
if let element=collection.item(at: index){
return element
}
return "<!>\(object.runTimeTypeName())"
}
}
return "ERROR #\(index)"
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let object=item as? ManagedModel{
return object is BartlebyCollection
}
return false
}
func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? {
if let object=item as? ManagedModel {
return object.alias().serialize()
}
return nil
}
func outlineView(_ outlineView: NSOutlineView, itemForPersistentObject object: Any) -> Any? {
if let data = object as? Data{
if let alias = try? Alias.deserialize(from:data) {
return Bartleby.instance(from:alias)
}
}
return nil
}
//MARK: - NSOutlineViewDelegate
public func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
if let object = item as? ManagedModel{
if let casted=object as? BartlebyCollection {
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "CollectionCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
textField.stringValue = casted.d_collectionName
}
self.configureInlineButton(view, object: casted)
return view
}else if let casted=object as? User {
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "UserCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
if casted.UID==self._documentReference.currentUser.UID{
textField.stringValue = "Current User"
}else{
textField.stringValue = casted.UID
}
}
self.configureInlineButton(view, object: casted)
return view
}else{
let casted=object
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ObjectCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
textField.stringValue = casted.UID
}
self.configureInlineButton(view, object: casted)
return view
}
}else{
// Value Object
if let object = item as? DocumentMetadata{
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ObjectCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
textField.stringValue = "Document Metadata"
}
self.configureInlineButton(view, object: object)
return view
}else{
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ObjectCell"), owner: self) as! NSTableCellView
if let textField = view.textField {
if let s=item as? String{
textField.stringValue = s
}else{
textField.stringValue = "Anomaly"
}
}
return view
}
}
}
fileprivate func configureInlineButton(_ view:NSView,object:Any){
if let inlineButton = view.viewWithTag(2) as? NSButton{
if let casted=object as? Collectible{
if let casted=object as? BartlebyCollection {
inlineButton.isHidden=false
inlineButton.title="\(casted.count) | \(casted.changedKeys.count)"
return
}else if object is DocumentMetadata{
inlineButton.isHidden=true
inlineButton.title=""
}else{
if casted.changedKeys.count > 0 {
inlineButton.isHidden=false
inlineButton.title="\(casted.changedKeys.count)"
return
}
}
}
inlineButton.isHidden=true
}
}
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
if let object=item as? ManagedModel {
if object is BartlebyCollection { return 20 }
return 20 // Any ManagedModel
}
if item is DocumentMetadata { return 20 }
if item is String{ return 20 }
return 30 // This is not normal.
}
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
return true
}
func outlineViewSelectionDidChange(_ notification: Notification) {
syncOnMain{
let selected=self._outlineView.selectedRow
if let item=self._outlineView.item(atRow: selected){
self._selectionHandler(item)
}
}
}
}
| apache-2.0 |
zcfsmile/Swifter | BasicSyntax/023错误处理/023ErrorHandling.playground/Contents.swift | 1 | 4561 | //: Playground - noun: a place where people can play
import UIKit
//: 错误处理
//: 错误处理(Error handling)是响应错误以及从错误中恢复的过程。
//: 表示并抛出错误
//: 在 Swift 中,错误用符合Error协议的类型的值来表示。这个空协议表明该类型可以用于错误处理。
enum VendingMachineError: Error {
case invalidSelection
case insufficienFunds(coinsNeeded: Int)
case outOfStock
}
//: 抛出一个错误可以让你表明有意外情况发生,导致正常的执行流程无法继续执行。抛出错误使用throw关键字。
throw VendingMachineError.insufficienFunds(coinsNeeded: 5)
//: 处理错误
//: 用 throwing 函数传递错误
//: 为了表示一个函数、方法或构造器可以抛出错误,在函数声明的参数列表之后加上throws关键字。一个标有throws关键字的函数被称作throwing 函数。如果这个函数指明了返回值类型,throws关键词需要写在箭头(->)的前面。
struct Item {
var price: Int
var count: Int
}
class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 14)
]
var coinsDeposited = 0
func dispenseSnack(snack: String) {
print("Dispensing \(snack)")
}
func vend(itemNamed name: String) throws {
guard let item = inventory[name] else {
throw VendingMachineError.invalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock
}
guard item.price <= coinsDeposited else {
throw VendingMachineError.insufficienFunds(coinsNeeded: item.price - coinsDeposited)
}
coinsDeposited -= item.price
var newItem = item
newItem.count -= 1
inventory[name] = newItem
print("Dispensing \(name)")
}
}
// vend(itemNamed name: String) 方法会返回错误,可以继续通过 throwing 函数传递
let favoriteSnacks = [
"Alice": "Chips",
"Bob": "Licorice",
"Eve": "Pretzels"
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
let sanckName = favoriteSnacks[person] ?? "Candy Bar"
// 因为vend(itemNamed:)方法能抛出错误,所以在调用的它时候在它前面加了try关键字。
try vendingMachine.vend(itemNamed: sanckName)
}
// throwing构造器能像throwing函数一样传递错误.
//struct PurchasedSnack {
// let name: String
// init(name: String, vendingMachine: VendingMachine) throws {
// try vendingMachine.vend(itemNamed: name)
// self.name = name
// }
//}
//: 使用 Do-Catch 处理错误
//: 可以使用一个do-catch语句运行一段闭包代码来处理错误。如果在do子句中的代码抛出了一个错误,这个错误会与catch子句做匹配,从而决定哪条子句能处理它。
var VM = VendingMachine()
VM.coinsDeposited = 8
do {
try buyFavoriteSnack(person: "Alice", vendingMachine: VM)
} catch VendingMachineError.invalidSelection {
print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
print("Out of Stock.")
} catch VendingMachineError.insufficienFunds(let coinsNeed) {
print("Insufficient funds. Please insert an additional \(coinsNeed) coins.")
}
//: 将错误转换为可选值
//: 可以使用try?通过将错误转换成一个可选值来处理错误。
//: 禁用错误传递
//: 有时你知道某个throwing函数实际上在运行时是不会抛出错误的,在这种情况下,你可以在表达式前面写try!来禁用错误传递,这会把调用包装在一个不会有错误抛出的运行时断言中。如果真的抛出了错误,你会得到一个运行时错误。
//: defer
//: 可以使用defer语句在即将离开当前代码块时执行一系列语句。该语句让你能执行一些必要的清理工作,不管是以何种方式离开当前代码块的——无论是由于抛出错误而离开,还是由于诸如return或者break的语句。
//func processFile(filename: String) throws {
// if exists(filename) {
// let file = open(filename)
// defer {
// close(file)
// }
// while let line = try file.readline() {
// // 处理文件。
// }
// // close(file) 会在这里被调用,即作用域的最后。
// }
//}
//: 即使没有涉及到错误处理,你也可以使用defer语句。
| mit |
mattfenwick/TodoRx | TodoRx/TodoList/TodoListAccumulator.swift | 1 | 778 | //
// TodoListAccumulator.swift
// TodoRx
//
// Created by Matt Fenwick on 7/19/17.
// Copyright © 2017 mf. All rights reserved.
//
import Foundation
func todoListAccumulator(oldModel: TodoListViewModel, command: TodoListCommand) -> (TodoListViewModel, TodoListAction?) {
print("todo list command: \(command)")
switch command {
case let .didTapItem(id):
return (oldModel, .showEdit(itemId: id))
case let .didToggleItemDone(id):
return (oldModel, .toggleItemDone(itemId: id))
case let .didDeleteItem(id):
return (oldModel, .deleteItem(itemId: id))
case let .updateItems(items):
return (oldModel.updateValues(items: items), nil)
case .didTapCreateTodo:
return (oldModel, .showCreate)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.