hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
791ced32db39d0aa53a62feb09a1c6a89e95c5fb | 1,231 | // Licensed under the **MIT** license
// Copyright (c) 2016 Bakken & Bæck
//
// 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 PackageDescription
let package = Package(
name: "SectionScrubber"
)
| 43.964286 | 73 | 0.760357 |
2243cf9a14434f48389d4e1c9bb379a523003cfa | 6,009 | //
// PhotoViewController.swift
// DriversLicenseReader
//
// Created by treastrain on 2019/11/12.
// Copyright © 2019 treastrain / Tanaka Ryoga. All rights reserved.
//
import UIKit
import CoreNFC
import TRETJapanNFCReader
class PhotoViewController: UITableViewController, DriversLicenseReaderSessionDelegate {
var reader: DriversLicenseReader!
var driversLicenseCard: DriversLicenseCard?
var isCalledViewDidAppear = false
override func viewDidLoad() {
super.viewDidLoad()
self.reader = DriversLicenseReader(viewController: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !self.isCalledViewDidAppear {
self.isCalledViewDidAppear = true
self.reread()
}
}
@IBAction func reread() {
let alertController = UIAlertController(title: NSLocalizedString("enterPINsTitle", bundle: Bundle(for: type(of: self)), comment: ""), message: NSLocalizedString("enterPINsMessage", bundle: Bundle(for: type(of: self)), comment: ""), preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.isSecureTextEntry = true
textField.placeholder = NSLocalizedString("enterPIN1TextFieldPlaceholder", bundle: Bundle(for: type(of: self)), comment: "")
textField.keyboardType = .numberPad
}
alertController.addTextField { (textField) in
textField.isSecureTextEntry = true
textField.placeholder = NSLocalizedString("enterPIN2TextFieldPlaceholder", bundle: Bundle(for: type(of: self)), comment: "")
textField.keyboardType = .numberPad
}
let nextAction = UIAlertAction(title: NSLocalizedString("next", bundle: Bundle(for: type(of: self)), comment: ""), style: .default) { (action) in
guard let textFields = alertController.textFields, textFields.count == 2, let enteredPIN1 = textFields[0].text, let enteredPIN2 = textFields[1].text else {
return
}
self.reader.get(items: [.photo], pin1: enteredPIN1, pin2: enteredPIN2)
}
let cancelAction = UIAlertAction(title: NSLocalizedString("cancel", bundle: Bundle(for: type(of: self)), comment: ""), style: .cancel, handler: nil)
alertController.addAction(nextAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func japanNFCReaderSession(didInvalidateWithError error: Error) {
var prompt: String? = nil
if let readerError = error as? NFCReaderError {
if (readerError.code != .readerSessionInvalidationErrorFirstNDEFTagRead)
&& (readerError.code != .readerSessionInvalidationErrorUserCanceled) {
self.driversLicenseCard = nil
prompt = error.localizedDescription
}
}
DispatchQueue.main.async {
self.navigationItem.prompt = prompt
self.tableView.reloadData()
}
if let driversLicenseReaderError = error as? DriversLicenseReaderError {
self.driversLicenseCard = nil
switch driversLicenseReaderError {
case .incorrectPIN:
let alertController = UIAlertController(
title: NSLocalizedString("incorrectPIN", bundle: Bundle(for: type(of: self)), comment: ""),
message: driversLicenseReaderError.errorDescription,
preferredStyle: .alert
)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alertController, animated: true, completion: nil)
}
default:
break
}
}
}
func driversLicenseReaderSession(didRead driversLicenseCard: DriversLicenseCard) {
self.driversLicenseCard = driversLicenseCard
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return NSLocalizedString("photo", bundle: Bundle(for: type(of: self)), comment: "")
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let imageView = cell.contentView.viewWithTag(1) as! UIImageView
if let photoData = self.driversLicenseCard?.photo?.photoData {
imageView.image = UIImage(data: photoData)
imageView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(self.copy(sender:))))
} else {
imageView.image = nil
}
return cell
}
@objc func copy(sender: UILongPressGestureRecognizer) {
if let image = (sender.view as? UIImageView)?.image {
let pasteboard = UIPasteboard.general
pasteboard.image = image
let alertController = UIAlertController(title: "Copied photo image.", message: nil, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alertController, animated: true, completion: nil)
}
}
}
}
| 41.157534 | 263 | 0.640373 |
1113ec934efdfa769af01d76d52f688811e5e2df | 263 | //
// User.swift
// SwiftBaseProject
//
// Created by Mauricio Cousillas on 3/15/18.
// Copyright © 2018 Mauricio Cousillas. All rights reserved.
//
import Foundation
struct User: Codable {
let username: String
let email: String
let phone: String?
}
| 15.470588 | 61 | 0.695817 |
71da34baa262b3c335241bb357a1dde49780a6eb | 409 | // RUN: %empty-directory(%t)
// RUN: mkdir -p %t
// RUN: cd %t
// RUN: cp %s .
// RUN: %target-swiftc_driver -g -debug-prefix-map %t=. \
// RUN: debug_prefix_map_abs_rel.swift \
// RUN: -emit-ir -o - | %FileCheck %s
public func f() {}
// CHECK-NOT: debug_prefix_map_abs_rel.swift
// CHECK: !DIFile(filename: "debug_prefix_map_abs_rel.swift", directory: ".")
// CHECK-NOT: debug_prefix_map_abs_rel.swift
| 29.214286 | 77 | 0.665037 |
086a2944d79318eddd099d21b45fea1c3bd68b9c | 1,312 | //
// URLRequest+WebRequest.swift
// WebRequest
//
// Created by Tyler Anger on 2021-01-02.
//
import Foundation
#if swift(>=4.1)
#if canImport(FoundationXML)
import FoundationNetworking
#endif
#endif
internal extension URLRequest {
/// Create new URLRequest copying old request details
init(url: URL,
_ oldRequest: URLRequest) {
self.init(url: url,
cachePolicy: oldRequest.cachePolicy,
timeoutInterval: oldRequest.timeoutInterval)
self.allHTTPHeaderFields = oldRequest.allHTTPHeaderFields
self.allowsCellularAccess = oldRequest.allowsCellularAccess
#if _runtime(_ObjC)
if #available(OSX 10.15, *) {
self.allowsConstrainedNetworkAccess = oldRequest.allowsConstrainedNetworkAccess
}
if #available(OSX 10.15, *) {
self.allowsExpensiveNetworkAccess = oldRequest.allowsExpensiveNetworkAccess
}
#endif
self.httpBody = oldRequest.httpBody
self.httpMethod = oldRequest.httpMethod
self.httpShouldHandleCookies = oldRequest.httpShouldHandleCookies
self.httpShouldUsePipelining = oldRequest.httpShouldUsePipelining
self.networkServiceType = oldRequest.networkServiceType
}
}
| 32.8 | 95 | 0.667683 |
cc19dcb0ef45dc2bb3bcb696896629affb05e735 | 1,206 | import Foundation
public struct GetWalletKDFResponse: Decodable {
public let attributes: Attributes
public let id: String
public let type: String
public struct Attributes: Decodable {
public let algorithm: String
public let bits: Int64
public let n: UInt64
public let p: UInt32
public let r: UInt32
public let salt: String
}
}
extension WalletKDFParams {
public static func fromResponse(_ response: GetWalletKDFResponse) -> WalletKDFParams? {
guard let salt = response.attributes.salt.dataFromBase64 else {
return nil
}
return WalletKDFParams(
kdfParams: KDFParams.fromResponse(response),
salt: salt
)
}
}
extension KDFParams {
public static func fromResponse(_ response: GetWalletKDFResponse) -> KDFParams {
return KDFParams(
algorithm: response.attributes.algorithm,
bits: response.attributes.bits,
id: response.id,
n: response.attributes.n,
p: response.attributes.p,
r: response.attributes.r,
type: response.type
)
}
}
| 25.659574 | 91 | 0.609453 |
edd36c2a286920774c0837e17e9333ff7e6d6ca6 | 2,916 | //
// RSDChoiceTableItem.swift
// ResearchSuite
//
// Copyright © 2017 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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.
//
import Foundation
/// `RSDChoiceTableItem` is used to represent a single row in a table where the user picks from a list of choices.
open class RSDChoiceTableItem : RSDInputFieldTableItem {
/// The choice for a single or multiple choice input field.
open private(set) var choice: RSDChoice
/// The answer associated with this choice
open override var answer: Any? {
return selected ? choice.value : nil
}
/// Whether or not the choice is currently selected.
public var selected: Bool = false
/// Initialize a new RSDChoiceTableItem.
/// parameters:
/// - rowIndex: The index of this item relative to all rows in the section in which this item resides.
/// - inputField: The RSDInputField representing this tableItem.
/// - uiHint: The UI hint for this row of the table.
/// - choice: The choice for a single or multiple choice input field.
public init(rowIndex: Int, inputField: RSDInputField, uiHint: RSDFormUIHint, choice: RSDChoice) {
self.choice = choice
super.init(rowIndex: rowIndex, inputField: inputField, uiHint: uiHint)
}
}
| 47.803279 | 115 | 0.731481 |
39cb0ae5678d7533ac1273258aaa0160b97301fb | 245 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a{{{{{}}}}typealias d:d
struct B<T where g:c
a<class d<T where B:d
| 30.625 | 87 | 0.738776 |
e0adbfb821d360e39431fcede4b70d73ae8181f4 | 13,126 | import Foundation
import TSCBasic
import TuistCore
import TuistCoreTesting
import TuistGraph
import TuistSupport
import XCTest
@testable import TuistCache
@testable import TuistCore
@testable import TuistSupportTesting
final class ContentHashingIntegrationTests: TuistTestCase {
var subject: GraphContentHasher!
var temporaryDirectoryPath: String!
var source1: SourceFile!
var source2: SourceFile!
var source3: SourceFile!
var source4: SourceFile!
var resourceFile1: ResourceFileElement!
var resourceFile2: ResourceFileElement!
var resourceFolderReference1: ResourceFileElement!
var resourceFolderReference2: ResourceFileElement!
var coreDataModel1: CoreDataModel!
var coreDataModel2: CoreDataModel!
override func setUp() {
super.setUp()
do {
let temporaryDirectoryPath = try temporaryPath()
source1 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "1", content: "1")
source2 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "2", content: "2")
source3 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "3", content: "3")
source4 = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "4", content: "4")
resourceFile1 = try createTemporaryResourceFile(on: temporaryDirectoryPath, name: "r1", content: "r1")
resourceFile2 = try createTemporaryResourceFile(on: temporaryDirectoryPath, name: "r2", content: "r2")
resourceFolderReference1 = try createTemporaryResourceFolderReference(on: temporaryDirectoryPath, name: "rf1", content: "rf1")
resourceFolderReference2 = try createTemporaryResourceFolderReference(on: temporaryDirectoryPath, name: "rf2", content: "rf2")
_ = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "CoreDataModel1", content: "cd1")
_ = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "CoreDataModel2", content: "cd2")
_ = try createTemporarySourceFile(on: temporaryDirectoryPath, name: "Info.plist", content: "plist")
coreDataModel1 = CoreDataModel(path: temporaryDirectoryPath.appending(component: "CoreDataModel1"), versions: [], currentVersion: "1")
coreDataModel2 = CoreDataModel(path: temporaryDirectoryPath.appending(component: "CoreDataModel2"), versions: [], currentVersion: "2")
} catch {
XCTFail("Error while creating files for stub project")
}
subject = GraphContentHasher(contentHasher: CacheContentHasher())
}
override func tearDown() {
subject = nil
source1 = nil
source2 = nil
source3 = nil
source4 = nil
resourceFile1 = nil
resourceFile2 = nil
resourceFolderReference1 = nil
resourceFolderReference2 = nil
coreDataModel1 = nil
coreDataModel2 = nil
super.tearDown()
}
// MARK: - Sources
func test_contentHashes_frameworksWithSameSources() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source2, source1])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_frameworksWithDifferentSources() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source3, source4])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_hashIsConsistent() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source3, source4])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
let cacheProfile = TuistGraph.Cache.Profile(name: "Simulator", configuration: "Debug")
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: cacheProfile, cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], "f79b6c2575a45ab4cf8c53b8539dfd04")
XCTAssertEqual(contentHash[framework2], "43dc6552dc27ac2acc3b5380708c7c9d")
}
func test_contentHashes_hashChangesWithCacheOutputType() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", sources: [source1, source2])
let framework2 = makeFramework(named: "f2", sources: [source3, source4])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentFrameworkHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
let contentXCFrameworkHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .xcframework)
// Then
XCTAssertNotEqual(contentFrameworkHash[framework1], contentXCFrameworkHash[framework1])
XCTAssertNotEqual(contentFrameworkHash[framework2], contentXCFrameworkHash[framework2])
}
// MARK: - Resources
func test_contentHashes_differentResourceFiles() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", resources: [resourceFile1])
let framework2 = makeFramework(named: "f2", resources: [resourceFile2])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_differentResourcesFolderReferences() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", resources: [resourceFolderReference1])
let framework2 = makeFramework(named: "f2", resources: [resourceFolderReference2])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_sameResources() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let resources: [ResourceFileElement] = [resourceFile1, resourceFolderReference1]
let framework1 = makeFramework(named: "f1", resources: resources)
let framework2 = makeFramework(named: "f2", resources: resources)
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - Core Data Models
func test_contentHashes_differentCoreDataModels() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", coreDataModels: [coreDataModel1])
let framework2 = makeFramework(named: "f2", coreDataModels: [coreDataModel2])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
func test_contentHashes_sameCoreDataModels() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", coreDataModels: [coreDataModel1])
let framework2 = makeFramework(named: "f2", coreDataModels: [coreDataModel1])
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
// Then
XCTAssertEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - Target Actions
// MARK: - Platform
func test_contentHashes_differentPlatform() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", platform: .iOS)
let framework2 = makeFramework(named: "f2", platform: .macOS)
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - ProductName
func test_contentHashes_differentProductName() throws {
// Given
let temporaryDirectoryPath = try temporaryPath()
let framework1 = makeFramework(named: "f1", productName: "1")
let framework2 = makeFramework(named: "f2", productName: "2")
let graph = Graph.test(targets: [
temporaryDirectoryPath: [framework1, framework2],
])
// When
let contentHash = try subject.contentHashes(for: graph, cacheProfile: .test(), cacheOutputType: .framework)
XCTAssertNotEqual(contentHash[framework1], contentHash[framework2])
}
// MARK: - Private helpers
private func createTemporarySourceFile(on temporaryDirectoryPath: AbsolutePath, name: String, content: String) throws -> SourceFile {
let filePath = temporaryDirectoryPath.appending(component: name)
try FileHandler.shared.touch(filePath)
try FileHandler.shared.write(content, path: filePath, atomically: true)
return SourceFile(path: filePath, compilerFlags: nil)
}
private func createTemporaryResourceFile(on temporaryDirectoryPath: AbsolutePath,
name: String,
content: String) throws -> ResourceFileElement
{
let filePath = temporaryDirectoryPath.appending(component: name)
try FileHandler.shared.touch(filePath)
try FileHandler.shared.write(content, path: filePath, atomically: true)
return ResourceFileElement.file(path: filePath)
}
private func createTemporaryResourceFolderReference(on temporaryDirectoryPath: AbsolutePath,
name: String,
content: String) throws -> ResourceFileElement
{
let filePath = temporaryDirectoryPath.appending(component: name)
try FileHandler.shared.touch(filePath)
try FileHandler.shared.write(content, path: filePath, atomically: true)
return ResourceFileElement.folderReference(path: filePath)
}
private func makeFramework(named: String,
platform: Platform = .iOS,
productName: String? = nil,
sources: [SourceFile] = [],
resources: [ResourceFileElement] = [],
coreDataModels: [CoreDataModel] = [],
targetActions: [TargetAction] = []) -> TargetNode
{
TargetNode.test(
project: .test(path: AbsolutePath("/test/\(named)")),
target: .test(platform: platform,
product: .framework,
productName: productName,
sources: sources,
resources: resources,
coreDataModels: coreDataModels,
actions: targetActions)
)
}
}
| 43.036066 | 146 | 0.655493 |
f72f3783a3f7fd29bda5e58e01ff38b5dd6353c2 | 199 | // MyViewController.swift - Copyright 2020 SwifterSwift
#if canImport(UIKit) && !os(watchOS)
import UIKit
class MyViewController: UIViewController {
@IBOutlet var testLabel: UILabel!
}
#endif
| 18.090909 | 55 | 0.758794 |
eb324852fcf664bed53b509caa122a678cb68bd9 | 12,390 | //
// UIWebViewController.swift
// UIWebViewController
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 8/8/17.
//
import UIKit
import WebKit
open class UIWebViewController: UIViewController, UIWebViewDelegate, UISearchBarDelegate, UIScrollViewDelegate {
open var webView: UIWebView! = {
let webView = UIWebView()
webView.allowsInlineMediaPlayback = true
webView.allowsLinkPreview = true
webView.backgroundColor = .white
return webView
}()
open var url: URL?
open var urlBar: UISearchBar! = {
let searchBar = UISearchBar()
searchBar.searchBarStyle = .minimal
searchBar.placeholder = "URL/Search"
searchBar.autocapitalizationType = .none
searchBar.autocorrectionType = .no
searchBar.keyboardType = .URL
searchBar.enablesReturnKeyAutomatically = true
searchBar.backgroundColor = .clear
searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
searchBar.isTranslucent = false
return searchBar
}()
open var toolbar: UIToolbar! = {
let toolbar = UIToolbar()
toolbar.isTranslucent = false
return toolbar
}()
open var isUITranslucent: Bool = false {
didSet {
toolbar.isTranslucent = isUITranslucent
urlBar.isTranslucent = isUITranslucent
navigationController?.navigationBar.isTranslucent = isUITranslucent
webView.scrollView.contentInset.bottom = isUITranslucent ? 44 : 0
}
}
private var previousScrollViewYOffset: CGFloat = 0
// MARK: - Initialization
public init() {
super.init(nibName: nil, bundle: nil)
}
public convenience init(url: URL) {
self.init(nibName: nil, bundle: nil)
self.url = url
urlBar.text = url.absoluteString
loadRequest(forURL: url)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setup() {
webView.delegate = self
webView.scrollView.delegate = self
view.addSubview(webView)
view.backgroundColor = .white
navigationController?.navigationItem.leftBarButtonItem?.title = String()
navigationController?.navigationItem.rightBarButtonItem = navigationItem(#imageLiteral(resourceName: "icon_share"), action: #selector(UIWebViewController.handleShare(_:)))
navigationItem.titleView = urlBar
urlBar.delegate = self
urlBar.sizeToFit()
toolbar.items = [
navigationItem(#imageLiteral(resourceName: "icon_back"), action: #selector(UIWebViewController.goBack(_:))),
UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil),
navigationItem(#imageLiteral(resourceName: "icon_forward"), action: #selector(UIWebViewController.goForward(_:))),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
navigationItem(#imageLiteral(resourceName: "icon_share"), action: #selector(UIWebViewController.handleShare(_:)))
]
view.addSubview(toolbar)
let inputView = EasyInputAccessoryView()
inputView.controller = self
inputView.addSubview(toolbar)
toolbar.translatesAutoresizingMaskIntoConstraints = false
webView.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leftAnchor.constraint(equalTo: view.leftAnchor),
webView.rightAnchor.constraint(equalTo: view.rightAnchor),
toolbar.leftAnchor.constraint(equalTo: inputView.leftAnchor),
toolbar.rightAnchor.constraint(equalTo: inputView.rightAnchor),
toolbar.topAnchor.constraint(equalTo: inputView.topAnchor),
toolbar.bottomAnchor.constraint(equalTo: inputView.bottomAnchor)
]
_ = constraints.map{ $0.isActive = true }
}
// MARK: - Helper Methods
private func navigationItem(_ icon: UIImage, action: Selector) -> UIBarButtonItem {
let image = icon.withRenderingMode(.alwaysTemplate)
return UIBarButtonItem(image: image, style: .plain, target: self, action: action)
}
@discardableResult
public func loadRequest(forURL: URL?) -> Bool {
guard let url = url else {
return false
}
let request = URLRequest(url: url)
webView.loadRequest(request)
return true
}
open func handleShare(_ sender: UIBarButtonItem?) {
guard let url = url else {
return
}
animateNavBar(to: 20)
updateBarButtonItems(1)
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [url] as [Any], applicationActivities: [OpenInSafariActivity()])
activityViewController.popoverPresentationController?.barButtonItem = sender
activityViewController.popoverPresentationController?.permittedArrowDirections = .unknown
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 150, y: 150, width: 0, height: 0)
present(activityViewController, animated: true, completion: nil)
}
open func makeValidURL(with text: String) -> String {
if !text.contains("https://") {
if text.contains("http://") {
// Force HTTPS
return text.replacingOccurrences(of: "http://", with: "https://")
} else {
if text.contains(" ") || !text.contains(".") {
// Make Google search
return "https://www.google.com/search?q=" + text.replacingOccurrences(of: " ", with: "+")
} else {
return "https://" + text
}
}
}
return text
}
// MARK: - View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setup()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isTranslucent = isUITranslucent
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
urlBar.resignFirstResponder()
webView.resignFirstResponder()
animateNavBar(to: 20)
updateBarButtonItems(1)
}
// MARK: - WebView Navigation
open func goBack(_ sender: UIBarButtonItem?) {
webView.goBack()
if webView.canGoBack {
updateBarButtonItems(1)
}
}
open func goForward(_ sender: UIBarButtonItem?) {
webView.goForward()
if webView.canGoForward {
updateBarButtonItems(1)
}
}
// MARK: - UIScrollView
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard var frame = navigationController?.navigationBar.frame else {
return
}
let size = frame.size.height - 21
let framePercentageHidden: CGFloat = (20 - frame.origin.y) / (frame.size.height - 1)
let scrollOffset: CGFloat = scrollView.contentOffset.y
let scrollDiff: CGFloat = scrollOffset - previousScrollViewYOffset
let scrollHeight: CGFloat = scrollView.frame.size.height
let scrollContentSizeHeight: CGFloat = scrollView.contentSize.height + scrollView.contentInset.bottom
if scrollOffset <= -scrollView.contentInset.top {
frame.origin.y = 20
updateWebViewFrameYOrigin(0)
}
else if (scrollOffset + scrollHeight) >= scrollContentSizeHeight {
frame.origin.y = -size
}
else {
let size = min(20, max(-size, frame.origin.y - scrollDiff))
frame.origin.y = size
updateWebViewFrameYOrigin(size - 20)
}
navigationController?.navigationBar.frame = frame
updateBarButtonItems((1 - framePercentageHidden))
previousScrollViewYOffset = scrollOffset
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
stoppedScrolling()
}
private func stoppedScrolling() {
guard let frame = navigationController?.navigationBar.frame else {
return
}
if frame.origin.y < 20 {
animateNavBar(to: -(frame.size.height - 21))
}
}
func updateBarButtonItems(_ alpha: CGFloat) {
_ = navigationItem.leftBarButtonItems?.map{
$0.customView?.alpha = alpha
}
_ = navigationItem.rightBarButtonItems?.map{
$0.customView?.alpha = alpha
}
navigationItem.titleView?.alpha = alpha
navigationController?.navigationBar.tintColor = navigationController?.navigationBar.tintColor?.withAlphaComponent(alpha)
}
private func animateNavBar(to y: CGFloat) {
UIView.animate(withDuration: 0.2, animations: {() -> Void in
guard var frame = self.navigationController?.navigationBar.frame else {
return
}
let alpha: CGFloat = (frame.origin.y >= y ? 0 : 1)
frame.origin.y = y
self.navigationController?.navigationBar.frame = frame
self.updateBarButtonItems(alpha)
})
}
private func updateWebViewFrameYOrigin(_ y: CGFloat) {
webView.frame.origin.y = isUITranslucent ? 0 : y
}
// MARK: - UIWebViewDelegate
open func webViewDidStartLoad(_ webView: UIWebView) {
}
open func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
urlBar.text = request.url?.absoluteString
return true
}
open func webViewDidFinishLoad(_ webView: UIWebView) {
}
open func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print("Failed to load with error: ", error.localizedDescription)
}
// MARK: - UISearchBarDelegate
open func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
}
open func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
guard var text = searchBar.text ?? url?.absoluteString else {
print("Failed to load with error: Invalid URL")
return
}
text = makeValidURL(with: text)
if url?.absoluteString != text {
url = URL(string: text)
loadRequest(forURL: url)
}
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
if searchBar.text?.isEmpty == true {
urlBar.text = url?.absoluteString
}
}
}
| 36.441176 | 179 | 0.638418 |
56461c813e45ab93e468ffab12443c12532913a2 | 1,791 | //
// ChooseCountryScreen.swift
// app-ios
//
// Created by Volodymyr Chernyshov on 04.04.2020.
// Copyright © 2020 Garage Development. All rights reserved.
//
import UIKit
import MultiPlatformLibrary
class ChooseCountryScreen: Screen<ChooseCountryPm>, UISearchResultsUpdating {
@IBOutlet weak var countriesView: UICollectionView!
private var adapter = CellAdapter()
override func viewDidLoad() {
super.viewDidLoad()
title = "Choose country"
adapter.attachToCollectionView(countriesView)
adapter.setClickListener { country in
self.pm.countryClicks.consumer.onNext(value: country)
}
let search = UISearchController(searchResultsController: nil)
search.searchResultsUpdater = self
search.obscuresBackgroundDuringPresentation = false
search.searchBar.placeholder = "Type country name to search"
navigationItem.searchController = search
}
override func providePm() -> ChooseCountryPm {
return ChooseCountryPm(phoneUtil: AppDelegate.mainComponent.phoneUtil)
}
override func onBindPm(_ pm: ChooseCountryPm) {
super.onBindPm(pm)
pm.countries.bindTo(consumer: { countries in
self.adapter.setCountries(countries as! [Country])
})
}
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
pm.searchQueryInput.textChanges.consumer.onNext(value: text)
}
static func newInstance() -> ChooseCountryScreen {
let storyboard = UIStoryboard.init(name: "ChooseCountryStoryboard", bundle: nil)
return storyboard.instantiateViewController(identifier: "ChooseCountryStoryboard")
}
}
| 34.442308 | 90 | 0.700168 |
d6a4ca92f85067d965fea4fb3af4f72c6f408b7d | 905 | /*:
## Answering Questions
In this playground, you're going to work on a function to make QuestionBot answer questions.
You can build the brains of the app in a playground before adding it to the app. This lets you concentrate on the part you’re working on right now.
The “brain” of QuestionBot is the function `responseTo(question:)`. You’re going to try out a few versions of that function.
Here’s an example:
*/
func responseTo(question: String) -> String {
return "Sorry, what was that?"
}
//: Now we can ask questions. Look at the answers in the sidebar. 👉
responseTo(question: "How are you?")
responseTo(question: "I said, how are you?")
responseTo(question: "Oh, never mind.")
/*:
This doesn’t make for great conversation. The function gives the same answer, whatever the question. There are more interesting examples coming up.
*/
//:page 1 of 7 | [Next: First Words](@next)
| 37.708333 | 148 | 0.727072 |
bb715acc408eef9b26622c1f1466e65be9d4220d | 8,447 | /*
RPiLight
Copyright (c) 2018 Adam Thayer
Licensed under the MIT license, as follows:
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
import LED
import Logging
@testable import Service
struct MockLayerPoint: LayerPoint {
var time: DayTime
var brightness: Brightness
init(time: String, brightness: Brightness) {
let date = MockLayerPoint.dateFormatter.date(from: time)!
self.time = DayTime(from: date)
self.brightness = brightness
}
static public let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
dateFormatter.calendar = Calendar.current
return dateFormatter
}()
}
class LayerTests: XCTestCase {
func testActiveIndex() {
// Segments are considered such that they don't include their start, but do include their end.
// It's not intuitive, hence these tests.
let testExpectations = [
// Time, Active Index
("07:30:00", LayerTests.testData.count - 1),
("08:00:01", 0),
("14:00:00", 2)
]
for (timeString, expectedIndex) in testExpectations {
let testTime = MockLayerPoint.dateFormatter.date(from: timeString)!
let testLayer = Layer(identifier: "Mock", points: LayerTests.testData, startTime: testTime)
XCTAssertEqual(testLayer.activeIndex, expectedIndex)
}
}
func testActiveSegment() {
// Segments are considered such that they don't include their start, but do include their end.
// It's not intuitive, hence these tests.
let testExpectations = [
// Time, Active Index
("07:30:00", LayerTests.testData.count - 1),
("08:00:01", 0),
("14:00:00", 2)
]
for (timeString, expectedIndex) in testExpectations {
let nextExpectedIndex = (expectedIndex + 1) % LayerTests.testData.count
let testTime = MockLayerPoint.dateFormatter.date(from: timeString)!
let testLayer = Layer(identifier: "Mock", points: LayerTests.testData, startTime: testTime)
let activeSegment = testLayer.activeSegment
XCTAssertLessThanOrEqual(activeSegment.startDate, testTime)
XCTAssertGreaterThanOrEqual(activeSegment.endDate, testTime)
XCTAssertEqual(activeSegment.range.origin, LayerTests.testData[expectedIndex].brightness)
XCTAssertEqual(activeSegment.range.end, LayerTests.testData[nextExpectedIndex].brightness)
}
}
func testLightLevel() {
let testExpectations = [
("08:00:00", 0.0),
("08:15:00", 0.125), // Midway
("08:30:00", 0.25),
("11:00:00", 0.25), // Midway
("12:00:00", 0.25),
("14:00:00", 0.50),
("18:00:00", 0.50),
("19:00:00", 0.30), // Midway
("20:00:00", 0.10),
("22:30:00", 0.10),
("23:00:00", 0.0)
]
for (timeString, expectedBrightness) in testExpectations {
// Start from known point every time
let startTime = MockLayerPoint.dateFormatter.date(from: "00:00:00")!
let testLayer = Layer(identifier: "Mock", points: LayerTests.testData, startTime: startTime)
let testDate = MockLayerPoint.dateFormatter.date(from: timeString)!
let brightness = testLayer.lightLevel(forDate: testDate)
XCTAssertEqual(brightness.rawValue, expectedBrightness, "\(timeString)")
}
}
func testLightLevelInReverse() {
let testExpectations = [
("08:00:00", 0.0),
("08:15:00", 0.125), // Midway
("08:30:00", 0.25),
("11:00:00", 0.25), // Midway
("12:00:00", 0.25),
("14:00:00", 0.50),
("18:00:00", 0.50),
("19:00:00", 0.30), // Midway
("20:00:00", 0.10),
("22:30:00", 0.10),
("23:00:00", 0.0)
]
for (timeString, expectedBrightness) in testExpectations.reversed() {
// Start from known point every time
let startTime = MockLayerPoint.dateFormatter.date(from: "23:59:59")!
let testLayer = Layer(identifier: "Mock", points: LayerTests.testData, startTime: startTime)
let testDate = MockLayerPoint.dateFormatter.date(from: timeString)!
let brightness = testLayer.lightLevel(forDate: testDate)
XCTAssertEqual(brightness.rawValue, expectedBrightness, "\(timeString)")
}
}
func testLayerRateOfChange() {
let testExpectations = [
// Time, Delta Change, Segment Start, Segment End
("07:00:00", 0.00, "23:00:00", "08:00:00"),
("08:15:00", 0.25, "08:00:00", "08:30:00"),
("10:00:00", 0.00, "08:30:00", "12:00:00"),
("13:00:00", 0.25, "12:00:00", "14:00:00"),
("16:00:00", 0.00, "14:00:00", "18:00:00"),
("19:00:00", 0.40, "18:00:00", "20:00:00"),
("21:00:00", 0.00, "20:00:00", "22:30:00"),
("22:45:00", 0.10, "22:30:00", "23:00:00"),
("23:30:00", 0.00, "23:00:00", "08:00:00")
]
// We should be able to query the same object at any time
let startTime = MockLayerPoint.dateFormatter.date(from: "00:00:00")!
let testLayer = Layer(identifier: "Mock", points: LayerTests.testData, startTime: startTime)
for (timeString, expectedChange, expectedStart, expectedEnd) in testExpectations {
let testDate = MockLayerPoint.dateFormatter.date(from: timeString)!
let startDate = MockLayerPoint.dateFormatter.date(from: expectedStart)!
let endDate = MockLayerPoint.dateFormatter.date(from: expectedEnd)!
let startComponents = DayTime(from: startDate)
let endComponents = DayTime(from: endDate)
let startDateCorrected = startComponents.calcNextDate(after: testDate, direction: .backward)!
let endDateCorrected = endComponents.calcNextDate(after: testDate, direction: .forward)!
let layerSegment = testLayer.segment(forDate: testDate)
XCTAssertEqual(layerSegment.totalBrightnessChange, expectedChange)
XCTAssertEqual(layerSegment.startDate, startDateCorrected, "\(startDateCorrected) -> \(endDateCorrected)")
XCTAssertEqual(layerSegment.endDate, endDateCorrected, "\(startDateCorrected) -> \(endDateCorrected)")
}
}
static var testData: [MockLayerPoint] = [
MockLayerPoint(time: "08:00:00", brightness: 0.0),
MockLayerPoint(time: "08:30:00", brightness: 0.25),
MockLayerPoint(time: "12:00:00", brightness: 0.25),
MockLayerPoint(time: "14:00:00", brightness: 0.50),
MockLayerPoint(time: "18:00:00", brightness: 0.50),
MockLayerPoint(time: "20:00:00", brightness: 0.10),
MockLayerPoint(time: "22:30:00", brightness: 0.10),
MockLayerPoint(time: "23:00:00", brightness: 0.0)
]
static var allTests = [
("testActiveIndex", testActiveIndex),
("testActiveSegment", testActiveSegment),
("testLightLevel", testLightLevel),
("testLightLevelInReverse", testLightLevelInReverse),
("testLayerRateOfChange", testLayerRateOfChange)
]
}
| 42.447236 | 118 | 0.624127 |
67d520242f09eed9a58861c817df1fa3b2f82f23 | 227 | //
// CalculatorApp.swift
// Calculator
//
// Created by Faiq on 12/10/2021.
//
import SwiftUI
@main
struct CalculatorApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.611111 | 34 | 0.563877 |
8f6a8c633e88872d975310525c377fd271f8976d | 15,742 | //
// RxRealmWriteSinks.swift
// RxRealm
//
// Created by Marin Todorov on 6/4/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import XCTest
import RxSwift
import RealmSwift
import RxRealm
import RxTest
enum WriteError: Error {
case def
}
class RxRealmWriteSinks: XCTestCase {
fileprivate func realmInMemoryConfiguration(_ name: String) -> Realm.Configuration {
var conf = Realm.Configuration()
conf.inMemoryIdentifier = name
return conf
}
fileprivate func realmInMemory(_ name: String) -> Realm {
var conf = Realm.Configuration()
conf.inMemoryIdentifier = name
return try! Realm(configuration: conf)
}
func testRxAddObject() {
let expectation = self.expectation(description: "Message1")
let realm = realmInMemory(#function)
let bag = DisposeBag()
let events = [
next(0, Message("1")),
completed(0)
]
let rx_add: AnyObserver<Message> = realm.rx.add()
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Array<Message>.self)
let observable = scheduler.createHotObservable(events).asObservable()
let messages$ = Observable.array(from: realm.objects(Message.self)).shareReplay(1)
messages$.subscribe(observer)
.disposed(by: bag)
messages$
.subscribe(onNext: { messages in
if messages.count == 1 {
expectation.fulfill()
}
})
.disposed(by: bag)
observable
.subscribe(rx_add)
.disposed(by: bag)
scheduler.start()
waitForExpectations(timeout: 1, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertTrue(observer.events.count > 0)
XCTAssertEqual(observer.events.last!.time, 0)
XCTAssertTrue(observer.events.last!.value.element!.equalTo([Message("1")]))
})
}
func testRxAddObjectWithError() {
let expectation = self.expectation(description: "Message1")
var conf = Realm.Configuration()
conf.fileURL = URL(string: "/asdasdasdsad")!
let bag = DisposeBag()
let subject = PublishSubject<UniqueObject>()
let o1 = UniqueObject()
o1.id = 1
var recordedError: Error?
let observer: AnyObserver<UniqueObject> = Realm.rx.add(configuration: conf, update: true, onError: {value, error in
XCTAssertNil(value)
recordedError = error
expectation.fulfill()
})
subject.asObservable()
.subscribe(observer)
.disposed(by: bag)
subject.onNext(o1)
waitForExpectations(timeout: 1, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertEqual((recordedError! as NSError).code, 3)
})
}
func testRxAddSequenceWithError() {
let expectation = self.expectation(description: "Message1")
var conf = Realm.Configuration()
conf.fileURL = URL(string: "/asdasdasdsad")!
let bag = DisposeBag()
let subject = PublishSubject<[UniqueObject]>()
let o1 = UniqueObject()
o1.id = 1
let o2 = UniqueObject()
o2.id = 2
var recordedError: Error?
let observer: AnyObserver<[UniqueObject]> = Realm.rx.add(configuration: conf, update: true, onError: {values, error in
XCTAssertNil(values)
recordedError = error
expectation.fulfill()
})
subject.asObservable()
.subscribe(observer)
.disposed(by: bag)
subject.onNext([o1, o2])
waitForExpectations(timeout: 1, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertEqual((recordedError! as NSError).code, 3)
})
}
func testRxAddSequence() {
let expectation = self.expectation(description: "Message1")
let realm = realmInMemory(#function)
let bag = DisposeBag()
let events = [
next(0, [Message("1"), Message("2")]),
completed(0)
]
let rx_add: AnyObserver<[Message]> = realm.rx.add()
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Array<Message>.self)
let observable = scheduler.createHotObservable(events).asObservable()
let messages$ = Observable.array(from: realm.objects(Message.self)).shareReplay(1)
observable.subscribe(rx_add)
.disposed(by: bag)
messages$.subscribe(observer)
.disposed(by: bag)
messages$.subscribe(onNext: {
if $0.count == 2 {
expectation.fulfill()
}
}).disposed(by: bag)
scheduler.start()
waitForExpectations(timeout: 0.1, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertTrue(observer.events.count > 0)
XCTAssertEqual(observer.events.last!.time, 0)
XCTAssertTrue(observer.events.last!.value.element!.equalTo([Message("1"), Message("2")]))
})
}
func testRxAddUpdateObjects() {
let expectation = self.expectation(description: "Message1")
let realm = realmInMemory(#function)
let bag = DisposeBag()
let events = [
next(0, [UniqueObject(1), UniqueObject(2)]),
next(1, [UniqueObject(1), UniqueObject(3)]),
completed(2)
]
let rx_add: AnyObserver<[UniqueObject]> = realm.rx.add(update: true)
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Array<UniqueObject>.self)
let observable = scheduler.createHotObservable(events).asObservable()
let messages$ = Observable.array(from: realm.objects(UniqueObject.self)).shareReplay(1)
observable.subscribe(rx_add)
.disposed(by: bag)
messages$.subscribe(observer)
.disposed(by: bag)
messages$.subscribe(onNext: {
switch $0.count {
case 3:
expectation.fulfill()
default:
break
}
}).disposed(by: bag)
scheduler.start()
waitForExpectations(timeout: 5, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
//check that UniqueObject with id == 1 was overwritten
XCTAssertTrue(observer.events.last!.value.element!.count == 3)
XCTAssertTrue(observer.events.last!.value.element![0] == UniqueObject(1))
XCTAssertTrue(observer.events.last!.value.element![1] == UniqueObject(2))
XCTAssertTrue(observer.events.last!.value.element![2] == UniqueObject(3))
})
}
func testRxDeleteItem() {
let expectation = self.expectation(description: "Message1")
let realm = realmInMemory(#function)
let element = Message("1")
let scheduler = TestScheduler(initialClock: 0)
let messages$ = Observable.array(from: realm.objects(Message.self)).shareReplay(1)
let rx_delete: AnyObserver<Message> = Realm.rx.delete()
try! realm.write {
realm.add(element)
}
let bag = DisposeBag()
let events = [
next(0, element),
completed(0)
]
let observer = scheduler.createObserver(Array<Message>.self)
let observable = scheduler.createHotObservable(events).asObservable()
observable.subscribe(rx_delete)
.disposed(by: bag)
messages$.subscribe(observer)
.disposed(by: bag)
messages$.subscribe(onNext: {
switch $0.count {
case 0:
expectation.fulfill()
default:
break
}
}).disposed(by: bag)
scheduler.start()
waitForExpectations(timeout: 0.1, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertTrue(observer.events.count > 0)
XCTAssertEqual(observer.events.last!.time, 0)
XCTAssertEqual(observer.events.last!.value.element!, [Message]())
})
}
func testRxDeleteItemWithError() {
let expectation = self.expectation(description: "Message1")
expectation.assertForOverFulfill = false
var conf = Realm.Configuration()
conf.fileURL = URL(string: "/asdasdasdsad")!
let element = Message("1")
let scheduler = TestScheduler(initialClock: 0)
let bag = DisposeBag()
let events = [
next(0, element),
completed(0)
]
let observer = scheduler.createObserver(Array<Message>.self)
let observable = scheduler.createHotObservable(events).asObservable()
let rx_delete: AnyObserver<Message> = Realm.rx.delete(onError: {elements, error in
XCTAssertNil(elements)
expectation.fulfill()
})
observable.subscribe(rx_delete)
.disposed(by: bag)
Observable.from(optional: [element]).subscribe(observer)
.disposed(by: bag)
scheduler.start()
waitForExpectations(timeout: 1.0, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertTrue(observer.events.count > 0)
XCTAssertEqual(observer.events.last!.time, 0)
})
}
func testRxDeleteItems() {
let expectation = self.expectation(description: "Message1")
let realm = realmInMemory(#function)
let elements = [Message("1"), Message("1")]
let scheduler = TestScheduler(initialClock: 0)
let messages$ = Observable.array(from: realm.objects(Message.self)).shareReplay(1)
let rx_delete: AnyObserver<[Message]> = Realm.rx.delete()
try! realm.write {
realm.add(elements)
}
let bag = DisposeBag()
let events = [
next(0, elements),
completed(0)
]
let observer = scheduler.createObserver(Array<Message>.self)
let observable = scheduler.createHotObservable(events).asObservable()
observable.subscribe(rx_delete)
.disposed(by: bag)
messages$.subscribe(observer)
.disposed(by: bag)
messages$.subscribe(onNext: {
switch $0.count {
case 0:
expectation.fulfill()
default:
break
}
}).disposed(by: bag)
scheduler.start()
waitForExpectations(timeout: 0.1, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertTrue(observer.events.count > 0)
XCTAssertEqual(observer.events.last!.time, 0)
XCTAssertTrue(observer.events.last!.value.element!.isEmpty)
})
}
func testRxDeleteItemsWithError() {
let expectation = self.expectation(description: "Message1")
expectation.assertForOverFulfill = false
var conf = Realm.Configuration()
conf.fileURL = URL(string: "/asdasdasdsad")!
let element = [Message("1")]
let scheduler = TestScheduler(initialClock: 0)
let bag = DisposeBag()
let events = [
next(0, element),
completed(0)
]
let observer = scheduler.createObserver(Array<Message>.self)
let observable = scheduler.createHotObservable(events).asObservable()
let rx_delete: AnyObserver<[Message]> = Realm.rx.delete(onError: {elements, error in
XCTAssertNil(elements)
expectation.fulfill()
})
observable.subscribe(rx_delete)
.disposed(by: bag)
Observable.from([element]).subscribe(observer)
.disposed(by: bag)
scheduler.start()
waitForExpectations(timeout: 1.0, handler: {error in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertTrue(observer.events.count > 0)
XCTAssertEqual(observer.events.last!.time, 0)
})
}
func testRxAddObjectsInBg() {
let expectation = self.expectation(description: "All writes completed")
let realm = realmInMemory(#function)
var conf = Realm.Configuration()
conf.inMemoryIdentifier = #function
let bag = DisposeBag()
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Results<Message>.self)
let messages$ = Observable.collection(from: realm.objects(Message.self)).shareReplay(1)
messages$
.subscribe(observer).disposed(by: bag)
messages$
.filter {$0.count == 8}
.subscribe(onNext: {_ in expectation.fulfill() })
.disposed(by: bag)
scheduler.start()
// subscribe/write on current thread
Observable.from([Message("1")])
.subscribe( realm.rx.add() )
.disposed(by: bag)
delayInBackground(0.1, closure: {
// subscribe/write on background thread
let realm = try! Realm(configuration: conf)
Observable.from([Message("2")])
.subscribe(realm.rx.add() )
.disposed(by: bag)
})
// subscribe on current/write on main
Observable.from([Message("3")])
.observeOn(MainScheduler.instance)
.subscribe( Realm.rx.add(configuration: conf) )
.disposed(by: bag)
Observable.from([Message("4")])
.observeOn( ConcurrentDispatchQueueScheduler(
queue: DispatchQueue.global(qos: .background)))
.subscribe( Realm.rx.add(configuration: conf) )
.disposed(by: bag)
// subscribe on current/write on background
Observable.from([[Message("5"), Message("6")]])
.observeOn( ConcurrentDispatchQueueScheduler(
queue: DispatchQueue.global(qos: .background)))
.subscribe( Realm.rx.add(configuration: conf) )
.disposed(by: bag)
// subscribe on current/write on a realm in background
Observable.from([[Message("7"), Message("8")]])
.observeOn( ConcurrentDispatchQueueScheduler(
queue: DispatchQueue.global(qos: .background)))
.subscribe(onNext: {messages in
let realm = try! Realm(configuration: conf)
try! realm.write {
realm.add(messages)
}
})
.disposed(by: bag)
waitForExpectations(timeout: 5.0, handler: {error in
XCTAssertNil(error)
let finalResult = observer.events.last!.value.element!
XCTAssertTrue(finalResult.count == 8, "The final amount of objects in realm are not correct")
XCTAssertTrue((try! Realm(configuration: conf)).objects(Message.self).sorted(byKeyPath: "text")
.reduce("", { acc, el in acc + el.text
}) == "12345678" /*😈*/, "The final list of objects is not the one expected")
})
}
}
| 34.073593 | 126 | 0.578453 |
acd2f2448dfb6ed84c0bda0eb3179e620df8edb3 | 416 | //
// CalendarTableViewHeaderViewModel.swift
// FinalProject
//
// Created by Huyen Nguyen T.T.[2] on 10/15/20.
// Copyright © 2020 Asian Tech Co., Ltd. All rights reserved.
//
import Foundation
final class CalendarTableViewHeaderViewModel {
let title: String
let isExpanded: Bool
init(title: String, isExpanded: Bool) {
self.title = title
self.isExpanded = isExpanded
}
}
| 20.8 | 62 | 0.673077 |
f9c97ce99015195fafa274f20879ffdf2115fa1c | 2,239 | //
// BaseCoordinator.swift
// SwiftRoutingKit
//
// Created by Vitaliy Kuzmenko on 21.03.2019.
// Copyright © 2019 Kuzmenko.info. All rights reserved.
//
import Foundation
import Swinject
open class TabBarCoordinator: Coordinator, TabBarCoordinatorProtocol {
public let router: TabBarRouterProtocol
public init(router: TabBarRouterProtocol, resolver: Resolver) {
self.router = router
super.init(resolver: resolver)
router.tabBarController.delegate = self
}
public func setFlows(_ coordinators: [NavigationCoordinatorProtocol], initialIndex: Int) {
childCoordinators = coordinators
let scenes = coordinators.compactMap({ $0.router.navigationController })
router.set(scenes)
router.tabBarController.selectedIndex = initialIndex
coordinators[initialIndex].start()
}
public var selectedCoordinator: CoordinatorProtocol {
return childCoordinators[router.tabBarController.selectedIndex]
}
public func selectFirst<T: CoordinatorProtocol>(of: T.Type, start: Bool = true) {
if let index = childCoordinators.firstIndex(where: { $0 is T }) {
router.tabBarController.selectedIndex = index
if start {
startCoorinatorForSelectedIndexIfNeeded()
}
}
}
public func getFirst<T: CoordinatorProtocol>(of: T.Type) -> T? {
if let index = childCoordinators.firstIndex(where: { $0 is T }) {
return childCoordinators[index] as? T
} else {
return nil
}
}
public func startCoorinatorForSelectedIndexIfNeeded() {
router.tabBarController.selectedIndex = router.tabBarController.selectedIndex
if let coordinator = self.childCoordinators[router.tabBarController.selectedIndex] as? NavigationCoordinator,
coordinator.router.navigationController.viewControllers.isEmpty {
coordinator.start()
}
}
}
extension TabBarCoordinator: UITabBarControllerDelegate {
public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
startCoorinatorForSelectedIndexIfNeeded()
}
}
| 32.926471 | 118 | 0.684234 |
5b77ff0c1ac9d58c3ad8995c236416a5fde1e518 | 9,760 | //
// IPaVRVideoPlayerView.swift
// IPaAVPlayer
//
// Created by IPa Chen on 2021/11/23.
//
import UIKit
import SceneKit
import SpriteKit
import CoreMotion
import AVFoundation
import IPaAVPlayer
public class IPaVRVideoPlayerView: UIView,IPaVRPlayerSceneControllerDelegate {
@objc public enum VideoMode:Int {
case origin = 0
case hou
case sbs
}
@objc public enum VideoProjection:Int {
case a360 = 0
case a180
case cinema
case fullscreen
}
@objc dynamic public var avPlayer:IPaAVPlayer? {
didSet {
self.leftViewController.setAVPlayer(avPlayer?.avPlayer)
self.rightViewController.setAVPlayer(avPlayer?.avPlayer)
}
}
public var currentEularAngle = SCNVector3(x: 0, y: 0, z: 0) {
didSet {
self.leftViewController.cameraEularAngle = currentEularAngle
self.rightViewController.cameraEularAngle = currentEularAngle
}
}
lazy var _centerHeadAttiture:CMAttitude? = {
return self.motionManager.deviceMotion?.attitude
}()
var centerHeadAttiture:CMAttitude? {
get {
if let _centerHeadAttiture = _centerHeadAttiture {
return _centerHeadAttiture
}
self._centerHeadAttiture = self.motionManager.deviceMotion?.attitude
return self._centerHeadAttiture
}
set {
self._centerHeadAttiture = newValue
}
}
lazy var motionManager:CMMotionManager = {
let manager = CMMotionManager()
manager.deviceMotionUpdateInterval = 1/60.0
return manager
}()
var motionAttitude:CMAttitude? {
return self.motionManager.deviceMotion?.attitude
}
var panGestureRecognizer:UIPanGestureRecognizer?
var pinchGestureRecognizer:UIPinchGestureRecognizer?
lazy var tapGestureRecognizer:UITapGestureRecognizer = {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.onTap(_:)))
self.addGestureRecognizer(recognizer)
return recognizer
}()
public var eyesInterval:Float = 10
@objc dynamic public lazy var vrMenu:IPaVRMenu = {
let menu = IPaVRMenu()
menu.vrPlayerView = self
let playButton = IPaVRMenuPlayButton("play")
let y = menu.size.height * 0.5 - 40
playButton.position = CGPoint(x: menu.size.width * 0.5, y: y)
menu.addUIItem(playButton)
return menu
}() {
didSet {
guard oldValue != vrMenu else {
return
}
vrMenu.vrPlayerView = self
self.leftViewController.vrMenuNode = vrMenu.generateSCNNode()
self.rightViewController.vrMenuNode = vrMenu.generateSCNNode()
}
}
@objc dynamic public var isCardboardMode:Bool {
get {
return !self.rightViewController.view.isHidden
}
set {
self.rightViewController.view.isHidden = !newValue
let interval = self.eyesInterval * 0.5
self.leftViewController.cameraOffsetX = newValue ? -interval : 0
self.rightViewController.cameraOffsetX = newValue ? interval : 0
}
}
@objc dynamic public var isShowVRMenu:Bool = false {
didSet {
self.tapGestureRecognizer.isEnabled = self.isShowVRMenu
self.leftViewController.showVRMenu(isShowVRMenu)
self.rightViewController.showVRMenu(isShowVRMenu)
}
}
public var isTrackingHead:Bool {
get {
return motionManager.isDeviceMotionActive
}
set {
if newValue {
guard !motionManager.isDeviceMotionActive else {
return
}
motionManager.startDeviceMotionUpdates(using: .xArbitraryZVertical)
self.faceToCenter()
self.isPanEnable = false
}
else {
motionManager.stopDeviceMotionUpdates()
}
}
}
public var isPanEnable:Bool {
get {
return self.panGestureRecognizer?.isEnabled ?? false
}
set {
if !newValue {
self.panGestureRecognizer?.isEnabled = false
}
else if self.panGestureRecognizer == nil {
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.onPan(_:)))
self.addGestureRecognizer(gestureRecognizer)
self.panGestureRecognizer = gestureRecognizer
}
else {
self.panGestureRecognizer?.isEnabled = true
}
}
}
public var isPinchEnable:Bool {
get {
return self.pinchGestureRecognizer?.isEnabled ?? false
}
set {
if !newValue {
self.pinchGestureRecognizer?.isEnabled = false
}
else if self.pinchGestureRecognizer == nil {
let gestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.onPinch(_:)))
self.addGestureRecognizer(gestureRecognizer)
self.pinchGestureRecognizer = gestureRecognizer
}
else {
self.pinchGestureRecognizer?.isEnabled = true
}
}
}
var _videoZoom:CGFloat = 1 {
didSet {
self.currentProjection.videoZoom = _videoZoom
self.reattachProjection()
}
}
//videoZoom is between 1 ~ 2
@objc dynamic public var videoZoom:CGFloat {
get {
return self._videoZoom
}
set {
let newZoom = max(1,min(2,newValue))
self._videoZoom = newZoom
}
}
var currentProjection:IPaVRVideoProjection {
get {
return self.leftViewController.projection
}
}
lazy var sphereProjection = IPaVRVideoSphereProjection()
lazy var planeProjection = IPaVRVideoPlaneProjection()
lazy var fullscreenProjection = IPaVRVideoFullScreenProjection()
lazy var leftViewController = IPaVRPlayerSceneController(self,projection:self.sphereProjection)
lazy var rightViewController = IPaVRPlayerSceneController(self,projection:self.sphereProjection)
lazy var stackView:UIStackView = {
let view = UIStackView()
view.distribution = .fillEqually
view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(view)
view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
return view
}()
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
init(_ frame:CGRect) {
super.init(frame: frame)
self.initialSetting()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
open override func awakeFromNib() {
super.awakeFromNib()
self.initialSetting()
}
func initialSetting() {
self.stackView.addArrangedSubview(self.leftViewController.view)
self.stackView.addArrangedSubview(self.rightViewController.view)
self.rightViewController.view.isHidden = true
self.currentEularAngle = self.leftViewController.cameraEularAngle
}
func reattachProjection() {
self.leftViewController.projection = self.currentProjection
self.rightViewController.projection = self.currentProjection
}
public func faceToCenter() {
self.leftViewController.faceToCenter()
self.rightViewController.faceToCenter()
self.currentEularAngle = self.leftViewController.cameraEularAngle
self.centerHeadAttiture = self.motionAttitude
}
@objc func onTap(_ sender:UITapGestureRecognizer) {
if let hitTestResult = self.vrMenu.currentHitTestResult {
guard let node = hitTestResult.node as? IPaVRUIItemResponsableNode else {
return
}
node.uiItem.onTap(hitTestResult)
}
else {
self.isShowVRMenu = false
}
}
@objc func onPinch(_ sender:UIPinchGestureRecognizer) {
self.currentProjection.onPinch(sender, originZoom: self.videoZoom)
if sender.state == .ended {
self.videoZoom = self.currentProjection.videoZoom
}
else {
self.reattachProjection()
}
}
@objc func onPan(_ sender:UIPanGestureRecognizer) {
var newEular = self.currentEularAngle
let translation = sender.translation(in: self)
newEular.y = self.currentEularAngle.y + Float(translation.x * 0.0025)
newEular.x = self.currentEularAngle.x + Float(translation.y * 0.0025)
if sender.state == .ended {
self.currentEularAngle = newEular
}
else {
self.leftViewController.cameraEularAngle = newEular
self.rightViewController.cameraEularAngle = newEular
}
}
func renderer(_ controller: IPaVRPlayerSceneController, updateAtTime time: TimeInterval)
{
if controller == self.leftViewController {
controller.uiHitTest()
}
}
}
| 33.31058 | 115 | 0.614344 |
67a1bdc4cf07ffe9a3f0f2ce64d81b4907dc513b | 626 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "victor-baleeiro",
dependencies: [
// 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),
// 🍃 An expressive, performant, and extensible templating language built for Swift.
.package(url: "https://github.com/vapor/leaf.git", from: "3.0.0"),
],
targets: [
.target(name: "App", dependencies: ["Leaf", "Vapor"]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"])
]
)
| 31.3 | 91 | 0.602236 |
16d5e0c8569ea00a7a0e6152973a61182f25f127 | 530 | import UIKit
var str = "Hello, ProtocolExtension"
protocol Student{
func instituteName()
func otherInfo()
}
extension Student {
func instituteName() {
print("SHKSC")
}
func idPrefix() {
print("ID")
}
func testMethod(){
}
}
struct StudentOne: Student {
func otherInfo() {
print("Other Info")
}
func idPrefix() {
print("Identity")
}
}
StudentOne().instituteName()
StudentOne().idPrefix()
StudentOne().testMethod()
StudentOne().otherInfo()
| 15.588235 | 36 | 0.59434 |
61219d49d0d195b91161a431ce9dc59b4c372e53 | 3,277 | //
// DatabaseClient+Instance.swift
// DatabaseClient
//
// Created by Ihor Yarovyi on 8/28/21.
//
import CoreData
import DatabaseLayer
import PredicateKit
public extension DatabaseClient {
final class Instance {
// MARK: - Properties
private let database: Database.Operator
private let executor = Database.Executor.shared
private static var modelURL: URL? {
Bundle(for: self).url(
forResource: Database.Instance.modelName,
withExtension: "momd"
)
}
// MARK: - Lifecycle
private init(database: Database.Operator) {
self.database = database
}
public static func sqlInstance() -> Instance {
.init(database: Database.Instance.sqliteInstance(modelURL: modelURL))
}
public static func inMemoryInstance() -> Instance {
.init(database: Database.Instance.inMemoryInstance(modelURL: modelURL))
}
}
}
// MARK: - CRUD
public extension DatabaseClient.Instance {
func create<Entity>(
from entity: Entity,
completion: @escaping (Result<Void, Error>) -> Void
) where Entity: Persistable {
database.writeAsync({ [unowned self] context in
let dbEntity = executor.create(Entity.Object.self, context: context)
entity.update(dbEntity)
}, completion: completion)
}
func create<Input>(
from inputs: Input,
completion: @escaping (Result<Void, Error>) -> Void
) where Input: Encodable & Persistable {
database.writeAsync { [unowned self] context in
do {
_ = try executor.batchInsertAndMergeChanges(
models: inputs,
to: Input.Object.self,
onContext: context,
mergeTo: [context, database.mainContext]
)
completion(.success(()))
} catch {
completion(.failure(error))
}
}
}
func contains<Entity>(
_ entity: Entity.Type,
where predicate: @escaping () -> Predicate<Entity.Object>,
completion: @escaping (Result<Bool, Error>) -> Void
) where Entity: Persistable {
database.backgroundReadSync { context in
do {
let result: Entity.Object? = try context.fetch(where: predicate()).result().first
completion(.success(result != nil))
} catch {
completion(.failure(error))
}
}
}
}
// MARK: - ProviderProtocol
extension DatabaseClient.Instance: ProviderProtocol {
public var storageOperator: Database.Operator {
database
}
public func configure() {
// empty implementation
}
public func removeData<Model>(_ data: [Model.Type]) where Model: NSManagedObject {
storageOperator.writeAsync { [unowned self] context in
data.forEach { entity in
try? executor.batchDeleteAndMergeChanges(
entity,
onContext: context,
mergeTo: [context, storageOperator.mainContext]
)
}
}
}
}
| 30.342593 | 97 | 0.563015 |
e8615cb4ae44277ac2c9c3a2cd7b08697272ebc9 | 755 | import UIKit
import XCTest
import Sonar
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.166667 | 111 | 0.602649 |
909d988435ac9b89678b0c833e8e0ec1418a0d5f | 1,953 | ///**
/**
Copyright © 2019 Ford Motor Company. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
@testable import retroquest
class FakeItemsService<T: Item> {
var dummyItemsMethodCalls: Int = 0
var dummyItemsReturned: [T]?
var getItemsCalled: Bool = false
func fakeRequestItemsFromServer(items: [T], callback: @escaping ([T]?) -> Void) -> Bool {
getItemsCalled = true
callback(items)
return false
}
func dummyItemsMethod(items: [T]?) {
dummyItemsMethodCalls += 1
dummyItemsReturned = items
}
func dummyItemMethod(item: T?) {
dummyItemsMethodCalls += 1
if item != nil {
if dummyItemsReturned == nil {
dummyItemsReturned = [item!]
} else {
dummyItemsReturned!.append(item!)
}
}
}
func resetDummies() {
dummyItemsMethodCalls = 0
dummyItemsReturned = nil
}
func getDummyResponse(team: String) -> Data? {
let exampleDummy = T.init(id: 1000, teamId: team, deletion: false)
var itemArray: [T] = []
itemArray.append(exampleDummy)
let encodedData = try? JSONEncoder().encode(itemArray)
return encodedData
}
func getBlankDummyResponse() -> Data? {
let emptyItemArray: [T] = []
let encodedData = try? JSONEncoder().encode(emptyItemArray)
return encodedData
}
}
| 26.753425 | 93 | 0.647209 |
1dfd7008e13fc70ca4fdcee1f6dab6f841f40237 | 565 | //
// AppResponse.swift
// AppStoreConnect-Swift-SDK
//
// Created by Pascal Edmond on 12/11/2018.
//
import Foundation
/// A response containing a single resource.
public struct AppResponse: Codable {
/// The resource data.
public let data: App
/// The requested relationship data.
/// Possible types: BetaGroup, PrereleaseVersion, BetaAppLocalization, Build, BetaLicenseAgreement, BetaAppReviewDetail
public let included: [AppRelationship]?
/// Navigational links that include the self-link.
public let links: DocumentLinks
}
| 24.565217 | 123 | 0.723894 |
0e16b84827a06486233cc69376cba15bd9d71c24 | 1,675 | //
// Tela2ViewController.swift
// TesteNavegacao
//
// Created by Ian Manor on 02/03/21.
//
import UIKit
class Tela2ViewController: UIViewController {
@IBOutlet weak var meuBotao: UIButton!
@IBOutlet weak var meuSwitch: UISwitch!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("Tela2ViewController:viewWillAppear")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("Tela2ViewController:viewDidAppear")
}
override func viewDidLoad() {
super.viewDidLoad()
print("Tela2ViewController:viewDidLoad")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("Tela2ViewController:viewWillDisappear")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("Tela2ViewController:viewDidDisappear")
}
@IBAction func voltar(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func irParaProximaTela(_ sender: Any) {
if meuSwitch.isOn {
irTela3()
} else {
irTela4()
}
}
@IBAction func mudouDeValor(_ sender: Any) {
if meuSwitch.isOn {
meuBotao.setTitle("Ir para tela 3", for: .normal)
} else {
meuBotao.setTitle("Ir para tela 4", for: .normal)
}
}
func irTela3() {
self.performSegue(withIdentifier: "irTela3", sender: nil)
}
func irTela4() {
self.performSegue(withIdentifier: "irTela4", sender: nil)
}
}
| 25 | 65 | 0.629254 |
7a214ba0f01560d0e3549defa702ad2126c95860 | 1,062 | //
// ContentView.swift
// eul
//
// Created by Gao Sun on 2020/6/21.
// Copyright © 2020 Gao Sun. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@ObservedObject var preferenceStore = PreferenceStore.shared
var body: some View {
VStack(alignment: .leading, spacing: 12) {
SectionView(title: "ui.general") {
Preference.GeneralView()
}
SectionView(title: "ui.display") {
Preference.DisplayView()
}
SectionView(title: "ui.refresh_rate") {
Preference.RefreshRateView()
}
SectionView(title: "ui.components") {
Preference
.ComponentsView()
.padding(.top, 8)
}
SectionView(title: "ui.menu_view") {
Preference.PreferenceMenuViewView()
}
}
.padding(20)
.frame(minWidth: 610)
.environmentObject(preferenceStore)
.id(preferenceStore.language)
}
}
| 26.55 | 64 | 0.530132 |
11978109d9596d72a587de0d1b8d2b864062b16e | 436 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class B{enum B:a{}protocol a{struct Q<f:f.c
| 43.6 | 78 | 0.747706 |
08d135ba53475025c355ab950d22cfbe2e142aca | 396 | //
// KeywordsTableViewCell.swift
// Discovery
//
// Created by 여나경 on 2021/05/23.
//
import UIKit
class KeywordsTableViewCell: UITableViewCell {
@IBOutlet weak var keywordImage: UIImageView!
@IBOutlet weak var keywordImageLabel: UIImageView!
// 재사용 준비
// override func prepareForReuse() {
// super.prepareForReuse()
//
// self.accessoryType = .none
// }
}
| 18 | 54 | 0.664141 |
7ae061d31b41c1178cc5482402fc3b7b877f1ed4 | 17,068 | //
// Condition.swift
// SwiftFHIR
//
// Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Condition) on 2016-09-16.
// 2016, SMART Health IT.
//
import Foundation
/**
* Detailed information about conditions, problems or diagnoses.
*
* Use to record detailed information about conditions, problems or diagnoses recognized by a clinician. There are many
* uses including: recording a diagnosis during an encounter; populating a problem list or a summary statement, such as
* a discharge summary.
*/
public class Condition: DomainResource {
override public class var resourceType: String {
get { return "Condition" }
}
/// If/when in resolution/remission.
public var abatementBoolean: Bool?
/// If/when in resolution/remission.
public var abatementDateTime: DateTime?
/// If/when in resolution/remission.
public var abatementPeriod: Period?
/// If/when in resolution/remission.
public var abatementQuantity: Quantity?
/// If/when in resolution/remission.
public var abatementRange: Range?
/// If/when in resolution/remission.
public var abatementString: String?
/// Person who asserts this condition.
public var asserter: Reference?
/// Anatomical location, if relevant.
public var bodySite: [CodeableConcept]?
/// complaint | symptom | finding | diagnosis.
public var category: CodeableConcept?
/// active | relapse | remission | resolved.
public var clinicalStatus: String?
/// Identification of the condition, problem or diagnosis.
public var code: CodeableConcept?
/// When first entered.
public var dateRecorded: FHIRDate?
/// Encounter when condition first asserted.
public var encounter: Reference?
/// Supporting evidence.
public var evidence: [ConditionEvidence]?
/// External Ids for this condition.
public var identifier: [Identifier]?
/// Additional information about the Condition.
public var notes: String?
/// Estimated or actual date, date-time, or age.
public var onsetDateTime: DateTime?
/// Estimated or actual date, date-time, or age.
public var onsetPeriod: Period?
/// Estimated or actual date, date-time, or age.
public var onsetQuantity: Quantity?
/// Estimated or actual date, date-time, or age.
public var onsetRange: Range?
/// Estimated or actual date, date-time, or age.
public var onsetString: String?
/// Who has the condition?.
public var patient: Reference?
/// Subjective severity of condition.
public var severity: CodeableConcept?
/// Stage/grade, usually assessed formally.
public var stage: ConditionStage?
/// provisional | differential | confirmed | refuted | entered-in-error | unknown.
public var verificationStatus: String?
/** Initialize with a JSON object. */
public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) {
super.init(json: json, owner: owner)
}
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(code: CodeableConcept, patient: Reference, verificationStatus: String) {
self.init(json: nil)
self.code = code
self.patient = patient
self.verificationStatus = verificationStatus
}
public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? {
var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]()
if let js = json {
if let exist = js["abatementBoolean"] {
presentKeys.insert("abatementBoolean")
if let val = exist as? Bool {
self.abatementBoolean = val
}
else {
errors.append(FHIRJSONError(key: "abatementBoolean", wants: Bool.self, has: Swift.type(of: exist)))
}
}
if let exist = js["abatementDateTime"] {
presentKeys.insert("abatementDateTime")
if let val = exist as? String {
self.abatementDateTime = DateTime(string: val)
}
else {
errors.append(FHIRJSONError(key: "abatementDateTime", wants: String.self, has: Swift.type(of: exist)))
}
}
if let exist = js["abatementPeriod"] {
presentKeys.insert("abatementPeriod")
if let val = exist as? FHIRJSON {
self.abatementPeriod = Period(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "abatementPeriod", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["abatementQuantity"] {
presentKeys.insert("abatementQuantity")
if let val = exist as? FHIRJSON {
self.abatementQuantity = Quantity(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "abatementQuantity", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["abatementRange"] {
presentKeys.insert("abatementRange")
if let val = exist as? FHIRJSON {
self.abatementRange = Range(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "abatementRange", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["abatementString"] {
presentKeys.insert("abatementString")
if let val = exist as? String {
self.abatementString = val
}
else {
errors.append(FHIRJSONError(key: "abatementString", wants: String.self, has: Swift.type(of: exist)))
}
}
if let exist = js["asserter"] {
presentKeys.insert("asserter")
if let val = exist as? FHIRJSON {
self.asserter = Reference(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "asserter", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["bodySite"] {
presentKeys.insert("bodySite")
if let val = exist as? [FHIRJSON] {
self.bodySite = CodeableConcept.instantiate(fromArray: val, owner: self) as? [CodeableConcept]
}
else {
errors.append(FHIRJSONError(key: "bodySite", wants: Array<FHIRJSON>.self, has: Swift.type(of: exist)))
}
}
if let exist = js["category"] {
presentKeys.insert("category")
if let val = exist as? FHIRJSON {
self.category = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "category", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["clinicalStatus"] {
presentKeys.insert("clinicalStatus")
if let val = exist as? String {
self.clinicalStatus = val
}
else {
errors.append(FHIRJSONError(key: "clinicalStatus", wants: String.self, has: Swift.type(of: exist)))
}
}
if let exist = js["code"] {
presentKeys.insert("code")
if let val = exist as? FHIRJSON {
self.code = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "code", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
else {
errors.append(FHIRJSONError(key: "code"))
}
if let exist = js["dateRecorded"] {
presentKeys.insert("dateRecorded")
if let val = exist as? String {
self.dateRecorded = FHIRDate(string: val)
}
else {
errors.append(FHIRJSONError(key: "dateRecorded", wants: String.self, has: Swift.type(of: exist)))
}
}
if let exist = js["encounter"] {
presentKeys.insert("encounter")
if let val = exist as? FHIRJSON {
self.encounter = Reference(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "encounter", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["evidence"] {
presentKeys.insert("evidence")
if let val = exist as? [FHIRJSON] {
self.evidence = ConditionEvidence.instantiate(fromArray: val, owner: self) as? [ConditionEvidence]
}
else {
errors.append(FHIRJSONError(key: "evidence", wants: Array<FHIRJSON>.self, has: Swift.type(of: exist)))
}
}
if let exist = js["identifier"] {
presentKeys.insert("identifier")
if let val = exist as? [FHIRJSON] {
self.identifier = Identifier.instantiate(fromArray: val, owner: self) as? [Identifier]
}
else {
errors.append(FHIRJSONError(key: "identifier", wants: Array<FHIRJSON>.self, has: Swift.type(of: exist)))
}
}
if let exist = js["notes"] {
presentKeys.insert("notes")
if let val = exist as? String {
self.notes = val
}
else {
errors.append(FHIRJSONError(key: "notes", wants: String.self, has: Swift.type(of: exist)))
}
}
if let exist = js["onsetDateTime"] {
presentKeys.insert("onsetDateTime")
if let val = exist as? String {
self.onsetDateTime = DateTime(string: val)
}
else {
errors.append(FHIRJSONError(key: "onsetDateTime", wants: String.self, has: Swift.type(of: exist)))
}
}
if let exist = js["onsetPeriod"] {
presentKeys.insert("onsetPeriod")
if let val = exist as? FHIRJSON {
self.onsetPeriod = Period(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "onsetPeriod", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["onsetQuantity"] {
presentKeys.insert("onsetQuantity")
if let val = exist as? FHIRJSON {
self.onsetQuantity = Quantity(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "onsetQuantity", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["onsetRange"] {
presentKeys.insert("onsetRange")
if let val = exist as? FHIRJSON {
self.onsetRange = Range(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "onsetRange", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["onsetString"] {
presentKeys.insert("onsetString")
if let val = exist as? String {
self.onsetString = val
}
else {
errors.append(FHIRJSONError(key: "onsetString", wants: String.self, has: Swift.type(of: exist)))
}
}
if let exist = js["patient"] {
presentKeys.insert("patient")
if let val = exist as? FHIRJSON {
self.patient = Reference(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "patient", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
else {
errors.append(FHIRJSONError(key: "patient"))
}
if let exist = js["severity"] {
presentKeys.insert("severity")
if let val = exist as? FHIRJSON {
self.severity = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "severity", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["stage"] {
presentKeys.insert("stage")
if let val = exist as? FHIRJSON {
self.stage = ConditionStage(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "stage", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["verificationStatus"] {
presentKeys.insert("verificationStatus")
if let val = exist as? String {
self.verificationStatus = val
}
else {
errors.append(FHIRJSONError(key: "verificationStatus", wants: String.self, has: Swift.type(of: exist)))
}
}
else {
errors.append(FHIRJSONError(key: "verificationStatus"))
}
}
return errors.isEmpty ? nil : errors
}
override public func asJSON() -> FHIRJSON {
var json = super.asJSON()
if let abatementBoolean = self.abatementBoolean {
json["abatementBoolean"] = abatementBoolean.asJSON()
}
if let abatementDateTime = self.abatementDateTime {
json["abatementDateTime"] = abatementDateTime.asJSON()
}
if let abatementPeriod = self.abatementPeriod {
json["abatementPeriod"] = abatementPeriod.asJSON()
}
if let abatementQuantity = self.abatementQuantity {
json["abatementQuantity"] = abatementQuantity.asJSON()
}
if let abatementRange = self.abatementRange {
json["abatementRange"] = abatementRange.asJSON()
}
if let abatementString = self.abatementString {
json["abatementString"] = abatementString.asJSON()
}
if let asserter = self.asserter {
json["asserter"] = asserter.asJSON()
}
if let bodySite = self.bodySite {
json["bodySite"] = bodySite.map() { $0.asJSON() }
}
if let category = self.category {
json["category"] = category.asJSON()
}
if let clinicalStatus = self.clinicalStatus {
json["clinicalStatus"] = clinicalStatus.asJSON()
}
if let code = self.code {
json["code"] = code.asJSON()
}
if let dateRecorded = self.dateRecorded {
json["dateRecorded"] = dateRecorded.asJSON()
}
if let encounter = self.encounter {
json["encounter"] = encounter.asJSON()
}
if let evidence = self.evidence {
json["evidence"] = evidence.map() { $0.asJSON() }
}
if let identifier = self.identifier {
json["identifier"] = identifier.map() { $0.asJSON() }
}
if let notes = self.notes {
json["notes"] = notes.asJSON()
}
if let onsetDateTime = self.onsetDateTime {
json["onsetDateTime"] = onsetDateTime.asJSON()
}
if let onsetPeriod = self.onsetPeriod {
json["onsetPeriod"] = onsetPeriod.asJSON()
}
if let onsetQuantity = self.onsetQuantity {
json["onsetQuantity"] = onsetQuantity.asJSON()
}
if let onsetRange = self.onsetRange {
json["onsetRange"] = onsetRange.asJSON()
}
if let onsetString = self.onsetString {
json["onsetString"] = onsetString.asJSON()
}
if let patient = self.patient {
json["patient"] = patient.asJSON()
}
if let severity = self.severity {
json["severity"] = severity.asJSON()
}
if let stage = self.stage {
json["stage"] = stage.asJSON()
}
if let verificationStatus = self.verificationStatus {
json["verificationStatus"] = verificationStatus.asJSON()
}
return json
}
}
/**
* Supporting evidence.
*
* Supporting Evidence / manifestations that are the basis on which this condition is suspected or confirmed.
*/
public class ConditionEvidence: BackboneElement {
override public class var resourceType: String {
get { return "ConditionEvidence" }
}
/// Manifestation/symptom.
public var code: CodeableConcept?
/// Supporting information found elsewhere.
public var detail: [Reference]?
/** Initialize with a JSON object. */
public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) {
super.init(json: json, owner: owner)
}
public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? {
var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]()
if let js = json {
if let exist = js["code"] {
presentKeys.insert("code")
if let val = exist as? FHIRJSON {
self.code = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "code", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
if let exist = js["detail"] {
presentKeys.insert("detail")
if let val = exist as? [FHIRJSON] {
self.detail = Reference.instantiate(fromArray: val, owner: self) as? [Reference]
}
else {
errors.append(FHIRJSONError(key: "detail", wants: Array<FHIRJSON>.self, has: Swift.type(of: exist)))
}
}
}
return errors.isEmpty ? nil : errors
}
override public func asJSON() -> FHIRJSON {
var json = super.asJSON()
if let code = self.code {
json["code"] = code.asJSON()
}
if let detail = self.detail {
json["detail"] = detail.map() { $0.asJSON() }
}
return json
}
}
/**
* Stage/grade, usually assessed formally.
*
* Clinical stage or grade of a condition. May include formal severity assessments.
*/
public class ConditionStage: BackboneElement {
override public class var resourceType: String {
get { return "ConditionStage" }
}
/// Formal record of assessment.
public var assessment: [Reference]?
/// Simple summary (disease specific).
public var summary: CodeableConcept?
/** Initialize with a JSON object. */
public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) {
super.init(json: json, owner: owner)
}
public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? {
var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]()
if let js = json {
if let exist = js["assessment"] {
presentKeys.insert("assessment")
if let val = exist as? [FHIRJSON] {
self.assessment = Reference.instantiate(fromArray: val, owner: self) as? [Reference]
}
else {
errors.append(FHIRJSONError(key: "assessment", wants: Array<FHIRJSON>.self, has: Swift.type(of: exist)))
}
}
if let exist = js["summary"] {
presentKeys.insert("summary")
if let val = exist as? FHIRJSON {
self.summary = CodeableConcept(json: val, owner: self)
}
else {
errors.append(FHIRJSONError(key: "summary", wants: FHIRJSON.self, has: Swift.type(of: exist)))
}
}
}
return errors.isEmpty ? nil : errors
}
override public func asJSON() -> FHIRJSON {
var json = super.asJSON()
if let assessment = self.assessment {
json["assessment"] = assessment.map() { $0.asJSON() }
}
if let summary = self.summary {
json["summary"] = summary.asJSON()
}
return json
}
}
| 30.424242 | 120 | 0.664987 |
20d780023119d06cab035d577ccc064d9047a2dd | 4,268 | /*
* Copyright (c) 2012-2020 MIRACL UK Ltd.
*
* This file is part of MIRACL Core
* (see https://github.com/miracl/core).
*
* 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.
*/
//
// rom.swift
//
// Created by Michael Scott on 12/06/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
public struct ROM{
#if D32
// Base Bits= 29
// nums512 Modulus
static let Modulus:[Chunk] = [0x1FFFFDC7,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFFF]
static let ROI:[Chunk] = [0x1FFFFDC6,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFFF]
static let R2modp:[Chunk] = [0xB100000,0x278,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let MConst:Chunk = 0x239
// nums512 Weierstrass Curve
static let CURVE_Cof_I:Int = 1
static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let CURVE_B_I:Int = 121243
static let CURVE_B:[Chunk] = [0x1D99B,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Order:[Chunk] = [0x433555D,0x10A9F9C8,0x1F3490F3,0xD166CC0,0xBDC63B5,0xC76CBE8,0xC6D3F09,0x1F729CF0,0x1F5B3CA4,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFFF]
static public let CURVE_Gx:[Chunk] = [0xCABAE57,0x4143CAC,0x1BD778B7,0x1AC026FA,0x15831D5,0x14312AB,0x167A4DE5,0xA20ED66,0x195021A1,0x129836CF,0x1141B830,0xA03ED0A,0xCAD83BB,0x1E9DA94C,0xDC00A80,0x1527B45,0x1447141D,0x1D601]
static public let CURVE_Gy:[Chunk] = [0x183527A6,0x1D043B01,0x1F43FA48,0x16B83C99,0x5602CF2,0x1420592D,0x17A70486,0x1B5161DD,0x14A28415,0x3DE8A78,0x3D2C983,0x17797719,0x197DBDEA,0x15D88025,0x1BBB718F,0xAD679C1,0x14CA29AD,0x4A1D2]
static public let CURVE_HTPC:[Chunk] = [0x1FFFFEE3,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x3FFFF]
#endif
#if D64
// Base Bits= 60
// nums512 Modulus
static let Modulus:[Chunk] = [0xFFFFFFFFFFFFDC7,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFF]
static let ROI:[Chunk] = [0xFFFFFFFFFFFFDC6,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFF]
static let R2modp:[Chunk] = [0x100000000000000,0x4F0B,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let MConst:Chunk = 0x239
// nums512 Weierstrass Curve
static let CURVE_Cof_I:Int = 1
static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let CURVE_B_I:Int = 121243
static let CURVE_B:[Chunk] = [0x1D99B,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Order:[Chunk] = [0xE153F390433555D,0x568B36607CD243C,0x258ED97D0BDC63B,0xA4FB94E7831B4FC,0xFFFFFFFFFFF5B3C,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFF]
static public let CURVE_Gx:[Chunk] = [0xC8287958CABAE57,0x5D60137D6F5DE2D,0x94286255615831D,0xA151076B359E937,0xC25306D9F95021,0x3BB501F6854506E,0x2A03D3B5298CAD8,0x141D0A93DA2B700,0x3AC03447]
static public let CURVE_Gy:[Chunk] = [0x3A08760383527A6,0x2B5C1E4CFD0FE92,0x1A840B25A5602CF,0x15DA8B0EEDE9C12,0x60C7BD14F14A284,0xDEABBCBB8C8F4B2,0xC63EBB1004B97DB,0x29AD56B3CE0EEED,0x943A54CA]
static public let CURVE_HTPC:[Chunk] = [0xFFFFFFFFFFFFEE3,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0x7FFFFFFF]
#endif
}
| 59.277778 | 235 | 0.81865 |
d9283878bc653017f9a3f2e3542cbdbccf8850cd | 357 | //
// V0AvatarPromoteResponseModel.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct V0AvatarPromoteResponseModel: Codable {
public var data: V0AvatarPromoteResponseItemModel?
public init(data: V0AvatarPromoteResponseItemModel?) {
self.data = data
}
}
| 15.521739 | 58 | 0.733894 |
1cfdeaed3e08d1239868dce52aa83166db4bdb4b | 4,749 | import BucketQueue
import BucketQueueModels
import BucketQueueTestHelpers
import Foundation
import QueueCommunication
import QueueCommunicationTestHelpers
import QueueModels
import QueueModelsTestHelpers
import RunnerModels
import WorkerAlivenessProvider
import UniqueIdentifierGeneratorTestHelpers
import XCTest
final class SingleBucketQueueStuckBucketsReenqueuerTests: XCTestCase {
lazy var bucketQueueHolder = BucketQueueHolder()
lazy var enqueuedBuckets = [Bucket]()
lazy var bucketEnqueuer = FakeBucketEnqueuer { buckets in
self.enqueuedBuckets.append(contentsOf: buckets)
}
lazy var uniqueIdentifierGenerator = FixedValueUniqueIdentifierGenerator()
lazy var workerAlivenessProvider = WorkerAlivenessProviderImpl(
logger: .noOp,
workerPermissionProvider: workerPermissionProvider
)
lazy var workerPermissionProvider = FakeWorkerPermissionProvider()
lazy var workerId = WorkerId("workerId")
lazy var reenqueuer = SingleBucketQueueStuckBucketsReenqueuer(
bucketEnqueuer: bucketEnqueuer,
bucketQueueHolder: bucketQueueHolder,
logger: .noOp,
workerAlivenessProvider: workerAlivenessProvider,
uniqueIdentifierGenerator: uniqueIdentifierGenerator
)
func test___when_no_stuck_buckets___nothing_reenqueued() {
workerAlivenessProvider.didRegisterWorker(workerId: workerId)
let bucket = BucketFixtures.createBucket()
workerAlivenessProvider.set(bucketIdsBeingProcessed: [bucket.bucketId], workerId: workerId)
bucketQueueHolder.add(
dequeuedBucket: DequeuedBucket(
enqueuedBucket: EnqueuedBucket(
bucket: bucket,
enqueueTimestamp: Date(),
uniqueIdentifier: "id"
),
workerId: workerId
)
)
XCTAssertTrue(try reenqueuer.reenqueueStuckBuckets().isEmpty)
XCTAssertTrue(enqueuedBuckets.isEmpty)
}
func test___when_worker_stops_processing_bucket___bucket_gets_reenqueued_into_individual_buckets_for_each_test_entry() {
workerAlivenessProvider.didRegisterWorker(workerId: workerId)
let testEntries = [
TestEntry(testName: TestName(className: "class", methodName: "method1"), tags: [], caseId: nil),
TestEntry(testName: TestName(className: "class", methodName: "method2"), tags: [], caseId: nil),
]
let bucket = BucketFixtures.createBucket(
testEntries: testEntries
)
workerAlivenessProvider.set(bucketIdsBeingProcessed: [], workerId: workerId)
bucketQueueHolder.add(
dequeuedBucket: DequeuedBucket(
enqueuedBucket: EnqueuedBucket(
bucket: bucket,
enqueueTimestamp: Date(),
uniqueIdentifier: "id"
),
workerId: workerId
)
)
XCTAssertEqual(
try reenqueuer.reenqueueStuckBuckets(),
[StuckBucket(reason: .bucketLost, bucket: bucket, workerId: workerId)]
)
XCTAssertTrue(bucketQueueHolder.allDequeuedBuckets.isEmpty)
XCTAssertEqual(
enqueuedBuckets.map { $0.payload.testEntries },
testEntries.map { [$0] }
)
}
func test___when_worker_is_silent___bucket_gets_reenqueued_into_individual_buckets_for_each_test_entry() {
workerAlivenessProvider.didRegisterWorker(workerId: workerId)
let testEntries = [
TestEntry(testName: TestName(className: "class", methodName: "method1"), tags: [], caseId: nil),
TestEntry(testName: TestName(className: "class", methodName: "method2"), tags: [], caseId: nil),
]
let bucket = BucketFixtures.createBucket(
testEntries: testEntries
)
workerAlivenessProvider.setWorkerIsSilent(workerId: workerId)
bucketQueueHolder.add(
dequeuedBucket: DequeuedBucket(
enqueuedBucket: EnqueuedBucket(
bucket: bucket,
enqueueTimestamp: Date(),
uniqueIdentifier: "id"
),
workerId: workerId
)
)
XCTAssertEqual(
try reenqueuer.reenqueueStuckBuckets(),
[StuckBucket(reason: .workerIsSilent, bucket: bucket, workerId: workerId)]
)
XCTAssertTrue(bucketQueueHolder.allDequeuedBuckets.isEmpty)
XCTAssertEqual(
enqueuedBuckets.map { $0.payload.testEntries },
testEntries.map { [$0] }
)
}
}
| 37.101563 | 124 | 0.645399 |
797d724a0d4054d0cafa8a7a6423723973a9b714 | 6,040 | //
// HomeServices.swift
// B2CSDK
//
// Created by Raj Kadam on 18/05/22.
//
import Foundation
import ObjectMapper
import Alamofire
import AVFAudio
struct HomeService {
func getJWTToken(param: [String: Any], completionHandler: @escaping (ServiceError?) -> Void){
let endPoint = "\(APIConstants.JWT_TOKEN)"
APIClient.getInstance().requestJson(endPoint, .post, parameters: param) { result, error, refresh, code in
if code == ResponseCode.success {
print("code: ", code)
}
if (200 ... 299).contains(code) {
if let result = result {
let tokenModel = Mapper<JWTModel>().map(JSONObject: result)
B2CUserDefaults.setAccessToken(token: tokenModel?.token)
completionHandler(nil)
} else {
completionHandler(error)
}//
}else {
completionHandler(error)
}
}
}
func getContentPublisherDetails(contentPublisherId: String, completionHandler: @escaping (ContentPublishersDetails?, ServiceError?) -> Void) {
let header = APIClient.getInstance().getJWTHeader()
let endPoint = "\(APIConstants.ContentPublisher)/\(contentPublisherId)"
APIClient.getInstance().requestJson( endPoint, .get, parameters: nil, headers: header) { (result, error, isExpire, code) in
if isExpire {
//UIUtils.showDefaultAlertView(title: AlertTitles.Error, message: "Token exp")
completionHandler(nil, ServiceError.init(statusCode: 0, message: ""))
} else {
if let error = error {
completionHandler(nil, error)
}else if let result = result {
let details = Mapper<ContentPublishersDetails>().map(JSONObject: result)
completionHandler(details, nil)
}
}
}
}
func getContentProviderVideos(contentProviderId: String, completionHandler: @escaping ([ContentProviderDetailsModel]?, ServiceError?) -> Void) {
// let fil = "https://dev.api.degpeg.com/content-providers/${id}/live-sessions?filter={"include":[{"relation":"liveSessionCategory"}],"where":{"status":{"neq":"deleted"}}}"
let header = APIClient.getInstance().getJWTHeader()
let endPoint = "\(APIConstants.ContentProviders)/\(contentProviderId)/live-sessions"
let neqDict = ["neq":"deleted"]
let whereParam = ["status":neqDict]
let includeObject = ["relation":"liveSessionCategory"]
let includeAr = [includeObject]
let filterParam = ["include":includeAr, "where":whereParam] as [String : Any]
let param = ["filter":filterParam]
APIClient.getInstance().requestJson( endPoint, .get, parameters: param, encoding: URLEncoding.default, headers: header) { (result, error, isExpire, code) in
if isExpire {
completionHandler(nil, ServiceError.init(statusCode: 0, message: ""))
} else {
if let error = error {
completionHandler(nil, error)
}else if let result = result as? NSArray{
let videoList = Mapper<ContentProviderDetailsModel>().mapArray(JSONArray: result as! [[String : Any]])
completionHandler(videoList, nil)
}
}
}
}
// MARK: - Get Channel Details
func getChannelDetails(for channelID: String, completionHandler: @escaping (ChannelData?, ServiceError?) -> Void) {
let endPoint = "\(APIConstants.Channels)/\(channelID)"
let header = APIClient.getInstance().getJWTHeader()
APIClient.getInstance().requestJson(endPoint, .get, headers: header) { result, error, refresh, code in
if let result = result {
let session = Mapper<ChannelData>().map(JSONObject: result as! [String: Any])
completionHandler(session, nil)
} else {
completionHandler(nil, error)
}
}
}
// MARK: - Get Categories
func getAllCategories(completionHandler: @escaping ([CategoryData]?, ServiceError?) -> Void) {
let endPoint = "\(APIConstants.CategoriesList)"
let header = APIClient.getInstance().getJWTHeader()
APIClient.getInstance().requestJson( endPoint, .get, parameters: nil, encoding: URLEncoding.default, headers: header) { (result, error, isExpire, code) in
if isExpire {
completionHandler(nil, ServiceError.init(statusCode: 0, message: "Token exp"))
} else {
if let error = error {
completionHandler(nil, error)
}else if let result = result {
let categories = Mapper<CategoryData>().mapArray(JSONArray: result as! [[String : Any]])
completionHandler(categories, nil)
}
}
}
}
}
extension HomeService {
// MARK: - User Details
func getUserDetails(param: [String: Any], completionHandler: @escaping ([UserDetails]?, ServiceError?) -> Void) {
let endPoint = "\(APIConstants.UserDetail)"
let header = APIClient.getInstance().getJWTHeader()
APIClient.getInstance().requestJson( endPoint, .get, parameters: param, encoding: URLEncoding.default, headers: header) { (result, error, isExpire, code) in
if isExpire {
completionHandler(nil, ServiceError.init(statusCode: 0, message: "Token exp"))
} else {
if let error = error {
completionHandler(nil, error)
}else if let result = result {
let details = Mapper<UserDetails>().mapArray(JSONArray: result as! [[String : Any]])
completionHandler(details, nil)
}
}
}
}
}
| 44.740741 | 179 | 0.58096 |
67f2fd3dfca199d59af3f4896334071afda41fbd | 722 | //
// Preferences.swift
// Asset Catalog Tinkerer
//
// Created by Guilherme Rambo on 22/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
final class Preferences {
enum Key: String {
case distinguishCatalogsAndThemeStores
case ignorePackedAssets
}
static let shared = Preferences()
private let defaults: UserDefaults
init(defaults: UserDefaults = UserDefaults.standard) {
self.defaults = defaults
}
subscript(key: Key) -> Bool {
get {
return defaults.bool(forKey: key.rawValue)
}
set {
defaults.set(newValue, forKey: key.rawValue)
}
}
}
| 20.055556 | 58 | 0.603878 |
117b016b80e1d18517e3683061069c5394e69b40 | 1,452 | //
// AppDelegate.swift
// Pitch Perfect
//
// Created by aekachai tungrattanavalee on 17/1/2563 BE.
// Copyright © 2563 aekachai tungrattanavalee. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 38.210526 | 179 | 0.752066 |
18262dc1c81ca34be81cda2563b5329f4abd132d | 1,077 | //
// String+encrypt.swift
// HHHKit
//
// Created by huahuahu on 2019/1/20.
//
import Foundation
import CommonCrypto
public extension String {
/// 对字符串MD5加密
///
/// - Returns: 字符串md5 之后的结果
func md5() -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
_ = withCString { (body) in
CC_MD5(body, CC_LONG(self.utf8.count), &digest)
}
return digest.reduce("") { $0 + String.init(format: "%02x", $1) }
}
/// 对字符串 sha1 加密
///
/// - Returns: 字符串 sha1 之后的结果
func sha1() -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
_ = withCString { (body) in
CC_SHA1(body, CC_LONG(self.utf8.count), &digest)
}
// if let d = self.data(using: String.Encoding.utf8) {
// _ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in
// CC_SHA1(body, CC_LONG(d.count), &digest)
// }
// }
return digest.reduce("") { $0 + String.init(format: "%02x", $1) }
}
}
| 26.268293 | 77 | 0.545961 |
29378e7c38a808a162af5318aca04b37e4bff79f | 8,557 | import Foundation
import UIKit
import TelegramCore
import SyncCore
import Display
enum InstantPageTextStyle {
case fontSize(CGFloat)
case lineSpacingFactor(CGFloat)
case fontSerif(Bool)
case fontFixed(Bool)
case bold
case italic
case underline
case strikethrough
case textColor(UIColor)
case `subscript`
case superscript
case markerColor(UIColor)
case marker
case anchor(String, NSAttributedString?, Bool)
case linkColor(UIColor)
case linkMarkerColor(UIColor)
case link(Bool)
}
let InstantPageLineSpacingFactorAttribute = "LineSpacingFactorAttribute"
let InstantPageMarkerColorAttribute = "MarkerColorAttribute"
let InstantPageMediaIdAttribute = "MediaIdAttribute"
let InstantPageMediaDimensionsAttribute = "MediaDimensionsAttribute"
let InstantPageAnchorAttribute = "AnchorAttribute"
final class InstantPageTextStyleStack {
private var items: [InstantPageTextStyle] = []
func push(_ item: InstantPageTextStyle) {
self.items.append(item)
}
func pop() {
if !self.items.isEmpty {
self.items.removeLast()
}
}
func textAttributes() -> [NSAttributedString.Key: Any] {
var fontSize: CGFloat?
var fontSerif: Bool?
var fontFixed: Bool?
var bold: Bool?
var italic: Bool?
var strikethrough: Bool?
var underline: Bool?
var color: UIColor?
var lineSpacingFactor: CGFloat?
var baselineOffset: CGFloat?
var markerColor: UIColor?
var marker: Bool?
var anchor: Dictionary<String, Any>?
var linkColor: UIColor?
var linkMarkerColor: UIColor?
var link: Bool?
for item in self.items.reversed() {
switch item {
case let .fontSize(value):
if fontSize == nil {
fontSize = value
}
case let .fontSerif(value):
if fontSerif == nil {
fontSerif = value
}
case let .fontFixed(value):
if fontFixed == nil {
fontFixed = value
}
case .bold:
if bold == nil {
bold = true
}
case .italic:
if italic == nil {
italic = true
}
case .strikethrough:
if strikethrough == nil {
strikethrough = true
}
case .underline:
if underline == nil {
underline = true
}
case let .textColor(value):
if color == nil {
color = value
}
case let .lineSpacingFactor(value):
if lineSpacingFactor == nil {
lineSpacingFactor = value
}
case .subscript:
if baselineOffset == nil {
baselineOffset = 0.35
underline = false
}
case .superscript:
if baselineOffset == nil {
baselineOffset = -0.35
}
case let .markerColor(color):
if markerColor == nil {
markerColor = color
}
case .marker:
if marker == nil {
marker = true
}
case let .anchor(name, anchorText, empty):
if anchor == nil {
if let anchorText = anchorText {
anchor = ["name": name, "text": anchorText, "empty": empty]
} else {
anchor = ["name": name, "empty": empty]
}
}
case let .linkColor(color):
if linkColor == nil {
linkColor = color
}
case let .linkMarkerColor(color):
if linkMarkerColor == nil {
linkMarkerColor = color
}
case let .link(instant):
if link == nil {
link = instant
}
}
}
var attributes: [NSAttributedString.Key: Any] = [:]
var parsedFontSize: CGFloat
if let fontSize = fontSize {
parsedFontSize = fontSize
} else {
parsedFontSize = 16.0
}
if let baselineOffset = baselineOffset {
attributes[NSAttributedString.Key.baselineOffset] = round(parsedFontSize * baselineOffset);
parsedFontSize = round(parsedFontSize * 0.85)
}
if (bold != nil && bold!) && (italic != nil && italic!) {
if fontSerif != nil && fontSerif! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Georgia-BoldItalic", size: parsedFontSize)
} else if fontFixed != nil && fontFixed! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Menlo-BoldItalic", size: parsedFontSize)
} else {
attributes[NSAttributedString.Key.font] = Font.semiboldItalic(parsedFontSize)
}
} else if bold != nil && bold! {
if fontSerif != nil && fontSerif! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Georgia-Bold", size: parsedFontSize)
} else if fontFixed != nil && fontFixed! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Menlo-Bold", size: parsedFontSize)
} else {
attributes[NSAttributedString.Key.font] = Font.bold(parsedFontSize)
}
} else if italic != nil && italic! {
if fontSerif != nil && fontSerif! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Georgia-Italic", size: parsedFontSize)
} else if fontFixed != nil && fontFixed! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Menlo-Italic", size: parsedFontSize)
} else {
attributes[NSAttributedString.Key.font] = Font.italic(parsedFontSize)
}
} else {
if fontSerif != nil && fontSerif! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Georgia", size: parsedFontSize)
} else if fontFixed != nil && fontFixed! {
attributes[NSAttributedString.Key.font] = UIFont(name: "Menlo", size: parsedFontSize)
} else {
attributes[NSAttributedString.Key.font] = Font.regular(parsedFontSize)
}
}
if strikethrough != nil && strikethrough! {
attributes[NSAttributedString.Key.strikethroughStyle] = NSUnderlineStyle.single.rawValue as NSNumber
}
if underline != nil && underline! {
attributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.single.rawValue as NSNumber
}
if let link = link, let linkColor = linkColor {
attributes[NSAttributedString.Key.foregroundColor] = linkColor
if link, let linkMarkerColor = linkMarkerColor {
attributes[NSAttributedString.Key(rawValue: InstantPageMarkerColorAttribute)] = linkMarkerColor
}
} else {
if let color = color {
attributes[NSAttributedString.Key.foregroundColor] = color
} else {
attributes[NSAttributedString.Key.foregroundColor] = UIColor.black
}
}
if let lineSpacingFactor = lineSpacingFactor {
attributes[NSAttributedString.Key(rawValue: InstantPageLineSpacingFactorAttribute)] = lineSpacingFactor as NSNumber
}
if marker != nil && marker!, let markerColor = markerColor {
attributes[NSAttributedString.Key(rawValue: InstantPageMarkerColorAttribute)] = markerColor
}
if let anchor = anchor {
attributes[NSAttributedString.Key(rawValue: InstantPageAnchorAttribute)] = anchor
}
return attributes
}
}
| 37.862832 | 127 | 0.518757 |
230226ea2486f586999ab5bf83ef742ad440ac01 | 601 | //
// ViewController.swift
// GenericTableView
//
// Created by saish chachad on 18/05/19.
// Copyright © 2019 Heady. All rights reserved.
//
import UIKit
class ViewController: BaseTableViewController {
override func viewDidLoad() {
//1: Initialisation
super.viewDidLoad()
//2: Registration
self.tableView.registerCell(UserCell.self)
self.tableView.registerCell(MessageCell.self)
self.tableView.registerCell(ImageCell.self)
//3: Data Transmission
self.viewModel = TableViewModel()
}
}
| 20.724138 | 53 | 0.628952 |
c1c75c40d9a9362b1dda3170949a3a99b0b2e691 | 829 | //
// Spinner.swift
// Direct to SwiftUI
//
// Copyright © 2019 ZeeZide GmbH. All rights reserved.
//
import SwiftUI
struct Spinner: View {
let isAnimating : Bool
let speed : Double
let size : CGFloat
init(isAnimating: Bool, speed: Double = 1.8, size: CGFloat = 64) {
self.isAnimating = isAnimating
self.speed = speed
self.size = size
}
#if os(iOS)
var body: some View {
Image(systemName: "arrow.2.circlepath.circle.fill")
.resizable()
.frame(width: size, height: size)
.rotationEffect(.degrees(isAnimating ? 360 : 0))
.animation(
Animation.linear(duration: speed)
.repeatForever(autoreverses: false)
)
}
#else // no systemImage on macOS ...
var body: some View {
Text("Connecting ...")
}
#endif
}
| 20.725 | 68 | 0.600724 |
2f550406c2c35fa49b8e3dee54c0307763b1b651 | 12,848 | //
// TopicCommentModel.swift
// V2ex-Swift
//
// Created by huangfeng on 3/24/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
import Alamofire
import Ji
import YYText
import Kingfisher
protocol V2CommentAttachmentImageTapDelegate : class {
func V2CommentAttachmentImageSingleTap(_ imageView:V2CommentAttachmentImage)
}
/// 评论中的图片
class V2CommentAttachmentImage:AnimatedImageView {
/// 父容器中第几张图片
var index:Int = 0
/// 图片地址
var imageURL:String?
weak var attachmentDelegate : V2CommentAttachmentImageTapDelegate?
init(){
super.init(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
self.autoPlayAnimatedImage = false;
self.contentMode = .scaleAspectFill
self.clipsToBounds = true
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if self.image != nil {
return
}
if let imageURL = self.imageURL , let URL = URL(string: imageURL) {
self.kf.setImage(with: URL, placeholder: nil, options: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in
if let image = image {
if image.size.width < 80 && image.size.height < 80 {
self.contentMode = .bottomLeft
}
}
})
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let tapCount = touch?.tapCount
if let tapCount = tapCount {
if tapCount == 1 {
self.handleSingleTap(touch!)
}
}
//取消后续的事件响应
self.next?.touchesCancelled(touches, with: event)
}
func handleSingleTap(_ touch:UITouch){
self.attachmentDelegate?.V2CommentAttachmentImageSingleTap(self)
}
}
class TopicCommentModel: NSObject,BaseHtmlModelProtocol {
var replyId:String?
var avata: String?
var userName: String?
var date: String?
var comment: String?
var favorites: Int = 0
var textLayout:YYTextLayout?
var images:NSMutableArray = NSMutableArray()
//楼层
var number:Int = 0
var textAttributedString:NSMutableAttributedString?
required init(rootNode: JiNode) {
super.init()
let id = rootNode.xPath("table/tr/td[3]/div[1]/div[attribute::id]").first?["id"]
if let id = id {
if id.hasPrefix("thank_area_") {
self.replyId = id.replacingOccurrences(of: "thank_area_", with: "")
}
}
self.avata = rootNode.xPath("table/tr/td[1]/img").first?["src"]
self.userName = rootNode.xPath("table/tr/td[3]/strong/a").first?.content
self.date = rootNode.xPath("table/tr/td[3]/span").first?.content
if let str = rootNode.xPath("table/tr/td[3]/div[@class='fr']/span").first?.content , let no = Int(str){
self.number = no;
}
if let favorite = rootNode.xPath("table/tr/td[3]/span[2]").first?.content {
let array = favorite.components(separatedBy: " ")
if array.count == 2 {
if let i = Int(array[1]){
self.favorites = i
}
}
}
//构造评论内容
let commentAttributedString:NSMutableAttributedString = NSMutableAttributedString(string: "")
let nodes = rootNode.xPath("table/tr/td[3]/div[@class='reply_content']/node()")
self.preformAttributedString(commentAttributedString, nodes: nodes)
let textContainer = YYTextContainer(size: CGSize(width: SCREEN_WIDTH - 24, height: 9999))
self.textLayout = YYTextLayout(container: textContainer, text: commentAttributedString)
self.textAttributedString = commentAttributedString
}
func preformAttributedString(_ commentAttributedString:NSMutableAttributedString,nodes:[JiNode]) {
for element in nodes {
let urlHandler: (_ attributedString:NSMutableAttributedString, _ url:String, _ url:String)->() = {attributedString,title,url in
let attr = NSMutableAttributedString(string: title ,attributes: [NSAttributedString.Key.font:v2ScaleFont(14)])
attr.yy_setTextHighlight(NSMakeRange(0, title.Lenght),
color: XZSwiftColor.linksColor,
backgroundColor: UIColor(white: 0.95, alpha: 1),
userInfo: ["url":url],
tapAction: { (view, text, range, rect) -> Void in
if let highlight = text.yy_attribute(YYTextHighlightAttributeName, at: UInt(range.location)) ,let url = (highlight as AnyObject).userInfo["url"] as? String {
AnalyzeURLHelper.Analyze(url)
}
}, longPressAction: nil)
commentAttributedString.append(attr)
}
if element.name == "text" , let content = element.content{//普通文本
commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSAttributedString.Key.font:v2ScaleFont(14) , NSAttributedString.Key.foregroundColor:XZSwiftColor.leftNodeTintColor]))
commentAttributedString.yy_lineSpacing = 5
}
else if element.name == "img" ,let imageURL = element["src"] {//图片
let image = V2CommentAttachmentImage()
image.imageURL = imageURL
let imageAttributedString = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit , attachmentSize: CGSize(width: 80,height: 80), alignTo: v2ScaleFont(14), alignment: .bottom)
commentAttributedString.append(imageAttributedString)
image.index = self.images.count
self.images.add(imageURL)
}
else if element.name == "a" ,let content = element.content,let url = element["href"]{//超链接
//递归处理所有子节点,主要是处理下 a标签下包含的img标签
let subNodes = element.xPath("./node()")
if subNodes.first?.name != "text" && subNodes.count > 0 {
self.preformAttributedString(commentAttributedString, nodes: subNodes)
}
if content.Lenght > 0 {
urlHandler(commentAttributedString,content,url)
}
}
else if element.name == "br" {
commentAttributedString.yy_appendString("\n")
}
else if element.children.first?.name == "iframe", let src = element.children.first?["src"] , src.Lenght > 0 {
// youtube 视频
urlHandler(commentAttributedString,src,src)
}
else if let content = element.content{//其他
commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSAttributedString.Key.foregroundColor:XZSwiftColor.leftNodeTintColor]))
}
}
}
}
//MARK: - Request
extension TopicCommentModel {
class func replyWithTopicId(_ topic:TopicDetailModel, content:String,
completionHandler: @escaping (V2Response) -> Void){
let requestPath = "t/" + topic.topicId!
let url = V2EXURL + requestPath
V2User.sharedInstance.getOnce(url) { (response) -> Void in
if response.success {
let prames = [
"content":content,
"once":V2User.sharedInstance.once!
] as [String:Any]
Alamofire.request(url, method: .post, parameters: prames, headers: MOBILE_CLIENT_HEADERS).responseJiHtml { (response) -> Void in
let url = response.response?.url
if url?.path.hasSuffix(requestPath) == true && url?.fragment?.hasPrefix("reply") == true{
completionHandler(V2Response(success: true))
}
else if let problems = response.result.value?.xPath("//*[@class='problem']/ul/li") {
let problemStr = problems.map{ $0.content ?? "回帖失败" }.joined(separator: "\n")
completionHandler(V2Response(success: false,message: problemStr))
}
else{
completionHandler(V2Response(success: false,message: "请求失败"))
}
//不管成功还是失败,更新一下once
if let jiHtml = response .result.value{
V2User.sharedInstance.once = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"]
}
}
}
else{
completionHandler(V2Response(success: false,message: "获取once失败,请重试"))
}
}
}
class func replyThankWithReplyId(_ replyId:String , token:String ,completionHandler: @escaping (V2Response) -> Void) {
_ = TopicApi.provider.requestAPI(.thankReply(replyId: replyId, once: token))
.filterResponseError().subscribe(onNext: { (response) in
if response["success"].boolValue {
completionHandler(V2Response(success: true))
}
else{
completionHandler(V2Response(success: false))
}
}, onError: { (error) in
completionHandler(V2Response(success: false))
})
}
}
//MARK: - Method
extension TopicCommentModel {
/**
用某一条评论,获取和这条评论有关的所有评论
- parameter array: 所有的评论数组
- parameter firstComment: 这条评论
- returns: 某一条评论相关的评论,里面包含它自己
*/
class func getRelevantCommentsInArray(_ allCommentsArray:[TopicCommentModel], firstComment:TopicCommentModel) -> [TopicCommentModel] {
var relevantComments:[TopicCommentModel] = []
var users = getUsersOfComment(firstComment)
//当前会话所有相关的用户( B 回复 A, C 回复 B, D 回复 C, 查看D的对话时, D C B 为相关联用户)
var relateUsers:Set<String> = users
for comment in allCommentsArray {
//被回复人所@的人也加进对话,但是不递归获取所有关系链(可能获取到无意义的数据)
if let username = comment.userName, users.contains(username) {
let commentUsers = getUsersOfComment(comment)
relateUsers = relateUsers.union(commentUsers)
}
//只找到点击的位置,之后就不找了
if comment == firstComment {
break;
}
}
users.insert(firstComment.userName!)
for comment in allCommentsArray {
//判断评论中是否@的所有用户和会话相关联的用户无关,是的话则证明这条评论是和别人讲的,不属于当前对话
let commentUsers = getUsersOfComment(comment)
let intersectUsers = commentUsers.intersection(relateUsers)
if commentUsers.count > 0 && intersectUsers.count <= 0 {
continue;
}
if let username = comment.userName {
if users.contains(username) {
relevantComments.append(comment)
}
}
//只找到点击的位置,之后就不找了
if comment == firstComment {
break;
}
}
return relevantComments
}
//获取评论中 @ 了多少用户
class func getUsersOfComment(_ comment:TopicCommentModel) -> Set<String> {
//获取到所有YYTextHighlight ,用以之后获取 这条评论@了多少用户
var textHighlights:[YYTextHighlight] = []
comment.textAttributedString!.enumerateAttribute(NSAttributedString.Key(rawValue: YYTextHighlightAttributeName), in: NSMakeRange(0, comment.textAttributedString!.length), options: []) { (attribute, range, stop) -> Void in
if let highlight = attribute as? YYTextHighlight {
textHighlights.append(highlight)
}
}
//获取这条评论 @ 了多少用户
var users:Set<String> = []
for highlight in textHighlights {
if let url = highlight.userInfo?["url"] as? String{
let result = AnalyzURLResultType(url: url)
if case .member(let member) = result {
users.insert(member.username)
}
}
}
return users
}
}
| 40.024922 | 232 | 0.561955 |
e0c8922fec0c4ffdf93c586a7ffd49b533376b5a | 1,571 | //
// FormatTest.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct FormatTest: Codable {
public var integer: Int?
public var int32: Int?
public var int64: Int64?
public var number: Double
public var float: Float?
public var double: Double?
public var string: String?
public var byte: Data
public var binary: URL?
public var date: Date
public var dateTime: Date?
public var uuid: UUID?
public var password: String
public var bigDecimal: Decimal?
public init(integer: Int?, int32: Int?, int64: Int64?, number: Double, float: Float?, double: Double?, string: String?, byte: Data, binary: URL?, date: Date, dateTime: Date?, uuid: UUID?, password: String, bigDecimal: Decimal?) {
self.integer = integer
self.int32 = int32
self.int64 = int64
self.number = number
self.float = float
self.double = double
self.string = string
self.byte = byte
self.binary = binary
self.date = date
self.dateTime = dateTime
self.uuid = uuid
self.password = password
self.bigDecimal = bigDecimal
}
public enum CodingKeys: String, CodingKey {
case integer
case int32
case int64
case number
case float
case double
case string
case byte
case binary
case date
case dateTime
case uuid
case password
case bigDecimal = "BigDecimal"
}
}
| 23.80303 | 233 | 0.609166 |
469cda49ea92ef9419ff41fe0d027bb9989035bb | 408 | //
// KJSlider.swift
// KJAudioPlayer
//
// Created by Kim on 2017/4/8.
// Copyright © 2017年 Kim. All rights reserved.
//
import UIKit
class KJSlider: UISlider {
override var currentThumbImage: UIImage? {
return #imageLiteral(resourceName: "mvplayer_progress_thumb")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print(subviews)
}
}
| 17.73913 | 69 | 0.654412 |
0102c04bf9d1a23a1dad4c89af09dbfb63b89e08 | 553 |
public func getVersion() -> Int {
#if BEFORE
return 0
#else
return 1
#endif
}
public struct AddConformance {
public init() {
x = 0
y = 0
}
public var x: Int
public var y: Int
public var z: Int {
get { return x + y }
set {
x = newValue / 2
y = newValue - x
}
}
}
public protocol PointLike {
var x: Int { get set }
var y: Int { get set }
}
public protocol Point3DLike {
var z: Int { get set }
}
#if AFTER
extension AddConformance : PointLike {}
extension AddConformance : Point3DLike {}
#endif
| 13.487805 | 41 | 0.600362 |
f74a247a2dec9559d4229405b0a06213378fc215 | 1,459 | // MXWebViewController.swift
//
// Copyright (c) 2017 Maxime Epain
//
// 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
class MXWebViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://nshipster.com/")!
let request = URLRequest(url: url)
webView.loadRequest(request)
}
}
| 39.432432 | 80 | 0.738862 |
5dafdc67f5b4ba886437bbb536f4d354bf3f42a3 | 540 | //
// EMGroupTitleCell.swift
// Hyphenate-Demo-Swift
//
// Created by 杜洁鹏 on 2017/6/26.
// Copyright © 2017年 杜洁鹏. All rights reserved.
//
import UIKit
class EMGroupTitleCell: UITableViewCell {
@IBOutlet weak var titleLabel: 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
}
}
| 20 | 65 | 0.657407 |
f778cfc8b3624f76fb3d1d41160e68565ae08583 | 11,148 | //
// IalEdxMaths2020OctList.swift
// Pastpaper2021
//
// Created by ZhuPinxi on 2021/12/25.
//
import SwiftUI
import WebKit
struct IalEdxMaths2020OctView: View {
@State var selected = 1
var body: some View {
VStack{
Picker(selection: $selected, label: Text("")){
Text("Question Paper").tag(1)
Text("Mark Scheme").tag(2)
Text("Examiner Report").tag(3)
}
.pickerStyle(SegmentedPickerStyle())
.padding(.horizontal, 10)
.padding(.vertical, 6.5)
if selected == 1{
IalEdxMaths2020OctList1()
}
if selected == 2{
IalEdxMaths2020OctList2()
}
if selected == 3{
IalEdxMaths2020OctList3()
}
}
.navigationBarTitle("20 Winter", displayMode: .inline)
.listStyle(.plain)
}
}
struct IalEdxMaths2020OctView1: View {
@State var selected = 1
var body: some View {
VStack{
Picker(selection: $selected, label: Text("")){
Text("Question Paper").tag(1)
Text("Mark Scheme").tag(2)
Text("Examiner Report").tag(3)
}
.pickerStyle(SegmentedPickerStyle())
.padding(.horizontal, 10)
.padding(.vertical, 6.5)
if selected == 1{
IalEdxMaths2020OctList1()
}
if selected == 2{
IalEdxMaths2020OctList2()
}
if selected == 3{
IalEdxMaths2020OctList3()
}
}
.navigationBarTitle("20 Winter", displayMode: .inline)
.listStyle(.plain)
.toolbar {
ToolbarItem(placement: .primaryAction){
Menu() {
ToolBarView()
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
}
}
struct IalEdxMaths2020OctList1: View {
var body: some View {
List {
ForEach(IalMaths2020OctData1) { ialMaths2020Oct1 in
NavigationLink(destination: IalEdxMaths2020OctWebView1(ialMaths2020Oct1: ialMaths2020Oct1)) {
Text(ialMaths2020Oct1.name)
}
}
}
}
}
struct IalEdxMaths2020OctList2: View {
var body: some View {
List {
ForEach(IalMaths2020OctData2) { ialMaths2020Oct2 in
NavigationLink(destination: IalEdxMaths2020OctWebView2(ialMaths2020Oct2: ialMaths2020Oct2)) {
Text(ialMaths2020Oct2.name)
}
}
}
}
}
struct IalEdxMaths2020OctList3: View {
var body: some View {
List {
ForEach(IalMaths2020OctData3) { ialMaths2020Oct3 in
NavigationLink(destination: IalEdxMaths2020OctWebView3(ialMaths2020Oct3: ialMaths2020Oct3)) {
Text(ialMaths2020Oct3.name)
}
}
}
}
}
struct IalEdxMaths2020OctWebView1: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass
@Environment(\.verticalSizeClass) var verticalSizeClass
@State private var isPresented = false
@State private var isActivityPopoverPresented = false
@State private var isActivitySheetPresented = false
var ialMaths2020Oct1: IalMaths2020Oct1
var body: some View {
Webview(url: ialMaths2020Oct1.url)
.edgesIgnoringSafeArea(.all)
.navigationBarTitle(ialMaths2020Oct1.name, displayMode: .inline)
.navigationBarItems(trailing: shareButton)
.sheet(isPresented: $isActivitySheetPresented, content: activityView)
}
private var shareButton: some View {
Button(action: {
switch (self.horizontalSizeClass, self.verticalSizeClass) {
case (.regular, .regular):
self.isActivityPopoverPresented.toggle()
default:
self.isActivitySheetPresented.toggle()
let impactLight = UIImpactFeedbackGenerator(style: .light)
impactLight.impactOccurred()
}
}, label: {
Image(systemName: "square.and.arrow.up")
.font(.system(size: 17))
.frame(width: 30, height: 30)
.popover(isPresented: $isActivityPopoverPresented, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
activityView()
}
})
}
private func activityView() -> some View {
let url = URL(string: ialMaths2020Oct1.url)!
let filename = url.pathComponents.last!
let fileManager = FileManager.default
let itemURL = fileManager.temporaryDirectory.appendingPathComponent(filename)
let data: Data
if fileManager.fileExists(atPath: itemURL.path) {
data = try! Data(contentsOf: itemURL)
} else {
data = try! Data(contentsOf: url)
fileManager.createFile(atPath: itemURL.path, contents: data, attributes: nil)
}
let activityView = ActivityView(activityItems: [itemURL], applicationActivities: nil)
return Group {
if self.horizontalSizeClass == .regular && self.verticalSizeClass == .regular {
activityView.frame(width: 333, height: 480)
} else {
activityView
.edgesIgnoringSafeArea(.all)
}
}
}
}
struct IalEdxMaths2020OctWebView2: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass
@Environment(\.verticalSizeClass) var verticalSizeClass
@State private var isPresented = false
@State private var isActivityPopoverPresented = false
@State private var isActivitySheetPresented = false
var ialMaths2020Oct2: IalMaths2020Oct2
var body: some View {
Webview(url: ialMaths2020Oct2.url)
.edgesIgnoringSafeArea(.all)
.navigationBarTitle(ialMaths2020Oct2.name, displayMode: .inline)
.navigationBarItems(trailing: shareButton)
.sheet(isPresented: $isActivitySheetPresented, content: activityView)
}
private var shareButton: some View {
Button(action: {
switch (self.horizontalSizeClass, self.verticalSizeClass) {
case (.regular, .regular):
self.isActivityPopoverPresented.toggle()
default:
self.isActivitySheetPresented.toggle()
let impactLight = UIImpactFeedbackGenerator(style: .light)
impactLight.impactOccurred()
}
}, label: {
Image(systemName: "square.and.arrow.up")
.font(.system(size: 17))
.frame(width: 30, height: 30)
.popover(isPresented: $isActivityPopoverPresented, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
activityView()
}
})
}
private func activityView() -> some View {
let url = URL(string: ialMaths2020Oct2.url)!
let filename = url.pathComponents.last!
let fileManager = FileManager.default
let itemURL = fileManager.temporaryDirectory.appendingPathComponent(filename)
let data: Data
if fileManager.fileExists(atPath: itemURL.path) {
data = try! Data(contentsOf: itemURL)
} else {
data = try! Data(contentsOf: url)
fileManager.createFile(atPath: itemURL.path, contents: data, attributes: nil)
}
let activityView = ActivityView(activityItems: [itemURL], applicationActivities: nil)
return Group {
if self.horizontalSizeClass == .regular && self.verticalSizeClass == .regular {
activityView.frame(width: 333, height: 480)
} else {
activityView
.edgesIgnoringSafeArea(.all)
}
}
}
}
struct IalEdxMaths2020OctWebView3: View {
@Environment(\.horizontalSizeClass) var horizontalSizeClass
@Environment(\.verticalSizeClass) var verticalSizeClass
@State private var isPresented = false
@State private var isActivityPopoverPresented = false
@State private var isActivitySheetPresented = false
var ialMaths2020Oct3: IalMaths2020Oct3
var body: some View {
Webview(url: ialMaths2020Oct3.url)
.edgesIgnoringSafeArea(.all)
.navigationBarTitle(ialMaths2020Oct3.name, displayMode: .inline)
.navigationBarItems(trailing: shareButton)
.sheet(isPresented: $isActivitySheetPresented, content: activityView)
}
private var shareButton: some View {
Button(action: {
switch (self.horizontalSizeClass, self.verticalSizeClass) {
case (.regular, .regular):
self.isActivityPopoverPresented.toggle()
default:
self.isActivitySheetPresented.toggle()
let impactLight = UIImpactFeedbackGenerator(style: .light)
impactLight.impactOccurred()
}
}, label: {
Image(systemName: "square.and.arrow.up")
.font(.system(size: 17))
.frame(width: 30, height: 30)
.popover(isPresented: $isActivityPopoverPresented, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) {
activityView()
}
})
}
private func activityView() -> some View {
let url = URL(string: ialMaths2020Oct3.url)!
let filename = url.pathComponents.last!
let fileManager = FileManager.default
let itemURL = fileManager.temporaryDirectory.appendingPathComponent(filename)
let data: Data
if fileManager.fileExists(atPath: itemURL.path) {
data = try! Data(contentsOf: itemURL)
} else {
data = try! Data(contentsOf: url)
fileManager.createFile(atPath: itemURL.path, contents: data, attributes: nil)
}
let activityView = ActivityView(activityItems: [itemURL], applicationActivities: nil)
return Group {
if self.horizontalSizeClass == .regular && self.verticalSizeClass == .regular {
activityView.frame(width: 333, height: 480)
} else {
activityView
.edgesIgnoringSafeArea(.all)
}
}
}
}
struct IalMaths2020Oct1: Hashable, Codable, Identifiable {
var id: Int
var name: String
var url: String
}
struct IalMaths2020Oct2: Hashable, Codable, Identifiable {
var id: Int
var name: String
var url: String
}
struct IalMaths2020Oct3: Hashable, Codable, Identifiable {
var id: Int
var name: String
var url: String
}
let IalMaths2020OctData1: [IalMaths2020Oct1] = load("IalMaths2020Oct1.json")
let IalMaths2020OctData2: [IalMaths2020Oct2] = load("IalMaths2020Oct2.json")
let IalMaths2020OctData3: [IalMaths2020Oct3] = load("IalMaths2020Oct3.json")
| 35.390476 | 123 | 0.59042 |
38b053334771be65be678b8ddf15f5ce3fb4bce8 | 3,404 | //
// ProfileViewController.swift
// Twitter
//
// Created by Neha Samant on 11/1/16.
// Copyright © 2016 Neha Samant. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var profilePictureView: UIImageView!
@IBOutlet weak var twitterHandleView: UILabel!
@IBOutlet weak var fullNameView: UILabel!
@IBOutlet weak var followersCount: UILabel!
@IBOutlet weak var followingCountView: UILabel!
var user: User!
var tweets: [Tweet]? {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
if user == nil {
user = User.currentUser!
}
print("USER123", user.backgroundImageUrl!)
backgroundImageView?.setImageWith((user.backgroundImageUrl!))
profilePictureView?.setImageWith((user.profileUrl)!)
profilePictureView.layer.cornerRadius = 3
profilePictureView.layer.borderColor = UIColor.white.cgColor
profilePictureView.layer.borderWidth = 2
profilePictureView.layer.masksToBounds = true
profilePictureView.clipsToBounds = true
twitterHandleView.text = "@\((user.screenName)!)"
fullNameView.text = user.name
print("FOLLOERS", user.followersCount)
followersCount?.text = String(describing: (user.followersCount))
followingCountView?.text = String(describing: user.friendsCount)
TwitterClient.sharedInstance?.getUserTimeline(screenName: (user?.screenName)!, success: { (tweets : [Tweet]) in
self.tweets = tweets
for tweet in self.tweets!{
print("@@@@@@@@@@@", tweet.user)
print("@@@@@@@@@@@", tweet.text)
}
self.tableView.reloadData()
}, failure: { (error : Error) in
print("ERROR: \(error.localizedDescription)")
})
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = 120
tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell
var tweet : Tweet?
if (indexPath.row < tweets?.count ?? 0) {
tweet = tweets?[indexPath.row]
cell.tweet = tweet
}
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 33.048544 | 119 | 0.629553 |
fbadc5c3f0181bb4b3ca376c2f27188f442d0be6 | 225,338 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Codable
//===----------------------------------------------------------------------===//
/// A type that can encode itself to an external representation.
public protocol Encodable {
/// Encodes this value into the given encoder.
///
/// If the value fails to encode anything, `encoder` will encode an empty
/// keyed container in its place.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
func encode(to encoder: Encoder) throws
}
/// A type that can decode itself from an external representation.
public protocol Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
init(from decoder: Decoder) throws
}
/// A type that can convert itself into and out of an external representation.
///
/// `Codable` is a type alias for the `Encodable` and `Decodable` protocols.
/// When you use `Codable` as a type or a generic constraint, it matches
/// any type that conforms to both protocols.
public typealias Codable = Encodable & Decodable
//===----------------------------------------------------------------------===//
// CodingKey
//===----------------------------------------------------------------------===//
/// A type that can be used as a key for encoding and decoding.
public protocol CodingKey: CustomStringConvertible,
CustomDebugStringConvertible {
/// The string to use in a named collection (e.g. a string-keyed dictionary).
var stringValue: String { get }
/// Creates a new instance from the given string.
///
/// If the string passed as `stringValue` does not correspond to any instance
/// of this type, the result is `nil`.
///
/// - parameter stringValue: The string value of the desired key.
init?(stringValue: String)
/// The value to use in an integer-indexed collection (e.g. an int-keyed
/// dictionary).
var intValue: Int? { get }
/// Creates a new instance from the specified integer.
///
/// If the value passed as `intValue` does not correspond to any instance of
/// this type, the result is `nil`.
///
/// - parameter intValue: The integer value of the desired key.
init?(intValue: Int)
}
extension CodingKey {
/// A textual representation of this key.
public var description: String {
let intValue = self.intValue?.description ?? "nil"
return "\(type(of: self))(stringValue: \"\(stringValue)\", intValue: \(intValue))"
}
/// A textual representation of this key, suitable for debugging.
public var debugDescription: String {
return description
}
}
//===----------------------------------------------------------------------===//
// Encoder & Decoder
//===----------------------------------------------------------------------===//
/// A type that can encode values into a native format for external
/// representation.
public protocol Encoder {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey: Any] { get }
/// Returns an encoding container appropriate for holding multiple values
/// keyed by the given key type.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `unkeyedContainer()` or after
/// encoding a value through a call to `singleValueContainer()`
///
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key>
/// Returns an encoding container appropriate for holding multiple unkeyed
/// values.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `container(keyedBy:)` or after
/// encoding a value through a call to `singleValueContainer()`
///
/// - returns: A new empty unkeyed container.
func unkeyedContainer() -> UnkeyedEncodingContainer
/// Returns an encoding container appropriate for holding a single primitive
/// value.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `unkeyedContainer()` or
/// `container(keyedBy:)`, or after encoding a value through a call to
/// `singleValueContainer()`
///
/// - returns: A new empty single value container.
func singleValueContainer() -> SingleValueEncodingContainer
}
/// A type that can decode values from a native format into in-memory
/// representations.
public protocol Decoder {
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// Any contextual information set by the user for decoding.
var userInfo: [CodingUserInfoKey: Any] { get }
/// Returns the data stored in this decoder as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
func container<Key>(
keyedBy type: Key.Type
) throws -> KeyedDecodingContainer<Key>
/// Returns the data stored in this decoder as represented in a container
/// appropriate for holding values with no keys.
///
/// - returns: An unkeyed container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
func unkeyedContainer() throws -> UnkeyedDecodingContainer
/// Returns the data stored in this decoder as represented in a container
/// appropriate for holding a single primitive value.
///
/// - returns: A single value container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a single value container.
func singleValueContainer() throws -> SingleValueDecodingContainer
}
//===----------------------------------------------------------------------===//
// Keyed Encoding Containers
//===----------------------------------------------------------------------===//
/// A type that provides a view into an encoder's storage and is used to hold
/// the encoded properties of an encodable type in a keyed manner.
///
/// Encoders should provide types conforming to
/// `KeyedEncodingContainerProtocol` for their format.
public protocol KeyedEncodingContainerProtocol {
associatedtype Key: CodingKey
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Encodes a null value for the given key.
///
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
mutating func encodeNil(forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Bool, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: String, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Double, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Float, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int8, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int16, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int32, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int64, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt8, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt16, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt32, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt64, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode<T: Encodable>(_ value: T, forKey key: Key) throws
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey>
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer
/// Stores a new nested container for the default `super` key and returns A
/// new encoder instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
/// Stores a new nested container for the given key and returns A new encoder
/// instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder
}
// An implementation of _KeyedEncodingContainerBase and
// _KeyedEncodingContainerBox are given at the bottom of this file.
/// A concrete container that provides a view into an encoder's storage, making
/// the encoded properties of an encodable type accessible by keys.
public struct KeyedEncodingContainer<K: CodingKey> :
KeyedEncodingContainerProtocol
{
public typealias Key = K
/// The container for the concrete encoder. The type is _*Base so that it's
/// generic on the key type.
internal var _box: _KeyedEncodingContainerBase<Key>
/// Creates a new instance with the given container.
///
/// - parameter container: The container to hold.
public init<Container: KeyedEncodingContainerProtocol>(
_ container: Container
) where Container.Key == Key {
_box = _KeyedEncodingContainerBox(container)
}
/// The path of coding keys taken to get to this point in encoding.
public var codingPath: [CodingKey] {
return _box.codingPath
}
/// Encodes a null value for the given key.
///
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
public mutating func encodeNil(forKey key: Key) throws {
try _box.encodeNil(forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Bool, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: String, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Double, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Float, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int8, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int16, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int32, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int64, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt8, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt16, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt32, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt64, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode<T: Encodable>(
_ value: T,
forKey key: Key
) throws {
try _box.encode(value, forKey: key)
}
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try _box.encodeConditional(object, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
public mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
return _box.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
public mutating func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer {
return _box.nestedUnkeyedContainer(forKey: key)
}
/// Stores a new nested container for the default `super` key and returns A
/// new encoder instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
public mutating func superEncoder() -> Encoder {
return _box.superEncoder()
}
/// Stores a new nested container for the given key and returns A new encoder
/// instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new encoder to pass to `super.encode(to:)`.
public mutating func superEncoder(forKey key: Key) -> Encoder {
return _box.superEncoder(forKey: key)
}
}
/// A type that provides a view into a decoder's storage and is used to hold
/// the encoded properties of a decodable type in a keyed manner.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for
/// their format.
public protocol KeyedDecodingContainerProtocol {
associatedtype Key: CodingKey
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different
/// keys here; it is possible to encode with multiple key types which are
/// not convertible to one another. This should report all keys present
/// which are convertible to the requested type.
var allKeys: [Key] { get }
/// Returns a Boolean value indicating whether the decoder contains a value
/// associated with the given key.
///
/// The value associated with `key` may be a null value as appropriate for
/// the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
func decodeNil(forKey key: Key) throws -> Bool
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: String.Type, forKey key: Key) throws -> String
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Double.Type, forKey key: Key) throws -> Double
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Float.Type, forKey key: Key) throws -> Float
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int.Type, forKey key: Key) throws -> Int
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T?
/// Returns the data stored for the given key as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey>
/// Returns the data stored for the given key as represented in an unkeyed
/// container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the default `super` key.
func superDecoder() throws -> Decoder
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func superDecoder(forKey key: Key) throws -> Decoder
}
// An implementation of _KeyedDecodingContainerBase and
// _KeyedDecodingContainerBox are given at the bottom of this file.
/// A concrete container that provides a view into a decoder's storage, making
/// the encoded properties of a decodable type accessible by keys.
public struct KeyedDecodingContainer<K: CodingKey> :
KeyedDecodingContainerProtocol
{
public typealias Key = K
/// The container for the concrete decoder. The type is _*Base so that it's
/// generic on the key type.
internal var _box: _KeyedDecodingContainerBase<Key>
/// Creates a new instance with the given container.
///
/// - parameter container: The container to hold.
public init<Container: KeyedDecodingContainerProtocol>(
_ container: Container
) where Container.Key == Key {
_box = _KeyedDecodingContainerBox(container)
}
/// The path of coding keys taken to get to this point in decoding.
public var codingPath: [CodingKey] {
return _box.codingPath
}
/// All the keys the decoder has for this container.
///
/// Different keyed containers from the same decoder may return different
/// keys here, because it is possible to encode with multiple key types
/// which are not convertible to one another. This should report all keys
/// present which are convertible to the requested type.
public var allKeys: [Key] {
return _box.allKeys
}
/// Returns a Boolean value indicating whether the decoder contains a value
/// associated with the given key.
///
/// The value associated with the given key may be a null value as
/// appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
public func contains(_ key: Key) -> Bool {
return _box.contains(key)
}
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
public func decodeNil(forKey key: Key) throws -> Bool {
return try _box.decodeNil(forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
return try _box.decode(Bool.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
return try _box.decode(String.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
return try _box.decode(Double.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
return try _box.decode(Float.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
return try _box.decode(Int.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
return try _box.decode(Int8.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
return try _box.decode(Int16.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
return try _box.decode(Int32.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
return try _box.decode(Int64.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
return try _box.decode(UInt.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
return try _box.decode(UInt8.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
return try _box.decode(UInt16.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
return try _box.decode(UInt32.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
return try _box.decode(UInt64.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T {
return try _box.decode(T.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
return try _box.decodeIfPresent(Bool.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
return try _box.decodeIfPresent(String.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
return try _box.decodeIfPresent(Double.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
return try _box.decodeIfPresent(Float.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
return try _box.decodeIfPresent(Int.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
return try _box.decodeIfPresent(Int8.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
return try _box.decodeIfPresent(Int16.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
return try _box.decodeIfPresent(Int32.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
return try _box.decodeIfPresent(Int64.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
return try _box.decodeIfPresent(UInt.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
return try _box.decodeIfPresent(UInt8.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
return try _box.decodeIfPresent(UInt16.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
return try _box.decodeIfPresent(UInt32.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
return try _box.decodeIfPresent(UInt64.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
return try _box.decodeIfPresent(T.self, forKey: key)
}
/// Returns the data stored for the given key as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
public func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
return try _box.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
/// Returns the data stored for the given key as represented in an unkeyed
/// container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
public func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer {
return try _box.nestedUnkeyedContainer(forKey: key)
}
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the default `super` key.
public func superDecoder() throws -> Decoder {
return try _box.superDecoder()
}
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _box.superDecoder(forKey: key)
}
}
//===----------------------------------------------------------------------===//
// Unkeyed Encoding Containers
//===----------------------------------------------------------------------===//
/// A type that provides a view into an encoder's storage and is used to hold
/// the encoded properties of an encodable type sequentially, without keys.
///
/// Encoders should provide types conforming to `UnkeyedEncodingContainer` for
/// their format.
public protocol UnkeyedEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// The number of elements encoded into the container.
var count: Int { get }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
mutating func encodeNil() throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Bool) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: String) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Double) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Float) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int8) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int16) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int32) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int64) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt8) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt16) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt32) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt64) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode<T: Encodable>(_ value: T) throws
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// For formats which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeConditional<T: AnyObject & Encodable>(_ object: T) throws
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Bool
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == String
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Double
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Float
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int8
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int16
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int32
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int64
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt8
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt16
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt32
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt64
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element: Encodable
/// Encodes a nested container keyed by the given type and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type
) -> KeyedEncodingContainer<NestedKey>
/// Encodes an unkeyed encoding container and returns it.
///
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer
/// Encodes a nested container and returns an `Encoder` instance for encoding
/// `super` into that container.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
}
/// A type that provides a view into a decoder's storage and is used to hold
/// the encoded properties of a decodable type sequentially, without keys.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for
/// their format.
public protocol UnkeyedDecodingContainer {
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// The number of elements contained within this container.
///
/// If the number of elements is unknown, the value is `nil`.
var count: Int? { get }
/// A Boolean value indicating whether there are no more elements left to be
/// decoded in the container.
var isAtEnd: Bool { get }
/// The current decoding index of the container (i.e. the index of the next
/// element to be decoded.) Incremented after every successful decode call.
var currentIndex: Int { get }
/// Decodes a null value.
///
/// If the value is not null, does not increment currentIndex.
///
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.valueNotFound` if there are no more values to
/// decode.
mutating func decodeNil() throws -> Bool
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Bool.Type) throws -> Bool
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: String.Type) throws -> String
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Double.Type) throws -> Double
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Float.Type) throws -> Float
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int.Type) throws -> Int
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int8.Type) throws -> Int8
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int16.Type) throws -> Int16
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int32.Type) throws -> Int32
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int64.Type) throws -> Int64
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt.Type) throws -> UInt
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt8.Type) throws -> UInt8
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt16.Type) throws -> UInt16
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt32.Type) throws -> UInt32
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt64.Type) throws -> UInt64
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode<T: Decodable>(_ type: T.Type) throws -> T
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: String.Type) throws -> String?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Double.Type) throws -> Double?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Float.Type) throws -> Float?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int.Type) throws -> Int?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent<T: Decodable>(_ type: T.Type) throws -> T?
/// Decodes a nested container keyed by the given type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
mutating func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type
) throws -> KeyedDecodingContainer<NestedKey>
/// Decodes an unkeyed nested container.
///
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer
/// Decodes a nested container and returns a `Decoder` instance for decoding
/// `super` from that container.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func superDecoder() throws -> Decoder
}
//===----------------------------------------------------------------------===//
// Single Value Encoding Containers
//===----------------------------------------------------------------------===//
/// A container that can support the storage and direct encoding of a single
/// non-keyed value.
public protocol SingleValueEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encodeNil() throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Bool) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: String) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Double) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Float) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int8) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int16) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int32) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int64) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt8) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt16) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt32) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt64) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode<T: Encodable>(_ value: T) throws
}
/// A container that can support the storage and direct decoding of a single
/// nonkeyed value.
public protocol SingleValueDecodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Bool.Type) throws -> Bool
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: String.Type) throws -> String
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Double.Type) throws -> Double
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Float.Type) throws -> Float
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int.Type) throws -> Int
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int8.Type) throws -> Int8
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int16.Type) throws -> Int16
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int32.Type) throws -> Int32
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int64.Type) throws -> Int64
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt.Type) throws -> UInt
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt8.Type) throws -> UInt8
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt16.Type) throws -> UInt16
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt32.Type) throws -> UInt32
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt64.Type) throws -> UInt64
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode<T: Decodable>(_ type: T.Type) throws -> T
}
//===----------------------------------------------------------------------===//
// User Info
//===----------------------------------------------------------------------===//
/// A user-defined key for providing context during encoding and decoding.
public struct CodingUserInfoKey: RawRepresentable, Equatable, Hashable {
public typealias RawValue = String
/// The key's string value.
public let rawValue: String
/// Creates a new instance with the given raw value.
///
/// - parameter rawValue: The value of the key.
public init?(rawValue: String) {
self.rawValue = rawValue
}
/// Returns a Boolean value indicating whether the given keys are equal.
///
/// - parameter lhs: The key to compare against.
/// - parameter rhs: The key to compare with.
public static func ==(
lhs: CodingUserInfoKey,
rhs: CodingUserInfoKey
) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// The key's hash value.
public var hashValue: Int {
return self.rawValue.hashValue
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher) {
hasher.combine(self.rawValue)
}
}
//===----------------------------------------------------------------------===//
// Errors
//===----------------------------------------------------------------------===//
/// An error that occurs during the encoding of a value.
public enum EncodingError: Error {
/// The context in which the error occurred.
public struct Context {
/// The path of coding keys taken to get to the point of the failing encode
/// call.
public let codingPath: [CodingKey]
/// A description of what went wrong, for debugging purposes.
public let debugDescription: String
/// The underlying error which caused this error, if any.
public let underlyingError: Error?
/// Creates a new context with the given path of coding keys and a
/// description of what went wrong.
///
/// - parameter codingPath: The path of coding keys taken to get to the
/// point of the failing encode call.
/// - parameter debugDescription: A description of what went wrong, for
/// debugging purposes.
/// - parameter underlyingError: The underlying error which caused this
/// error, if any.
public init(
codingPath: [CodingKey],
debugDescription: String,
underlyingError: Error? = nil
) {
self.codingPath = codingPath
self.debugDescription = debugDescription
self.underlyingError = underlyingError
}
}
/// An indication that an encoder or its containers could not encode the
/// given value.
///
/// As associated values, this case contains the attempted value and context
/// for debugging.
case invalidValue(Any, Context)
// MARK: - NSError Bridging
// CustomNSError bridging applies only when the CustomNSError conformance is
// applied in the same module as the declared error type. Since we cannot
// access CustomNSError (which is defined in Foundation) from here, we can
// use the "hidden" entry points.
public var _domain: String {
return "NSCocoaErrorDomain"
}
public var _code: Int {
switch self {
case .invalidValue: return 4866
}
}
public var _userInfo: AnyObject? {
// The error dictionary must be returned as an AnyObject. We can do this
// only on platforms with bridging, unfortunately.
#if _runtime(_ObjC)
let context: Context
switch self {
case .invalidValue(_, let c): context = c
}
var userInfo: [String: Any] = [
"NSCodingPath": context.codingPath,
"NSDebugDescription": context.debugDescription
]
if let underlyingError = context.underlyingError {
userInfo["NSUnderlyingError"] = underlyingError
}
return userInfo as AnyObject
#else
return nil
#endif
}
}
/// An error that occurs during the decoding of a value.
public enum DecodingError: Error {
/// The context in which the error occurred.
public struct Context {
/// The path of coding keys taken to get to the point of the failing decode
/// call.
public let codingPath: [CodingKey]
/// A description of what went wrong, for debugging purposes.
public let debugDescription: String
/// The underlying error which caused this error, if any.
public let underlyingError: Error?
/// Creates a new context with the given path of coding keys and a
/// description of what went wrong.
///
/// - parameter codingPath: The path of coding keys taken to get to the
/// point of the failing decode call.
/// - parameter debugDescription: A description of what went wrong, for
/// debugging purposes.
/// - parameter underlyingError: The underlying error which caused this
/// error, if any.
public init(
codingPath: [CodingKey],
debugDescription: String,
underlyingError: Error? = nil
) {
self.codingPath = codingPath
self.debugDescription = debugDescription
self.underlyingError = underlyingError
}
}
/// An indication that a value of the given type could not be decoded because
/// it did not match the type of what was found in the encoded payload.
///
/// As associated values, this case contains the attempted type and context
/// for debugging.
case typeMismatch(Any.Type, Context)
/// An indication that a non-optional value of the given type was expected,
/// but a null value was found.
///
/// As associated values, this case contains the attempted type and context
/// for debugging.
case valueNotFound(Any.Type, Context)
/// An indication that a keyed decoding container was asked for an entry for
/// the given key, but did not contain one.
///
/// As associated values, this case contains the attempted key and context
/// for debugging.
case keyNotFound(CodingKey, Context)
/// An indication that the data is corrupted or otherwise invalid.
///
/// As an associated value, this case contains the context for debugging.
case dataCorrupted(Context)
// MARK: - NSError Bridging
// CustomNSError bridging applies only when the CustomNSError conformance is
// applied in the same module as the declared error type. Since we cannot
// access CustomNSError (which is defined in Foundation) from here, we can
// use the "hidden" entry points.
public var _domain: String {
return "NSCocoaErrorDomain"
}
public var _code: Int {
switch self {
case .keyNotFound, .valueNotFound: return 4865
case .typeMismatch, .dataCorrupted: return 4864
}
}
public var _userInfo: AnyObject? {
// The error dictionary must be returned as an AnyObject. We can do this
// only on platforms with bridging, unfortunately.
#if _runtime(_ObjC)
let context: Context
switch self {
case .keyNotFound(_, let c): context = c
case .valueNotFound(_, let c): context = c
case .typeMismatch(_, let c): context = c
case .dataCorrupted( let c): context = c
}
var userInfo: [String: Any] = [
"NSCodingPath": context.codingPath,
"NSDebugDescription": context.debugDescription
]
if let underlyingError = context.underlyingError {
userInfo["NSUnderlyingError"] = underlyingError
}
return userInfo as AnyObject
#else
return nil
#endif
}
}
// The following extensions allow for easier error construction.
internal struct _GenericIndexKey: CodingKey {
internal var stringValue: String
internal var intValue: Int?
internal init?(stringValue: String) {
return nil
}
internal init?(intValue: Int) {
self.stringValue = "Index \(intValue)"
self.intValue = intValue
}
}
extension DecodingError {
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is constructed by appending the
/// given key to the given container's coding path.
///
/// - param key: The key which caused the failure.
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError<C: KeyedDecodingContainerProtocol>(
forKey key: C.Key,
in container: C,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(
codingPath: container.codingPath + [key],
debugDescription: debugDescription)
return .dataCorrupted(context)
}
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is constructed by appending the
/// given container's current index to its coding path.
///
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError(
in container: UnkeyedDecodingContainer,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(
codingPath: container.codingPath +
[_GenericIndexKey(intValue: container.currentIndex)!],
debugDescription: debugDescription)
return .dataCorrupted(context)
}
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is the given container's coding
/// path.
///
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError(
in container: SingleValueDecodingContainer,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(codingPath: container.codingPath,
debugDescription: debugDescription)
return .dataCorrupted(context)
}
}
//===----------------------------------------------------------------------===//
// Keyed Encoding Container Implementations
//===----------------------------------------------------------------------===//
internal class _KeyedEncodingContainerBase<Key: CodingKey> {
internal init(){}
deinit {}
// These must all be given a concrete implementation in _*Box.
internal var codingPath: [CodingKey] {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeNil(forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Bool, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: String, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Double, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Float, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int8, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int16, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int32, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: Int64, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt8, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt16, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt32, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode(_ value: UInt64, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<T: Encodable>(_ value: T, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Bool?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: String?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Double?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Float?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int8?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int16?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int32?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: Int64?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder() -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder(forKey key: Key) -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedEncodingContainerBox<
Concrete: KeyedEncodingContainerProtocol
>: _KeyedEncodingContainerBase<Concrete.Key> {
typealias Key = Concrete.Key
internal var concrete: Concrete
internal init(_ container: Concrete) {
concrete = container
}
override internal var codingPath: [CodingKey] {
return concrete.codingPath
}
override internal func encodeNil(forKey key: Key) throws {
try concrete.encodeNil(forKey: key)
}
override internal func encode(_ value: Bool, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: String, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Double, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Float, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int8, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int16, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int32, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: Int64, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt8, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt16, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt32, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode(_ value: UInt64, forKey key: Key) throws {
try concrete.encode(value, forKey: key)
}
override internal func encode<T: Encodable>(
_ value: T,
forKey key: Key
) throws {
try concrete.encode(value, forKey: key)
}
override internal func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try concrete.encodeConditional(object, forKey: key)
}
override internal func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
return concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer {
return concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superEncoder() -> Encoder {
return concrete.superEncoder()
}
override internal func superEncoder(forKey key: Key) -> Encoder {
return concrete.superEncoder(forKey: key)
}
}
internal class _KeyedDecodingContainerBase<Key: CodingKey> {
internal init(){}
deinit {}
internal var codingPath: [CodingKey] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal var allKeys: [Key] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func contains(_ key: Key) -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeNil(forKey key: Key) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: String.Type,
forKey key: Key
) throws -> String {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Double.Type,
forKey key: Key
) throws -> Double {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Float.Type,
forKey key: Key
) throws -> Float {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int.Type,
forKey key: Key
) throws -> Int {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder() throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder(forKey key: Key) throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedDecodingContainerBox<
Concrete: KeyedDecodingContainerProtocol
>: _KeyedDecodingContainerBase<Concrete.Key> {
typealias Key = Concrete.Key
internal var concrete: Concrete
internal init(_ container: Concrete) {
concrete = container
}
override var codingPath: [CodingKey] {
return concrete.codingPath
}
override var allKeys: [Key] {
return concrete.allKeys
}
override internal func contains(_ key: Key) -> Bool {
return concrete.contains(key)
}
override internal func decodeNil(forKey key: Key) throws -> Bool {
return try concrete.decodeNil(forKey: key)
}
override internal func decode(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool {
return try concrete.decode(Bool.self, forKey: key)
}
override internal func decode(
_ type: String.Type,
forKey key: Key
) throws -> String {
return try concrete.decode(String.self, forKey: key)
}
override internal func decode(
_ type: Double.Type,
forKey key: Key
) throws -> Double {
return try concrete.decode(Double.self, forKey: key)
}
override internal func decode(
_ type: Float.Type,
forKey key: Key
) throws -> Float {
return try concrete.decode(Float.self, forKey: key)
}
override internal func decode(
_ type: Int.Type,
forKey key: Key
) throws -> Int {
return try concrete.decode(Int.self, forKey: key)
}
override internal func decode(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8 {
return try concrete.decode(Int8.self, forKey: key)
}
override internal func decode(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16 {
return try concrete.decode(Int16.self, forKey: key)
}
override internal func decode(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32 {
return try concrete.decode(Int32.self, forKey: key)
}
override internal func decode(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64 {
return try concrete.decode(Int64.self, forKey: key)
}
override internal func decode(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt {
return try concrete.decode(UInt.self, forKey: key)
}
override internal func decode(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8 {
return try concrete.decode(UInt8.self, forKey: key)
}
override internal func decode(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16 {
return try concrete.decode(UInt16.self, forKey: key)
}
override internal func decode(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32 {
return try concrete.decode(UInt32.self, forKey: key)
}
override internal func decode(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64 {
return try concrete.decode(UInt64.self, forKey: key)
}
override internal func decode<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T {
return try concrete.decode(T.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
return try concrete.decodeIfPresent(Bool.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
return try concrete.decodeIfPresent(String.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
return try concrete.decodeIfPresent(Double.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
return try concrete.decodeIfPresent(Float.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
return try concrete.decodeIfPresent(Int.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
return try concrete.decodeIfPresent(Int8.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
return try concrete.decodeIfPresent(Int16.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
return try concrete.decodeIfPresent(Int32.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
return try concrete.decodeIfPresent(Int64.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
return try concrete.decodeIfPresent(UInt.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
return try concrete.decodeIfPresent(UInt8.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
return try concrete.decodeIfPresent(UInt16.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
return try concrete.decodeIfPresent(UInt32.self, forKey: key)
}
override internal func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
return try concrete.decodeIfPresent(UInt64.self, forKey: key)
}
override internal func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
return try concrete.decodeIfPresent(T.self, forKey: key)
}
override internal func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
return try concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer {
return try concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superDecoder() throws -> Decoder {
return try concrete.superDecoder()
}
override internal func superDecoder(forKey key: Key) throws -> Decoder {
return try concrete.superDecoder(forKey: key)
}
}
//===----------------------------------------------------------------------===//
// Primitive and RawRepresentable Extensions
//===----------------------------------------------------------------------===//
extension Bool: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Bool.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Bool, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Bool`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Bool, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Bool`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension String: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(String.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == String, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `String`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == String, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `String`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Double: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Double.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Double, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Double`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Double, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Double`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Float: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Float.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Float, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Float`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Float, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Float`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
@available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *)
extension Float16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let floatValue = try Float(from: decoder)
self = Float16(floatValue)
if isInfinite && floatValue.isFinite {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Parsed JSON number \(floatValue) does not fit in Float16."
)
)
}
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
try Float(self).encode(to: encoder)
}
}
extension Int: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int8: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int8.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int8, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int8`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int8, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int8`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int16.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int16, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int16`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int16, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int16`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int32: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int32.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int32, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int32`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int32, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int32`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int64: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int64.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int64, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int64`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int64, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int64`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt8: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt8.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt8, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt8`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt8, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt8`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt16.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt16, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt16`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt16, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt16`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt32: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt32.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt32, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt32`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt32, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt32`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt64: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt64.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt64, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt64`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt64, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt64`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
//===----------------------------------------------------------------------===//
// Optional/Collection Type Conformances
//===----------------------------------------------------------------------===//
extension Optional: Encodable where Wrapped: Encodable {
/// Encodes this optional value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .none: try container.encodeNil()
case .some(let wrapped): try container.encode(wrapped)
}
}
}
extension Optional: Decodable where Wrapped: Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .none
} else {
let element = try container.decode(Wrapped.self)
self = .some(element)
}
}
}
extension Array: Encodable where Element: Encodable {
/// Encodes the elements of this array into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Array: Decodable where Element: Decodable {
/// Creates a new array by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
extension ContiguousArray: Encodable where Element: Encodable {
/// Encodes the elements of this contiguous array into the given encoder
/// in an unkeyed container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension ContiguousArray: Decodable where Element: Decodable {
/// Creates a new contiguous array by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
extension Set: Encodable where Element: Encodable {
/// Encodes the elements of this set into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Set: Decodable where Element: Decodable {
/// Creates a new set by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.insert(element)
}
}
}
/// A wrapper for dictionary keys which are Strings or Ints.
internal struct _DictionaryCodingKey: CodingKey {
internal let stringValue: String
internal let intValue: Int?
internal init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = Int(stringValue)
}
internal init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
}
extension Dictionary: Encodable where Key: Encodable, Value: Encodable {
/// Encodes the contents of this dictionary into the given encoder.
///
/// If the dictionary uses `String` or `Int` keys, the contents are encoded
/// in a keyed container. Otherwise, the contents are encoded as alternating
/// key-value pairs in an unkeyed container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
if Key.self == String.self {
// Since the keys are already Strings, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(stringValue: key as! String)!
try container.encode(value, forKey: codingKey)
}
} else if Key.self == Int.self {
// Since the keys are already Ints, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(intValue: key as! Int)!
try container.encode(value, forKey: codingKey)
}
} else {
// Keys are Encodable but not Strings or Ints, so we cannot arbitrarily
// convert to keys. We can encode as an array of alternating key-value
// pairs, though.
var container = encoder.unkeyedContainer()
for (key, value) in self {
try container.encode(key)
try container.encode(value)
}
}
}
}
extension Dictionary: Decodable where Key: Decodable, Value: Decodable {
/// Creates a new dictionary by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
if Key.self == String.self {
// The keys are Strings, so we should be able to expect a keyed container.
let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
for key in container.allKeys {
let value = try container.decode(Value.self, forKey: key)
self[key.stringValue as! Key] = value
}
} else if Key.self == Int.self {
// The keys are Ints, so we should be able to expect a keyed container.
let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
for key in container.allKeys {
guard key.intValue != nil else {
// We provide stringValues for Int keys; if an encoder chooses not to
// use the actual intValues, we've encoded string keys.
// So on init, _DictionaryCodingKey tries to parse string keys as
// Ints. If that succeeds, then we would have had an intValue here.
// We don't, so this isn't a valid Int key.
var codingPath = decoder.codingPath
codingPath.append(key)
throw DecodingError.typeMismatch(
Int.self,
DecodingError.Context(
codingPath: codingPath,
debugDescription: "Expected Int key but found String key instead."
)
)
}
let value = try container.decode(Value.self, forKey: key)
self[key.intValue! as! Key] = value
}
} else {
// We should have encoded as an array of alternating key-value pairs.
var container = try decoder.unkeyedContainer()
// We're expecting to get pairs. If the container has a known count, it
// had better be even; no point in doing work if not.
if let count = container.count {
guard count % 2 == 0 else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Expected collection of key-value pairs; encountered odd-length array instead."
)
)
}
}
while !container.isAtEnd {
let key = try container.decode(Key.self)
guard !container.isAtEnd else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Unkeyed container reached end before value in key-value pair."
)
)
}
let value = try container.decode(Value.self)
self[key] = value
}
}
}
}
//===----------------------------------------------------------------------===//
// Convenience Default Implementations
//===----------------------------------------------------------------------===//
// Default implementation of encodeConditional(_:forKey:) in terms of
// encode(_:forKey:)
extension KeyedEncodingContainerProtocol {
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try encode(object, forKey: key)
}
}
// Default implementation of encodeIfPresent(_:forKey:) in terms of
// encode(_:forKey:)
extension KeyedEncodingContainerProtocol {
public mutating func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
}
// Default implementation of decodeIfPresent(_:forKey:) in terms of
// decode(_:forKey:) and decodeNil(forKey:)
extension KeyedDecodingContainerProtocol {
public func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Bool.self, forKey: key)
}
public func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(String.self, forKey: key)
}
public func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Double.self, forKey: key)
}
public func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Float.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int8.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int16.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int32.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int64.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt8.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt16.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt32.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt64.self, forKey: key)
}
public func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(T.self, forKey: key)
}
}
// Default implementation of encodeConditional(_:) in terms of encode(_:),
// and encode(contentsOf:) in terms of encode(_:) loop.
extension UnkeyedEncodingContainer {
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T
) throws {
try self.encode(object)
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Bool {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == String {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Double {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Float {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int8 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int16 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int32 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int64 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt8 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt16 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt32 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt64 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element: Encodable {
for element in sequence {
try self.encode(element)
}
}
}
// Default implementation of decodeIfPresent(_:) in terms of decode(_:) and
// decodeNil()
extension UnkeyedDecodingContainer {
public mutating func decodeIfPresent(
_ type: Bool.Type
) throws -> Bool? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Bool.self)
}
public mutating func decodeIfPresent(
_ type: String.Type
) throws -> String? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(String.self)
}
public mutating func decodeIfPresent(
_ type: Double.Type
) throws -> Double? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Double.self)
}
public mutating func decodeIfPresent(
_ type: Float.Type
) throws -> Float? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Float.self)
}
public mutating func decodeIfPresent(
_ type: Int.Type
) throws -> Int? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int.self)
}
public mutating func decodeIfPresent(
_ type: Int8.Type
) throws -> Int8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int8.self)
}
public mutating func decodeIfPresent(
_ type: Int16.Type
) throws -> Int16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int16.self)
}
public mutating func decodeIfPresent(
_ type: Int32.Type
) throws -> Int32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int32.self)
}
public mutating func decodeIfPresent(
_ type: Int64.Type
) throws -> Int64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int64.self)
}
public mutating func decodeIfPresent(
_ type: UInt.Type
) throws -> UInt? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt.self)
}
public mutating func decodeIfPresent(
_ type: UInt8.Type
) throws -> UInt8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt8.self)
}
public mutating func decodeIfPresent(
_ type: UInt16.Type
) throws -> UInt16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt16.self)
}
public mutating func decodeIfPresent(
_ type: UInt32.Type
) throws -> UInt32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt32.self)
}
public mutating func decodeIfPresent(
_ type: UInt64.Type
) throws -> UInt64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt64.self)
}
public mutating func decodeIfPresent<T: Decodable>(
_ type: T.Type
) throws -> T? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(T.self)
}
}
| 37.462677 | 111 | 0.678936 |
0eb157f3b64a2a67f9feea96e779e2ec54fa6d32 | 1,759 | //
// TurkishKit
// Apple dünyasında sınırları belirleyecek nitelikte uygulamalar
// tasarlamak ve geliştirmek isteyen lise & üniversite öğrencilerinin buluşma noktası.
// HeaderView.swift
// Emirhan Erdoğan tarafından 8.12.2018 tarihinde oluşturuldu.
// Telif Hakkı © 2019 TurkishKit. Tüm hakları saklıdır.
//
import UIKit
/// HeaderView, bir Instagram gönderisinde gönderinin kime ait olduğu bilgisini içeren alandır.
public class HeaderView: UIView, ViewInitializable {
// ---------------------------------------------------------------------
// Arayüz Elementlerinin Tanımlanması
// ......
// ---------------------------------------------------------------------
// Arayüz Elementlerinin Eklenmesi
/// Bir HeaderView alanı oluşturmak için kullanacağımız fonksiyon.
public convenience init(position: Position, profileImage: UIImage, username: String, location: String) {
self.init(position: position, size: (375, 55))
// Gönderi bilgilerini ekranda gösterebilmek için arayüz elementleri oluşturmalıyız. Bunlar;
// profileImageView: Profil fotoğrafı
// usernameLabel: Kullanıcı adı
// locationLabel: Lokasyon bilgisi
// moreButton: (yan-yana üç daire) butonu
// -----------------------------------
// Arayüz Elementi 1: profileImageView
// ......
// -----------------------------------
// Arayüz Elementi 2: usernameLabel
// ......
// -----------------------------------
// Arayüz Elementi 3: locationLabel
// ......
// -----------------------------------
// Arayüz Elementi 4: moreButton
// ......
}
}
| 31.981818 | 108 | 0.521887 |
2644f75af6c00ffa813b616a150e291ac8031349 | 3,370 | import Quick
import Nimble
@testable import Cogito
class TelepathSubscriberSpec: QuickSpec {
override func spec() {
var subscriber: TelepathSubscriber!
var store: RecordingStore!
let exampleChannel = TelepathChannel.example
beforeEach {
store = RecordingStore()
subscriber = TelepathSubscriber(store: store)
}
describe("subscribe/unsubscribe") {
var newStateReceived = false
beforeEach {
newStateReceived = false
subscriber.onNewState = { _ in return { _ in
newStateReceived = true
}}
}
it("subscribes to changes to the telepath channel") {
subscriber.start()
store.dispatch(TracerAction())
expect(newStateReceived).to(beTrue())
}
it("unsubscribes") {
subscriber.stop()
store.dispatch(TracerAction())
expect(newStateReceived).to(beFalse())
}
}
describe("incoming JSON RPC requests") {
let message = "{" +
"\"jsonrpc\":\"2.0\"," +
"\"id\":42," +
"\"method\":\"test\"" +
"}"
var service1: ServiceSpy!
var service2: ServiceSpy!
beforeEach {
service1 = ServiceSpy()
service2 = ServiceSpy()
subscriber.addService(service1)
subscriber.addService(service2)
let telepathMessage = TelepathMessage(message: message, channel: exampleChannel)
subscriber.newState(state: [telepathMessage])
}
it("notifies subscribed services") {
let request = JsonRpcRequest(parse: message)
expect(service1.latestRequest) == request
expect(service2.latestRequest) == request
}
it("signals that the message has been handled") {
expect(store.actions).to(containElementSatisfying({
$0 is TelepathActions.ReceivedMessageHandled
}))
}
}
context("when an invalid JSON RPC request is received") {
beforeEach {
subscriber.newState(state: [
TelepathMessage(message: "invalid request", channel: exampleChannel)
])
}
it("ignores the message and signals that it has been handled") {
expect(store.actions).to(containElementSatisfying({
$0 is TelepathActions.ReceivedMessageHandled
}))
}
}
context("when there are no messages waiting") {
beforeEach {
subscriber.newState(state: [])
}
it("does nothing") {
expect(store.actions).toNot(containElementSatisfying({
$0 is TelepathActions.ReceivedMessageHandled
}))
}
}
}
}
class ServiceSpy: TelepathService {
var latestRequest: JsonRpcRequest?
var latestChannel: TelepathChannel?
func onRequest(_ request: JsonRpcRequest, on channel: TelepathChannel) {
latestRequest = request
latestChannel = channel
}
}
| 31.203704 | 96 | 0.5273 |
879f46587ba5d084b1b78857ff06b42f846ef9b4 | 3,307 | //
// network.swift
// RosSwift
//
// Created by Thomas Gustafsson on 2018-03-03.
//
import Foundation
import NIO
import Logging
fileprivate let logger = Logger(label: "network")
extension SocketAddress {
var host: String {
switch self {
case .v4(let addr):
return addr.host
case .v6(let addr):
return addr.host
case .unixDomainSocket:
return ""
}
}
}
public struct RosNetwork {
public let gHost: String
public let gTcprosServerPort: UInt16
public init(remappings: [String:String]) {
var host = ""
if let it = remappings["__hostname"] {
host = it
} else if let it = remappings["__ip"] {
host = it
}
if let it = remappings["__tcpros_server_port"] {
guard let tcprosServerPort = UInt16(it) else {
fatalError("__tcpros_server_port [\(it)] was not specified as a number within the 0-65535 range")
}
gTcprosServerPort = tcprosServerPort
} else {
gTcprosServerPort = 0
}
if host.isEmpty {
host = RosNetwork.determineHost()
}
gHost = host
}
public static func splitURI(uri: String) -> (host: String, port: UInt16)? {
var uri = uri
if uri.hasPrefix("http://") {
uri = String(uri.dropFirst(7))
} else if uri.hasPrefix("rosrpc://") {
uri = String(uri.dropFirst(9))
}
let parts = uri.components(separatedBy: ":")
guard parts.count == 2 else {
return nil
}
var portString = parts[1]
let segs = portString.components(separatedBy: "/")
portString = segs[0]
guard let portNr = UInt16(portString) else {
return nil
}
return (parts[0], portNr)
}
public static func determineHost() -> String {
if let hostname = ProcessInfo.processInfo.environment["ROS_HOSTNAME"] {
logger.debug("determineIP: using value of ROS_HOSTNAME:\(hostname)")
if hostname.isEmpty {
logger.warning("invalid ROS_HOSTNAME (an empty string)")
}
return hostname
}
if let rosIP = ProcessInfo.processInfo.environment["ROS_IP"] {
logger.debug("determineIP: using value of ROS_IP:\(rosIP)")
if rosIP.isEmpty {
logger.warning("invalid ROS_IP (an empty string)")
}
return rosIP
}
let host = ProcessInfo.processInfo.hostName
let trimmedHost = host.trimmingCharacters(in: .whitespacesAndNewlines)
// We don't want localhost to be our ip
if !trimmedHost.isEmpty && host != "localhost" && !trimmedHost.hasSuffix("local") && trimmedHost.contains(".") {
return trimmedHost
}
do {
for i in try System.enumerateInterfaces() {
let host = i.address.host
if host != "127.0.0.1" && i.address.protocolFamily == PF_INET {
return host
}
}
} catch {
logger.error("\(error)")
}
return "127.0.0.1"
}
}
| 28.264957 | 120 | 0.534321 |
0187fb27e1ba4a4517578c20eb9ee366a99e6bb0 | 16,754 | import Foundation
import StoreKit
/// The `Merchant` manages a set of registered products. The `Merchant` creates tasks to perform various operations, and tracks the `PurchasedState` of products.
/// There will typically be only one `Merchant` instantiated in an application.
public final class Merchant {
/// The `delegate` will be called to respond to various events.
public let delegate: MerchantDelegate
/// The parameters to forward onto the underlying `StoreKit` framework. These parameters apply to all transactions handled by the `Merchant`.
public var storeParameters: StoreParameters = StoreParameters()
private let storage: PurchaseStorage
private let transactionObserver: StoreKitTransactionObserver = StoreKitTransactionObserver()
private var _registeredProducts: [String : Product] = [:]
private var activeTasks: [MerchantTask] = []
private var purchaseObservers: Buckets<String, MerchantPurchaseObserver> = Buckets()
private var receiptFetchers: [ReceiptFetchPolicy : ReceiptDataFetcher] = [:]
private var receiptDataFetcherCustomInitializer: ReceiptDataFetcherInitializer?
private var identifiersForPendingObservedPurchases: Set<String> = []
public private(set) var isLoading: Bool = false
private let nowDate: Date = Date()
private var latestFetchedReceipt: Receipt?
/// Create a `Merchant`, probably at application launch. Assign a consistent `storage` and a `delegate` to receive callbacks.
public init(storage: PurchaseStorage, delegate: MerchantDelegate) {
self.delegate = delegate
self.storage = storage
}
/// Products must be registered before their states are consistently valid. Products should be registered as early as possible.
/// See `LocalConfiguration` for a basic way to register products using a locally stored file.
public func register<Products : Sequence>(_ products: Products) where Products.Iterator.Element == Product {
for product in products {
self._registeredProducts[product.identifier] = product
}
}
/// Call this method at application launch. It performs necessary initialization routines.
public func setup() {
self.beginObservingTransactions()
self.checkReceipt(updateProducts: .all, policy: .onlyFetch, reason: .initialization)
}
/// Returns a registered product for a given `productIdentifier`, or `nil` if not found.
public func product(withIdentifier productIdentifier: String) -> Product? {
return self._registeredProducts[productIdentifier]
}
/// Returns the state for a `product`. Consumable products always report that they are `notPurchased`.
public func state(for product: Product) -> PurchasedState {
guard let record = self.storage.record(forProductIdentifier: product.identifier) else {
return .notPurchased
}
switch product.kind {
case .consumable:
return .notPurchased
case .nonConsumable, .subscription(automaticallyRenews: _):
let info = PurchasedProductInfo(expiryDate: record.expiryDate)
return .isPurchased(info)
}
}
/// Find possible purchases for the given products. If `products` is empty, then the merchant looks up all purchases for all registered products.
public func availablePurchasesTask(for products: Set<Product> = []) -> AvailablePurchasesTask {
return self.makeTask(initializing: {
let products = products.isEmpty ? Set(self._registeredProducts.values) : products
let task = AvailablePurchasesTask(for: products, with: self)
return task
})
}
/// Begin buying a product, supplying a `purchase` fetched from the `AvailablePurchasesTask`.
public func commitPurchaseTask(for purchase: Purchase) -> CommitPurchaseTask {
return self.makeTask(initializing: {
let task = CommitPurchaseTask(for: purchase, with: self)
return task
})
}
/// Restore the user's purchases. Calling this method may present modal UI.
public func restorePurchasesTask() -> RestorePurchasesTask {
return self.makeTask(initializing: {
let task = RestorePurchasesTask(with: self)
return task
})
}
}
// MARK: Testing hooks
extension Merchant {
typealias ReceiptDataFetcherInitializer = (ReceiptFetchPolicy) -> ReceiptDataFetcher
/// Allows tests in the test suite to change the receipt data fetcher that is created.
internal func setCustomReceiptDataFetcherInitializer(_ initializer: @escaping ReceiptDataFetcherInitializer) {
self.receiptDataFetcherCustomInitializer = initializer
}
}
// MARK: Purchase observers
extension Merchant {
internal func addPurchaseObserver(_ observer: MerchantPurchaseObserver, forProductIdentifier productIdentifier: String) {
var observers = self.purchaseObservers[productIdentifier]
if !observers.contains(where: { $0 === observer }) {
observers.append(observer)
}
self.purchaseObservers[productIdentifier] = observers
}
internal func removePurchaseObserver(_ observer: MerchantPurchaseObserver, forProductIdentifier productIdentifier: String) {
var observers = self.purchaseObservers[productIdentifier]
if let index = observers.index(where: { $0 === observer }) {
observers.remove(at: index)
self.purchaseObservers[productIdentifier] = observers
}
}
}
// MARK: Task management
extension Merchant {
private func makeTask<Task : MerchantTask>(initializing creator: () -> Task) -> Task {
let task = creator()
self.addActiveTask(task)
return task
}
private func addActiveTask(_ task: MerchantTask) {
self.activeTasks.append(task)
self.updateLoadingStateIfNecessary()
}
// Call on main thread only.
internal func updateActiveTask(_ task: MerchantTask) {
self.updateLoadingStateIfNecessary()
}
// Call on main thread only.
internal func resignActiveTask(_ task: MerchantTask) {
guard let index = self.activeTasks.index(where: { $0 === task }) else { return }
self.activeTasks.remove(at: index)
self.updateLoadingStateIfNecessary()
}
}
// MARK: Loading state changes
extension Merchant {
private var _isLoading: Bool {
return !self.activeTasks.filter { $0.isStarted }.isEmpty || !self.receiptFetchers.isEmpty
}
/// Call on main thread only.
private func updateLoadingStateIfNecessary() {
let isLoading = self.isLoading
let updatedIsLoading = self._isLoading
if updatedIsLoading != isLoading {
self.isLoading = updatedIsLoading
self.delegate.merchantDidChangeLoadingState(self)
}
}
}
// MARK: Subscription utilities
extension Merchant {
private func isSubscriptionActive(forExpiryDate expiryDate: Date) -> Bool {
return expiryDate > self.nowDate
}
}
// MARK: Payment queue related behaviour
extension Merchant {
private func beginObservingTransactions() {
self.transactionObserver.delegate = self
SKPaymentQueue.default().add(self.transactionObserver)
}
private func stopObservingTransactions() {
SKPaymentQueue.default().remove(self.transactionObserver)
}
// Right now, Merchant relies on refreshing receipts to restore purchases. The implementation may be changed in future.
internal func restorePurchases(completion: @escaping CheckReceiptCompletion) {
self.checkReceipt(updateProducts: .all, policy: .alwaysRefresh, reason: .restorePurchases, completion: completion)
}
}
// MARK: Receipt fetch and validation
extension Merchant {
internal typealias CheckReceiptCompletion = (_ updatedProducts: Set<Product>, Error?) -> Void
private func checkReceipt(updateProducts updateType: ReceiptUpdateType, policy: ReceiptFetchPolicy, reason: ReceiptValidationRequest.Reason, completion: @escaping CheckReceiptCompletion = { _,_ in }) {
let fetcher: ReceiptDataFetcher
let isStarted: Bool
if let activeFetcher = self.receiptFetchers[policy] { // the same fetcher may be pooled and used multiple times, this is because `enqueueCompletion` can add blocks even after the fetcher has been started
fetcher = activeFetcher
isStarted = true
} else {
fetcher = self.makeFetcher(for: policy)
isStarted = false
self.receiptFetchers[policy] = fetcher
}
fetcher.enqueueCompletion { [weak self] dataResult in
guard let strongSelf = self else { return }
switch dataResult {
case .succeeded(let receiptData):
strongSelf.validateReceipt(with: receiptData, reason: reason, completion: { [weak self] validateResult in
guard let strongSelf = self else { return }
switch validateResult {
case .succeeded(let receipt):
strongSelf.latestFetchedReceipt = receipt
let updatedProducts = strongSelf.updateStorageWithValidatedReceipt(receipt, updateProducts: updateType)
if !updatedProducts.isEmpty {
DispatchQueue.main.async {
strongSelf.didChangeState(for: updatedProducts)
}
}
completion(updatedProducts, nil)
case .failed(let error):
completion([], error)
}
})
case .failed(let error):
completion([], error)
}
strongSelf.receiptFetchers.removeValue(forKey: policy)
if strongSelf.receiptFetchers.isEmpty && strongSelf.isLoading {
DispatchQueue.main.async {
strongSelf.updateLoadingStateIfNecessary()
}
}
}
if !isStarted {
fetcher.start()
if !self.receiptFetchers.isEmpty && !self.isLoading {
self.updateLoadingStateIfNecessary()
}
}
}
private func makeFetcher(for policy: ReceiptFetchPolicy) -> ReceiptDataFetcher {
if let initializer = self.receiptDataFetcherCustomInitializer {
return initializer(policy)
}
return StoreKitReceiptDataFetcher(policy: policy)
}
private func validateReceipt(with data: Data, reason: ReceiptValidationRequest.Reason, completion: @escaping (Result<Receipt>) -> Void) {
DispatchQueue.main.async {
let request = ReceiptValidationRequest(data: data, reason: reason)
self.delegate.merchant(self, validate: request, completion: completion)
}
}
private func updateStorageWithValidatedReceipt(_ receipt: Receipt, updateProducts updateType: ReceiptUpdateType) -> Set<Product> {
var updatedProducts = Set<Product>()
let productIdentifiers: Set<String>
switch updateType {
case .all:
productIdentifiers = receipt.productIdentifiers
case .specific(let identifiers):
productIdentifiers = identifiers
}
for identifier in productIdentifiers {
guard let product = self.product(withIdentifier: identifier) else { continue }
guard product.kind != .consumable else { continue } // consumables are special-cased as they are not recorded, but may temporarily appear in receipts
let entries = receipt.entries(forProductIdentifier: identifier)
let hasEntry = !entries.isEmpty
let result: PurchaseStorageUpdateResult
if hasEntry {
let expiryDate = entries.compactMap { $0.expiryDate }.max()
if let expiryDate = expiryDate, !self.isSubscriptionActive(forExpiryDate: expiryDate) {
result = self.storage.removeRecord(forProductIdentifier: identifier)
} else {
let record = PurchaseRecord(productIdentifier: identifier, expiryDate: expiryDate)
result = self.storage.save(record)
}
} else {
result = self.storage.removeRecord(forProductIdentifier: identifier)
}
if result == .didChangeRecords {
updatedProducts.insert(product)
}
}
if updateType == .all { // clean out from storage if registered products are not in the receipt
let registeredProductIdentifiers = Set(self._registeredProducts.map { $0.key })
let identifiersForProductsNotInReceipt = registeredProductIdentifiers.subtracting(receipt.productIdentifiers)
for productIdentifier in identifiersForProductsNotInReceipt {
let result = self.storage.removeRecord(forProductIdentifier: productIdentifier)
if result == .didChangeRecords {
updatedProducts.insert(self._registeredProducts[productIdentifier]!)
}
}
}
return updatedProducts
}
private enum ReceiptUpdateType : Equatable {
case all
case specific(productIdentifiers: Set<String>)
}
}
// MARK: Product state changes
extension Merchant {
/// Call on main thread only.
private func didChangeState(for products: Set<Product>) {
self.delegate.merchant(self, didChangeStatesFor: products)
}
}
// MARK: `StoreKitTransactionObserverDelegate` Conformance
extension Merchant : StoreKitTransactionObserverDelegate {
internal func storeKitTransactionObserverWillUpdatePurchases(_ observer: StoreKitTransactionObserver) {
}
internal func storeKitTransactionObserver(_ observer: StoreKitTransactionObserver, didPurchaseProductWith identifier: String) {
if let product = self.product(withIdentifier: identifier) {
if product.kind == .consumable { // consumable product purchases are not recorded
self.delegate.merchant(self, didConsume: product)
} else { // non-consumable and subscription products are recorded
let record = PurchaseRecord(productIdentifier: identifier, expiryDate: nil)
let result = self.storage.save(record)
if result == .didChangeRecords {
self.didChangeState(for: [product])
}
if case .subscription(_) = product.kind {
self.identifiersForPendingObservedPurchases.insert(product.identifier) // we need to get the receipt to find the expiry date, the `PurchaseRecord` will be updated when that information is available
}
}
}
for observer in self.purchaseObservers[identifier] {
observer.merchant(self, didCompletePurchaseForProductWith: identifier)
}
}
internal func storeKitTransactionObserver(_ observer: StoreKitTransactionObserver, didFailToPurchaseWith error: Error, forProductWith identifier: String) {
for observer in self.purchaseObservers[identifier] {
observer.merchant(self, didFailPurchaseWith: error, forProductWith: identifier)
}
}
internal func storeKitTransactionObserverDidUpdatePurchases(_ observer: StoreKitTransactionObserver) {
if !self.identifiersForPendingObservedPurchases.isEmpty {
self.checkReceipt(updateProducts: .specific(productIdentifiers: self.identifiersForPendingObservedPurchases), policy: .onlyFetch, reason: .completePurchase, completion: { _, _ in })
}
self.identifiersForPendingObservedPurchases.removeAll()
}
}
| 41.470297 | 217 | 0.634356 |
bfbfe5f14e02ad676ae2bdfdec62bda505d9481d | 2,016 | //
// PostTableViewCell.swift
// RedditReader
//
// Created by Javier Loucim on 25/08/2019.
// Copyright © 2019 Javier Loucim. All rights reserved.
//
import UIKit
class PostTableViewCell: UITableViewCell {
@IBOutlet weak var unreadIndicatorView: UIView!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var timeAgoLabel: UILabel!
@IBOutlet weak var commentsLabel: UILabel!
@IBOutlet weak var postImageView: UIImageView!
@IBOutlet weak var titleLabel: 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 configure(with post: Post) {
unreadIndicatorView.layer.cornerRadius = unreadIndicatorView.bounds.height/2
unreadIndicatorView.layer.masksToBounds = true
unreadIndicatorView.backgroundColor = UIColor.unread
unreadIndicatorView.isHidden = post.isRead
authorLabel.text = post.author
timeAgoLabel.text = post.timeAgo
commentsLabel.text = post.commentsText
titleLabel.text = post.title
backgroundColor = UIColor.mainBackground
authorLabel.textColor = UIColor.mainText
timeAgoLabel.textColor = UIColor.mainText
commentsLabel.textColor = UIColor.highLightedText
titleLabel.textColor = UIColor.mainText
if let url = post.thumbnailURL {
self.postImageView.downloadImageFromUrl(url, defaultImage: nil)
} else {
self.postImageView.image = nil
}
updateSelection()
}
func updateSelection() {
if isSelected {
let selectionView = UIView()
selectionView.backgroundColor = UIColor.selectedRow
selectedBackgroundView = selectionView
} else {
selectedBackgroundView = nil
}
}
}
| 31.015385 | 84 | 0.668155 |
387502866b32ac36a690a665739c4b6f937e991a | 490 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
let a {
enum S<h , A {
{
{
}
}
class d {
enum B {
struct S< b {
struct A
enum S<c> : AnyObject, A
| 24.5 | 78 | 0.710204 |
e52d3bb7f101cae166c3e95d3bed35919cee4574 | 1,218 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import UIKit
import FeedFeature
public final class FeedUIComposer {
private init() {}
public static func feedComposedWith(feedLoader: FeedLoader, imageLoader: FeedImageDataLoader) -> FeedViewController {
let presentationAdapter = FeedLoaderPresentationAdapter(feedLoader:
MainQueueDispatchDecorator(decoratee: feedLoader))
let feedController = makeFeedViewController(
delegate: presentationAdapter,
title: Localized.Feed.title)
presentationAdapter.presenter = FeedPresenter(
feedView: FeedViewAdapter(
controller: feedController,
imageLoader: MainQueueDispatchDecorator(decoratee: imageLoader)),
loadingView: WeakRefVirtualProxy(feedController))
return feedController
}
private static func makeFeedViewController(delegate: FeedViewControllerDelegate, title: String) -> FeedViewController {
let bundle = Bundle(for: FeedViewController.self)
let storyboard = UIStoryboard(name: "Feed", bundle: bundle)
let feedController = storyboard.instantiateInitialViewController() as! FeedViewController
feedController.delegate = delegate
feedController.title = title
return feedController
}
}
| 32.918919 | 120 | 0.788998 |
14a5cc671ef924a95eb28694664f8baa4d4a01c5 | 1,346 | //
// SpeakerCell.swift
// DevFest
//
// Created by Brendon Justin on 11/23/16.
// Copyright © 2016 GDGConferenceApp. All rights reserved.
//
import UIKit
class SpeakerCell: UICollectionViewCell {
@IBOutlet var speakerTitleView: SpeakerTitleView!
var faceRect: CGRect? {
get {
return speakerTitleView.faceRect
}
set {
speakerTitleView.faceRect = newValue
}
}
var image: UIImage? {
get {
return speakerTitleView.image
}
set {
speakerTitleView.image = newValue
}
}
var viewModel: SpeakerViewModel? {
get {
return speakerTitleView.viewModel
}
set {
speakerTitleView.viewModel = newValue
}
}
override func awakeFromNib() {
super.awakeFromNib()
dev_registerForAppearanceUpdates()
dev_updateAppearance()
}
override func dev_updateAppearance() {
super.dev_updateAppearance()
// Add side margins so our `speakerTitleView` is inset a bit
contentView.layoutMargins = UIEdgeInsetsMake(0, .dev_standardMargin, 0, .dev_standardMargin)
}
}
extension SpeakerCell: ReusableItem {
static let reuseID: String = String(describing: SpeakerCell.self)
}
| 22.813559 | 100 | 0.600297 |
233b75bc52d54b6b8ffe27f2fa4cb48724c38f77 | 4,383 | //
// TouchCheck.swift
// TouchDemo
//
// Created by Ross Beale on 18/04/2018.
// Copyright © 2018 Airbyte Ltd. All rights reserved.
//
import UIKit
private struct TouchNode {
let view: UIView
let touchView: UIView
let height = 39
let width = 39
init(view: UIView) {
self.view = view
self.touchView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
self.touchView.backgroundColor = UIColor.blue.withAlphaComponent(0.4)
self.touchView.isUserInteractionEnabled = false
self.touchView.center = view.center
}
}
extension UIViewController {
private func showControlSubviews() {
// get all views
let views = view.subviewsRecursive()
let controlViews = views.filter { $0.isControl() }
let controlNodes = controlViews.map { TouchNode(view: $0) }
// find nodes
for node in controlNodes {
// add touch
node.view.superview?.addSubview(node.touchView)
}
for node in controlNodes {
// determine if touch node is too small
var valid = true
let klass = NSStringFromClass(type(of: node.view))
if !["_UIButtonBarButton", "_UIModernBarButton"].contains(klass) {
valid = valid && node.view.frame.contains(node.touchView.frame)
if let touchViewWindowFrame0 = node.view.superview?.convert(node.view.frame, to: nil) {
valid = valid && !controlNodes.contains(where: {
if let touchViewWindowFrame1 = $0.view.superview?.convert($0.view.frame, to: nil) {
return $0.view != node.view && touchViewWindowFrame0.intersects(touchViewWindowFrame1)
}
return false
})
}
}
// add overlay
let subview = UIView(frame: node.view.frame)
subview.backgroundColor = valid ? UIColor.green.withAlphaComponent(0.3) : UIColor.red.withAlphaComponent(0.3)
subview.isUserInteractionEnabled = false
node.view.superview?.insertSubview(subview, aboveSubview: node.touchView)
}
}
}
private extension UIView {
func isControl() -> Bool {
return self is UIControl || self.gestureRecognizers?.count ?? 0 == 1
}
func subviewsRecursive() -> [UIView] {
return subviews + subviews.flatMap { $0.subviewsRecursive() }
}
}
private let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in
let originalMethod = class_getInstanceMethod(forClass, originalSelector)
let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
private extension UIViewController {
static let classInit: Void = {
let originalSelector = #selector(viewDidAppear(_:))
let swizzledSelector = #selector(swizzled_viewDidAppear(animated:))
swizzling(UIViewController.self, originalSelector, swizzledSelector)
}()
@objc func swizzled_viewDidAppear(animated: Bool) {
swizzled_viewDidAppear(animated: animated)
showControlSubviews()
}
}
public final class TouchCheck: NSObject {
/// Defines if and when TouchCheck should be enabled.
///
/// - always: TouchCheck is always enabled.
/// - never: TouchCheck is never enabled.
/// - debugOnly: TouchCheck is enabled while the `DEBUG` flag is set and enabled.
@objc public enum Enabled: Int {
case always
case never
case debugOnly
}
@objc private static var enabled: TouchCheck.Enabled = .never
static var shouldEnable: Bool {
guard enabled != .never else { return false }
guard enabled != .debugOnly else {
#if DEBUG
return true
#else
return false
#endif
}
return true
}
static public func configure(enabled: TouchCheck.Enabled) {
self.enabled = enabled
if shouldEnable {
UIViewController.classInit
}
}
}
| 30.866197 | 121 | 0.593885 |
ffd14ddbf68e59c83992e84793e336d0bb6013f6 | 3,790 | //
// TweetsViewController.swift
// TwitterDemo
//
// Created by Mendoza, Alejandro on 4/15/17.
// Copyright © 2017 Alejandro Mendoza. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
import MBProgressHUD
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tweetsTableView: UITableView!
var tweets: [Tweet]!
override func viewDidLoad() {
super.viewDidLoad()
tweetsTableView.delegate = self
tweetsTableView.dataSource = self
tweetsTableView.rowHeight = UITableViewAutomaticDimension
tweetsTableView.estimatedRowHeight = 120
TwitterClient.sharedInstance?.homeTimeline(success: { (tweets: [Tweet]) in
self.tweets = tweets
self.tweetsTableView.reloadData()
}, failure: { (error: Error) in
})
// Initialize a UIRefreshControl
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector (refreshControlAction(refreshControl:) ), for: UIControlEvents.valueChanged)
// add refresh control to table view
tweetsTableView.insertSubview(refreshControl, at: 0)
// Do any additional setup after loading the view.
}
// MARK: refresh func
// Makes a network request to get updated data
// Updates the tableView with the new data
// Hides the RefreshControl
func refreshControlAction(refreshControl: UIRefreshControl) {
// Display HUD right before the request is made
MBProgressHUD.showAdded(to: self.view, animated: true)
TwitterClient.sharedInstance?.homeTimeline(success: { (tweets: [Tweet]) in
self.tweets = tweets
MBProgressHUD.hide(for: self.view, animated: true)
self.tweetsTableView.reloadData()
// Tell the refreshControl to stop spinning
refreshControl.endRefreshing()
}, failure: { (error: Error) in
})
}
// MARK: table view funcs
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tweets != nil {
return tweets.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tweetsTableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell
cell.tweet = tweets[indexPath.row]
return cell
}
//MATK: system funcs
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogout(_ sender: Any) {
TwitterClient.sharedInstance?.logout()
}
@IBAction func onProfileTouched(_ sender: Any) {
self.performSegue(withIdentifier: "profileSegue", sender: nil)
}
// 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.
print("Performing segue")
if let cell = sender as? UITableViewCell {
let indexPath = tweetsTableView.indexPath(for: cell)
let tweet = tweets![indexPath!.row]
let retweetVC = segue.destination as! RetweetViewController
retweetVC.tweet = tweet
}
}
}
| 31.583333 | 133 | 0.630343 |
c1e095a9814fddac889d15936eac068cc0f3f90c | 6,388 | //
// MyGiftsController.swift
// QHAwemeDemo
//
// Created by mac on 2019-12-23.
// Copyright © 2019 AnakinChen Network Technology. All rights reserved.
//
import UIKit
import MJRefresh
class MyGiftsController: QHBaseViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
private lazy var navBar: QHNavigationBar = {
let bar = QHNavigationBar()
bar.titleLabel.text = "我的奖品"
bar.titleLabel.textColor = UIColor.init(r: 34, g: 34, b: 34)
bar.backButton.isHidden = false
bar.lineView.isHidden = true
bar.backgroundColor = UIColor.white
bar.backButton.setImage(UIImage(named: "navBackBlack"), for: .normal)
bar.delegate = self
return bar
}()
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.allowsSelection = false
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor.clear
tableView.showsVerticalScrollIndicator = false
tableView.register(UINib.init(nibName: "MyGiftTableCell", bundle: Bundle.main), forCellReuseIdentifier: MyGiftTableCell.cellId)
tableView.mj_header = refreshView
tableView.mj_footer = loadMoreView
return tableView
}()
lazy private var loadMoreView: MJRefreshAutoNormalFooter = {
weak var weakSelf = self
let loadmore = MJRefreshAutoNormalFooter(refreshingBlock: {
weakSelf?.loadNextpage()
})
loadmore?.isHidden = true
loadmore?.stateLabel.font = ConstValue.kRefreshLableFont
return loadmore!
}()
lazy private var refreshView: MJRefreshGifHeader = {
weak var weakSelf = self
let mjRefreshHeader = MJRefreshGifHeader(refreshingBlock: {
weakSelf?.loadFirstpage()
})
var gifImages = [UIImage]()
for string in ConstValue.refreshImageNames {
gifImages.append(UIImage(named: string)!)
}
mjRefreshHeader?.setImages(gifImages, for: .refreshing)
mjRefreshHeader?.setImages(gifImages, for: .idle)
mjRefreshHeader?.stateLabel.font = ConstValue.kRefreshLableFont
mjRefreshHeader?.lastUpdatedTimeLabel.font = ConstValue.kRefreshLableFont
return mjRefreshHeader!
}()
var giftModelList = [MyGiftModle]()
let viewModel = GameViewModel()
deinit {
DLog("vc - Gift relase")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.init(r: 244, g: 244, b: 244)
view.addSubview(navBar)
view.addSubview(tableView)
layoutPageViews()
addViewModelCallback()
loadData()
}
private func loadData() {
NicooErrorView.removeErrorMeesageFrom(view)
XSProgressHUD.showCustomAnimation(msg: nil, onView: view, imageNames: nil, bgColor: nil, animated: false)
viewModel.loadMgGiftListData()
}
private func loadFirstpage() {
viewModel.loadMgGiftListData()
}
private func loadNextpage() {
viewModel.loadMyGiftListNextPage()
}
private func addViewModelCallback() {
viewModel.myGiftListSuccessHandler = { [weak self] (models, pageNumber) in
guard let strongSelf = self else { return }
if pageNumber == 1 {
strongSelf.giftModelList = models
if models.count == 0 {
NicooErrorView.showErrorMessage(.noData, "您还没有奖品 \n快去夺宝吧", on: strongSelf.view, topMargin: safeAreaTopHeight+30) {
strongSelf.loadData()
}
}
} else {
strongSelf.giftModelList.append(contentsOf: models)
}
strongSelf.loadMoreView.isHidden = models.count < GameGiftListApi.kDefaultCount
strongSelf.tableView.reloadData()
strongSelf.endRefreshing()
}
viewModel.myGiftListFailHandler = { [weak self] (msg, pageNumber) in
guard let strongSelf = self else { return }
strongSelf.endRefreshing()
if pageNumber == 1 {
NicooErrorView.showErrorMessage(.noData, "数据加载异常,请重试", on: strongSelf.view, topMargin: safeAreaTopHeight+30) {
strongSelf.loadData()
}
}
}
}
private func endRefreshing() {
loadMoreView.endRefreshing()
refreshView.endRefreshing()
XSProgressHUD.hide(for: view, animated: false)
}
}
//MARK: - UITableViewDataSource, UITableViewDelegate
extension MyGiftsController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return giftModelList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MyGiftTableCell.cellId, for: indexPath) as! MyGiftTableCell
cell.setGiftModel(giftModelList[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 123.0
}
}
// MARK: - QHNavigationBarDelegate
extension MyGiftsController: QHNavigationBarDelegate {
func backAction() {
navigationController?.popViewController(animated: true)
}
}
//MARK: -Layout
private extension MyGiftsController {
func layoutPageViews() {
layoutNavBar()
layoutTableView()
}
func layoutNavBar() {
navBar.snp.makeConstraints { (make) in
make.leading.trailing.top.equalToSuperview()
make.height.equalTo(safeAreaTopHeight)
}
}
func layoutTableView() {
tableView.snp.makeConstraints { (make) in
make.top.equalTo(navBar.snp.bottom)
make.leading.trailing.equalToSuperview()
if #available(iOS 11.0, *) {
make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
} else {
// Fallback on earlier versions
make.bottom.equalToSuperview()
}
}
}
}
| 34.160428 | 135 | 0.632436 |
5da424d578f9c19c5577d4ac4963f90a9d17aade | 3,884 | //
// VGSDeepMergeUtils.swift
// VGSCollectSDK
//
// Created on 04.03.2021.
// Copyright © 2021 VGS. All rights reserved.
//
import Foundation
/// Utils for deepMerge.
final internal class VGSDeepMergeUtils {
// MARK: - Helpers
/// Deep merge JSON objects and arrays.
/// - Parameters:
/// - target: `JsonData` object, target to merge.
/// - source: `JsonData` object, source to merge.
/// - mergeArrayPolicy: `VGSCollectArrayMergePolicy` object, array merge policy.
/// - Returns: `JsonData` object, merged data.
static func deepMerge(target: JsonData, source: JsonData, mergeArrayPolicy: VGSCollectArrayMergePolicy) -> JsonData {
var result = target
for (k2, v2) in source {
// If JSON and JSON, deep merge JSONData recursively.
if let v1 = result[k2] as? JsonData, let v2 = v2 as? JsonData {
result[k2] = deepMerge(target: v1, source: v2, mergeArrayPolicy: mergeArrayPolicy)
// Try to merge Array1 and Array2.
} else if let array1 = result[k2] as? Array<Any?>, let array2 = v2 as? Array<Any?> {
switch mergeArrayPolicy {
case .merge:
result[k2] = deepArrayMerge(target: array1, source: array2, mergeArrayPolicy: mergeArrayPolicy)
case .overwrite:
result[k2] = v2
}
} else {
// Just add value since d1 doesn't have value k2.
result[k2] = v2
}
}
return result
}
/// Deep merge content of arrays of JSON objects.
/// - Parameters:
/// - target: `Array<Any>` object, target to merge.
/// - source: `Array<Any>` object, source to merge.
/// - mergeArrayPolicy: `VGSCollectArrayMergePolicy` object, array merge policy.
/// - Returns: `Array<Any>` object, merged arrays.
static func deepArrayMerge(target: Array<Any?>, source: Array<Any?>, mergeArrayPolicy: VGSCollectArrayMergePolicy) -> Array<Any?> {
var result = target
// Iterate through source array.
for index in 0..<source.count {
let value2 = source[index]
// If target array has element at index try to merge.
if let value1 = target[safe: index] {
// Try to deepMerge value1 and value2 (JSON & JSON).
if let data1 = value1 as? JsonData, let data2 = value2 as? JsonData {
result[index] = deepMerge(target: data1, source: data2, mergeArrayPolicy: mergeArrayPolicy)
} else {
let isSourceJSON = isJSON(value2)
// Source is JSON, but target is not JSON. Overwrite target with source JSON.
if isSourceJSON {
result[index] = value2
} else {
// Try to keep both values. Append only non-nil since target array iteration not finished.
appendValueIfNeeded(value2, at: index, array: &result)
}
}
} else {
// Target doesn't have value at index of source. Add item from source if result is not nil at this index (already append some values from source before). In this way we can save specified array capacity in source.
// Append all non-nil values.
appendValueIfNeeded(value2, at: index, array: &result)
}
}
return result
}
/// Append value if needed to array.
/// - Parameters:
/// - value: `Any?`, value to append.
/// - index: `Int` object, iteration index.
/// - array: Array of `Any?`, `inout`.
private static func appendValueIfNeeded(_ value: Any?, at index: Int, array: inout [Any?]) {
// Append all non-nil values.
guard value == nil else {
array.append(value)
return
}
// Don't append nil if result array has element at this index.
// We can have this case when new value from source has already been appended on the previous iteration (non JSON source element).
// So we iterate through all target values but appended some values from source.
if index > array.count - 1 {
array.append(value)
}
}
/// Check if value is `JSON`.
/// - Parameter json: `Any?` value.
/// - Returns: `true` if JSON.
private static func isJSON(_ json: Any?) -> Bool {
return json is JsonData
}
}
| 34.371681 | 217 | 0.672245 |
0e26ab0ce94db901cf3f29ce00d38bae4c47dfb3 | 315 | //
// Logger.swift
// JuniorWeekend
//
// Created by Jelle Vandebeeck on 11/06/16.
// Copyright © 2016 Fousa. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
enum Logger {
static func info(string: String) {
fputs(string, stdout)
fflush(stdout)
}
} | 15.75 | 48 | 0.625397 |
c15cd635f2122212f2deaf1d0d3fae2d4888277d | 1,237 | //
// MemeMeUITests.swift
// MemeMeUITests
//
// Created by Mickey Cheong on 20/10/16.
// Copyright © 2016 CHEO.NG. All rights reserved.
//
import XCTest
class MemeMeUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.432432 | 182 | 0.660469 |
0e1fad19f5d0808241510611d3c4748bdc4dc4ed | 3,294 | // TODO: UPDATE FOR UIKIT
// import UIKit
/// HGReport is used to create generic error messaging throughout the app. User may turn on or off specific message types. Used to create uniformity in message reporting.
struct HGReport {
static var shared = HGReport()
var isOn = true
let hgReportHandlerInfo = true
let hgReportHandlerWarn = true
let hgReportHandlerError = true
let hgReportHandlerAlert = true
let hgReportHandlerAssert = true
func report(_ msg: String, type: HGErrorType) {
if !isOn { return }
switch (type) {
case .info: if hgReportHandlerInfo == false { return }
case .warn: if hgReportHandlerWarn == false { return }
case .error: if hgReportHandlerError == false { return }
case .alert: if hgReportHandlerAlert == false { return }
case .assert:
if hgReportHandlerAssert == false { return }
let report = "[\(type.string)] " + msg
assert(true, report)
}
let report = "[\(type.string)] " + msg
print(report)
}
func optionalFailed<T>(_ decoder: T, object: Any?, returning: Any?) {
HGReport.shared.report("|\(decoder)| |OPTIONAL UNWRAP FAILED| object: |\(String(describing: object))|, returning: |\(String(describing: returning))|", type: .error)
}
func defaultsFailed<T>(_ decoder: T, key: String) {
HGReport.shared.report("|\(decoder)| |DEFAULTS RETRIEVAL FAILED| invalid key: |\(key)|", type: .error)
}
func decodeFailed<T>(_ decoder: T, object: Any) {
HGReport.shared.report("|\(decoder)| |DECODING FAILED| not mapable object: |\(object)|", type: .error)
}
func setDecodeFailed<T>(_ decoder: T, object: Any) {
HGReport.shared.report("|\(decoder)| |DECODING FAILED| not inserted object: |\(object)|", type: .error)
}
func notMatching(_ object: Any, object2: Any) {
HGReport.shared.report("|\(object)| is does not match |\(object2)|", type: .error)
}
func insertFailed<T>(set: T, object: Any) {
HGReport.shared.report("|\(set)| |INSERT FAILED| object: \(object)", type: .error)
}
func deleteFailed<T>(set: T, object: Any) {
HGReport.shared.report("|\(set)| |DELETE FAILED| object: \(object)", type: .error)
}
func getFailed<T>(set: T, keys: [Any], values: [Any]) {
HGReport.shared.report("|\(set)| |GET FAILED| for keys: |\(keys)| values: |\(values)|", type: .error)
}
func updateFailed<T>(set: T, key: Any, value: Any) {
HGReport.shared.report("|\(set)| |UPDATE FAILED| for key: |\(key)| not valid value: |\(value)|", type: .error)
}
func updateFailedGeneric<T>(set: T) {
HGReport.shared.report("|\(set)| |UPDATE FAILED| nil object returned, possible stale objects", type: .error)
}
func usedName<T>(decoder: T, name: String) {
HGReport.shared.report("|\(decoder)| |USED NAME| name: |\(name)| already used", type: .error)
}
func validateFailed<T,U>(decoder: T, value: Any, key: Any, expectedType: U) {
HGReport.shared.report("|\(decoder)| |VALIDATION FAILED| for key: |\(key)| value: |\(value)| expected type: |\(expectedType)|", type: .error)
}
}
| 40.170732 | 172 | 0.606557 |
46142a69269cf307f875855a37c83793d9bfb5dd | 35 | public func testingLib() {
{}()
}
| 8.75 | 26 | 0.571429 |
ac9a0b4afc42a4effe54e2ad2ebe9006579cfe13 | 18,129 | //
// MainFLImagePicker.swift
// FLImagePicker
//
// Created by Allen Lee on 2021/12/23.
//
// MIT License
//
// Copyright (c) 2021 Allen Lee
//
// 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 Photos
internal class MainFLImagePicker: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate {
@IBOutlet weak var mainCV: UICollectionView!
@IBOutlet weak var cvFlow: UICollectionViewFlowLayout!
var btnFinish: UIButton!
var btnCancel: UIButton!
// photoKit
var assetResult: PHFetchResult<PHAsset> = PHFetchResult()
let imgCacher = PHCachingImageManager()
// link
var imagePicker: FLImagePicker!
var imagePickerDelegate: FLImagePickerDelegate?
var imagePickerStyle: FLImagePickerStyle?{
didSet{
if isViewLoaded{
for cell in mainCV.visibleCells{
if let cell = cell as? MainFLImagePickerCell{
setCellStyle(cell, style: imagePickerStyle)
}
}
// btn
btnFinish.setTitleColor(imagePickerStyle?.btnColor ?? .link, for: .normal)
btnCancel.setTitleColor(imagePickerStyle?.btnColor ?? .link, for: .normal)
}
}
}
// picker data
private var numsOfRow: CGFloat = 3 // cells of row
private var maxPick = 100
private var fspd: CGFloat = 3 // step of pixel
private var fps: CGFloat = 120 // update speed
private var detectAreaHeight: CGFloat = 240
/* calculate data, no need to change*/
// pan
var multiAction = true // reverse from start state
var startIndexPath : IndexPath?
var thisSelected: Set<IndexPath> = [] // record single action's cell
var cvSelCount: Int{
get{
return mainCV.indexPathsForSelectedItems?.count ?? 0
}
}
// auto Scroll
var panY: CGFloat = 0
var timer: Timer?
// windows
var safeAreaBottom: CGFloat = 0
// feedback
var lastSelect = 0
let notificationFeedbackGenerator = UINotificationFeedbackGenerator()
let generator = UIImpactFeedbackGenerator(style: .light)
/* initialize*/
init(){
#if !SPM
super.init(nibName: "MainFLImagePicker", bundle: Bundle(for: MainFLImagePicker.self))
#else
super.init(nibName: "MainFLImagePicker", bundle: .module)
#endif
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
uiInit()
dataInit()
}
/* ui*/
func uiInit(){
var uib: UINib!
#if !SPM
uib = UINib(nibName: "MainFLImagePickerCell", bundle: Bundle(for: MainFLImagePickerCell.self))
#else
uib = UINib(nibName: "MainFLImagePickerCell", bundle: .module)
#endif
mainCV.register(uib, forCellWithReuseIdentifier: "FLImgCell")
btnFinish = UIButton(type: .system)
btnFinish.frame = CGRect(x: 0, y: 0, width: 120, height: 36)
btnFinish.setTitle(NSLocalizedString("done", comment: "done"), for: .normal)
btnFinish.setTitleColor(imagePickerStyle?.btnColor, for: .normal)
btnFinish.contentHorizontalAlignment = .right
btnFinish.addTarget(self, action: #selector(onFinish), for: .touchUpInside)
let rightCustomView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 36))
rightCustomView.addSubview(btnFinish)
let right = UIBarButtonItem(customView: rightCustomView)
navigationItem.rightBarButtonItem = right
btnCancel = UIButton(type: .system)
btnCancel.frame = CGRect(x: 0, y: 0, width: 120, height: 36)
btnCancel.setTitle(NSLocalizedString("cancel", comment: "cancel"), for: .normal)
btnCancel.setTitleColor(imagePickerStyle?.btnColor, for: .normal)
btnCancel.contentHorizontalAlignment = .left
btnCancel.addTarget(self, action: #selector(onCancel), for: .touchUpInside)
let leftCustomView = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 36))
leftCustomView.addSubview(btnCancel)
let left = UIBarButtonItem(customView: leftCustomView)
navigationItem.leftBarButtonItem = left
// prevent drag to dismiss
isModalInPresentation = true
// cv setup - numsOfRow + 1
let edge = (UIScreen.main.bounds.width - numsOfRow + 1) / numsOfRow
cvFlow.itemSize = CGSize(width: edge, height: edge)
cvFlow.minimumLineSpacing = 1
cvFlow.minimumInteritemSpacing = 1
// cvFlow.prepare() // <-- call prepare before invalidateLayout
// cvFlow.invalidateLayout()
// gesture
mainCV.allowsMultipleSelection = true
mainCV.allowsSelection = true
// pan
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panWhenScroll))
panGesture.addTarget(self, action: #selector(cvPan))
let ori = (mainCV.gestureRecognizers?.firstIndex(of: mainCV.panGestureRecognizer)) ?? 0
mainCV.gestureRecognizers?.insert(panGesture, at: ori)
// tap
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(cvTap))
mainCV.addGestureRecognizer(tapGesture)
// long tap
let longTapGesture = UILongPressGestureRecognizer(target: self, action: #selector(cvLongPress))
longTapGesture.delaysTouchesBegan = false
mainCV.addGestureRecognizer(longTapGesture)
}
func setCellStyle(_ cell: MainFLImagePickerCell, style: FLImagePickerStyle?){
cell.coverColor = style?.coverColor
cell.checkImage = style?.checkImage
cell.checkBorderColor = style?.checkBorderColor
cell.checkBackgroundColor = style?.checkBackgroundColor
}
// outlet
@objc func onFinish(_ sender: Any) {
dismiss(animated: true){[self] in
imagePickerDelegate?.flImagePicker(imagePicker, didFinished: getSelectedAssets())
imagePicker = nil
}
}
@objc func onCancel(_ sender: Any) {
dismiss(animated: true){[self] in
imagePickerDelegate?.flImagePicker(didCancelled: imagePicker)
imagePicker = nil
}
}
/* data*/
func dataInit(){
notificationFeedbackGenerator.prepare()
if #available(iOS 15.0, *) {
let windowScene = UIApplication.shared.connectedScenes.first as! UIWindowScene
safeAreaBottom = windowScene.windows.first?.safeAreaInsets.bottom ?? 0
} else {
safeAreaBottom = UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0
}
// collection view
mainCV.delegate = self
mainCV.dataSource = self
// album
if #available(iOS 14, *){
PHPhotoLibrary.requestAuthorization(for: .readWrite){status in
if status != .authorized{
return
}
self.getFetch()
}
}else{
PHPhotoLibrary.requestAuthorization(){status in
if status != .authorized{
return
}
self.getFetch()
}
}
}
func updateOptions(_ options: FLImagePickerOptions){
numsOfRow = options.numsOfRow
maxPick = options.maxPick
fspd = options.ppm
fps = options.fps
detectAreaHeight = options.detectAreaHeight
}
func getFetch(){
// fetch assets
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
// get result
assetResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
// reload
DispatchQueue.main.async {
self.mainCV.reloadData()
}
}
func getSelectedAssets() -> [PHAsset]{
var result: [PHAsset] = []
if let items = mainCV.indexPathsForSelectedItems?.sorted(by: {$0.row < $1.row}){
for i in items{
result.append(assetResult[i.row])
}
}
return result
}
// set select item
func setCellStatus(_ indexPath: IndexPath, status: Bool){
if status{
if cvSelCount < maxPick{
mainCV.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
}
}else{
mainCV.deselectItem(at: indexPath, animated: true)
}
// update btn total
let count = cvSelCount
if count != lastSelect{
generator.impactOccurred()
lastSelect = count
}
var total = ""
if count > 0 {
total = "(\(count))"
}
btnFinish.setTitle("\(NSLocalizedString("done", comment: "done"))\(total)", for: .normal)
}
// auto scoll timer
func autoRoll(isStop: Bool = false){
if isStop{
timer?.invalidate()
timer = nil
}else{
if timer != nil{
return
}
timer = Timer.scheduledTimer(withTimeInterval: 1 / fps, repeats: true){[self] _ in
if panY > mainCV.frame.maxY - detectAreaHeight{ // go down
let spd = ((panY - mainCV.frame.maxY + detectAreaHeight) / detectAreaHeight * fspd)
if mainCV.frameLayoutGuide.layoutFrame.maxY - safeAreaBottom < mainCV.collectionViewLayout.collectionViewContentSize.height{
mainCV.scrollRectToVisible(CGRect(x: 0, y: mainCV.frameLayoutGuide.layoutFrame.maxY - safeAreaBottom, width: 1, height: spd), animated: false)
}
}else if panY < mainCV.frame.minY + detectAreaHeight{ // go up
let spd = ((mainCV.frame.minY + detectAreaHeight - panY) / detectAreaHeight * fspd)
mainCV.scrollRectToVisible(CGRect(x: 0, y: mainCV.frameLayoutGuide.layoutFrame.minY - spd, width: 1, height: spd), animated: false)
}
}
}
}
/* objc*/
// pan func
@objc func cvPan(pan: UIPanGestureRecognizer){
guard let curIndexPath = mainCV.indexPathForItem(at: pan.location(in: mainCV)) else{
return
}
// init and deinit
if pan.state == .began{
// if true, then action will be false
multiAction = !mainCV.cellForItem(at: curIndexPath)!.isSelected
// self initial
startIndexPath = curIndexPath
}else if pan.state == .ended{
startIndexPath = nil
thisSelected.removeAll()
}
if let startIndexPath = startIndexPath {
// check need to clear beyond or under indexPath
var isCross = false
for i in thisSelected{
if (curIndexPath.row < startIndexPath.row && i.row > startIndexPath.row) ||
(curIndexPath.row > startIndexPath.row && i.row < startIndexPath.row) {
isCross = true
break
}
}
if isCross{
for i in thisSelected{
if i != startIndexPath{
setCellStatus(i, status: !multiAction)
thisSelected.remove(i)
}
}
}
// start pan
var hasNew = false
// go down
if curIndexPath.row >= startIndexPath.row{ // down
for cell in mainCV.visibleCells.sorted(by: {
return mainCV.indexPath(for: $0)?.row ?? 0 < mainCV.indexPath(for: $1)?.row ?? 1
}){
if let tIndexPath = mainCV.indexPath(for: cell){
// pan back reset to origin
if tIndexPath.row > curIndexPath.row && thisSelected.contains(tIndexPath){
setCellStatus(tIndexPath, status: !multiAction)
thisSelected.remove(tIndexPath)
hasNew = true
}
// pan new
if tIndexPath.row >= startIndexPath.row && tIndexPath.row <= curIndexPath.row {
if cell.isSelected != multiAction && !thisSelected.contains(tIndexPath){
setCellStatus(tIndexPath, status: multiAction)
thisSelected.insert(tIndexPath)
hasNew = true
}
}
}
}
}
// up
if curIndexPath.row <= startIndexPath.row{
for cell in mainCV.visibleCells.sorted(by: {
mainCV.indexPath(for: $0)?.row ?? 1 > mainCV.indexPath(for: $1)?.row ?? 0
}){
if let tIndexPath = mainCV.indexPath(for: cell){
// pan back reset to origin
if tIndexPath.row < curIndexPath.row && thisSelected.contains(tIndexPath){
setCellStatus(tIndexPath, status: !multiAction)
thisSelected.remove(tIndexPath)
hasNew = true
}
// pan new
if tIndexPath.row <= startIndexPath.row && tIndexPath.row >= curIndexPath.row{
if cell.isSelected != multiAction && !thisSelected.contains(tIndexPath){
setCellStatus(tIndexPath, status: multiAction)
thisSelected.insert(tIndexPath)
hasNew = true
}
}
}
}
}
// notify delegate if selected cell has change
if hasNew && (timer != nil || cvSelCount < maxPick){
var selAssets: [PHAsset] = []
if let items = mainCV.indexPathsForSelectedItems{
for i in items.sorted(by: {$0.row < $1.row}){
selAssets.append(assetResult[i.row])
}
}
imagePickerDelegate?.flImagePicker(imagePicker, multiAssetsChanged: selAssets, isSelected: multiAction)
}
}
}
@objc func cvTap(_ gesture: UITapGestureRecognizer){
if let curIndexPath = mainCV.indexPathForItem(at: gesture.location(in: mainCV)) {
if let cell = mainCV.cellForItem(at: curIndexPath){
if !(cvSelCount >= maxPick && !cell.isSelected){
setCellStatus(curIndexPath, status: !cell.isSelected)
if let data = (cell as! MainFLImagePickerCell).imgAsset{
imagePickerDelegate?.flImagePicker(imagePicker, singleAssetChanged: data, isSelected: cell.isSelected)
}
generator.impactOccurred()
}
}
}
}
@objc func cvLongPress(_ gesture: UILongPressGestureRecognizer){
// TODO: photo Preview
print("\(#function)")
}
@objc func panWhenScroll(pan: UIPanGestureRecognizer){
let overPick = cvSelCount >= maxPick && multiAction
panY = pan.location(in: view).y
if timer == nil{
if !overPick{
autoRoll()
}
}else{
if overPick{
notificationFeedbackGenerator.notificationOccurred(.warning)
autoRoll(isStop: true)
imagePickerDelegate?.flImagePicker(imagePicker, reachMaxSelected: getSelectedAssets())
}else if pan.state == .ended{
autoRoll(isStop: true)
}
}
}
/* collection delegate*/
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
assetResult.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let asset = assetResult[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FLImgCell", for: indexPath) as! MainFLImagePickerCell
// set default style
setCellStyle(cell, style: imagePickerStyle)
// set data
cell.imgAsset = asset
cell.isSelected = mainCV.indexPathsForSelectedItems?.contains(indexPath) ?? false
return cell
}
}
| 38.820128 | 166 | 0.569088 |
d5f74659cb661bba399c46d40477679e311a74be | 2,259 | import Foundation
import MungoHealer
import Toml
struct TransformOptions {
let codePaths: [String]
let localizablePaths: [String]
let transformer: Transformer
let supportedLanguageEnumPath: String
let typeName: String
let translateMethodName: String
let customLocalizableName: String?
}
extension TransformOptions: TomlCodable {
static func make(toml: Toml) throws -> TransformOptions {
let update: String = "update"
let transform: String = "transform"
guard let transformer = Transformer(rawValue: toml.string(update, transform, "transformer") ?? Transformer.foundation.rawValue) else {
throw MungoError(
source: .invalidUserInput,
message: "Unknown `transformer` provided in [update.code.transform]. Supported: \(Transformer.allCases)"
)
}
return TransformOptions(
codePaths: toml.filePaths(update, transform, singularKey: "codePath", pluralKey: "codePaths"),
localizablePaths: toml.filePaths(update, transform, singularKey: "localizablePath", pluralKey: "localizablePaths"),
transformer: transformer,
supportedLanguageEnumPath: toml.string(update, transform, "supportedLanguageEnumPath") ?? ".",
typeName: toml.string(update, transform, "typeName") ?? "BartyCrouch",
translateMethodName: toml.string(update, transform, "translateMethodName") ?? "translate",
customLocalizableName: toml.string(update, transform, "customLocalizableName")
)
}
func tomlContents() -> String {
var lines: [String] = ["[update.transform]"]
lines.append("codePaths = \(codePaths)")
lines.append("localizablePaths = \(localizablePaths)")
lines.append("transformer = \"\(transformer.rawValue)\"")
lines.append("supportedLanguageEnumPath = \"\(supportedLanguageEnumPath)\"")
lines.append("typeName = \"\(typeName)\"")
lines.append("translateMethodName = \"\(translateMethodName)\"")
if let customLocalizableName = customLocalizableName {
lines.append("customLocalizableName = \"\(customLocalizableName)\"")
}
return lines.joined(separator: "\n")
}
}
| 41.072727 | 142 | 0.665339 |
f5907d313cfac8b71955dae0b1ea5ab10f56da0e | 3,434 | //
// PartialSheetWrapper.swift
// SeatingSwfitUI
//
// Created by Simon Bachmann on 13.12.20.
//
import SwiftUI
struct CheckoutView: View {
@EnvironmentObject var config: SeatingChartConfig
@State var txt = ""
var body: some View {
VStack {
Capsule()
.frame(width: 50, height: 5)
.padding(.top)
HStack {
Text("Selected: \(config.selectedSeats.count)")
.font(.headline)
.foregroundColor(Color("systemBlack"))
Spacer()
Text("Total: \(config.price(amount: config.totalPrice))")
.font(.headline)
.foregroundColor(Color(UIColor.systemGray6))
.padding()
.background(Color("systemBlack"))
.cornerRadius(15)
}
.padding(.vertical, 10)
.cornerRadius(15)
.padding(.horizontal)
ScrollView(.vertical, showsIndicators: false) {
LazyVStack(alignment: .leading, spacing: 15) {
ForEach(config.selectedSeats, id: \.id) { seat in
VStack {
HStack {
SeatView(selected: false, color: seat.color, fill: true)
.frame(width: 20, height: 20)
Text("\(config.coordinate(id: seat.id).col)\(config.coordinate(id: seat.id).row) \(config.seatDetails[seat.char]?.category ?? "")")
Spacer()
if seat.price != 0 {
Text("\(String(format: "%.2f", seat.price)) $")
}
Button(action: {
withAnimation {
config.toggle(id: seat.id)
}
}, label: {
Image(systemName: "xmark.circle")
})
}
Divider()
.padding(.top, 10)
}
}
}
}
.padding()
.padding(.top)
HStack {
Spacer()
Button("Checkout") {
print("User wants to checkout following tickets (\(config.price(amount: config.totalPrice))): ")
for ticket in config.selectedSeats {
let coordinates = config.coordinate(id: ticket.id)
print("\(coordinates.col)\(coordinates.row)")
}
}
.font(.headline)
.foregroundColor(Color(UIColor.systemGray6))
Spacer()
}
.padding()
.background(Color.accentColor)
.cornerRadius(15)
.padding()
.padding(.bottom, 30)
}
.background(Color("systemWhite"))
.cornerRadius(15)
.shadow(color: Color(.black).opacity(0.3), radius: 10.0)
}
}
| 36.531915 | 163 | 0.387595 |
5617680aa5e225953a3c2acdd90b0a7ab454b25f | 905 | import Foundation
import Combine
public protocol RadioGateway {
func getCurrentTrack() -> AnyPublisher<QueuedTrack,RadioError>
func getCurrentStatus() -> AnyPublisher<RadioStatus,RadioError>
func getSongQueue() -> AnyPublisher<[QueuedTrack],RadioError>
func getLastPlayed() -> AnyPublisher<[QueuedTrack],RadioError>
func getCurrentDJ() -> AnyPublisher<RadioDJ,RadioError>
func searchFor(term: String) -> AnyPublisher<[SearchedTrack], RadioError>
func request(songId: Int) -> AnyPublisher<Bool, RadioError>
func updateNow()
func getTrackWith(identifier: String) -> QueuedTrack?
func getFavorites(for username: String) -> AnyPublisher<[FavoriteTrack], RadioError>
func getNews() -> AnyPublisher<[NewsEntry], RadioError>
func canRequestSong() -> AnyPublisher<Bool, RadioError>
}
public enum RadioError: Error {
case apiContentMismatch
case unknown
}
| 39.347826 | 88 | 0.746961 |
7aae7f5d06028f4fa0f77a3903e4b0cdbafd1f03 | 5,376 | import Foundation
/// Represents the humidity ratio (or mixing ratio) of a given moist air sample.
///
/// Defined as the ratio of the mass of water vapor to the mass of dry air in the sample and is often represented
/// by the symbol `W` in the ASHRAE Fundamentals (2017).
///
/// This value can not be negative, so it will be set to ``PsychrometricEnvironment.minimumHumidityRatio`` if
/// initialized with a value that's out of range. For methods that use a humidity ratio they should check that the humidity ratio
/// is valid by calling ``HumidityRatio.ensureHumidityRatio(_:)``.
///
public struct HumidityRatio: Equatable {
/// Constant for the mole weight of water.
public static let moleWeightWater = 18.015268
/// Constant for the mole weight of air.
public static let moleWeightAir = 28.966
/// Constant for the ratio of the mole weight of water over the mole weight of air.
public static let moleWeightRatio = (Self.moleWeightWater / Self.moleWeightAir)
public static func ensureHumidityRatio(_ ratio: HumidityRatio) -> HumidityRatio {
guard ratio.rawValue > PsychrometricEnvironment.shared.minimumHumidityRatio else {
return .init(PsychrometricEnvironment.shared.minimumHumidityRatio)
}
return ratio
}
/// The raw humidity ratio.
public var rawValue: Double
/// Create a new ``HumidityRatio`` with the given raw value.
///
/// - Parameters:
/// - value: The raw humidity ratio value.
public init(_ value: Double) {
self.rawValue = max(value, PsychrometricEnvironment.shared.minimumHumidityRatio)
}
/// The humidity ratio of air for the given mass of water and mass of dry air.
///
/// - Parameters:
/// - waterMass: The mass of the water in the air.
/// - dryAirMass: The mass of the dry air.
public init(
water waterMass: Double,
dryAir dryAirMass: Double
) {
self.init(Self.moleWeightRatio * (waterMass / dryAirMass))
}
internal init(
totalPressure: Pressure,
partialPressure: Pressure,
units: PsychrometricEnvironment.Units? = nil
) {
let units = units ?? PsychrometricEnvironment.shared.units
let partialPressure =
units.isImperial ? partialPressure.psi : partialPressure.pascals
let totalPressure = units.isImperial ? totalPressure.psi : totalPressure.pascals
self.init(
Self.moleWeightRatio * partialPressure
/ (totalPressure - partialPressure)
)
}
/// The humidity ratio of the air for the given total pressure and vapor pressure.
///
/// - Parameters:
/// - totalPressure: The total pressure of the air.
/// - vaporPressure: The partial pressure of the air.
public init(
totalPressure: Pressure,
vaporPressure: VaporPressure,
units: PsychrometricEnvironment.Units? = nil
) {
self.init(
totalPressure: totalPressure,
partialPressure: vaporPressure.pressure,
units: units
)
}
/// The humidity ratio of the air for the given total pressure and saturation pressure.
///
/// - Parameters:
/// - totalPressure: The total pressure of the air.
/// - saturationPressure: The saturation of the air.
public init(
totalPressure: Pressure,
saturationPressure: SaturationPressure,
units: PsychrometricEnvironment.Units? = nil
) {
self.init(
totalPressure: totalPressure,
partialPressure: saturationPressure.pressure,
units: units
)
}
/// The humidity ratio of the air for the given dry bulb temperature and total pressure.
///
/// - Parameters:
/// - temperature: The dry bulb temperature of the air.
/// - totalPressure: The total pressure of the air.
public init(
dryBulb temperature: Temperature,
pressure totalPressure: Pressure,
units: PsychrometricEnvironment.Units? = nil
) {
self.init(
totalPressure: totalPressure,
saturationPressure: .init(at: temperature, units: units),
units: units
)
}
/// The humidity ratio of the air for the given temperature, humidity, and pressure.
///
/// - Parameters:
/// - temperature: The temperature of the air.
/// - humidity: The humidity of the air.
/// - totalPressure: The pressure of the air.
public init(
dryBulb temperature: Temperature,
humidity: RelativeHumidity,
pressure totalPressure: Pressure,
units: PsychrometricEnvironment.Units? = nil
) {
self.init(
totalPressure: totalPressure,
partialPressure: VaporPressure(
dryBulb: temperature,
humidity: humidity,
units: units
).pressure,
units: units
)
}
/// The humidity ratio of the air for the given temperature, humidity, and altitude.
///
/// - Parameters:
/// - temperature: The temperature of the air.
/// - humidity: The humidity of the air.
/// - altitude: The altitude of the air.
public init(
dryBulb temperature: Temperature,
humidity: RelativeHumidity,
altitude: Length,
units: PsychrometricEnvironment.Units? = nil
) {
self.init(
dryBulb: temperature,
humidity: humidity,
pressure: .init(altitude: altitude),
units: units
)
}
}
extension HumidityRatio: RawNumericType {
public typealias IntegerLiteralType = Double.IntegerLiteralType
public typealias FloatLiteralType = Double.FloatLiteralType
public typealias Magnitude = Double.Magnitude
}
| 31.810651 | 130 | 0.691592 |
f9cff2d84912688c56b83116edc9a7c8689c2792 | 2,351 | //
// SceneDelegate.swift
// GHImageSizeDetector
//
// Created by Run Liao on 2020/7/2.
// Copyright © 2020 Run Liao. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.537037 | 147 | 0.713739 |
75ce09846990abd244de7a89780f696945e2e5b3 | 562 | //
// EventDetectorMock.swift
// AppliverySDK
//
// Created by Alejandro Jiménez on 23/2/16.
// Copyright © 2016 Applivery S.L. All rights reserved.
//
import Foundation
@testable import Applivery
class EventDetectorMock: EventDetector {
var spyListenEventCalled = false
var spyEndListeningCalled = false
var spyOnDetectionClosure: (() -> Void)!
func listenEvent(_ onDetection: @escaping () -> Void) {
self.spyListenEventCalled = true
self.spyOnDetectionClosure = onDetection
}
func endListening() {
self.spyEndListeningCalled = true
}
}
| 19.37931 | 56 | 0.736655 |
ef0f4f2f693ba84b6ef18dd7be81fc5c1a1d641e | 1,570 | //
// Copyright (c) 2020 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import QuartzCore
public extension CACornerMask {
static var topCorners: Self {
[.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
static var bottomCorners: Self {
[.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
}
static var allCorners: Self {
[
.layerMinXMinYCorner,
.layerMaxXMinYCorner,
.layerMinXMaxYCorner,
.layerMaxXMaxYCorner
]
}
}
| 36.511628 | 81 | 0.713376 |
d644e0920349a8bdac615b635c538b61f5716709 | 4,331 | //
// SpaceXService.swift
// SpaceX
//
// Created by Bruno Guedes on 19/10/19.
// Copyright © 2019 Bruno Guedes. All rights reserved.
//
import Foundation
import RxSwift
protocol SpaceXServiceProtocol {
var isLoading: Observable<Bool> { get }
func getLaunches() -> Observable<Launches>
func getLaunchDetails(for flightNumber: Int) -> Observable<LaunchDetails>
func getRocketDetails(for rocketId: String) -> Observable<RocketDetails>
}
class SpaceXService: SpaceXServiceProtocol {
var isLoading: Observable<Bool> {
return isLoadingSubject.asObservable().observeOn(MainScheduler.instance)
}
private let baseService: BaseServiceProtocol
private let baseURL = URL(string: "https://api.spacexdata.com/v3/launches")
private let isLoadingSubject = BehaviorSubject(value: false)
init(baseService: BaseServiceProtocol = BaseService()) {
self.baseService = baseService
}
func getLaunches() -> Observable<Launches> {
isLoadingSubject.onNext(true)
guard let url = URL(string: "launches", relativeTo: baseURL) else {
return Observable.create { [weak self] (observer) -> Disposable in
self?.isLoadingSubject.onNext(false)
observer.onError(BaseServiceError.invalidURL)
return Disposables.create()
}
}
let urlRequest = URLRequest(url: url)
return baseService.data(request: urlRequest).map { [weak self] (data) -> Launches in
self?.isLoadingSubject.onNext(false)
do {
let launches = try JSONDecoder().decode(Launches.self, from: data)
return launches
} catch {
throw BaseServiceError.invalidJSON
}
}.observeOn(MainScheduler.instance)
}
func getLaunchDetails(for flightNumber: Int) -> Observable<LaunchDetails> {
isLoadingSubject.onNext(true)
guard let url = URL(string: "launches/\(flightNumber)", relativeTo: baseURL) else {
return Observable.create { [weak self] (observer) -> Disposable in
self?.isLoadingSubject.onNext(false)
observer.onError(BaseServiceError.invalidURL)
return Disposables.create()
}
}
let urlRequest = URLRequest(url: url)
return baseService.data(request: urlRequest).map { [weak self] (data) -> LaunchDetails in
self?.isLoadingSubject.onNext(false)
do {
let launchDetails = try JSONDecoder().decode(LaunchDetails.self, from: data)
return launchDetails
} catch {
throw BaseServiceError.invalidJSON
}
}.observeOn(MainScheduler.instance)
}
func getRocketDetails(for rocketId: String) -> Observable<RocketDetails> {
isLoadingSubject.onNext(true)
guard let url = URL(string: "rockets/\(rocketId)", relativeTo: baseURL) else {
return Observable.create { [weak self] (observer) -> Disposable in
self?.isLoadingSubject.onNext(false)
observer.onError(BaseServiceError.invalidURL)
return Disposables.create()
}
}
let urlRequest = URLRequest(url: url)
return baseService.data(request: urlRequest).map { [weak self] (data) -> RocketDetails in
self?.isLoadingSubject.onNext(false)
do {
let rocketDetails = try JSONDecoder().decode(RocketDetails.self, from: data)
return rocketDetails
} catch {
throw BaseServiceError.invalidJSON
}
}.observeOn(MainScheduler.instance)
}
func getLaunchAndRocketDetails(for flightNumber: Int) -> Observable<(LaunchDetails, RocketDetails)> {
return getLaunchDetails(for: flightNumber).flatMap { [weak self] (launchDetails) -> Observable<(LaunchDetails, RocketDetails)> in
guard let this = self else {
fatalError()
}
return this.getRocketDetails(for: launchDetails.rocketId)
.map { (rocketDetails) -> (LaunchDetails, RocketDetails) in
return (launchDetails, rocketDetails)
}
}.observeOn(MainScheduler.instance)
}
}
| 40.101852 | 137 | 0.622951 |
235d8205d5bd0be5ab7dc39ad1d0e7d9f155867d | 20,700 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// Source file reorder_collection.proto
import Foundation
public extension Services.Post.Actions{ public struct ReorderCollection { }}
public func == (lhs: Services.Post.Actions.ReorderCollection.RequestV1, rhs: Services.Post.Actions.ReorderCollection.RequestV1) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasCollectionId == rhs.hasCollectionId) && (!lhs.hasCollectionId || lhs.collectionId == rhs.collectionId)
fieldCheck = fieldCheck && (lhs.diffs == rhs.diffs)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public func == (lhs: Services.Post.Actions.ReorderCollection.ResponseV1, rhs: Services.Post.Actions.ReorderCollection.ResponseV1) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public extension Services.Post.Actions.ReorderCollection {
public struct ReorderCollectionRoot {
public static var sharedInstance : ReorderCollectionRoot {
struct Static {
static let instance : ReorderCollectionRoot = ReorderCollectionRoot()
}
return Static.instance
}
public var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(extensionRegistry)
Services.Post.Containers.ContainersRoot.sharedInstance.registerAllExtensions(extensionRegistry)
}
public func registerAllExtensions(registry:ExtensionRegistry) {
}
}
final public class RequestV1 : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var hasCollectionId:Bool = false
public private(set) var collectionId:String = ""
public private(set) var diffs:Array<Services.Post.Containers.PositionDiffV1> = Array<Services.Post.Containers.PositionDiffV1>()
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasCollectionId {
try output.writeString(1, value:collectionId)
}
for oneElementdiffs in diffs {
try output.writeMessage(2, value:oneElementdiffs)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasCollectionId {
serialize_size += collectionId.computeStringSize(1)
}
for oneElementdiffs in diffs {
serialize_size += oneElementdiffs.computeMessageSize(2)
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.Post.Actions.ReorderCollection.RequestV1> {
var mergedArray = Array<Services.Post.Actions.ReorderCollection.RequestV1>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.ReorderCollection.RequestV1? {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Services.Post.Actions.ReorderCollection.RequestV1 {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeFromData(data, extensionRegistry:Services.Post.Actions.ReorderCollection.ReorderCollectionRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.RequestV1 {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.ReorderCollection.RequestV1 {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.RequestV1 {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.ReorderCollection.RequestV1 {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.RequestV1 {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
return Services.Post.Actions.ReorderCollection.RequestV1.classBuilder() as! Services.Post.Actions.ReorderCollection.RequestV1.Builder
}
public func getBuilder() -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
return classBuilder() as! Services.Post.Actions.ReorderCollection.RequestV1.Builder
}
public override class func classBuilder() -> MessageBuilder {
return Services.Post.Actions.ReorderCollection.RequestV1.Builder()
}
public override func classBuilder() -> MessageBuilder {
return Services.Post.Actions.ReorderCollection.RequestV1.Builder()
}
public func toBuilder() throws -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
return try Services.Post.Actions.ReorderCollection.RequestV1.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Services.Post.Actions.ReorderCollection.RequestV1) throws -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
return try Services.Post.Actions.ReorderCollection.RequestV1.Builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) throws {
if hasCollectionId {
output += "\(indent) collectionId: \(collectionId) \n"
}
var diffsElementIndex:Int = 0
for oneElementdiffs in diffs {
output += "\(indent) diffs[\(diffsElementIndex)] {\n"
try oneElementdiffs.writeDescriptionTo(&output, indent:"\(indent) ")
output += "\(indent)}\n"
diffsElementIndex++
}
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasCollectionId {
hashCode = (hashCode &* 31) &+ collectionId.hashValue
}
for oneElementdiffs in diffs {
hashCode = (hashCode &* 31) &+ oneElementdiffs.hashValue
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Services.Post.Actions.ReorderCollection.RequestV1"
}
override public func className() -> String {
return "Services.Post.Actions.ReorderCollection.RequestV1"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Services.Post.Actions.ReorderCollection.RequestV1.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Services.Post.Actions.ReorderCollection.RequestV1 = Services.Post.Actions.ReorderCollection.RequestV1()
public func getMessage() -> Services.Post.Actions.ReorderCollection.RequestV1 {
return builderResult
}
required override public init () {
super.init()
}
public var hasCollectionId:Bool {
get {
return builderResult.hasCollectionId
}
}
public var collectionId:String {
get {
return builderResult.collectionId
}
set (value) {
builderResult.hasCollectionId = true
builderResult.collectionId = value
}
}
public func setCollectionId(value:String) -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
self.collectionId = value
return self
}
public func clearCollectionId() -> Services.Post.Actions.ReorderCollection.RequestV1.Builder{
builderResult.hasCollectionId = false
builderResult.collectionId = ""
return self
}
public var diffs:Array<Services.Post.Containers.PositionDiffV1> {
get {
return builderResult.diffs
}
set (value) {
builderResult.diffs = value
}
}
public func setDiffs(value:Array<Services.Post.Containers.PositionDiffV1>) -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
self.diffs = value
return self
}
public func clearDiffs() -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
builderResult.diffs.removeAll(keepCapacity: false)
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
builderResult = Services.Post.Actions.ReorderCollection.RequestV1()
return self
}
public override func clone() throws -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
return try Services.Post.Actions.ReorderCollection.RequestV1.builderWithPrototype(builderResult)
}
public override func build() throws -> Services.Post.Actions.ReorderCollection.RequestV1 {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Services.Post.Actions.ReorderCollection.RequestV1 {
let returnMe:Services.Post.Actions.ReorderCollection.RequestV1 = builderResult
return returnMe
}
public func mergeFrom(other:Services.Post.Actions.ReorderCollection.RequestV1) throws -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
if other == Services.Post.Actions.ReorderCollection.RequestV1() {
return self
}
if other.hasCollectionId {
collectionId = other.collectionId
}
if !other.diffs.isEmpty {
builderResult.diffs += other.diffs
}
try mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.RequestV1.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10 :
collectionId = try input.readString()
case 18 :
let subBuilder = Services.Post.Containers.PositionDiffV1.Builder()
try input.readMessage(subBuilder,extensionRegistry:extensionRegistry)
diffs += [subBuilder.buildPartial()]
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
final public class ResponseV1 : GeneratedMessage, GeneratedMessageProtocol {
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.Post.Actions.ReorderCollection.ResponseV1> {
var mergedArray = Array<Services.Post.Actions.ReorderCollection.ResponseV1>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.ReorderCollection.ResponseV1? {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Services.Post.Actions.ReorderCollection.ResponseV1 {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeFromData(data, extensionRegistry:Services.Post.Actions.ReorderCollection.ReorderCollectionRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.ResponseV1 {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.ReorderCollection.ResponseV1 {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.ResponseV1 {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.ReorderCollection.ResponseV1 {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.ResponseV1 {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
return Services.Post.Actions.ReorderCollection.ResponseV1.classBuilder() as! Services.Post.Actions.ReorderCollection.ResponseV1.Builder
}
public func getBuilder() -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
return classBuilder() as! Services.Post.Actions.ReorderCollection.ResponseV1.Builder
}
public override class func classBuilder() -> MessageBuilder {
return Services.Post.Actions.ReorderCollection.ResponseV1.Builder()
}
public override func classBuilder() -> MessageBuilder {
return Services.Post.Actions.ReorderCollection.ResponseV1.Builder()
}
public func toBuilder() throws -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
return try Services.Post.Actions.ReorderCollection.ResponseV1.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Services.Post.Actions.ReorderCollection.ResponseV1) throws -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
return try Services.Post.Actions.ReorderCollection.ResponseV1.Builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) throws {
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Services.Post.Actions.ReorderCollection.ResponseV1"
}
override public func className() -> String {
return "Services.Post.Actions.ReorderCollection.ResponseV1"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Services.Post.Actions.ReorderCollection.ResponseV1.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Services.Post.Actions.ReorderCollection.ResponseV1 = Services.Post.Actions.ReorderCollection.ResponseV1()
public func getMessage() -> Services.Post.Actions.ReorderCollection.ResponseV1 {
return builderResult
}
required override public init () {
super.init()
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
builderResult = Services.Post.Actions.ReorderCollection.ResponseV1()
return self
}
public override func clone() throws -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
return try Services.Post.Actions.ReorderCollection.ResponseV1.builderWithPrototype(builderResult)
}
public override func build() throws -> Services.Post.Actions.ReorderCollection.ResponseV1 {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Services.Post.Actions.ReorderCollection.ResponseV1 {
let returnMe:Services.Post.Actions.ReorderCollection.ResponseV1 = builderResult
return returnMe
}
public func mergeFrom(other:Services.Post.Actions.ReorderCollection.ResponseV1) throws -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
if other == Services.Post.Actions.ReorderCollection.ResponseV1() {
return self
}
try mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.ReorderCollection.ResponseV1.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
}
// @@protoc_insertion_point(global_scope)
| 47.15262 | 219 | 0.717101 |
d76c7c2f115fca6e456254958e835d9b702ce632 | 4,021 | //
// AppDelegate.swift
// Twitter
//
// Created by Mike Lam on 10/30/16.
// Copyright © 2016 Matchbox. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let storyboard = UIStoryboard(name:"Main",bundle:nil)
let hamburgerViewController = storyboard.instantiateViewController(withIdentifier: "HamburgerViewController") as! HamburgerViewController
if User.currentUser != nil {
// Segue to tweets screen
print("There is a current user")
//let vc = storyboard.instantiateViewController(withIdentifier: "TweetsNavigationController")
window?.rootViewController = hamburgerViewController
}
NotificationCenter.default.addObserver(forName: User.userDidLogoutNotification, object: nil, queue: OperationQueue.main) { (NSNotification) -> Void in
print("User logged out event fired")
let storyboard = UIStoryboard(name:"Main",bundle:nil)
let vc = storyboard.instantiateInitialViewController()
self.window?.rootViewController = vc
}
// reference to hamburgerViewController
//let hamburgerViewController = vc.topViewController as! HamburgerViewController
// Create menuViewController
let listMenuViewController = storyboard.instantiateViewController(withIdentifier: "ListMenuViewController") as! ListMenuViewController
listMenuViewController.hamburgerViewController = hamburgerViewController
hamburgerViewController.listMenuViewController = listMenuViewController
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:.
}
// When app is opened via a URL
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print(url.description)
let twitterClient = TwitterClient.sharedInstance
twitterClient?.handleOpenUrl(url: url)
return true
}
}
| 45.693182 | 285 | 0.715494 |
e4eb6d5055689e1b978397b8d58fca078c428572 | 13,462 | //
// ExperienceViewController.swift
// Memorabilia
//
// Created by André Mello Alves on 15/03/20.
// Copyright © 2020 André Mello Alves. All rights reserved.
//
import UIKit
import ARKit
import SceneKit
import MediaPlayer
import MobileCoreServices
protocol ExperienceViewInput: class {
// Update
func loadSnapshot(with data: Data)
func loadWorld(with data: Data)
func reloadReminder(with identifier: String)
}
class ExperienceViewController: UIViewController {
// MARK: Clean Properties
var interactor: ExperienceInteractorInput?
var router: (ExperienceRouterInput & ExperienceRouterOutput)?
// MARK: View properties
let exitButton: CircleButton = {
let button = CircleButton()
button.setImage(UIImage(systemName: "xmark"), for: .normal)
button.addTarget(self, action: #selector(exitButtonAction), for: .primaryActionTriggered)
return button
}()
let infoView: InfoView = {
let view = InfoView()
let state = ARCamera.TrackingState.limited(.initializing)
view.update(title: state.description, info: state.feedback)
return view
}()
let infoButton: CircleButton = {
let button = CircleButton()
button.setImage(UIImage(systemName: "info"), for: .normal)
button.addTarget(self, action: #selector(infoButtonAction), for: .primaryActionTriggered)
return button
}()
let restartButton: CircleButton = {
let button = CircleButton()
button.setImage(UIImage(systemName: "arrow.counterclockwise"), for: .normal)
button.addTarget(self, action: #selector(restartButtonAction), for: .primaryActionTriggered)
return button
}()
lazy var snapshotView: SnapshotView = {
let view = SnapshotView(frame: self.view.frame)
return view
}()
let actionView: ActionView = {
let view = ActionView()
view.alpha = 0
return view
}()
// MARK: Control properties
var selectedInfo: InformationType = .experienceLocation
var selectedReminder: ReminderAnchor?
var isLimited: Bool = true
// MARK: AR properties
var world: ARWorldMap?
lazy var arView: ARSCNView = {
let view = ARSCNView(frame: self.view.frame)
view.delegate = self
view.session.delegate = self
view.autoenablesDefaultLighting = true
view.debugOptions = [.showFeaturePoints]
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
view.addGestureRecognizer(tap)
return view
}()
lazy var worldTrackingConfiguration: ARWorldTrackingConfiguration = {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .vertical
configuration.initialWorldMap = world
return configuration
}()
// MARK: Initializers
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
cleanSetup()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
cleanSetup()
setup()
}
// MARK: Setup
func setup() {
// Self
view.backgroundColor = .systemBackground
// AR view
view.addSubview(arView)
// Exit button
view.addSubview(exitButton)
// Info view
view.addSubview(infoView)
// Info button
view.addSubview(infoButton)
// Restart button
view.addSubview(restartButton)
// Snapshot view
view.addSubview(snapshotView)
// Action view
view.addSubview(actionView)
// Constraints
setupConstraints()
}
// MARK: Constraints
func setupConstraints() {
NSLayoutConstraint.activate([
// AR view
arView.topAnchor.constraint(equalTo: view.topAnchor),
arView.leftAnchor.constraint(equalTo: view.leftAnchor),
arView.rightAnchor.constraint(equalTo: view.rightAnchor),
arView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
// Exit button
exitButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
exitButton.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 16),
// Info view
infoView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
infoView.leftAnchor.constraint(equalTo: exitButton.rightAnchor, constant: 16),
infoView.rightAnchor.constraint(equalTo: infoButton.leftAnchor, constant: -16),
// Info button
infoButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
infoButton.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: -16),
// Restart button
restartButton.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 16),
restartButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16),
// Action view
actionView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
actionView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
])
}
// MARK: View life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
interactor?.readSnapshot()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// AR support
guard ARWorldTrackingConfiguration.isSupported else { routeBack(); return }
// Screen dimming
UIApplication.shared.isIdleTimerDisabled = true
// Start AR Session
requestStart()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Screen dimming
UIApplication.shared.isIdleTimerDisabled = false
// Pause AR Session
arView.session.pause()
}
// MARK: Control
func controlMediaPlayback(for anchor: ARAnchor?, play: Bool = true) {
guard let anchor = anchor,
let node = arView.node(for: anchor),
let reminder = interactor?.readReminder(with: anchor.identifier.uuidString) else { return }
if let video = reminder as? VideoReminder, let player = video.player {
if player.timeControlStatus == .playing || !play {
player.pause()
player.seek(to: .zero)
} else {
player.play()
}
} else if let audio = reminder as? AudioReminder, let player = audio.player {
if player.isPlaying || !play {
player.pause()
player.currentTime = .zero
animate(node, play: false)
} else {
player.play()
animate(node, play: true)
}
}
}
func updateState(isLimited: Bool) {
self.isLimited = isLimited
snapshotView.isHidden = !isLimited
if isLimited {
arView.debugOptions = [.showFeaturePoints]
} else {
arView.debugOptions = []
}
}
// MARK: Action
@objc func handleTap(_ sender: UITapGestureRecognizer) {
guard !isLimited else { return }
let point = sender.location(in: arView)
if let node = arView.hitTest(point).first?.node, let anchor = arView.anchor(for: node) as? ReminderAnchor {
guard selectedReminder?.identifier != anchor.identifier else { return }
controlMediaPlayback(for: selectedReminder, play: false)
controlMediaPlayback(for: anchor)
selectedReminder = anchor
} else {
controlMediaPlayback(for: selectedReminder, play: false)
selectedReminder = nil
}
}
@objc func infoButtonAction() {
controlMediaPlayback(for: selectedReminder, play: false)
routeToInformation()
}
@objc func exitButtonAction() {
routeBack()
}
@objc func restartButtonAction() {
controlMediaPlayback(for: selectedReminder, play: false)
selectedReminder = nil
startSession(shouldRestart: true)
}
// MARK: Animation
func showAction(with symbol: String, and text: String, for duration: TimeInterval) {
actionView.update(symbol: symbol, text: text)
let fadeIn = { [unowned self] in self.actionView.alpha = 1 }
let fadeOut = { [unowned self] in self.actionView.alpha = 0 }
let fadeInAnimator = UIViewPropertyAnimator(duration: duration / 4, curve: .easeInOut, animations: fadeIn)
let fadeOutAnimator = UIViewPropertyAnimator(duration: duration / 4, curve: .easeInOut, animations: fadeOut)
fadeInAnimator.startAnimation()
fadeInAnimator.addCompletion { _ in fadeOutAnimator.startAnimation(afterDelay: duration / 2) }
}
func animate(_ node: SCNNode, play: Bool) {
if play {
let scaleUp = SCNAction.scale(to: 1.5, duration: 0.5)
let scaleDown = SCNAction.scale(to: 1, duration: 0.5)
let sequence = SCNAction.sequence([scaleUp, scaleDown])
let forever = SCNAction.repeatForever(sequence)
node.runAction(forever)
} else {
let scaleDown = SCNAction.scale(to: 1, duration: 0.5)
node.runAction(scaleDown) {
node.removeAllActions()
}
}
}
// MARK: Navigation
func routeBack() {
router?.routeBack()
}
func routeToInformation() {
router?.routeToInformation(type: selectedInfo)
}
// MARK: Request
func requestStart() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
interactor?.readWorld()
case .denied:
showAction(with: "exclamationmark.triangle.fill", and: "Sem acesso à camera", for: 2)
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { granted in
if granted {
DispatchQueue.main.async {
self.interactor?.readWorld()
}
} else {
DispatchQueue.main.async {
self.showAction(with: "exclamationmark.triangle.fill", and: "Sem acesso à camera", for: 2)
}
}
}
default:
routeBack()
}
}
// MARK: AR
func startSession(shouldRestart: Bool = false) {
var options: ARSession.RunOptions = []
if shouldRestart {
options.insert([.resetTracking, .removeExistingAnchors])
}
arView.session.run(worldTrackingConfiguration, options: options)
}
}
extension ExperienceViewController {
// MARK: Clean setup
private func cleanSetup() {
let viewController = self
let interactor = ExperienceInteractor()
let presenter = ExperiencePresenter()
let router = ExperienceRouter()
viewController.interactor = interactor
viewController.router = router
interactor.presenter = presenter
presenter.viewController = viewController
router.viewController = viewController
router.interactor = interactor
}
}
extension ExperienceViewController: ExperienceViewInput {
// Update
func loadSnapshot(with data: Data) {
snapshotView.image = UIImage(data: data)
}
func loadWorld(with data: Data) {
do {
guard let world = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self, from: data) else {
routeBack()
return
}
var anchors = world.anchors
anchors.removeAll(where: { $0 is SnapshotAnchor })
self.world = world
guard let reminderAnchors = anchors.filter({ $0.isMember(of: ReminderAnchor.self) }) as? [ReminderAnchor] else { return }
let reminders = reminderAnchors.map({ ExperienceEntity.Fetch(identifier: $0.identifier.uuidString, type: $0.type, name: $0.name)})
interactor?.create(reminders)
startSession(shouldRestart: true)
} catch let error {
print(error.localizedDescription)
routeBack()
}
}
func reloadReminder(with identifier: String) {
guard !isLimited, let anchor = world?.anchors.first(where: { $0.identifier.uuidString == identifier }) else { return }
arView.session.remove(anchor: anchor)
arView.session.add(anchor: anchor)
}
}
| 31.75 | 142 | 0.599762 |
f79acb81e307794a42d88e2c253b1af92f46b757 | 769 | //
// ImageLoader.swift
// SwiftUICombineCollection
//
//
import SwiftUI
import UIKit
import Combine
final class ImageLoaderCache {
@Environment(\.injected.loaders) var dataLoaders: DIContainer.Loaders
static let shared = ImageLoaderCache()
private var loaders: NSCache<NSString, BreedImageViewModel> = NSCache()
func loaderFor(url: URL) -> BreedImageViewModel {
let key = NSString(string: url.absoluteString)
if let loader = loaders.object(forKey: key) {
return loader
} else {
let loader = BreedImageViewModel(url: url,
loader: dataLoaders.imageDataLoader)
loaders.setObject(loader, forKey: key)
return loader
}
}
}
| 26.517241 | 81 | 0.628088 |
e5928b959258b404cfb520fe50178affc20bc702 | 39,270 | //
// ResourceCommandGenerator.swift
//
//
// Created by Thomas Roughton on 6/04/20.
//
import SubstrateUtilities
/// The value to wait for on the event associated with this RenderGraph context.
struct ContextWaitEvent {
var waitValue : UInt64 = 0
var afterStages : RenderStages = []
}
struct CompactedResourceCommand<T> : Comparable {
var command : T
var index : Int
var order : PerformOrder
public static func ==(lhs: CompactedResourceCommand<T>, rhs: CompactedResourceCommand<T>) -> Bool {
return lhs.index == rhs.index && lhs.order == rhs.order
}
public static func <(lhs: CompactedResourceCommand<T>, rhs: CompactedResourceCommand<T>) -> Bool {
if lhs.index < rhs.index { return true }
if lhs.index == rhs.index, lhs.order < rhs.order {
return true
}
return false
}
}
extension Range where Bound: AdditiveArithmetic {
func offset(by: Bound) -> Self {
return (self.lowerBound + by)..<(self.upperBound + by)
}
}
enum PreFrameCommands {
// These commands mutate the ResourceRegistry and should be executed before render pass execution:
case materialiseBuffer(Buffer)
case materialiseTexture(Texture)
case materialiseTextureView(Texture)
case materialiseArgumentBuffer(ArgumentBuffer)
case materialiseArgumentBufferArray(ArgumentBufferArray)
case disposeResource(Resource, afterStages: RenderStages)
case waitForHeapAliasingFences(resource: Resource, waitDependency: FenceDependency)
case waitForCommandBuffer(index: UInt64, queue: Queue)
case updateCommandBufferWaitIndex(Resource, accessType: ResourceAccessType)
var isMaterialiseNonArgumentBufferResource: Bool {
switch self {
case .materialiseBuffer, .materialiseTexture, .materialiseTextureView:
return true
default:
return false
}
}
func execute<Backend: SpecificRenderBackend, Dependency: Substrate.Dependency>(commandIndex: Int, context: RenderGraphContextImpl<Backend>, textureIsStored: (Texture) -> Bool, encoderDependencies: inout DependencyTable<Dependency?>, waitEventValues: inout QueueCommandIndices, signalEventValue: UInt64) {
let queue = context.renderGraphQueue
let queueIndex = Int(queue.index)
let resourceMap = context.resourceMap
let resourceRegistry = context.resourceRegistry // May be nil iff the render graph does not support transient resources.
switch self {
case .materialiseBuffer(let buffer):
// If the resource hasn't already been allocated and is transient, we should force it to be GPU private since the CPU is guaranteed not to use it.
_ = resourceRegistry!.allocateBufferIfNeeded(buffer, forceGPUPrivate: !buffer._usesPersistentRegistry && buffer._deferredSliceActions.isEmpty)
let waitEvent = buffer.flags.contains(.historyBuffer) ? resourceRegistry!.historyBufferResourceWaitEvents[Resource(buffer)] : resourceRegistry!.bufferWaitEvents[buffer]
waitEventValues[queueIndex] = max(waitEvent!.waitValue, waitEventValues[queueIndex])
buffer.applyDeferredSliceActions()
case .materialiseTexture(let texture):
// If the resource hasn't already been allocated and is transient, we should force it to be GPU private since the CPU is guaranteed not to use it.
_ = resourceRegistry!.allocateTextureIfNeeded(texture, forceGPUPrivate: !texture._usesPersistentRegistry, isStoredThisFrame: textureIsStored(texture))
if let textureWaitEvent = (texture.flags.contains(.historyBuffer) ? resourceRegistry!.historyBufferResourceWaitEvents[Resource(texture)] : resourceRegistry!.textureWaitEvents[texture]) {
waitEventValues[queueIndex] = max(textureWaitEvent.waitValue, waitEventValues[queueIndex])
} else {
precondition(texture.flags.contains(.windowHandle))
}
case .materialiseTextureView(let texture):
_ = resourceRegistry!.allocateTextureView(texture, resourceMap: resourceMap)
case .materialiseArgumentBuffer(let argumentBuffer):
let argBufferReference : Backend.ArgumentBufferReference
if argumentBuffer.flags.contains(.persistent) {
argBufferReference = resourceMap.persistentRegistry.allocateArgumentBufferIfNeeded(argumentBuffer)
} else {
argBufferReference = resourceRegistry!.allocateArgumentBufferIfNeeded(argumentBuffer)
waitEventValues[queueIndex] = max(resourceRegistry!.argumentBufferWaitEvents?[argumentBuffer]!.waitValue ?? 0, waitEventValues[queueIndex])
}
Backend.fillArgumentBuffer(argumentBuffer, storage: argBufferReference, firstUseCommandIndex: commandIndex, resourceMap: resourceMap)
case .materialiseArgumentBufferArray(let argumentBuffer):
let argBufferReference : Backend.ArgumentBufferArrayReference
if argumentBuffer.flags.contains(.persistent) {
argBufferReference = resourceMap.persistentRegistry.allocateArgumentBufferArrayIfNeeded(argumentBuffer)
} else {
argBufferReference = resourceRegistry!.allocateArgumentBufferArrayIfNeeded(argumentBuffer)
waitEventValues[queueIndex] = max(resourceRegistry!.argumentBufferArrayWaitEvents?[argumentBuffer]!.waitValue ?? 0, waitEventValues[queueIndex])
}
Backend.fillArgumentBufferArray(argumentBuffer, storage: argBufferReference, firstUseCommandIndex: commandIndex, resourceMap: resourceMap)
case .disposeResource(let resource, let afterStages):
let disposalWaitEvent = ContextWaitEvent(waitValue: signalEventValue, afterStages: afterStages)
if let buffer = Buffer(resource) {
resourceRegistry!.disposeBuffer(buffer, waitEvent: disposalWaitEvent)
} else if let texture = Texture(resource) {
resourceRegistry!.disposeTexture(texture, waitEvent: disposalWaitEvent)
} else if let argumentBuffer = ArgumentBuffer(resource) {
resourceRegistry!.disposeArgumentBuffer(argumentBuffer, waitEvent: disposalWaitEvent)
} else {
fatalError()
}
case .waitForCommandBuffer(let index, let waitQueue):
waitEventValues[Int(waitQueue.index)] = max(index, waitEventValues[Int(waitQueue.index)])
case .updateCommandBufferWaitIndex(let resource, let accessType):
resource[waitIndexFor: queue, accessType: accessType] = signalEventValue
case .waitForHeapAliasingFences(let resource, let waitDependency):
resourceRegistry!.withHeapAliasingFencesIfPresent(for: resource.handle, perform: { fenceDependencies in
for signalDependency in fenceDependencies {
let dependency = Dependency(signal: signalDependency, wait: waitDependency)
let newDependency = encoderDependencies.dependency(from: dependency.wait.encoderIndex, on: dependency.signal.encoderIndex)?.merged(with: dependency) ?? dependency
encoderDependencies.setDependency(from: dependency.wait.encoderIndex, on: dependency.signal.encoderIndex, to: newDependency)
}
})
}
}
}
struct BarrierScope: OptionSet {
let rawValue: Int
static let buffers: BarrierScope = BarrierScope(rawValue: 1 << 0)
static let textures: BarrierScope = BarrierScope(rawValue: 1 << 1)
static let renderTargets: BarrierScope = BarrierScope(rawValue: 1 << 2)
}
enum FrameResourceCommands {
// These commands need to be executed during render pass execution and do not modify the ResourceRegistry.
case useResource(Resource, usage: ResourceUsageType, stages: RenderStages, allowReordering: Bool) // Must happen before the FrameResourceCommand command index.
case memoryBarrier(Resource, afterUsage: ResourceUsageType, afterStages: RenderStages, beforeCommand: Int, beforeUsage: ResourceUsageType, beforeStages: RenderStages, activeRange: ActiveResourceRange) // beforeCommand is the command that this memory barrier must have been executed before, while the FrameResourceCommand's command index is the index that this must happen after.
}
struct PreFrameResourceCommand : Comparable {
var command : PreFrameCommands
var sortIndex : Int
public init(command: PreFrameCommands, index: Int, order: PerformOrder) {
self.command = command
var sortIndex = index << 2
if order == .after {
sortIndex |= 0b10
}
if !command.isMaterialiseNonArgumentBufferResource {
sortIndex |= 0b01 // Materialising argument buffers always needs to happen last, after materialising all resources within it.
}
self.sortIndex = sortIndex
}
public var index: Int {
return self.sortIndex >> 2
}
public static func ==(lhs: PreFrameResourceCommand, rhs: PreFrameResourceCommand) -> Bool {
return lhs.sortIndex == rhs.sortIndex
}
public static func <(lhs: PreFrameResourceCommand, rhs: PreFrameResourceCommand) -> Bool {
return lhs.sortIndex < rhs.sortIndex
}
}
struct FrameResourceCommand : Comparable {
var command : FrameResourceCommands
var index : Int
public static func ==(lhs: FrameResourceCommand, rhs: FrameResourceCommand) -> Bool {
return lhs.index == rhs.index
}
public static func <(lhs: FrameResourceCommand, rhs: FrameResourceCommand) -> Bool {
if lhs.index < rhs.index { return true }
return false
}
}
extension ChunkArray.RandomAccessView where Element == ResourceUsage {
func indexOfPreviousWrite(before index: Int, resource: Resource) -> Int? {
let usageActiveRange = index >= self.endIndex ? .fullResource : self[index].activeRange
for i in (0..<index).reversed() {
if self[i].isWrite, self[i].affectsGPUBarriers, self[i].activeRange.intersects(with: usageActiveRange, resource: resource) {
return i
}
}
return nil
}
func indexOfPreviousRead(before index: Int, resource: Resource) -> Int? {
let usageActiveRange = index >= self.endIndex ? .fullResource : self[index].activeRange
for i in (0..<index).reversed() {
if self[i].isRead, self[i].affectsGPUBarriers, self[i].activeRange.intersects(with: usageActiveRange, resource: resource) {
return i
}
}
return nil
}
}
final class ResourceCommandGenerator<Backend: SpecificRenderBackend> {
typealias Dependency = Backend.InterEncoderDependencyType
private var preFrameCommands = [PreFrameResourceCommand]()
var commands = [FrameResourceCommand]()
var commandEncoderDependencies = DependencyTable<Dependency?>(capacity: 1, defaultValue: nil)
static var resourceCommandGeneratorTag: TaggedHeap.Tag {
return UInt64(bitPattern: Int64("ResourceCommandGenerator".hashValue))
}
func processResourceResidency(resource: Resource, frameCommandInfo: FrameCommandInfo<Backend.RenderTargetDescriptor>) {
guard Backend.requiresResourceResidencyTracking else { return }
var resourceIsRenderTarget = false
// Track resource residency.
var previousEncoderIndex: Int = -1
var previousUsageType: ResourceUsageType = .unusedArgumentBuffer
var previousUsageStages: RenderStages = []
var pendingUsageType: ResourceUsageType = .unusedArgumentBuffer
var pendingUsageStages: RenderStages = []
var pendingUsageIndex: Int = .max
for usage in resource.usages
where usage.renderPassRecord.type != .external &&
usage.resource == resource // rather than a view of this resource.
// && usage.inArgumentBuffer
{
assert(usage.stages != .cpuBeforeRender) // CPU-only usages should have been filtered out by the RenderGraph
assert(usage.renderPassRecord.isActive) // Only usages for active render passes should be here.
let usageEncoderIndex = frameCommandInfo.encoderIndex(for: usage.renderPassRecord)
if usageEncoderIndex > previousEncoderIndex {
if pendingUsageIndex < .max {
self.commands.append(FrameResourceCommand(command: .useResource(resource, usage: pendingUsageType, stages: pendingUsageStages, allowReordering: !resourceIsRenderTarget), // Keep the useResource call as late as possible for render targets, and don't allow reordering within an encoder.
index: pendingUsageIndex))
}
pendingUsageType = .unusedArgumentBuffer
pendingUsageStages = []
pendingUsageIndex = .max
resourceIsRenderTarget = false
}
let isEmulatedInputAttachment = usage.type == .inputAttachmentRenderTarget && RenderBackend.requiresEmulatedInputAttachments
if usage.type.isRenderTarget {
resourceIsRenderTarget = true
if !isEmulatedInputAttachment {
continue
}
}
if isEmulatedInputAttachment ||
usage.type.isRenderTarget != previousUsageType.isRenderTarget ||
usage.stages != previousUsageStages {
self.commands.append(FrameResourceCommand(command: .useResource(resource, usage: usage.type, stages: usage.stages, allowReordering: !resourceIsRenderTarget && usageEncoderIndex != previousEncoderIndex), // Keep the useResource call as late as possible for render targets, and don't allow reordering within an encoder.
index: usage.commandRange.lowerBound))
} else {
if usage.isWrite || pendingUsageType.isWrite {
if usage.isRead || pendingUsageType.isRead {
pendingUsageType = .readWrite
} else {
pendingUsageType = .write
}
} else {
pendingUsageType = usage.type
}
pendingUsageStages.formUnion(usage.stages)
pendingUsageIndex = min(usage.commandRange.lowerBound, pendingUsageIndex)
}
previousUsageType = usage.type
previousEncoderIndex = usageEncoderIndex
previousUsageStages = usage.stages
}
if pendingUsageIndex < .max {
self.commands.append(FrameResourceCommand(command: .useResource(resource, usage: pendingUsageType, stages: pendingUsageStages, allowReordering: !resourceIsRenderTarget), // Keep the useResource call as late as possible for render targets, and don't allow reordering within an encoder.
index: pendingUsageIndex))
}
}
func processInputAttachmentUsage(_ usage: ResourceUsage, activeRange: ActiveResourceRange) {
guard RenderBackend.requiresEmulatedInputAttachments else { return }
// To simulate input attachments on desktop platforms, we need to insert a render target barrier between every draw.
let applicableRange = usage.commandRange
let resource = usage.resource
let commands = usage.renderPassRecord.commands!
let passCommandRange = usage.renderPassRecord.commandRange!
var previousCommandIndex = -1
let rangeInPass = applicableRange.offset(by: -passCommandRange.lowerBound)
for i in rangeInPass {
let command = commands[i]
if command.isDrawCommand {
let commandIndex = i + passCommandRange.lowerBound
if previousCommandIndex >= 0 {
self.commands.append(FrameResourceCommand(command: .memoryBarrier(Resource(resource), afterUsage: usage.type, afterStages: usage.stages, beforeCommand: commandIndex, beforeUsage: usage.type, beforeStages: usage.stages, activeRange: activeRange), index: previousCommandIndex))
// self.commands.append(FrameResourceCommand(command: .useResource(resource, usage: .read, stages: usage.stages, allowReordering: false), index: commandIndex))
}
previousCommandIndex = commandIndex
}
}
}
func generateCommands(passes: [RenderPassRecord], usedResources: Set<Resource>, transientRegistry: Backend.TransientResourceRegistry?, backend: Backend, frameCommandInfo: inout FrameCommandInfo<Backend.RenderTargetDescriptor>) {
if passes.isEmpty {
return
}
self.commandEncoderDependencies.resizeAndClear(capacity: frameCommandInfo.commandEncoders.count, clearValue: nil)
let allocator = AllocatorType.threadLocalTag(ThreadLocalTagAllocator(tag: Self.resourceCommandGeneratorTag))
defer { TaggedHeap.free(tag: Self.resourceCommandGeneratorTag) }
resourceLoop: for resource in usedResources {
if resource.usages.isEmpty { continue }
self.processResourceResidency(resource: resource, frameCommandInfo: frameCommandInfo)
let usagesArray = resource.usages.makeRandomAccessView(allocator: allocator)
let firstUsage = usagesArray.first!
if resource.baseResource == nil, Backend.TransientResourceRegistry.isAliasedHeapResource(resource: resource) {
let fenceDependency = FenceDependency(encoderIndex: frameCommandInfo.encoderIndex(for: firstUsage.renderPassRecord), index: firstUsage.commandRange.lowerBound, stages: firstUsage.stages)
self.preFrameCommands.append(PreFrameResourceCommand(command: .waitForHeapAliasingFences(resource: resource, waitDependency: fenceDependency), index: firstUsage.commandRange.lowerBound, order: .before))
}
var remainingSubresources = ActiveResourceRange.inactive
var remainingSubresourcesUsageIndex: Int = -1
var activeSubresources = ActiveResourceRange.fullResource
var usageIndex = usagesArray.startIndex
var skipUntilAfterInapplicableUsage = false // When processing subresources, we skip until we encounter a usage that is incompatible with our current subresources, since every usage up until that point will have already been processed.
while usageIndex < usagesArray.count {
defer {
usageIndex += 1
if usageIndex == usagesArray.count, !remainingSubresources.isEqual(to: .inactive, resource: resource) {
// Reset the tracked state to the remainingSubresources
activeSubresources = remainingSubresources
remainingSubresources = .inactive
usageIndex = remainingSubresourcesUsageIndex
skipUntilAfterInapplicableUsage = true
}
}
let usage = usagesArray[usageIndex]
if !usage.affectsGPUBarriers {
continue
}
// Check for subresource tracking
if resource.type == .texture { // We only track subresources for textures.
if usage.activeRange.isEqual(to: .fullResource, resource: resource) {
if !remainingSubresources.isEqual(to: .inactive, resource: resource) {
// Reset the tracked state to the remainingSubresources
activeSubresources = remainingSubresources
remainingSubresources = .inactive
usageIndex = remainingSubresourcesUsageIndex - 1 // since it will have 1 added to it in the defer statement
skipUntilAfterInapplicableUsage = true
continue
} else {
activeSubresources = .fullResource
}
} else {
let activeRangeIntersection = usage.activeRange.intersection(with: activeSubresources, resource: resource, allocator: allocator)
if activeRangeIntersection.isEqual(to: .inactive, resource: resource) {
skipUntilAfterInapplicableUsage = false
continue
} else if skipUntilAfterInapplicableUsage {
continue
} else if !activeRangeIntersection.isEqual(to: activeSubresources, resource: resource) {
if remainingSubresources.isEqual(to: .inactive, resource: resource) {
remainingSubresourcesUsageIndex = usageIndex
}
remainingSubresources.formUnion(with: activeSubresources.subtracting(range: activeRangeIntersection, resource: resource, allocator: allocator), resource: resource, allocator: allocator)
activeSubresources = activeRangeIntersection
}
}
}
if usage.type == .inputAttachmentRenderTarget {
processInputAttachmentUsage(usage, activeRange: activeSubresources)
}
let previousWriteIndex = usagesArray.indexOfPreviousWrite(before: usageIndex, resource: resource)
if usage.isWrite {
assert(!resource.flags.contains(.immutableOnceInitialised) || !resource.stateFlags.contains(.initialised), "A resource with the flag .immutableOnceInitialised is being written to in \(usage) when it has already been initialised.")
// Process all the reads since the last write.
for previousReadIndex in ((previousWriteIndex ?? -1) + 1)..<usageIndex {
let previousRead = usagesArray[previousReadIndex]
guard previousRead.affectsGPUBarriers, previousRead.isRead, frameCommandInfo.encoderIndex(for: previousRead.renderPassRecord) != frameCommandInfo.encoderIndex(for: usage.renderPassRecord) else { continue }
let fromEncoder = frameCommandInfo.encoderIndex(for: usage.renderPassRecord)
let onEncoder = frameCommandInfo.encoderIndex(for: previousRead.renderPassRecord)
let dependency = Dependency(resource: resource, producingUsage: previousRead, producingEncoder: onEncoder, consumingUsage: usage, consumingEncoder: fromEncoder)
commandEncoderDependencies.setDependency(from: fromEncoder,
on: onEncoder,
to: commandEncoderDependencies.dependency(from: fromEncoder, on: onEncoder)?.merged(with: dependency) ?? dependency)
}
}
if let previousWrite = previousWriteIndex.map({ usagesArray[$0] }) {
if usage.isRead, usage.resource == resource, // rather than processing a texture view/base resource
frameCommandInfo.encoderIndex(for: previousWrite.renderPassRecord) == frameCommandInfo.encoderIndex(for: usage.renderPassRecord),
!(previousWrite.type.isRenderTarget && usage.type == .readWriteRenderTarget) {
assert(!usage.stages.isEmpty || usage.renderPassRecord.type != .draw)
assert(!previousWrite.stages.isEmpty || previousWrite.renderPassRecord.type != .draw)
self.commands.append(FrameResourceCommand(command: .memoryBarrier(Resource(resource), afterUsage: previousWrite.type, afterStages: previousWrite.stages, beforeCommand: usage.commandRange.lowerBound, beforeUsage: usage.type, beforeStages: usage.stages, activeRange: activeSubresources), index: previousWrite.commandRange.last!))
}
if (usage.isRead || usage.isWrite), frameCommandInfo.encoderIndex(for: previousWrite.renderPassRecord) != frameCommandInfo.encoderIndex(for: usage.renderPassRecord) {
let fromEncoder = frameCommandInfo.encoderIndex(for: usage.renderPassRecord)
let onEncoder = frameCommandInfo.encoderIndex(for: previousWrite.renderPassRecord)
let dependency = Dependency(resource: resource, producingUsage: previousWrite, producingEncoder: onEncoder, consumingUsage: usage, consumingEncoder: fromEncoder)
commandEncoderDependencies.setDependency(from: fromEncoder,
on: onEncoder,
to: commandEncoderDependencies.dependency(from: fromEncoder, on: onEncoder)?.merged(with: dependency) ?? dependency)
}
} else {
#if canImport(Vulkan)
if Backend.self == VulkanBackend.self, resource.type == .texture, !resource.flags.contains(.windowHandle),
usage.resource == resource { // rather than processing a texture view/base resource
// We may need a pipeline barrier for image layout transitions or queue ownership transfers.
// Put the barrier as early as possible unless it's a render target barrier, in which case put it at the time of first usage
// so that it can be inserted as a subpass dependency.
if let previousRead = usagesArray.indexOfPreviousRead(before: usageIndex, resource: resource).map({ usagesArray[$0] }) {
if previousRead.type != usage.type { // We only need to check if the usage types differ, since otherwise the layouts are guaranteed to be the same.
let onEncoder = frameCommandInfo.encoderIndex(for: previousRead.renderPassRecord)
let fromEncoder = frameCommandInfo.encoderIndex(for: usage.renderPassRecord)
if fromEncoder == onEncoder {
self.commands.append(FrameResourceCommand(command:
.memoryBarrier(Resource(resource), afterUsage: previousRead.type, afterStages: previousRead.stages, beforeCommand: usage.commandRange.lowerBound, beforeUsage: usage.type, beforeStages: usage.stages, activeRange: activeSubresources),
index: previousRead.commandRange.upperBound))
} else {
let dependency = Dependency(resource: resource, producingUsage: previousRead, producingEncoder: onEncoder, consumingUsage: usage, consumingEncoder: fromEncoder)
commandEncoderDependencies.setDependency(from: fromEncoder,
on: onEncoder,
to: commandEncoderDependencies.dependency(from: fromEncoder, on: onEncoder)?.merged(with: dependency) ?? dependency)
}
}
} else if !usage.type.isRenderTarget { // Render target layout transitions are handled by the render pass.
self.commands.append(FrameResourceCommand(command:
.memoryBarrier(Resource(resource), afterUsage: .frameStartLayoutTransitionCheck, afterStages: .cpuBeforeRender, beforeCommand: usage.commandRange.lowerBound, beforeUsage: usage.type, beforeStages: usage.stages, activeRange: activeSubresources),
index: usage.type.isRenderTarget ? usage.commandRange.lowerBound : 0))
}
}
#endif
}
}
let lastUsage = usagesArray.last!
defer {
if usagesArray.contains(where: { $0.isWrite }), resource.flags.intersection([.historyBuffer, .persistent]) != [] {
resource.markAsInitialised()
}
}
let historyBufferUseFrame = resource.flags.contains(.historyBuffer) && resource.stateFlags.contains(.initialised)
if historyBufferUseFrame {
resource.dispose() // This will dispose it in the RenderGraph persistent allocator, which will in turn call dispose in the resource registry at the end of the frame.
}
var canBeMemoryless = false
// We dispose at the end of a command encoder since resources can't alias against each other within a command encoder.
let lastCommandEncoderIndex = frameCommandInfo.encoderIndex(for: lastUsage.renderPassRecord)
let disposalIndex = frameCommandInfo.commandEncoders[lastCommandEncoderIndex].commandRange.last!
// Insert commands to materialise and dispose of the resource.
if let argumentBuffer = ArgumentBuffer(resource) {
// Unlike textures and buffers, we materialise persistent argument buffers at first use rather than immediately.
if !historyBufferUseFrame {
self.preFrameCommands.append(PreFrameResourceCommand(command: .materialiseArgumentBuffer(argumentBuffer), index: firstUsage.commandRange.lowerBound, order: .before))
}
if !resource.flags.contains(.persistent), !resource.flags.contains(.historyBuffer) || historyBufferUseFrame {
self.preFrameCommands.append(PreFrameResourceCommand(command: .disposeResource(resource, afterStages: lastUsage.stages), index: disposalIndex, order: .after))
}
} else if !resource.flags.contains(.persistent) || resource.flags.contains(.windowHandle) {
if let buffer = Buffer(resource) {
if !historyBufferUseFrame {
self.preFrameCommands.append(PreFrameResourceCommand(command: .materialiseBuffer(buffer), index: firstUsage.commandRange.lowerBound, order: .before))
}
if !resource.flags.contains(.historyBuffer) || historyBufferUseFrame {
self.preFrameCommands.append(PreFrameResourceCommand(command: .disposeResource(resource, afterStages: lastUsage.stages), index: disposalIndex, order: .after))
}
} else if let texture = Texture(resource) {
canBeMemoryless = backend.supportsMemorylessAttachments &&
(texture.flags.intersection([.persistent, .historyBuffer]) == [] || (texture.flags.contains(.persistent) && texture.descriptor.usageHint == .renderTarget))
&& usagesArray.allSatisfy({ $0.type.isRenderTarget })
&& !frameCommandInfo.storedTextures.contains(texture)
if !historyBufferUseFrame {
if texture.isTextureView {
self.preFrameCommands.append(PreFrameResourceCommand(command: .materialiseTextureView(texture), index: firstUsage.commandRange.lowerBound, order: .before))
} else {
self.preFrameCommands.append(PreFrameResourceCommand(command: .materialiseTexture(texture), index: firstUsage.commandRange.lowerBound, order: .before))
}
}
if !resource.flags.contains(.historyBuffer) || historyBufferUseFrame {
self.preFrameCommands.append(PreFrameResourceCommand(command: .disposeResource(resource, afterStages: lastUsage.stages), index: disposalIndex, order: .after))
}
}
}
let lastWriteIndex = usagesArray.indexOfPreviousWrite(before: usagesArray.count, resource: resource)
let lastWrite = lastWriteIndex.map { usagesArray[$0] }
if resource.flags.contains(.persistent) || historyBufferUseFrame {
// Prepare the resource for being used this frame. For Vulkan, this means computing the image layouts.
if let buffer = Buffer(resource) {
backend.resourceRegistry.prepareMultiframeBuffer(buffer, frameIndex: frameCommandInfo.globalFrameIndex)
} else if let texture = Texture(resource) {
backend.resourceRegistry.prepareMultiframeTexture(texture, frameIndex: frameCommandInfo.globalFrameIndex)
}
for queue in QueueRegistry.allQueues {
// TODO: separate out the wait index for the first read from the first write.
let waitIndex = resource[waitIndexFor: queue, accessType: lastWriteIndex != nil ? .readWrite : .read]
self.preFrameCommands.append(PreFrameResourceCommand(command: .waitForCommandBuffer(index: waitIndex, queue: queue), index: firstUsage.commandRange.first!, order: .before))
}
if !resource.stateFlags.contains(.initialised) || !resource.flags.contains(.immutableOnceInitialised) {
if lastUsage.isWrite {
self.preFrameCommands.append(PreFrameResourceCommand(command: .updateCommandBufferWaitIndex(resource, accessType: .readWrite), index: lastUsage.commandRange.last!, order: .after))
} else {
if let lastWrite = lastWrite {
self.preFrameCommands.append(PreFrameResourceCommand(command: .updateCommandBufferWaitIndex(resource, accessType: .readWrite), index: lastWrite.commandRange.last!, order: .after))
}
// Process all the reads since the last write.
for readIndex in ((lastWriteIndex ?? -1) + 1)..<usagesArray.count {
let read = usagesArray[readIndex]
guard read.affectsGPUBarriers, read.isRead else { continue }
self.preFrameCommands.append(PreFrameResourceCommand(command: .updateCommandBufferWaitIndex(resource, accessType: .write), index: read.commandRange.last!, order: .after))
}
}
}
}
if Backend.TransientResourceRegistry.isAliasedHeapResource(resource: resource), !canBeMemoryless {
// Reads need to wait for all previous writes to complete.
// Writes need to wait for all previous reads and writes to complete.
var storeFences : [FenceDependency] = []
// We only need to wait for the write to complete if there have been no reads since the write; otherwise, we wait on the reads
// which in turn have a transitive dependency on the write.
if let lastWriteIndex = lastWriteIndex, usagesArray.index(after: lastWriteIndex) == usagesArray.endIndex {
let lastWrite = lastWrite!
storeFences = [FenceDependency(encoderIndex: frameCommandInfo.encoderIndex(for: lastWrite.renderPassRecord), index: lastWrite.commandRange.last!, stages: lastWrite.stages)]
}
// Process all the reads since the last write.
for readIndex in ((lastWriteIndex ?? -1) + 1)..<usagesArray.count {
let read = usagesArray[readIndex]
guard read.affectsGPUBarriers, read.isRead, read.renderPassRecord.type != .external else { continue }
storeFences.append(FenceDependency(encoderIndex: frameCommandInfo.encoderIndex(for: read.renderPassRecord), index: read.commandRange.last!, stages: read.stages))
}
transientRegistry!.setDisposalFences(on: resource, to: storeFences)
}
}
}
func executePreFrameCommands(context: RenderGraphContextImpl<Backend>, frameCommandInfo: inout FrameCommandInfo<Backend.RenderTargetDescriptor>) {
self.preFrameCommands.sort()
var commandEncoderIndex = 0
var queueCommandWaitIndices = QueueCommandIndices()
for command in self.preFrameCommands {
while command.index >= frameCommandInfo.commandEncoders[commandEncoderIndex].commandRange.upperBound {
frameCommandInfo.commandEncoders[commandEncoderIndex].queueCommandWaitIndices = queueCommandWaitIndices
commandEncoderIndex += 1
queueCommandWaitIndices = QueueCommandIndices()
}
let commandBufferIndex = frameCommandInfo.commandEncoders[commandEncoderIndex].commandBufferIndex
command.command.execute(commandIndex: command.index,
context: context,
textureIsStored: { frameCommandInfo.storedTextures.contains($0) },
encoderDependencies: &self.commandEncoderDependencies,
waitEventValues: &queueCommandWaitIndices,
signalEventValue: frameCommandInfo.globalCommandBufferIndex(frameIndex: commandBufferIndex))
}
frameCommandInfo.commandEncoders[commandEncoderIndex].queueCommandWaitIndices = queueCommandWaitIndices
self.preFrameCommands.removeAll(keepingCapacity: true)
}
func reset() {
self.commands.removeAll(keepingCapacity: true)
}
}
| 60.695518 | 382 | 0.623122 |
e4643bb68d002ef9ec48cad9d76d247e1a78ef8b | 910 | //
// personable.swift
// CDAKit
//
// Created by Eric Whitley on 11/30/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import Foundation
/**
Defines basic "person-like" attributes shared by Person and Provider objects
*/
public protocol CDAKPersonable {
// MARK: CDA properties
///prefix (was: title)
var prefix: String? { get set }
///Given / First name
var given_name: String? { get set }
///Family / Last name
var family_name: String? { get set }
///suffix
var suffix: String? { get set }
///addresses
var addresses: [CDAKAddress] {get set}
///telecoms
var telecoms: [CDAKTelecom] {get set}
}
extension CDAKPersonable {
public var has_name: Bool {
let name: String = "\(prefix ?? "")\(given_name ?? "")\(family_name ?? "")\(suffix ?? "")".trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return ( name.characters.count > 0 );
}
} | 23.947368 | 154 | 0.659341 |
1ae466616edd04bb29ed0f01c1a2bc12849d63c1 | 1,820 | //
// Auth.swift
// MeFocus
//
// Created by Hao on 11/19/16.
// Copyright © 2016 Group5. All rights reserved.
//
import UIKit
import Lock
import SimpleKeychain
class Auth: NSObject {
static private var _shared:Auth?
static var shared:Auth{
get {
if self._shared == nil {
self._shared = Auth()
}
return self._shared!
}
}
var profile:A0UserProfile? {
didSet {
if let p = profile {
keychain.setData(
NSKeyedArchiver.archivedData(withRootObject: p),
forKey: "profile"
)
}
}
}
var token:A0Token? {
didSet {
if let t = token {
keychain.setString(t.idToken, forKey: "idToken")
}
}
}
var keychain:A0SimpleKeychain
var client:A0APIClient
override init() {
keychain = A0SimpleKeychain(service: "Auth0")
client = A0Lock.shared().apiClient()
}
func check(completion:@escaping ((Auth)->Void)){
if profile != nil {
completion(self)
return
}
guard let idToken = keychain.string(forKey: "idToken") else {
completion(self)
return
}
client.fetchUserProfile(
withIdToken: idToken,
success: { profile in
// Our idToken is still valid...
// We store the fetched user profile
self.profile = profile
completion(self)
},
failure: { error in
self.keychain.clearAll()
completion(self)
}
)
}
}
| 21.666667 | 69 | 0.467033 |
e6cbe0b006fd00787b236ee77e550bad017e6c84 | 1,763 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class GroupMemberCell: UATableViewCell {
// MARK: -
// MARK: Private vars
private var usernameLabel: UILabel!
// MARK: -
// MARK: Public vars
var userAvatarView: AvatarView!
// MARK: -
// MARK: Constructors
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
userAvatarView = AvatarView(frameSize: 40, type: .Rounded)
contentView.addSubview(userAvatarView)
usernameLabel = UILabel()
usernameLabel.textColor = MainAppTheme.list.textColor
usernameLabel.font = UIFont.systemFontOfSize(18.0)
usernameLabel.text = " "
usernameLabel.sizeToFit()
contentView.addSubview(usernameLabel)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
// MARK: Setters
func setUsername(username: String) {
usernameLabel.text = username
}
// MARK: -
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
let userAvatarViewFrameSize: CGFloat = CGFloat(userAvatarView.frameSize)
userAvatarView.frame = CGRect(x: 14.0, y: (contentView.bounds.size.height - userAvatarViewFrameSize) / 2.0, width: userAvatarViewFrameSize, height: userAvatarViewFrameSize)
usernameLabel.frame = CGRect(x: 65.0, y: (contentView.bounds.size.height - usernameLabel.bounds.size.height) / 2.0, width: contentView.bounds.size.width - 65.0 - 15.0, height: usernameLabel.bounds.size.height)
}
}
| 29.383333 | 217 | 0.640386 |
dbdf255071a619cbff4da8113866773cb0e2c5c2 | 4,111 | //
// FSFindZongHeWorksCell.swift
// fitsky
// 搜索发现 作品 cell 测
// Created by gouyz on 2019/10/14.
// Copyright © 2019 gyz. All rights reserved.
//
import UIKit
private let findZongHeWorksCell = "findZongHeWorksCell"
class FSFindZongHeWorksCell: UITableViewCell {
let itemWidth = floor((kScreenWidth - kMargin * 3)/2)
var didSelectItemBlock:((_ index: Int) -> Void)?
/// 填充数据
var dataModel : [FSSquareHotModel]?{
didSet{
if dataModel != nil {
self.collectionView.reloadData()
self.collectionView.layoutIfNeeded()
let height = self.collectionView.collectionViewLayout.collectionViewContentSize.height
self.collectionView.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
}
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI(){
contentView.backgroundColor = kWhiteColor
contentView.addSubview(collectionView)
collectionView.snp.makeConstraints { (make) in
// make.left.equalTo(kMargin)
// make.right.equalTo(-kMargin)
make.top.left.right.equalTo(contentView)
make.bottom.equalTo(-kMargin)
make.height.equalTo(itemWidth + 84)
}
}
lazy var collectionView: UICollectionView = {
let layout = CHTCollectionViewWaterfallLayout()
layout.sectionInset = UIEdgeInsets.init(top: kMargin, left: kMargin, bottom: kMargin, right: kMargin)
let collView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
collView.dataSource = self
collView.delegate = self
collView.alwaysBounceHorizontal = false
collView.backgroundColor = kWhiteColor
collView.isScrollEnabled = false
collView.register(FSSquareHotCell.classForCoder(), forCellWithReuseIdentifier: findZongHeWorksCell)
return collView
}()
}
extension FSFindZongHeWorksCell : UICollectionViewDataSource,UICollectionViewDelegate,CHTCollectionViewDelegateWaterfallLayout{
// MARK: UICollectionViewDataSource 代理方法
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (dataModel?.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: findZongHeWorksCell, for: indexPath) as! FSSquareHotCell
cell.playImgView.isHidden = true
cell.tuiJianImgView.isHidden = true
cell.dataModel = dataModel?[indexPath.row]
return cell
}
// MARK: UICollectionViewDelegate的代理方法
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if didSelectItemBlock != nil {
didSelectItemBlock!(indexPath.row)
}
}
//MARK: - CollectionView Waterfall Layout Delegate Methods (Required)
//** Size for the cells in the Waterfall Layout */
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
let model = (dataModel?[indexPath.row])!
var height: CGFloat = 0
if model.thumb!.isEmpty {
height = 0
}else{
height = itemWidth * CGFloat(GYZTool.getThumbScale(url: model.material!, thumbUrl: model.thumb!))
}
return CGSize(width: itemWidth, height: height + 84)
}
}
| 35.439655 | 159 | 0.646072 |
de99e46742ce815331d88a01a78f2a0a74a1da6f | 857 | //
// IpifyEndpoint.swift
// MKRXLocalization
//
// Created by Maciej Kowszewicz on 19.06.2017.
// Copyright © 2017 Maciej Kowszewicz. All rights reserved.
//
import Foundation
import Moya
enum Ipify {
case ip()
}
extension Ipify: TargetType {
var baseURL: URL { return URL(string: "https://api.ipify.org?format=json")! }
var path: String {
switch self {
case .ip(): return "/"
}
}
var method: Moya.Method {
return .get
}
var parameters: [String: Any]? {
return nil
}
var sampleData: Data {
switch self {
case
.ip():
return "{\"ip\":\"127.0.0.1\"}".data(using: .utf8)!
}
}
var task: Task {
return .request
}
var parameterEncoding: ParameterEncoding {
return JSONEncoding.default
}
}
| 17.14 | 81 | 0.553092 |
d5d6b68d606495d0ae6feda7fc37d5cbcd5e5075 | 8,500 | //
// GithubVisitorTests.swift
// GithubVisitorTests
//
// Created by David Yang on 2021/1/14.
//
import XCTest
@testable import GithubVisitor
class GithubVisitorTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
class GitbubNetworkTests: XCTestCase {
func testLoad() throws {
let expectNormal = expectation(description: "Request should OK")
GithubNetworkOperation.shared.load(path: "/") { (error, dict) in
XCTAssertTrue(error == nil)
XCTAssertTrue(dict != nil)
expectNormal.fulfill()
}
let expectNotexist = expectation(description: "Request should fail")
GithubNetworkOperation.shared.load(path: "/notexist") { (error, dict) in
XCTAssertTrue(error != nil)
XCTAssertTrue(dict == nil)
expectNotexist.fulfill()
}
self.wait(for: [expectNormal, expectNotexist, ], timeout: 10)
}
func testEndpoit() throws {
let expectNormal = expectation(description: "Request should OK")
GithubNetworkOperation.shared.visitEndpoint() { (error, dict) in
XCTAssertTrue(error == nil)
XCTAssertTrue(dict != nil)
XCTAssertTrue(dict?["current_user_url"] != nil)
XCTAssertTrue(dict?["current_user_url"] as? String != nil)
expectNormal.fulfill()
}
wait(for: [expectNormal], timeout: 10)
}
}
class SimpleRootInfoTests: XCTestCase {
private var cacheRecord: CacheRecord!
override func setUpWithError() throws {
let rawStr =
"""
{
"current_user_url": "https://api.github.com/user",
"current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}",
"authorizations_url": "https://api.github.com/authorizations",
"code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",
"commit_search_url": "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}",
"emails_url": "https://api.github.com/user/emails",
"emojis_url": "https://api.github.com/emojis",
"events_url": "https://api.github.com/events",
"feeds_url": "https://api.github.com/feeds",
"followers_url": "https://api.github.com/user/followers",
"following_url": "https://api.github.com/user/following{/target}",
"gists_url": "https://api.github.com/gists{/gist_id}",
"hub_url": "https://api.github.com/hub",
"issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}",
"issues_url": "https://api.github.com/issues",
"keys_url": "https://api.github.com/user/keys",
"label_search_url": "https://api.github.com/search/labels?q={query}&repository_id={repository_id}{&page,per_page}",
"notifications_url": "https://api.github.com/notifications",
"organization_url": "https://api.github.com/orgs/{org}",
"organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}",
"organization_teams_url": "https://api.github.com/orgs/{org}/teams",
"public_gists_url": "https://api.github.com/gists/public",
"rate_limit_url": "https://api.github.com/rate_limit",
"repository_url": "https://api.github.com/repos/{owner}/{repo}",
"repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}",
"current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}",
"starred_url": "https://api.github.com/user/starred{/owner}{/repo}",
"starred_gists_url": "https://api.github.com/gists/starred",
"user_url": "https://api.github.com/users/{user}",
"user_organizations_url": "https://api.github.com/user/orgs",
"user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}",
"user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"
}
"""
cacheRecord = CacheRecord(id: 0, startTime: 0, endTime: 0, errorCode: 0, statusCode: 0, rawString: rawStr)
}
func testParse() throws {
if let obj = SimpleRootInfo(cache: cacheRecord) {
XCTAssertTrue(obj["current_user_url"] == "https://api.github.com/user")
XCTAssertTrue(obj["current_user_authorizations_html_url"] == "https://github.com/settings/connections/applications{/client_id}")
XCTAssertTrue(obj["authorizations_url"] == "https://api.github.com/authorizations")
XCTAssertTrue(obj["code_search_url"] == "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}")
XCTAssertTrue(obj["commit_search_url"] == "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}")
XCTAssertTrue(obj["emails_url"] == "https://api.github.com/user/emails")
XCTAssertTrue(obj["emojis_url"] == "https://api.github.com/emojis")
XCTAssertTrue(obj["events_url"] == "https://api.github.com/events")
XCTAssertTrue(obj["feeds_url"] == "https://api.github.com/feeds")
XCTAssertTrue(obj["followers_url"] == "https://api.github.com/user/followers")
XCTAssertTrue(obj["following_url"] == "https://api.github.com/user/following{/target}")
XCTAssertTrue(obj["gists_url"] == "https://api.github.com/gists{/gist_id}")
XCTAssertTrue(obj["hub_url"] == "https://api.github.com/hub")
XCTAssertTrue(obj["issue_search_url"] == "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}")
XCTAssertTrue(obj["issues_url"] == "https://api.github.com/issues")
XCTAssertTrue(obj["keys_url"] == "https://api.github.com/user/keys")
XCTAssertTrue(obj["label_search_url"] == "https://api.github.com/search/labels?q={query}&repository_id={repository_id}{&page,per_page}")
XCTAssertTrue(obj["notifications_url"] == "https://api.github.com/notifications")
XCTAssertTrue(obj["organization_url"] == "https://api.github.com/orgs/{org}")
XCTAssertTrue(obj["organization_repositories_url"] == "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}")
XCTAssertTrue(obj["organization_teams_url"] == "https://api.github.com/orgs/{org}/teams")
XCTAssertTrue(obj["public_gists_url"] == "https://api.github.com/gists/public")
XCTAssertTrue(obj["rate_limit_url"] == "https://api.github.com/rate_limit")
XCTAssertTrue(obj["repository_url"] == "https://api.github.com/repos/{owner}/{repo}")
XCTAssertTrue(obj["repository_search_url"] == "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}")
XCTAssertTrue(obj["current_user_repositories_url"] == "https://api.github.com/user/repos{?type,page,per_page,sort}")
XCTAssertTrue(obj["starred_url"] == "https://api.github.com/user/starred{/owner}{/repo}")
XCTAssertTrue(obj["starred_gists_url"] == "https://api.github.com/gists/starred")
XCTAssertTrue(obj["user_url"] == "https://api.github.com/users/{user}")
XCTAssertTrue(obj["user_organizations_url"] == "https://api.github.com/user/orgs")
XCTAssertTrue(obj["user_repositories_url"] == "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}")
XCTAssertTrue(obj["user_search_url"] == "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}")
} else {
XCTAssertTrue(false)
}
}
}
| 53.459119 | 148 | 0.638824 |
38cbb53fb8683b6466070ad3c9193ecb2389f618 | 3,349 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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.
*/
#if !os(watchOS)
import UIKit
/// A cell used in the `collectionView` of the `OCKGridTaskView`. The cell shows a circular `completionButton` that has an image and a
/// `titleLabel`. The default image is a checkmark.
open class OCKGridTaskCell: UICollectionViewCell {
// MARK: Properties
/// Circular button that shows an image and label. The default image is a checkmark when selected.
/// The text for the deselected state will automatically adapt to the `tintColor`.
public let completionButton = OCKLabeledCheckmarkButton()
// MARK: Life cycle
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
// MARK: Methods
override open func prepareForReuse() {
super.prepareForReuse()
completionButton.isSelected = false
completionButton.label.text = nil
accessibilityLabel = nil
accessibilityValue = nil
}
private func setup() {
addSubviews()
constrainSubviews()
completionButton.isEnabled = false
isAccessibilityElement = true
accessibilityTraits = .button
}
private func addSubviews() {
contentView.addSubview(completionButton)
}
private func constrainSubviews() {
completionButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
completionButton.constraints(equalTo: contentView, directions: [.top, .leading]) +
completionButton.constraints(equalTo: contentView, directions: [.bottom, .trailing], priority: .almostRequired)
)
}
}
#endif
| 38.494253 | 134 | 0.73395 |
03846129d2d375e99eb9851086e40ad3e3779f65 | 841 | //
// APImage.swift
// Card Transactions (iOS)
//
// Created by Daniel Bergquist on 1/17/21.
//
import SwiftUI
#if os(iOS) || os(watchOS) || os(tvOS)
public typealias APImage = UIImage
public extension UIImage {
convenience init?(contentsOf url: URL) {
self.init(contentsOfFile: url.absoluteString)
}
}
public extension Image {
init(apImage: APImage) {
self.init(uiImage: apImage)
}
}
#elseif os(macOS)
public typealias APImage = NSImage
public extension NSImage {
var cgImage: CGImage? {
var imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let imageRef = cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
return imageRef
}
}
public extension Image {
init(apImage: APImage) {
self.init(nsImage: apImage)
}
}
#endif
| 20.02381 | 85 | 0.653983 |
e915577918f2ebe4748370e499a066ee66eb3732 | 1,254 | //
// TripTableViewCell.swift
// TravelPal
//
// Created by Ayaz Rahman on 18/11/19.
// Copyright © 2019 Ayaz Rahman. All rights reserved.
//
import UIKit
class TripTableViewCell: UITableViewCell {
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var tripNameLabel: UILabel!
@IBOutlet weak var cellImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
cardView.addShadowAndRoundedCorners()
cardView.backgroundColor = Theme.accent
tripNameLabel.font = UIFont(name: Theme.displayFont, size: 32)
cellImageView.layer.cornerRadius = cardView.layer.cornerRadius
}
func setup(trip: TripModel){
tripNameLabel.text = trip.title
cellImageView.image = nil
if let tripImage = trip.image{
cellImageView.alpha = 0
cellImageView.image = tripImage
UIView.animate(withDuration: 1) {
self.cellImageView.alpha = 0.7
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 25.591837 | 70 | 0.630781 |
26634bceb89d3106741714b0cf6d694ba5470f1e | 6,571 | //
// TransactionTests.swift
//
// Copyright © 2018 Kishikawa Katsumi
// Copyright © 2018 BitcoinKit developers
//
// 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 BitcoinKit
class TransactionTests: XCTestCase {
func testSignTransaction1() {
// Transaction in testnet3
// https://api.blockcypher.com/v1/btc/test3/txs/0189910c263c4d416d5c5c2cf70744f9f6bcd5feaf0b149b02e5d88afbe78992
let prevTxID = "1524ca4eeb9066b4765effd472bc9e869240c4ecb5c1ee0edb40f8b666088231"
let hash = Data(Data(hex: prevTxID)!.reversed())
let index: UInt32 = 1
let outpoint = TransactionOutPoint(hash: hash, index: index)
let balance: UInt64 = 169012961
let amount: UInt64 = 50000000
let fee: UInt64 = 10000000
let change: UInt64 = balance - amount - fee
let toAddress = try! BitcoinAddress(legacy: "mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB") // https://testnet.coinfaucet.eu/en/
let privateKey = try! PrivateKey(wif: "92pMamV6jNyEq9pDpY4f6nBy9KpV2cfJT4L5zDUYiGqyQHJfF1K")
let changeAddress = privateKey.publicKey().toBitcoinAddress()
let lockScript = Script(address: changeAddress)!.data
let output = TransactionOutput(value: 169012961, lockingScript: lockScript)
let unspentTransaction = UnspentTransaction(output: output, outpoint: outpoint)
let plan = TransactionPlan(unspentTransactions: [unspentTransaction], amount: amount, fee: fee, change: change)
let transaction = TransactionBuilder.build(from: plan, toAddress: toAddress, changeAddress: changeAddress)
let sighashHelper = BTCSignatureHashHelper(hashType: .ALL)
let sighash = sighashHelper.createSignatureHash(of: transaction, for: unspentTransaction.output, inputIndex: 0)
XCTAssertEqual(sighash.hex, "fd2f20da1c28b008abcce8a8ac7e1a7687fc944e001a24fc3aacb6a7570a3d0f")
let signature = privateKey.sign(sighash)
XCTAssertEqual(signature.hex, "3044022074ddd327544e982d8dd53514406a77a96de47f40c186e58cafd650dd71ea522702204f67c558cc8e771581c5dda630d0dfff60d15e43bf13186669392936ec539d03")
let signer = TransactionSigner(unspentTransactions: plan.unspentTransactions, transaction: transaction, sighashHelper: BTCSignatureHashHelper(hashType: .ALL))
let signedTransaction = try! signer.sign(with: [privateKey])
XCTAssertEqual(signedTransaction.serialized().hex, "010000000131820866b6f840db0eeec1b5ecc44092869ebc72d4ff5e76b46690eb4eca2415010000008a473044022074ddd327544e982d8dd53514406a77a96de47f40c186e58cafd650dd71ea522702204f67c558cc8e771581c5dda630d0dfff60d15e43bf13186669392936ec539d030141047e000cc16c9a4d38cb1572b9dc34c1452626aa170b46150d0e806be1b42517f0832c8a58f543128083ffb8632bae94dd5f3e1e89fad0a17f64ed8bbbb90b5753ffffffff0280f0fa02000000001976a9149f9a7abd600c0caa03983a77c8c3df8e062cb2fa88ace1677f06000000001976a9142a539adfd7aefcc02e0196b4ccf76aea88a1f47088ac00000000")
XCTAssertEqual(signedTransaction.txID, "0189910c263c4d416d5c5c2cf70744f9f6bcd5feaf0b149b02e5d88afbe78992")
}
func testSignTransaction2() {
// Transaction on Bitcoin Cash Mainnet
// TxID : 96ee20002b34e468f9d3c5ee54f6a8ddaa61c118889c4f35395c2cd93ba5bbb4
// https://explorer.bitcoin.com/bch/tx/96ee20002b34e468f9d3c5ee54f6a8ddaa61c118889c4f35395c2cd93ba5bbb4
let toAddress: BitcoinAddress = try! BitcoinAddress(legacy: "1Bp9U1ogV3A14FMvKbRJms7ctyso4Z4Tcx")
let changeAddress: BitcoinAddress = try! BitcoinAddress(legacy: "1FQc5LdgGHMHEN9nwkjmz6tWkxhPpxBvBU")
let unspentOutput = TransactionOutput(value: 5151, lockingScript: Data(hex: "76a914aff1e0789e5fe316b729577665aa0a04d5b0f8c788ac")!)
let unspentOutpoint = TransactionOutPoint(hash: Data(hex: "e28c2b955293159898e34c6840d99bf4d390e2ee1c6f606939f18ee1e2000d05")!, index: 2)
let unspentTransaction = UnspentTransaction(output: unspentOutput, outpoint: unspentOutpoint)
let utxoKey = try! PrivateKey(wif: "L1WFAgk5LxC5NLfuTeADvJ5nm3ooV3cKei5Yi9LJ8ENDfGMBZjdW")
let feePerByte: UInt64 = 1
let planner = TransactionPlanner(feePerByte: feePerByte)
let plan = planner.plan(unspentTransactions: [unspentTransaction], target: 600)
let transaction = TransactionBuilder.build(from: plan, toAddress: toAddress, changeAddress: changeAddress)
let signer = TransactionSigner(unspentTransactions: plan.unspentTransactions, transaction: transaction, sighashHelper: BCHSignatureHashHelper(hashType: .ALL))
let signedTransaction = try! signer.sign(with: [utxoKey])
XCTAssertEqual(signedTransaction.txID, "96ee20002b34e468f9d3c5ee54f6a8ddaa61c118889c4f35395c2cd93ba5bbb4")
XCTAssertEqual(signedTransaction.serialized().hex, "0100000001e28c2b955293159898e34c6840d99bf4d390e2ee1c6f606939f18ee1e2000d05020000006b483045022100b70d158b43cbcded60e6977e93f9a84966bc0cec6f2dfd1463d1223a90563f0d02207548d081069de570a494d0967ba388ff02641d91cadb060587ead95a98d4e3534121038eab72ec78e639d02758e7860cdec018b49498c307791f785aa3019622f4ea5bffffffff0258020000000000001976a914769bdff96a02f9135a1d19b749db6a78fe07dc9088ace5100000000000001976a9149e089b6889e032d46e3b915a3392edfd616fb1c488ac00000000")
}
func testIsCoinbase() {
let data = Data(hex: "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025151ffffffff010000000000000000015100000000")!
let tx = Transaction.deserialize(data)
XCTAssert(tx.isCoinbase())
}
}
| 70.655914 | 576 | 0.793943 |
f55aab7b96e974ab125de4b2eeefb3b4974f27f9 | 1,409 | //
// AppDelegate.swift
// Sandbox
//
// Created by Solomon on 6/15/20.
// Copyright © 2020 TechSolomon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.078947 | 179 | 0.747339 |
23f0d666cbbf743e06fdcb93f720f43370036b74 | 266 | //
// NutrientDetailResposne.swift
// FoodDetailModule
//
// Created by aldo vernando on 13/02/21.
//
import Foundation
public class NutrientDetailResponse: Codable {
public var label: String?
public var quantity: Double?
public var unit: String?
}
| 17.733333 | 46 | 0.714286 |
20161acd7382d61e5eef9cfd151f1f340e4bc25f | 11,774 | @testable import KsApi
@testable import Library
import Prelude
import ReactiveExtensions_TestHelpers
import ReactiveSwift
import XCTest
internal final class MessagesSearchViewModelTests: TestCase {
fileprivate let vm: MessagesSearchViewModelType = MessagesSearchViewModel()
fileprivate let emptyStateIsVisible = TestObserver<Bool, Never>()
fileprivate let isSearching = TestObserver<Bool, Never>()
fileprivate let hasMessageThreads = TestObserver<Bool, Never>()
fileprivate let showKeyboard = TestObserver<Bool, Never>()
fileprivate let goToMessageThread = TestObserver<MessageThread, Never>()
override func setUp() {
super.setUp()
self.vm.outputs.emptyStateIsVisible.observe(self.emptyStateIsVisible.observer)
self.vm.outputs.isSearching.observe(self.isSearching.observer)
self.vm.outputs.messageThreads.map { !$0.isEmpty }.observe(self.hasMessageThreads.observer)
self.vm.outputs.showKeyboard.observe(self.showKeyboard.observer)
self.vm.outputs.goToMessageThread.observe(self.goToMessageThread.observer)
}
func testKeyboard() {
self.showKeyboard.assertValues([])
self.vm.inputs.configureWith(project: nil)
self.vm.inputs.viewDidLoad()
self.vm.inputs.viewWillAppear()
self.showKeyboard.assertValues([true])
self.vm.inputs.viewWillDisappear()
self.showKeyboard.assertValues([true, false])
}
func testSearch_NoProject() {
self.vm.inputs.configureWith(project: nil)
XCTAssertEqual([], self.trackingClient.events)
self.vm.inputs.viewDidLoad()
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.vm.inputs.viewWillAppear()
self.hasMessageThreads.assertValues([])
self.isSearching.assertValues([false])
self.vm.inputs.searchTextChanged("hello")
self.hasMessageThreads.assertValues([])
self.isSearching.assertValues([false, true])
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true])
self.isSearching.assertValues([false, true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual([nil, nil, nil, nil], self.trackingClient.properties.map { $0["project_pid"] as! Int? })
XCTAssertEqual([nil, nil, nil, true], self.trackingClient.properties.map { $0["has_results"] as! Bool? })
withEnvironment(apiService: MockService(fetchMessageThreadsResponse: [])) {
self.vm.inputs.searchTextChanged("hello world")
self.hasMessageThreads.assertValues([true, false])
self.isSearching.assertValues([false, true, false, true])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true, false])
self.isSearching.assertValues([false, true, false, true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil, true, true, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual(
[nil, nil, nil, nil, nil, nil, nil],
self.trackingClient.properties.map { $0["project_pid"] as! Int? }
)
XCTAssertEqual(
[nil, nil, nil, true, nil, nil, false],
self.trackingClient.properties.map { $0["has_results"] as! Bool? }
)
self.vm.inputs.searchTextChanged("")
self.vm.inputs.searchTextChanged(nil)
self.hasMessageThreads.assertValues([true, false])
self.isSearching.assertValues([false, true, false, true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true, false])
self.isSearching.assertValues([false, true, false, true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
}
}
func testSearch_WithProject() {
let project = Project.template |> Project.lens.id .~ 123
self.vm.inputs.configureWith(project: project)
XCTAssertEqual([], self.trackingClient.events)
self.vm.inputs.viewDidLoad()
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.vm.inputs.viewWillAppear()
self.hasMessageThreads.assertValues([])
self.vm.inputs.searchTextChanged("hello")
self.hasMessageThreads.assertValues([])
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual(
[project.id, project.id, project.id, project.id],
self.trackingClient.properties.map { $0["project_pid"] as! Int? }
)
self.vm.inputs.searchTextChanged("hello world")
self.hasMessageThreads.assertValues([true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true, false, true])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil, true, true, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual(
[project.id, project.id, project.id, project.id, project.id, project.id, project.id],
self.trackingClient.properties.map { $0["project_pid"] as! Int? }
)
self.vm.inputs.searchTextChanged("")
self.hasMessageThreads.assertValues([true, false, true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true, false, true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
}
func testGoToMessageThread() {
let project = Project.template |> Project.lens.id .~ 123
let messageThread = MessageThread.template
self.vm.inputs.configureWith(project: project)
self.vm.inputs.viewDidLoad()
self.vm.inputs.viewWillAppear()
self.vm.inputs.tappedMessageThread(messageThread)
self.goToMessageThread.assertValues([messageThread])
}
func testClearSearchTerm_NoProject() {
self.vm.inputs.configureWith(project: nil)
XCTAssertEqual([], self.trackingClient.events)
self.vm.inputs.viewDidLoad()
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.vm.inputs.viewWillAppear()
self.hasMessageThreads.assertValues([])
self.vm.inputs.searchTextChanged("hello")
self.hasMessageThreads.assertValues([])
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual(
[nil, nil, nil, nil],
self.trackingClient.properties.map { $0["project_pid"] as! Int? }
)
self.vm.inputs.clearSearchText()
self.hasMessageThreads.assertValues([true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Cleared Message Search Term"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual(
[nil, nil, nil, nil, nil],
self.trackingClient.properties.map { $0["project_pid"] as! Int? }
)
}
func testClearSearchTerm_WithProject() {
let project = Project.template |> Project.lens.id .~ 123
self.vm.inputs.configureWith(project: project)
XCTAssertEqual([], self.trackingClient.events)
self.vm.inputs.viewDidLoad()
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.vm.inputs.viewWillAppear()
self.hasMessageThreads.assertValues([])
self.vm.inputs.searchTextChanged("hello")
self.hasMessageThreads.assertValues([])
XCTAssertEqual(["Viewed Message Search"], self.trackingClient.events)
self.scheduler.advance()
self.hasMessageThreads.assertValues([true])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual(
[project.id, project.id, project.id, project.id],
self.trackingClient.properties.map { $0["project_pid"] as! Int? }
)
self.vm.inputs.clearSearchText()
self.hasMessageThreads.assertValues([true, false])
XCTAssertEqual(
[
"Viewed Message Search", "Message Threads Search", "Message Inbox Search",
"Viewed Message Search Results", "Cleared Message Search Term"
],
self.trackingClient.events
)
XCTAssertEqual(
[nil, true, true, nil, nil],
self.trackingClient.properties.map { $0[Koala.DeprecatedKey] as! Bool? }
)
XCTAssertEqual(
[project.id, project.id, project.id, project.id, project.id],
self.trackingClient.properties.map { $0["project_pid"] as! Int? }
)
}
}
| 31.821622 | 109 | 0.676915 |
1cd378efcb5229b84954f38d7524d0cdc952cda6 | 1,162 | //
// ScheduleOperationDispatch.swift
// RsyncOSX
//
// Created by Thomas Evensen on 21.10.2017.
// Copyright © 2017 Thomas Evensen. All rights reserved.
//
import Foundation
class QuickbackupDispatch {
weak var workitem: DispatchWorkItem?
// Process termination and filehandler closures
var processtermination: () -> Void
var filehandler: () -> Void
private func dispatchtask(seconds: Int, outputprocess: OutputfromProcess?) {
let work = DispatchWorkItem { () in
_ = ExecuteQuickbackupTask(processtermination: self.processtermination,
filehandler: self.filehandler,
outputprocess: outputprocess)
}
workitem = work
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(seconds), execute: work)
}
init(processtermination: @escaping () -> Void,
filehandler: @escaping () -> Void,
outputprocess: OutputfromProcess?)
{
self.processtermination = processtermination
self.filehandler = filehandler
dispatchtask(seconds: 0, outputprocess: outputprocess)
}
}
| 32.277778 | 90 | 0.640275 |
0aec5be604ff6dfa4e6e9688e6c79cd43db7df21 | 3,055 | //
// API.swift
// FoodCompass
//
// Created by Mitchell Sweet on 12/4/20.
// Copyright © 2020 Mitchell Sweet. All rights reserved.
//
import Foundation
struct Keys {
static let API_KEY = "DyWTsp2-9XneDlpPrhCfN4Wr_5S4EFQniy_tMtumgIvPR5ig6m-uJAjRjAdahQ27HKp6ggB0fyUPqxPSa3luW0pqA77n6rsrR6qc672BBdNNzF_G7AwevUcImalfW3Yx"
}
/// Corisponds to business category name in Yelp API
enum RestaurantCategory: String {
case coffee = "coffee"
case fastFood = "hotdogs"
case icecream = "icecream"
case chinese = "chinese"
case pancakes = "pancakes"
case italian = "italian"
case pizza = "pizza"
case salad = "salad"
case sushi = "sushi"
case tacos = "tacos"
case tea = "tea"
case sandwiches = "sandwiches"
case bars = "bars"
case hotdog = "hotdog"
case grocery = "grocery"
case seafood = "seafood"
case donuts = "donuts"
case candy = "candy"
case chicken = "chicken_wings"
case mexican = "mexican"
}
enum APIError: Error {
case locationError
case parseError
case internetError
case apiError
case unknown
}
class API {
// MARK: Constants
public static let shared = API()
private let address = "https://api.yelp.com/v3/businesses/search"
// MARK: Functions
public func searchYelpFor(category: RestaurantCategory, completion: @escaping (SearchResults?, APIError?) -> Void) {
LocationManager.shared.refreshLocation()
guard let lat = LocationManager.shared.latitude,
let long = LocationManager.shared.longitude else {
print("Location is not available for API call...")
completion(nil, .locationError)
return
}
var urlString = "\(address)?latitude=\(lat)&longitude=\(long)&categories=\(category.rawValue)&sort_by=distance"
if !SettingsManager.showClosed { urlString += "&open_now=true"}
urlString += "&radius=\(Int(SettingsManager.radiusInMeters))"
let url = URL(string: urlString)!
let sessionConfig = URLSessionConfiguration.default
sessionConfig.httpAdditionalHeaders = ["Authorization": "Bearer \(Keys.API_KEY)"]
let session = URLSession(configuration: sessionConfig, delegate: self as? URLSessionDelegate, delegateQueue: nil)
let task = session.dataTask(with: url) {(data, response, error) in
guard let data = data else {
print("ERROR searching yelp: \(error?.localizedDescription ?? "N/A")")
DispatchQueue.main.async { completion(nil, .apiError) }
return
}
do {
let res = try JSONDecoder().decode(SearchResults.self, from: data)
DispatchQueue.main.async { completion(res, nil) }
} catch let error {
print("ERROR parsing data: \(error.localizedDescription)")
DispatchQueue.main.async { completion(nil, .parseError) }
}
}
task.resume()
}
}
| 33.571429 | 155 | 0.627823 |
f7157b14eae59c5ba52908deb138484a16c04bd4 | 2,964 | ////
/// LoggedOutViewController.swift
//
import SnapKit
protocol BottomBarController: class {
var navigationBarsVisible: Bool? { get }
var bottomBarVisible: Bool { get }
var bottomBarHeight: CGFloat { get }
var bottomBarView: UIView { get }
func setNavigationBarsVisible(_ visible: Bool, animated: Bool)
}
class LoggedOutViewController: BaseElloViewController, BottomBarController {
private var _navigationBarsVisible: Bool = true
override var navigationBarsVisible: Bool? { return _navigationBarsVisible }
let bottomBarVisible: Bool = true
var bottomBarHeight: CGFloat { return screen.bottomBarHeight }
var bottomBarView: UIView { return screen.bottomBarView }
var childView: UIView?
private var _mockScreen: LoggedOutScreenProtocol?
var screen: LoggedOutScreenProtocol {
set(screen) { _mockScreen = screen }
get { return fetchScreen(_mockScreen) }
}
private var userActionAttemptedObserver: NotificationObserver?
func setNavigationBarsVisible(_ visible: Bool, animated: Bool) {
_navigationBarsVisible = visible
}
override func addChild(_ childController: UIViewController) {
super.addChild(childController)
childView = childController.view
if isViewLoaded {
screen.setControllerView(childController.view)
}
}
override func loadView() {
let screen = LoggedOutScreen()
screen.delegate = self
view = screen
}
override func viewDidLoad() {
super.viewDidLoad()
if let childView = childView {
screen.setControllerView(childView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupNotificationObservers()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
removeNotificationObservers()
}
}
extension LoggedOutViewController {
func setupNotificationObservers() {
userActionAttemptedObserver = NotificationObserver(
notification: LoggedOutNotifications.userActionAttempted
) { [weak self] action in
switch action {
case .relationshipChange:
Tracker.shared.loggedOutRelationshipAction()
case .postTool:
Tracker.shared.loggedOutPostTool()
case .artistInviteSubmit:
Tracker.shared.loggedOutArtistInviteSubmit()
}
self?.screen.showJoinText()
}
}
func removeNotificationObservers() {
userActionAttemptedObserver?.removeObserver()
}
}
extension LoggedOutViewController: LoggedOutProtocol {
func showLoginScreen() {
Tracker.shared.loginButtonTapped()
appViewController?.showLoginScreen()
}
func showJoinScreen() {
Tracker.shared.joinButtonTapped()
appViewController?.showJoinScreen()
}
}
| 28.5 | 79 | 0.674764 |
768f902f3fe0d5301f6bd387be2a0055afd7728f | 2,115 | //
// AppDelegate.swift
// BackCol
//
// Auto generated by ReflectCode.com
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47 | 285 | 0.756974 |
edffe2ee3ae302dad7b52f73dcebec080aa8abb0 | 4,582 | //
// MoreDetailsViewController.swift
// MMOpenWeatherForecast
//
// Created by Madhura Marathe on 1/22/17.
// Copyright © 2017 Madhura. All rights reserved.
//
import UIKit
class MoreDetailsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var weatherInfo : WeatherForecast? = nil
@IBOutlet weak var tableViewMoreDetails: UITableView!
var weatherParameters: [String] = [WEATHER_DETAIL_KEY_WEATHER_CONDITION_DESCRIPTION,WEATHER_DETAIL_KEY_CLOUDINESS,WEATHER_DETAIL_KEY_WIND_SPEED,WEATHER_DETAIL_KEY_WIND_DIRECTION_IN_DEGREES,WEATHER_DETAIL_KEY_HUMIDITY,WEATHER_DETAIL_KEY_PRESSURE,WEATHER_DETAIL_KEY_TEMP, WEATHER_DETAIL_KEY_MIN_DAILY_TEMP, WEATHER_DETAIL_KEY_MAX_DAILY_TEMP];
override func viewDidLoad() {
super.viewDidLoad()
self.tableViewMoreDetails.tableFooterView = UIView(frame: .zero)
if(weatherInfo?.name != nil)
{
self.navigationController?.topViewController?.title = "\(weatherInfo!.name) : More Weather Details"
}
else
{
self.navigationController?.topViewController?.title = "More Weather Details"
}
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:" ", style:.plain, target:nil, action:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getValueForWeatherParameter(_ weatherParameter: String) -> String
{
var weatherParameterValue: String = "";
if(weatherParameter == WEATHER_DETAIL_KEY_WEATHER_CONDITION_DESCRIPTION)
{
weatherParameterValue = (weatherInfo?.weatherDescription)!
}
else if(weatherParameter == WEATHER_DETAIL_KEY_CLOUDINESS)
{
weatherParameterValue = String(format:"%.1f",(weatherInfo?.all)!);
weatherParameterValue += "%";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_WIND_SPEED)
{
weatherParameterValue = String(format:"%.1f",(weatherInfo?.windSpeed)!);
weatherParameterValue += " m/sec";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_WIND_DIRECTION_IN_DEGREES)
{
weatherParameterValue = String(format:"%.1f",(weatherInfo?.windDirectionInDegrees)!);
weatherParameterValue += " degrees";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_HUMIDITY)
{
weatherParameterValue = String(format:"%.1f",(weatherInfo?.humidity)!);
weatherParameterValue += "%";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_PRESSURE)
{
weatherParameterValue = String(format:"%.1f",(weatherInfo?.pressure)!);
weatherParameterValue += " hPa";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_TEMP)
{
//For Celsius
weatherParameterValue = String(format: "%.0f °C", (weatherInfo?.temperature)! - 273.15)
}
else if(weatherParameter == WEATHER_DETAIL_KEY_MAX_DAILY_TEMP)
{
//For Celsius
weatherParameterValue = String(format: "%.0f °C", (weatherInfo?.temperatureMax)! - 273.15)
}
else if(weatherParameter == WEATHER_DETAIL_KEY_MIN_DAILY_TEMP)
{
//For Celsius
weatherParameterValue = String(format: "%.0f °C", (weatherInfo?.temperatureMin)! - 273.15)
}
return weatherParameterValue;
}
// MARK: UITablevieDatasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return weatherParameters.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let weatherParameter = weatherParameters[(indexPath as NSIndexPath).row];
let cell = tableViewMoreDetails.dequeueReusableCell(withIdentifier: UI_TABLEVIEW_WEATHER_PARAMETER_CELL) ;
cell!.textLabel?.text = weatherParameter;
let weatherParameterValue = self.getValueForWeatherParameter(weatherParameter);
cell!.detailTextLabel?.text = weatherParameterValue;
cell!.selectionStyle = UITableViewCellSelectionStyle.none;
cell!.accessoryType = UITableViewCellAccessoryType.none;
return cell!;
}
// MARK: UITableView delegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 44;
}
}
| 39.5 | 344 | 0.666085 |
db5e83ed279fd3a4566b9782aaea96852c8b36ad | 1,230 | //
// PlayableItem.swift
// SwiftyPlayer
//
// Created by shiwei on 2020/6/2.
//
import AVFoundation
import MediaPlayer
import UIKit
public class PlayableItem: NSObject, Playable {
public let itemResources: [PlayableQuality: ResourceConvertible]
@objc
public dynamic var artist: String?
@objc
public dynamic var title: String?
@objc
public dynamic var album: String?
@objc
public dynamic var trackCount: NSNumber?
@objc
public dynamic var trackNumber: NSNumber?
@objc
public dynamic var artwork: MPMediaItemArtwork?
@objc
public dynamic var data: AVAsset?
public var artworkImageSize: CGSize?
public required init?(itemResources: [PlayableQuality: ResourceConvertible]) {
if itemResources.isEmpty {
return nil
}
self.itemResources = itemResources
super.init()
}
public subscript(
_ quality: PlayableQuality,
default defaultValue: @autoclosure () -> ResourceConvertible
) -> ResourceConvertible {
itemResources[quality, default: defaultValue()]
}
public subscript(_ quality: PlayableQuality) -> ResourceConvertible? {
itemResources[quality]
}
}
| 20.847458 | 82 | 0.673171 |
d9f7b7f05d3b29ba1132cacde00941f5a1e509c9 | 2,642 | //
// MapCell.swift
// FirstCitizen
//
// Created by Fury on 24/09/2019.
// Copyright © 2019 Kira. All rights reserved.
//
import UIKit
import NMapsMap
class MapCell: UITableViewCell {
static let identifier = "MapCell"
private let nmapView = NMFMapView(frame: .zero)
private let gradientView = UIImageView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
attribute()
layout()
}
func modifyProperties(_ latitude: Double?, _ longitude: Double?, pinImageUrlStr: String) {
let pinImageURL: URL = URL(string: pinImageUrlStr)!
let task = URLSession.shared.dataTask(with: pinImageURL) { (data, response, error) in
guard error == nil else { return print(error!) }
guard let response = response as? HTTPURLResponse,
// ~= 범위 사이에 있는지 확인하는 것
200..<400 ~= response.statusCode
else { return print("StatusCode is not valid") }
guard let data = data else { return }
let iconImg = UIImage(data: data)
guard let lat = latitude, let lng = longitude else { return }
let marker = NMFMarker(position: NMGLatLng(lat: lat, lng: lng), iconImage: NMFOverlayImage(image: iconImg!))
let markerWidth: CGFloat = 40
let markerHeight: CGFloat = 50
marker.width = markerWidth.dynamic(1)
marker.height = markerHeight.dynamic(1)
DispatchQueue.main.async {
marker.mapView = self.nmapView
let cameraUpdate = NMFCameraUpdate(scrollTo: NMGLatLng(lat: lat, lng: lng))
cameraUpdate.animation = .easeIn
self.nmapView.moveCamera(cameraUpdate)
}
}
task.resume()
}
private func attribute() {
nmapView.mapType = .basic
nmapView.logoAlign = .rightTop
nmapView.logoMargin = UIEdgeInsets(top: 60, left: 0, bottom: 0, right: 0)
nmapView.minZoomLevel = 15
gradientView.image = UIImage(named: "Gradient")
gradientView.contentMode = .scaleToFill
}
private func layout() {
let margin: CGFloat = 10
[nmapView, gradientView]
.forEach { contentView.addSubview($0) }
nmapView.snp.makeConstraints {
$0.top.leading.trailing.bottom.equalTo(contentView)
$0.height.equalTo(UIScreen.main.bounds.height / 2)
}
gradientView.snp.makeConstraints {
$0.leading.trailing.equalTo(contentView)
$0.bottom.equalTo(nmapView.snp.bottom)
$0.height.equalTo(margin.dynamic(10))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 29.685393 | 114 | 0.658592 |
62eafd87c8840588a69ffd0a8553b289846794c1 | 1,828 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// This class represents profiling event information for a syntax error
/// identified during prediction. Syntax errors occur when the prediction
/// algorithm is unable to identify an alternative which would lead to a
/// successful parse.
///
/// - seealso: org.antlr.v4.runtime.Parser#notifyErrorListeners(org.antlr.v4.runtime.Token, String, org.antlr.v4.runtime.RecognitionException)
/// - seealso: org.antlr.v4.runtime.ANTLRErrorListener#syntaxError
///
/// - 4.3
///
public class ErrorInfo: DecisionEventInfo {
///
/// Constructs a new instance of the _org.antlr.v4.runtime.atn.ErrorInfo_ class with the
/// specified detailed syntax error information.
///
/// - parameter decision: The decision number
/// - parameter configs: The final configuration set reached during prediction
/// prior to reaching the _org.antlr.v4.runtime.atn.ATNSimulator#ERROR_ state
/// - parameter input: The input token stream
/// - parameter startIndex: The start index for the current prediction
/// - parameter stopIndex: The index at which the syntax error was identified
/// - parameter fullCtx: `true` if the syntax error was identified during LL
/// prediction; otherwise, `false` if the syntax error was identified
/// during SLL prediction
///
public init(_ decision: Int,
_ configs: ATNConfigSet,
_ input: TokenStream, _ startIndex: Int, _ stopIndex: Int,
_ fullCtx: Bool) {
super.init(decision, configs, input, startIndex, stopIndex, fullCtx)
}
}
| 42.511628 | 143 | 0.678337 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.