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
|
---|---|---|---|---|---|
d757327421fec27abdbe140184aaa55fbd49f6fd | 291 | //
// ListDictionary.swift
// MailChimpTest
//
// Created by Austin Sirkin on 1/7/18.
// Copyright © 2018 Austin Sirkin. All rights reserved.
//
import Foundation
/* Wasn't able to get this working in time.
struct ListDictionary {
init(todo: [String: Any]){
}
}
*/
| 13.857143 | 56 | 0.635739 |
0a91a76a1a9173a0c024f891a7a6db5215e8a59c | 557 | //
// AppEnvironmentPredicate.swift
// Taskem
//
// Created by Wilson on 07.01.2018.
// Copyright © 2018 Wilson. All rights reserved.
//
import PainlessInjection
struct AppEnvironmentPredicate: ModuleLoadingPredicate {
let environments: [AppEnvironment]
init(environments: [AppEnvironment]) {
self.environments = environments
}
init(environment: AppEnvironment) {
self.init(environments: [environment])
}
func shouldLoadModule() -> Bool {
return environments.contains(AppEnvironment.current)
}
}
| 21.423077 | 60 | 0.694794 |
d547085dfe563890138e7a0d9fa8d8daf9e7d3e7 | 156 | import Library
import UIKit
internal final class ProfileEmptyStateCell: UICollectionViewCell, ValueCell {
func configureWith(value value: Void) {
}
}
| 17.333333 | 77 | 0.788462 |
cc2126bce4dfe18179b37a452ccae8dc51390b11 | 1,444 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 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 Swift project authors
*/
import XCTest
@testable import Markdown
final class AtomicCounterTests: XCTestCase {
func testIncremental() {
XCTAssertEqual(AtomicCounter.current, AtomicCounter.current)
XCTAssertNotEqual(AtomicCounter.next(), AtomicCounter.next())
}
func testSimultaneousFetch() {
var counters = Set<UInt64>()
let group = DispatchGroup()
let fetchQueue = DispatchQueue(label: "AtomicCounterTests.testSimultaneousFetch.fetch", attributes: [.concurrent])
let collectQueue = DispatchQueue(label: "AtomicCounterTests.testSimultaneousFetch.collect")
let numTasks = 4
let idsPerQueue = 200000
for _ in 0..<numTasks {
group.enter()
fetchQueue.async {
let ids = (0..<idsPerQueue).map { _ in AtomicCounter.next() }
collectQueue.sync {
for id in ids {
counters.insert(id)
}
}
group.leave()
}
}
group.wait()
XCTAssertEqual(numTasks * idsPerQueue, counters.count)
}
}
| 33.581395 | 122 | 0.629501 |
906ea9a2bbb6e29041997c873516b45ceba902da | 905 | //
// Util.swift
// TFTabBarController
//
// Created by duoji on 2020/5/14.
// Copyright © 2020 duoji. All rights reserved.
//
import UIKit
class Util {
//获取拉伸后的图片
class func getResizableImage(imageName: String) -> UIImage {
let originalImage = UIImage.init(named: imageName)!
let w = originalImage.size.width / 2
let h = originalImage.size.height / 2
let handledImage = originalImage.resizableImage(withCapInsets: .init(top: h, left: w, bottom: h, right: w))
return handledImage
}
//16进制数转rgb
func ColorFromRGB(rgbValue: UInt32) -> UIColor {
let temp = UInt32(255.0)
let red = ((rgbValue & 0xFF0000) >> 16) / temp
let green = ((rgbValue & 0xFF00) >> 8) / temp
let blue = (rgbValue & 0xFF) / temp
return UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: 1)
}
}
| 29.193548 | 115 | 0.61989 |
e5143144dc6b58ff28103c490fe05f22c543a910 | 1,401 | import XCTest
import class Foundation.Bundle
final class hockeyapp_crash_dataTests: XCTestCase {
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
// Some of the APIs that we use below are available in macOS 10.13 and above.
guard #available(macOS 10.13, *) else {
return
}
let fooBinary = productsDirectory.appendingPathComponent("hockeyapp_crash_data")
let process = Process()
process.executableURL = fooBinary
let pipe = Pipe()
process.standardOutput = pipe
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
XCTAssertEqual(output, "Hello, world!\n")
}
/// Returns path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
static var allTests = [
("testExample", testExample),
]
}
| 29.1875 | 88 | 0.641685 |
f485077254e7e66cf42662064e13e091c27b6ec6 | 1,291 | //
// StakeableLockedInput.swift
//
//
// Created by Ostap Danylovych on 01.09.2021.
//
import Foundation
public struct StakeableLockedInput: Equatable {
public static let typeID: PChainTypeID = .stakeableLockedInput
public let locktime: Date
public let transferableInput: TransferableInput
public init(locktime: Date, transferableInput: TransferableInput) {
self.locktime = locktime
self.transferableInput = transferableInput
}
}
extension StakeableLockedInput: AvalancheCodable {
public init(from decoder: AvalancheDecoder) throws {
let typeID: PChainTypeID = try decoder.decode(name: "typeID")
guard typeID == Self.typeID else {
throw AvalancheDecoderError.dataCorrupted(
typeID,
AvalancheDecoderError.Context(path: decoder.path)
)
}
self.init(
locktime: try decoder.decode(name: "locktime"),
transferableInput: try decoder.decode(name: "transferableInput")
)
}
public func encode(in encoder: AvalancheEncoder) throws {
try encoder.encode(Self.typeID, name: "typeID")
.encode(locktime, name: "locktime")
.encode(transferableInput, name: "transferableInput")
}
}
| 30.023256 | 76 | 0.655306 |
e9f25d530dd16b1d6e98960fb16cbed1e829d8a1 | 4,058 | // MainViewController.swift
// Tipper
//
// Created by Favian Flores on 1/30/21.
import UIKit
class MainViewController: UIViewController {
let defaults = UserDefaults.standard
@IBOutlet weak var billAmountTextField: UITextField!
@IBOutlet weak var numberOfPeopleTextField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipPerPersonLabel: UILabel!
@IBOutlet weak var totalPerPersonLabel: UILabel!
@IBOutlet weak var tipChoiceSegCtrl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(saveData),
name: UIApplication.willResignActiveNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(restoreData),
name: UIApplication.willEnterForegroundNotification,
object: nil
)
setDefaults()
restoreData()
billAmountTextField.becomeFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateTipController()
calculateTip()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@IBAction func userInput(_ sender: Any) {
calculateTip()
}
func setDefaults() {
if defaults.value(forKey: "tipChoiceSegCtrl0") == nil {
defaults.set(15, forKey: "tipChoiceSegCtrl0")
}
if defaults.value(forKey: "tipChoiceSegCtrl1") == nil {
defaults.set(18, forKey: "tipChoiceSegCtrl1")
}
if defaults.value(forKey: "tipChoiceSegCtrl2") == nil {
defaults.set(20, forKey: "tipChoiceSegCtrl2")
}
if defaults.value(forKey: "tipChoiceSegCtrlDefault") == nil {
defaults.set(1, forKey: "tipChoiceSegCtrlDefault")
}
if defaults.value(forKey: "tipChoiceSegCtrlIndex") == nil {
defaults.set(1, forKey: "tipChoiceSegCtrlIndex")
}
}
func updateTipController() {
tipChoiceSegCtrl.setTitle(
String(defaults.integer(forKey: "tipChoiceSegCtrl0")) + "%",
forSegmentAt: 0
)
tipChoiceSegCtrl.setTitle(
String(defaults.integer(forKey: "tipChoiceSegCtrl1")) + "%",
forSegmentAt: 1
)
tipChoiceSegCtrl.setTitle(
String(defaults.integer(forKey: "tipChoiceSegCtrl2")) + "%",
forSegmentAt: 2
)
}
func calculateTip() {
let left = defaults.integer(forKey: "tipChoiceSegCtrl0")
let mid = defaults.integer(forKey: "tipChoiceSegCtrl1")
let right = defaults.integer(forKey: "tipChoiceSegCtrl2")
let tipPercentages = [left, mid, right]
let people = Double(numberOfPeopleTextField.text!) ?? 1.0
let bill = Double(billAmountTextField.text!) ?? 0.0
let tip = (bill * Double(tipPercentages[tipChoiceSegCtrl.selectedSegmentIndex]) * 0.01)
let total = bill + tip
let billPerPerson = bill / people
let tipPerPerson = tip / people
let totalPerPerson = billPerPerson + tipPerPerson
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
tipPerPersonLabel.text = String(format: "$%.2f", tipPerPerson)
totalPerPersonLabel.text = String(format: "$%.2f", totalPerPerson)
}
@objc func restoreData() {
let date = Date()
let deleteDataby = defaults.value(forKey: "deleteDataBy")
if deleteDataby != nil && date > deleteDataby as! Date {
defaults.set("", forKey: "billAmount")
defaults.set("", forKey: "numberOfPeople")
defaults.set(
defaults.integer(forKey: "tipChoiceSegCtrlDefault"),
forKey: "tipChoiceSegCtrlIndex"
)
}
billAmountTextField.text = defaults.string(forKey: "billAmount")
numberOfPeopleTextField.text = defaults.string(forKey: "numberOfPeople")
tipChoiceSegCtrl.selectedSegmentIndex = defaults.integer(forKey: "tipChoiceSegCtrlIndex")
updateTipController()
calculateTip()
}
@objc func saveData() {
defaults.set(Double(billAmountTextField.text!), forKey: "billAmount")
defaults.set(Int(numberOfPeopleTextField.text!), forKey: "numberOfPeople")
defaults.set(Int(tipChoiceSegCtrl.selectedSegmentIndex), forKey: "tipChoiceSegCtrlIndex")
defaults.set(Date(timeInterval: 600, since: Date()), forKey: "deleteDataBy")
}
}
| 30.977099 | 91 | 0.734598 |
87c2f9f50a26d0c63a484252c7ecd841661a8841 | 2,663 | //
// Copyright: Ambrosus Technologies GmbH
// Email: [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import AmbrosusSDK
final class SampleFetcher {
func fetch() {
requestSampleJSON()
}
private func requestSampleJSON() {
requestSamples(assetPath: "CowAsset", eventsPath: "CowEvents")
requestSamples(assetPath: "PharmacyAsset", eventsPath: "PharmacyEvents")
requestSamples(assetPath: "PharmacyAsset2", eventsPath: "PharmacyEvents2")
}
private func requestSamples(assetPath: String, eventsPath: String) {
if let assetDictionary = requestJSON(path: assetPath) as? [String: Any],
let asset = AMBAsset(json: assetDictionary) {
AMBDataStore.sharedInstance.assetStore.insert(asset)
}
guard let eventDictionaries = requestJSON(path: eventsPath) as? [String: Any],
let eventPairs = eventDictionaries["results"] as? [[String: Any]] else {
return
}
let events = eventPairs.compactMap { AMBEvent(json: $0) }
AMBDataStore.sharedInstance.eventStore.insert(events)
}
private func requestJSON(path: String) -> Any? {
if let path = Bundle.main.path(forResource: path, ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
return jsonResult
} catch {
return nil
}
}
return nil
}
}
| 45.913793 | 261 | 0.684566 |
eb16372d68778e8a6aae13d2bbae3bb188da22b8 | 883 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
/// Error enum for Opsworks
public enum OpsworksError: AWSErrorType {
case validationException(message: String?)
case resourceNotFoundException(message: String?)
}
extension OpsworksError {
public init?(errorCode: String, message: String?){
var errorCode = errorCode
if let index = errorCode.index(of: "#") {
errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...])
}
switch errorCode {
case "ValidationException":
self = .validationException(message: message)
case "ResourceNotFoundException":
self = .resourceNotFoundException(message: message)
default:
return nil
}
}
} | 33.961538 | 143 | 0.669309 |
e67ab225439ae6ce7ff74ce9f9e4a157a242dcd0 | 2,485 | //
// OperationRepositoryTests.swift
// core.root-all-notifications-Unit-Tests
//
// Created by Federico Bond on 05/01/2021.
//
import XCTest
import Firebase
@testable import core
@testable import Muun
class OperationRepositoryTests: MuunTestCase {
var operationRepository: OperationRepository!
override func setUp() {
super.setUp()
operationRepository = resolve()
}
func testGetOperationsState() {
let state = operationRepository.getOperationsState()
XCTAssertTrue(state == .confirmed)
let op = Factory.pendingIncomingOperation()
wait(for: operationRepository.storeOperations([op]))
let state2 = operationRepository.getOperationsState()
XCTAssertTrue(state2 == .pending)
let op2 = Factory.pendingIncomingOperation(isRBF: true)
wait(for: operationRepository.storeOperations([op2]))
let state3 = operationRepository.getOperationsState()
XCTAssertTrue(state3 == .cancelable)
}
func testHasPendingOperations() {
let op = Factory.operation(status: OperationStatus.SETTLED)
wait(for: operationRepository.storeOperations([op]))
XCTAssertFalse(operationRepository.hasPendingOperations())
let op2 = Factory.pendingOutgoingOperation()
wait(for: operationRepository.storeOperations([op2]))
XCTAssertTrue(operationRepository.hasPendingOperations())
}
func testHasPendingSwaps() {
let op = Factory.operation(status: OperationStatus.SWAP_PAYED)
wait(for: operationRepository.storeOperations([op]))
XCTAssertFalse(operationRepository.hasPendingSwaps())
let op2 = Factory.operation(status: .SWAP_PENDING)
wait(for: operationRepository.storeOperations([op2]))
XCTAssertTrue(operationRepository.hasPendingSwaps())
}
func testHasPendingIncomingSwaps() {
let op = Factory.pendingIncomingOperation()
wait(for: operationRepository.storeOperations([op]))
XCTAssertFalse(operationRepository.hasPendingIncomingSwaps())
let op2 = Factory.incomingSwapOperation(status: .SETTLED)
wait(for: operationRepository.storeOperations([op2]))
XCTAssertFalse(operationRepository.hasPendingIncomingSwaps())
let op3 = Factory.incomingSwapOperation(status: .BROADCASTED)
wait(for: operationRepository.storeOperations([op3]))
XCTAssertTrue(operationRepository.hasPendingIncomingSwaps())
}
}
| 30.679012 | 70 | 0.712274 |
1aa62996296fce3acde57f1c1c3d91378a7824e8 | 2,161 | //
// AppDelegate.swift
// ToDo List
//
// Created by NWPU on 15/12/2017.
// Copyright © 2017 NWPU. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.978723 | 285 | 0.75428 |
eb66193db471d6780098ef91856d6f5888566355 | 3,910 | public protocol DirectoryManager {
func homeDirectory() -> URL
func temporaryDirectory() -> URL
func documentDirectory() -> URL
func libraryDirectory() -> URL
func cachesDirectory() -> URL
func documentationDirectory() -> URL
func autosavedInformationDirectory() -> URL
func applicationSupportDirectory() -> URL
func inputMethodsDirectory() -> URL
func preferencePanesDirectory() -> URL
func applicationDirectory() -> URL
func demoApplicationDirectory() -> URL
func adminApplicationDirectory() -> URL
func developerDirectory() -> URL
func developerApplicationDirectory() -> URL
func desktopDirectory() -> URL
func downloadsDirectory() -> URL
func moviesDirectory() -> URL
func musicDirectory() -> URL
func picturesDirectory() -> URL
func sharedPublicDirectory() -> URL
}
public struct DirectoryManagerImp: DirectoryManager {
public init() {}
public func homeDirectory() -> URL {
return URL(fileURLWithPath: NSHomeDirectory())
}
public func temporaryDirectory() -> URL {
return URL(fileURLWithPath: NSTemporaryDirectory())
}
public func documentDirectory() -> URL {
return FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
}
public func libraryDirectory() -> URL {
return FileManager().urls(for: .libraryDirectory, in: .userDomainMask).first!
}
public func cachesDirectory() -> URL {
return FileManager().urls(for: .cachesDirectory, in: .userDomainMask).first!
}
public func documentationDirectory() -> URL {
return FileManager().urls(for: .documentationDirectory, in: .userDomainMask).first!
}
public func autosavedInformationDirectory() -> URL {
return FileManager().urls(for: .autosavedInformationDirectory, in: .userDomainMask).first!
}
public func applicationSupportDirectory() -> URL {
return FileManager().urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
}
public func inputMethodsDirectory() -> URL {
return FileManager().urls(for: .inputMethodsDirectory, in: .userDomainMask).first!
}
public func preferencePanesDirectory() -> URL {
return FileManager().urls(for: .preferencePanesDirectory, in: .userDomainMask).first!
}
public func applicationDirectory() -> URL {
return FileManager().urls(for: .applicationDirectory, in: .userDomainMask).first!
}
public func demoApplicationDirectory() -> URL {
return FileManager().urls(for: .demoApplicationDirectory, in: .userDomainMask).first!
}
public func adminApplicationDirectory() -> URL {
return FileManager().urls(for: .adminApplicationDirectory, in: .userDomainMask).first!
}
public func developerDirectory() -> URL {
return FileManager().urls(for: .developerDirectory, in: .userDomainMask).first!
}
public func developerApplicationDirectory() -> URL {
return FileManager().urls(for: .developerApplicationDirectory, in: .userDomainMask).first!
}
public func desktopDirectory() -> URL {
return FileManager().urls(for: .desktopDirectory, in: .userDomainMask).first!
}
public func downloadsDirectory() -> URL {
return FileManager().urls(for: .downloadsDirectory, in: .userDomainMask).first!
}
public func moviesDirectory() -> URL {
return FileManager().urls(for: .moviesDirectory, in: .userDomainMask).first!
}
public func musicDirectory() -> URL {
return FileManager().urls(for: .musicDirectory, in: .userDomainMask).first!
}
public func picturesDirectory() -> URL {
return FileManager().urls(for: .picturesDirectory, in: .userDomainMask).first!
}
public func sharedPublicDirectory() -> URL {
return FileManager().urls(for: .sharedPublicDirectory, in: .userDomainMask).first!
}
}
| 38.333333 | 98 | 0.68312 |
e822e78f5bef6d8e09a9125587c4f1fc1da49efd | 20,022 | //
// SpinWheelControl.swift
// SpinWheelControl
//
// Created by Josh Henry on 4/27/17.
// Copyright © 2017 Big Smash Software. All rights reserved.
//
//Trigonometry is used extensively in SpinWheel Control. Here is a quick refresher.
//Sine, Cosine and Tangent are each a ratio of sides of a right angled triangle
//Arc tangent (atan2) calculates the angles of a right triangle (tangent = Opposite / Adjacent)
//The sin is ratio of the length of the side that is opposite that angle to the length of the longest side of the triangle (the hypotenuse) (sin = Opposite / Hypotenuse)
//The cosine is (cosine = Adjacent / Hypotenuse)
import UIKit
public typealias Degrees = CGFloat
public typealias Radians = CGFloat
typealias Velocity = CGFloat
public enum SpinWheelStatus {
case idle, decelerating, snapping
}
public enum SpinWheelDirection {
case up, right, down, left
var radiansValue: Radians {
switch self {
case .up:
return Radians.pi / 2
case .right:
return 0
case .down:
return -(Radians.pi / 2)
case .left:
return Radians.pi
}
}
var degreesValue: Degrees {
switch self {
case .up:
return 90
case .right:
return 0
case .down:
return 270
case .left:
return 180
}
}
}
@objc public enum WedgeLabelOrientation: Int {
case inOut
case around
}
@IBDesignable
open class SpinWheelControl: UIControl {
//MARK: Properties
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var snapOrientation: CGFloat = SpinWheelDirection.up.degreesValue {
didSet {
snappingPositionRadians = snapOrientation.toRadians
}
}
@IBInspectable var wedgeLabelOrientation: Int {
get {
return self.wedgeLabelOrientationIndex.rawValue
}
set (wedgeLabelOrientationIndex) {
self.wedgeLabelOrientationIndex = WedgeLabelOrientation(rawValue: wedgeLabelOrientationIndex) ?? WedgeLabelOrientation.inOut
}
}
@objc weak public var dataSource: SpinWheelControlDataSource?
@objc public var delegate: SpinWheelControlDelegate?
@objc static let kMinimumRadiansForSpin: Radians = 0.1
@objc static let kMinDistanceFromCenter: CGFloat = 30.0
@objc static let kMaxVelocity: Velocity = 20
@objc static let kDecelerationVelocityMultiplier: CGFloat = 0.98 //The deceleration multiplier is not to be set past 0.99 in order to avoid issues
@objc static let kSpeedToSnap: CGFloat = 0.1
@objc static let kSnapRadiansProximity: Radians = 0.001
@objc static let kWedgeSnapVelocityMultiplier: CGFloat = 10.0
@objc static let kZoomZoneThreshold = 1.5
@objc static let kPreferredFramesPerSecond: Int = 60
@objc static let kMinRandomSpinVelocity: Velocity = 12
@objc static let kDefaultSpinVelocityMultiplier: Velocity = 0.75
//A circle = 360 degrees = 2 * pi radians
@objc let kCircleRadians: Radians = 2 * CGFloat.pi
@objc public var spinWheelView: UIView!
private var numberOfWedges: UInt!
private var radiansPerWedge: CGFloat!
@objc var decelerationDisplayLink: CADisplayLink? = nil
@objc var snapDisplayLink: CADisplayLink? = nil
var startTrackingTime: CFTimeInterval!
var endTrackingTime: CFTimeInterval!
var previousTouchRadians: Radians!
var currentTouchRadians: Radians!
var startTouchRadians: Radians!
var currentlyDetectingTap: Bool!
var currentStatus: SpinWheelStatus = .idle
var currentDecelerationVelocity: Velocity!
@objc var snappingPositionRadians: Radians = SpinWheelDirection.up.radiansValue
var snapDestinationRadians: Radians!
var snapIncrementRadians: Radians!
var wedgeLabelOrientationIndex: WedgeLabelOrientation = WedgeLabelOrientation.inOut
@objc public var selectedIndex: Int = 0
//MARK: Computed Properties
@objc var spinWheelCenter: CGPoint {
return convert(center, from: superview)
}
@objc var diameter: CGFloat {
return min(self.spinWheelView.frame.width, self.spinWheelView.frame.height)
}
@objc var degreesPerWedge: Degrees {
return 360 / CGFloat(numberOfWedges)
}
//The radius of the spin wheel's circle
@objc var radius: CGFloat {
return diameter / 2
}
//How far the wheel is turned from its default position
@objc var currentRadians: Radians {
return atan2(self.spinWheelView.transform.b, self.spinWheelView.transform.a)
}
//How many radians there are to snapDestinationRadians
@objc var radiansToDestinationSlice: Radians {
return snapDestinationRadians - currentRadians
}
//The velocity of the spinwheel
@objc var velocity: Velocity {
var computedVelocity: Velocity = 0
//If the wheel was actually spun, calculate the new velocity
if endTrackingTime != startTrackingTime &&
abs(previousTouchRadians - currentTouchRadians) >= SpinWheelControl.kMinimumRadiansForSpin {
computedVelocity = (previousTouchRadians - currentTouchRadians) / CGFloat(endTrackingTime - startTrackingTime)
}
//If the velocity is beyond the maximum allowed velocity, throttle it
if computedVelocity > SpinWheelControl.kMaxVelocity {
computedVelocity = SpinWheelControl.kMaxVelocity
}
else if computedVelocity < -SpinWheelControl.kMaxVelocity {
computedVelocity = -SpinWheelControl.kMaxVelocity
}
return computedVelocity
}
//MARK: Initialization Methods
override public init(frame: CGRect) {
super.init(frame: frame)
self.drawWheel()
}
public init(frame: CGRect, snapOrientation: SpinWheelDirection) {
super.init(frame: frame)
self.snappingPositionRadians = snapOrientation.radiansValue
self.drawWheel()
}
public init(frame: CGRect, wedgeLabelOrientation: WedgeLabelOrientation) {
super.init(frame: frame)
self.wedgeLabelOrientationIndex = wedgeLabelOrientation
self.drawWheel()
}
public init(frame: CGRect, snapOrientation: SpinWheelDirection, wedgeLabelOrientation: WedgeLabelOrientation) {
super.init(frame: frame)
self.wedgeLabelOrientationIndex = wedgeLabelOrientation
self.snappingPositionRadians = snapOrientation.radiansValue
self.drawWheel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.drawWheel()
}
//MARK: Methods
//Clear the SpinWheelControl from the screen
@objc public func clear() {
for subview in spinWheelView.subviews {
subview.removeFromSuperview()
}
guard let sublayers = spinWheelView.layer.sublayers else {
return
}
for sublayer in sublayers {
sublayer.removeFromSuperlayer()
}
}
//Draw the spinWheelView
@objc public func drawWheel() {
spinWheelView = UIView(frame: self.bounds)
guard self.dataSource?.numberOfWedgesInSpinWheel(spinWheel: self) != nil else {
return
}
numberOfWedges = self.dataSource?.numberOfWedgesInSpinWheel(spinWheel: self)
guard numberOfWedges >= 2 else {
return
}
radiansPerWedge = kCircleRadians / CGFloat(numberOfWedges)
guard let source = self.dataSource else {
return
}
for wedgeNumber in 0..<numberOfWedges {
let wedge: SpinWheelWedge = source.wedgeForSliceAtIndex(index: wedgeNumber)
//Wedge shape
wedge.shape.configureWedgeShape(index: wedgeNumber, radius: radius, position: spinWheelCenter, degreesPerWedge: degreesPerWedge)
wedge.layer.addSublayer(wedge.shape)
//Wedge label
wedge.label.configureWedgeLabel(index: wedgeNumber, width: radius * 0.9, position: spinWheelCenter, orientation: self.wedgeLabelOrientationIndex, radiansPerWedge: radiansPerWedge)
wedge.addSubview(wedge.label)
//Add the shape and label to the spinWheelView
spinWheelView.addSubview(wedge)
}
self.spinWheelView.isUserInteractionEnabled = false
//Rotate the wheel to put the first wedge at the top
self.spinWheelView.transform = CGAffineTransform(rotationAngle: -(snappingPositionRadians) - (radiansPerWedge / 2))
self.addSubview(self.spinWheelView)
}
//When the SpinWheelControl ends rotation, trigger the UIControl's valueChanged to reflect the newly selected value.
@objc func didEndRotationOnWedgeAtIndex(index: UInt) {
selectedIndex = Int(index)
delegate?.spinWheelDidEndDecelerating?(spinWheel: self)
self.sendActions(for: .valueChanged)
}
//User began touching/dragging the UIControl
override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
switch currentStatus {
case SpinWheelStatus.idle:
currentlyDetectingTap = true
case SpinWheelStatus.decelerating:
endDeceleration()
endSnap()
case SpinWheelStatus.snapping:
endSnap()
}
let touchPoint: CGPoint = touch.location(in: self)
if distanceFromCenter(point: touchPoint) < SpinWheelControl.kMinDistanceFromCenter {
return false
}
startTrackingTime = CACurrentMediaTime()
endTrackingTime = startTrackingTime
startTouchRadians = radiansForTouch(touch: touch)
currentTouchRadians = startTouchRadians
previousTouchRadians = startTouchRadians
return true
}
//User is in the middle of dragging the UIControl
override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
currentlyDetectingTap = false
startTrackingTime = endTrackingTime
endTrackingTime = CACurrentMediaTime()
let touchPoint: CGPoint = touch.location(in: self)
let distanceFromCenterOfSpinWheel: CGFloat = distanceFromCenter(point: touchPoint)
if distanceFromCenterOfSpinWheel < SpinWheelControl.kMinDistanceFromCenter {
return true
}
previousTouchRadians = currentTouchRadians
currentTouchRadians = radiansForTouch(touch: touch)
let touchRadiansDifference: Radians = currentTouchRadians - previousTouchRadians
self.spinWheelView.transform = self.spinWheelView.transform.rotated(by: touchRadiansDifference)
delegate?.spinWheelDidRotateByRadians?(radians: touchRadiansDifference)
return true
}
//User ended touching/dragging the UIControl
override open func endTracking(_ touch: UITouch?, with event: UIEvent?) {
let tapCount = touch?.tapCount != nil ? (touch?.tapCount)! : 0
//TODO: Implement tap to move to wedge
//If the user just tapped, move to that wedge
if currentStatus == .idle &&
tapCount > 0 &&
currentlyDetectingTap {}
//Else decelerate
else {
beginDeceleration()
}
}
//After user has lifted their finger from dragging, begin the deceleration
func beginDeceleration(withVelocity customVelocity: Velocity? = nil) {
if let customVelocity = customVelocity, customVelocity <= SpinWheelControl.kMaxVelocity {
currentDecelerationVelocity = customVelocity
} else {
currentDecelerationVelocity = velocity
}
//If the wheel was spun, begin deceleration
if currentDecelerationVelocity != 0 {
currentStatus = .decelerating
decelerationDisplayLink?.invalidate()
decelerationDisplayLink = CADisplayLink(target: self, selector: #selector(SpinWheelControl.decelerationStep))
if #available(iOS 10.0, *) {
decelerationDisplayLink?.preferredFramesPerSecond = SpinWheelControl.kPreferredFramesPerSecond
}
else {
decelerationDisplayLink?.frameInterval = SpinWheelControl.kPreferredFramesPerSecond
}
decelerationDisplayLink?.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
//Else snap to the nearest wedge. No deceleration necessary.
else {
snapToNearestWedge()
}
}
//Deceleration step run for each frame of decelerationDisplayLink
@objc func decelerationStep() {
let newVelocity: Velocity = currentDecelerationVelocity * SpinWheelControl.kDecelerationVelocityMultiplier
let radiansToRotate: Radians = currentDecelerationVelocity / CGFloat(SpinWheelControl.kPreferredFramesPerSecond)
//If the spinwheel has slowed down to under the minimum speed, end the deceleration
if newVelocity <= SpinWheelControl.kSpeedToSnap &&
newVelocity >= -SpinWheelControl.kSpeedToSnap {
endDeceleration()
}
//else continue decelerating the SpinWheel
else {
currentDecelerationVelocity = newVelocity
self.spinWheelView.transform = self.spinWheelView.transform.rotated(by: -radiansToRotate)
delegate?.spinWheelDidRotateByRadians?(radians: -radiansToRotate)
}
}
//End decelerating the spinwheel
@objc func endDeceleration() {
decelerationDisplayLink?.invalidate()
snapToNearestWedge()
}
//Snap to the nearest wedge
@objc func snapToNearestWedge() {
currentStatus = .snapping
let nearestWedge: Int = Int(round(((currentRadians + (radiansPerWedge / 2)) + snappingPositionRadians) / radiansPerWedge))
selectWedgeAtIndexOffset(index: nearestWedge, animated: true)
}
@objc func snapStep() {
let difference: Radians = atan2(sin(radiansToDestinationSlice), cos(radiansToDestinationSlice))
//If the spin wheel is turned close enough to the destination it is snapping to, end snapping
if abs(difference) <= SpinWheelControl.kSnapRadiansProximity {
endSnap()
}
//else continue snapping to the nearest wedge
else {
let newPositionRadians: Radians = currentRadians + snapIncrementRadians
self.spinWheelView.transform = CGAffineTransform(rotationAngle: newPositionRadians)
delegate?.spinWheelDidRotateByRadians?(radians: newPositionRadians)
}
}
//End snapping
@objc func endSnap() {
//snappingPositionRadians is the default snapping position (in this case, up)
//currentRadians in this case is where in the wheel it is currently snapped
//Distance of zero wedge from the default snap position (up)
var indexSnapped: Radians = (-(snappingPositionRadians) - currentRadians - (radiansPerWedge / 2))
//Number of wedges from the zero wedge to the default snap position (up)
indexSnapped = indexSnapped / radiansPerWedge + CGFloat(numberOfWedges)
indexSnapped = indexSnapped.rounded(FloatingPointRoundingRule.toNearestOrAwayFromZero)
indexSnapped = indexSnapped.truncatingRemainder(dividingBy: CGFloat(numberOfWedges))
didEndRotationOnWedgeAtIndex(index: UInt(indexSnapped))
snapDisplayLink?.invalidate()
currentStatus = .idle
}
//Return the radians at the touch point. Return values range from -pi to pi
@objc func radiansForTouch(touch: UITouch) -> Radians {
let touchPoint: CGPoint = touch.location(in: self)
let dx: CGFloat = touchPoint.x - self.spinWheelView.center.x
let dy: CGFloat = touchPoint.y - self.spinWheelView.center.y
return atan2(dy, dx)
}
//Select a wedge with an index offset relative to 0 position. May be positive or negative.
@objc func selectWedgeAtIndexOffset(index: Int, animated: Bool) {
snapDestinationRadians = -(snappingPositionRadians) + (CGFloat(index) * radiansPerWedge) - (radiansPerWedge / 2)
if currentRadians != snapDestinationRadians {
snapIncrementRadians = radiansToDestinationSlice / SpinWheelControl.kWedgeSnapVelocityMultiplier
}
else {
return
}
currentStatus = .snapping
snapDisplayLink?.invalidate()
snapDisplayLink = CADisplayLink(target: self, selector: #selector(snapStep))
if #available(iOS 10.0, *) {
snapDisplayLink?.preferredFramesPerSecond = SpinWheelControl.kPreferredFramesPerSecond
} else {
snapDisplayLink?.frameInterval = SpinWheelControl.kPreferredFramesPerSecond
}
snapDisplayLink?.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
//Distance of a point from the center of the spinwheel
@objc func distanceFromCenter(point: CGPoint) -> CGFloat {
let dx: CGFloat = point.x - spinWheelCenter.x
let dy: CGFloat = point.y - spinWheelCenter.y
return sqrt(dx * dx + dy * dy)
}
//Clear all views and redraw the spin wheel
@objc public func reloadData() {
clear()
drawWheel()
}
//Spin the wheel with a given velocity multiplier (or default velocity multiplier if no velocity provided)
//TODO: Due to a bug in Swift 4, private constants cannot be used as default arguments when Enable Testability is turned on. Therefore,
//the default velocity multiplier value is hand-coded until this is fixed.
//More info: https://bugs.swift.org/browse/SR-5111
// @objc public func spin(velocityMultiplier: CGFloat = SpinWheelControl.kDefaultSpinVelocityMultiplier) {
@objc public func spin(velocityMultiplier: CGFloat = 0.75) {
//If the velocity multiplier is valid, spin the wheel.
if (0...1).contains(velocityMultiplier) {
beginDeceleration(withVelocity: SpinWheelControl.kMaxVelocity * velocityMultiplier)
}
}
//Perform a random spin of the wheel
@objc public func randomSpin() {
//Get the range to find a random number between
let range = UInt32(SpinWheelControl.kMaxVelocity - SpinWheelControl.kMinRandomSpinVelocity)
//The velocity subtractor is a random number between 1 and the range value
let velocitySubtractor = Double(arc4random_uniform(range)) + 1
//Subtract the velocity subtractor from max velocity to get the final random velocity
let randomSpinVelocity = Velocity(Double(SpinWheelControl.kMaxVelocity) - velocitySubtractor)
//Get the spin multiplier using the new random spin velocity value
let randomSpinMultiplier = randomSpinVelocity / SpinWheelControl.kMaxVelocity
spin(velocityMultiplier: randomSpinMultiplier)
}
}
| 35.626335 | 191 | 0.653431 |
c1e9fcffbe7002829414346ef2acaafa286eb2ae | 526 | // Copyright Keefer Taylor, 2018
import Foundation
/// Parse the given data as a JSON encoded string representing an array of nested dictionaries.
public class JSONArrayResponseAdapter: AbstractResponseAdapter<[[String: Any]]> {
public override class func parse(input: Data) -> [[String: Any]]? {
do {
let json = try JSONSerialization.jsonObject(with: input)
guard let typedJSON = json as? [[String: Any]] else {
return nil
}
return typedJSON
} catch {
return nil
}
}
}
| 27.684211 | 95 | 0.669202 |
16f164e7f3fd5bed405d6adb8190e4a04503d94a | 449 | //
// MockedIntegerHTTPClient.swift
// CachingServiceTests
//
// Created by Alexander Cyon on 2017-11-15.
// Copyright © 2017 Alexander Cyon. All rights reserved.
//
import Foundation
final class MockedIntegerHTTPClient: BaseMockedHTTPClient<Int> {
init(mockedEvent: MockedEvent<Int>, reachability: MockedReachabilityService = MockedReachabilityService()) {
super.init(reachability: reachability, mockedEvent: mockedEvent)
}
}
| 28.0625 | 112 | 0.757238 |
6986476c2c5c2ea28d71f5f53bd490ab2d8408a9 | 6,779 | //
// MZRealmManager.swift
// Pods
//
// Created by muzcity on 2017. 6. 22..
//
//
import Foundation
import RealmSwift
final public class MZRealmManager : NSObject {
public typealias MZ_INT_HANDLER = ((Int)->())?
private var workerThread : dispatch_queue_t! = dispatch_queue_create("realm db worker thread", DISPATCH_QUEUE_SERIAL)
private var db : Realm!
private var token : NotificationToken!
public static var migrationList : [MZRealmMigratable.Type] = []
public static var SCHEMA_VERSION : UInt64 = 0
public override init() {
Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion : MZRealmManager.SCHEMA_VERSION, migrationBlock : { migration, oldSchemaVersion in
if (oldSchemaVersion < MZRealmManager.SCHEMA_VERSION) {
MZRealmManager.migrationList.forEach({ (dbModel) in
migration.enumerate(dbModel.objectName(), { (oldObject, newObject) in
dbModel.migration(oldSchemaVersion, oldObject: oldObject, newObject: newObject)
})
})
}
})
}
private static func fileCreateFailed() {
fatalError("db file create failed")
}
private static func makeRealmDB() -> Realm! {
return try? Realm()
}
private func createDb() {
if nil == db {
db = MZRealmManager.makeRealmDB()
}
if nil == db {
MZRealmManager.fileCreateFailed()
}
}
/**
* 해당 타입에 해당하는 카운트를 리턴한다.
*/
public func count<T : Object>(type: T.Type) -> Int {
var count : Int = 0
syncWorkerThread {
if let db = MZRealmManager.makeRealmDB() {
count = db.objects(type).count
}
}
return count
}
/**
* 비동기로 카운트를 얻는다.
*/
public func asyncCount<T : Object>(type:T.Type, handler : MZ_INT_HANDLER) {
asyncWorkerThread { [weak self] in
guard let `self` = self else {
handler?(0)
return
}
let count = self.count(type)
self.asyncMainThread({
handler?(count)
})
}
}
/**
* 조건절 추가. 해당 객체의 모든 데이터를 얻으려면 "" 입력.
*/
public func filter<T:Object>(type:T.Type, query : String = "" ) -> Results<T>? {
var resultAny : Any?
syncWorkerThread {
if let db = MZRealmManager.makeRealmDB() {
if query.isEmpty {
let results = db.objects(type)
resultAny = results
}
else {
let results = db.objects(type).filter(query)
resultAny = results
}
}
}
return resultAny as? Results<T>
}
/**
* 비동기 조건절 추가. 해당 객체의 모든 데이터를 얻으려면 "" 입력
*/
public func asyncFilter <T:Object>(type:T.Type, query : String = "", resultHandler:((Results<T>)->())?) {
asyncWorkerThread {
if let db = MZRealmManager.makeRealmDB() {
if query.isEmpty {
let results = db.objects(type)
resultHandler?(results)
}
else {
let results = db.objects(type).filter(query)
resultHandler?(results)
}
}
else {
MZRealmManager.fileCreateFailed()
}
}
}
/**
* 디비에 객체를 때려박는다.
*/
public func add(object obj:Object) {
createDb()
try! db.write({
db.add(obj)
})
}
/**
* 비동기로 디비에 객체를 쑤셔넣는다.
*/
public func asyncAdd(object obj:Object) {
asyncWorkerThread {
if let db = MZRealmManager.makeRealmDB() {
try! db.write({
db.add(obj)
})
}
else {
MZRealmManager.fileCreateFailed()
}
}
}
/**
* 해당 객체 제거
*/
public func remove(object obj:Object) {
createDb()
try! db.write({
db.delete(obj)
})
}
/**
* 비동기로 해당 객체 제거
*/
public func asyncRemove(object obj:Object) {
asyncWorkerThread {
if let db = MZRealmManager.makeRealmDB() {
try! db.write({
db.delete(obj)
})
}
else {
MZRealmManager.fileCreateFailed()
}
}
}
/**
* 노티 등록
*/
public func addNotifications<T>(target: Results<T>, completeHandler:(( obj : Results<T>, deletions : [Int], insertions : [Int], modifications : [Int] )->())?) {
token = target.addNotificationBlock { (changes) in
switch changes {
case .Initial( _) :
// print("init")
break
case .Update(let f, deletions: let deletions, insertions: let insertions, modifications: let modifications):
completeHandler?(obj: f, deletions: deletions, insertions: insertions, modifications: modifications)
default :
break
}
}
}
/**
* 노티해제
*/
public func removeNotifications() {
if nil != token {
token.stop()
}
}
//메인쓰레드로 블럭내를 실행시킨다.
private func asyncMainThread(block: ()->()) {
dispatch_async(dispatch_get_main_queue(), {
autoreleasepool(block)
})
}
private func asyncWorkerThread(block: ()->()) {
dispatch_async(workerThread, {
autoreleasepool(block)
})
}
private func syncWorkerThread(block: ()->()) {
dispatch_sync(workerThread, {
autoreleasepool(block)
})
}
deinit {
if nil != token {
token.stop()
token = nil
}
}
}
| 23.538194 | 167 | 0.439888 |
72d65794e4df3fc233ce9dde083406a26d99097d | 6,020 | //
// SideMenuProfileCollectionView.swift
// Monotone
//
// Created by Xueliang Chen on 2020/12/18.
//
import Foundation
import RxSwift
import RxRelay
class SideMenuProfileCollectionView: BaseView{
// MARK: - Public
var collection: BehaviorRelay<Collection?> = BehaviorRelay<Collection?>(value: nil)
// MARK: - Controls
private var photoContainerView: UIView!
private var photoAImageView: UIImageView!
private var photoBImageView: UIImageView!
private var photoCImageView: UIImageView!
private var titleLabel: UILabel!
private var descriptionLabel: UILabel!
// MARK: - Private
private let disposeBag: DisposeBag = DisposeBag()
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func buildSubviews() {
super.buildSubviews()
// PhotoContainerView
self.photoContainerView = UIView()
self.addSubview(self.photoContainerView)
self.photoContainerView.snp.makeConstraints { (make) in
make.top.right.left.equalTo(self)
}
// PhotoAImageView
self.photoAImageView = UIImageView()
self.photoAImageView.contentMode = .scaleAspectFill
self.photoAImageView.backgroundColor = ColorPalette.colorGrayLighter
self.photoAImageView.layer.masksToBounds = true
self.photoAImageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
self.photoAImageView.setContentHuggingPriority(.defaultLow, for: .vertical)
self.photoContainerView.addSubview(self.photoAImageView)
self.photoAImageView.snp.makeConstraints { (make) in
make.top.left.equalTo(self.photoContainerView)
make.bottom.equalTo(self.photoContainerView.snp.bottom).multipliedBy(1.0/3).offset(-2.0)
make.right.equalTo(self.photoContainerView.snp.right).multipliedBy(1.0/2).offset(-2.0)
}
// PhotoBImageView
self.photoBImageView = UIImageView()
self.photoBImageView.contentMode = .scaleAspectFill
self.photoBImageView.backgroundColor = ColorPalette.colorGrayLighter
self.photoBImageView.layer.masksToBounds = true
self.photoBImageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
self.photoBImageView.setContentHuggingPriority(.defaultLow, for: .vertical)
self.photoContainerView.addSubview(self.photoBImageView)
self.photoBImageView.snp.makeConstraints { (make) in
make.left.bottom.equalTo(self.photoContainerView)
make.top.equalTo(self.photoContainerView.snp.bottom).multipliedBy(1.0/3).offset(2.0)
make.right.equalTo(self.photoContainerView.snp.right).multipliedBy(1.0/2).offset(-2.0)
}
// PhotoCImageView
self.photoCImageView = UIImageView()
self.photoCImageView.contentMode = .scaleAspectFill
self.photoCImageView.backgroundColor = ColorPalette.colorGrayLighter
self.photoCImageView.layer.masksToBounds = true
self.photoCImageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
self.photoCImageView.setContentHuggingPriority(.defaultLow, for: .vertical)
self.photoContainerView.addSubview(self.photoCImageView)
self.photoCImageView.snp.makeConstraints { (make) in
make.top.right.bottom.equalTo(self.photoContainerView)
make.left.equalTo(self.photoContainerView.snp.right).multipliedBy(1.0/2).offset(2.0)
}
// TitleLabel
self.titleLabel = UILabel()
self.titleLabel.textColor = ColorPalette.colorBlack
self.titleLabel.font = UIFont.boldSystemFont(ofSize: 12)
self.titleLabel.text = "nil"
self.addSubview(self.titleLabel)
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.top.equalTo(self.photoContainerView.snp.bottom).offset(7.0)
}
// DescriptionLabel
self.descriptionLabel = UILabel()
self.descriptionLabel.textColor = ColorPalette.colorGrayLight
self.descriptionLabel.font = UIFont.systemFont(ofSize: 12)
self.descriptionLabel.text = "0 photos · Curated by nil"
self.addSubview(self.descriptionLabel)
self.descriptionLabel.snp.makeConstraints { (make) in
make.left.bottom.equalTo(self)
make.top.equalTo(self.titleLabel.snp.bottom).offset(7.0)
}
}
override func buildLogic() {
super.buildLogic()
// Bindings.
// Collection.
self.collection
.unwrap()
.subscribe(onNext:{ [weak self] (collection) in
guard let self = self else { return }
let editor = collection.sponsorship?.sponsor ?? collection.user
self.titleLabel.text = collection.title
self.descriptionLabel.text = String(format: NSLocalizedString("uns_side_menu_collection_description",
comment: "%d Photos · Curated by %@"),
collection.totalPhotos ?? 0,
editor?.username ?? "")
collection.previewPhotos?
.prefix(self.photoContainerView.subviews.count)
.enumerated()
.forEach({ (index, element) in
let imageView = self.photoContainerView.subviews[index] as! UIImageView
imageView.setPhoto(photo: element, size: .small)
})
})
.disposed(by: self.disposeBag)
}
}
| 41.805556 | 117 | 0.63289 |
ab71a52df7805cc561447631468314918c17a10f | 509 | import XCTest
import SubstrateSdk
class ScaleInfoMappingTests: XCTestCase {
func testCamelCaseMapping() throws {
let mapper = ScaleInfoCamelCaseMapper()
XCTAssertEqual("miscFrozen", mapper.map(name: "misc_frozen"))
XCTAssertEqual("feeFrozenMiscFrozen", mapper.map(name: "fee_frozen_misc_frozen"))
XCTAssertEqual("Fee", mapper.map(name: "Fee"))
XCTAssertEqual("miscFrozen", mapper.map(name: "miscFrozen"))
XCTAssertEqual("", mapper.map(name: ""))
}
}
| 31.8125 | 89 | 0.691552 |
21ab900c4a3f62ac51c65ed127ab1b45d451e188 | 68,295 | import Foundation
/// A raw SQLite connection, suitable for the SQLite C API.
public typealias SQLiteConnection = OpaquePointer
/// A raw SQLite function argument.
typealias SQLiteValue = OpaquePointer
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// A Database connection.
///
/// You don't create a database directly. Instead, you use a DatabaseQueue, or
/// a DatabasePool:
///
/// let dbQueue = DatabaseQueue(...)
///
/// // The Database is the `db` in the closure:
/// try dbQueue.write { db in
/// try Player(...).insert(db)
/// }
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
// The Database class is not thread-safe. An instance should always be
// used through a SerializedDatabase.
// MARK: - SQLite C API
/// The raw SQLite connection, suitable for the SQLite C API.
/// It is constant, until close() sets it to nil.
public var sqliteConnection: SQLiteConnection?
// MARK: - Configuration
/// The error logging function.
///
/// Quoting <https://www.sqlite.org/errlog.html>:
///
/// > SQLite can be configured to invoke a callback function containing an
/// > error code and a terse error message whenever anomalies occur. This
/// > mechanism is very helpful in tracking obscure problems that occur
/// > rarely and in the field. Application developers are encouraged to take
/// > advantage of the error logging facility of SQLite in their products,
/// > as it is very low CPU and memory cost but can be a huge aid
/// > for debugging.
public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
registerErrorLogCallback { (_, code, message) in
guard let logError = Database.logError else { return }
guard let message = message.map(String.init) else { return }
let resultCode = ResultCode(rawValue: code)
logError(resultCode, message)
}
} else {
registerErrorLogCallback(nil)
}
}
}
/// The database configuration
public let configuration: Configuration
/// See `Configuration.label`
public let description: String
public var debugDescription: String { "<Database: \(description)>" }
// MARK: - Database Information
/// The rowID of the most recently inserted row.
///
/// If no row has ever been inserted using this database connection,
/// returns zero.
///
/// For more detailed information, see <https://www.sqlite.org/c3ref/last_insert_rowid.html>
public var lastInsertedRowID: Int64 {
SchedulingWatchdog.preconditionValidQueue(self)
return sqlite3_last_insert_rowid(sqliteConnection)
}
/// The number of rows modified, inserted or deleted by the most recent
/// successful INSERT, UPDATE or DELETE statement.
///
/// For more detailed information, see <https://www.sqlite.org/c3ref/changes.html>
public var changesCount: Int {
SchedulingWatchdog.preconditionValidQueue(self)
return Int(sqlite3_changes(sqliteConnection))
}
/// The total number of rows modified, inserted or deleted by all successful
/// INSERT, UPDATE or DELETE statements since the database connection was
/// opened.
///
/// For more detailed information, see <https://www.sqlite.org/c3ref/total_changes.html>
public var totalChangesCount: Int {
SchedulingWatchdog.preconditionValidQueue(self)
return Int(sqlite3_total_changes(sqliteConnection))
}
/// True if the database connection is currently in a transaction.
public var isInsideTransaction: Bool {
// https://sqlite.org/c3ref/get_autocommit.html
//
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
// > the given database connection is or is not in autocommit mode,
// > respectively.
//
// > Autocommit mode is on by default. Autocommit mode is disabled by a
// > BEGIN statement. Autocommit mode is re-enabled by a COMMIT
// > or ROLLBACK.
//
// > If another thread changes the autocommit status of the database
// > connection while this routine is running, then the return value
// > is undefined.
SchedulingWatchdog.preconditionValidQueue(self)
if sqliteConnection == nil { return false } // Support for SerializedDatabase.deinit
return sqlite3_get_autocommit(sqliteConnection) == 0
}
/// The last error code
public var lastErrorCode: ResultCode { ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
/// The last error message
public var lastErrorMessage: String? { String(cString: sqlite3_errmsg(sqliteConnection)) }
// MARK: - Internal properties
// Caches
struct SchemaCache {
var schemaIdentifiers: [SchemaIdentifier]?
fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:]
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
get {
schemas[schemaID] ?? DatabaseSchemaCache()
}
set {
schemas[schemaID] = newValue
}
}
mutating func clear() {
schemaIdentifiers = nil
schemas.removeAll()
}
}
var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded()
var schemaCache = SchemaCache()
lazy var internalStatementCache = StatementCache(database: self)
lazy var publicStatementCache = StatementCache(database: self)
/// Statement authorizer. Use withAuthorizer(_:_:).
fileprivate var _authorizer: StatementAuthorizer?
// Transaction observers management
lazy var observationBroker = DatabaseObservationBroker(self)
/// The list of compile options used when building SQLite
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS"))
}
/// If true, select statement execution is recorded.
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
var _isRecordingSelectedRegion = false
var _selectedRegion = DatabaseRegion()
/// Support for checkForAbortedTransaction()
var isInsideTransactionBlock = false
/// Support for checkForSuspensionViolation(from:)
@LockedBox var isSuspended = false
/// Support for checkForSuspensionViolation(from:)
/// This cache is never cleared: we assume journal mode never changes.
var journalModeCache: String?
// MARK: - Private properties
private var busyCallback: BusyCallback?
private var trace: ((TraceEvent) -> Void)?
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
// MARK: - Initializer
init(
path: String,
description: String,
configuration: Configuration) throws
{
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.description = description
self.configuration = configuration
}
deinit {
assert(sqliteConnection == nil)
}
// MARK: - Database Opening
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
// See <https://www.sqlite.org/c3ref/open.html>
var sqliteConnection: SQLiteConnection? = nil
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
guard code == SQLITE_OK else {
// https://www.sqlite.org/c3ref/open.html
// > Whether or not an error occurs when it is opened, resources
// > associated with the database connection handle should be
// > released by passing it to sqlite3_close() when it is no
// > longer required.
//
// https://www.sqlite.org/c3ref/close.html
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
// > pointer argument is a harmless no-op.
_ = sqlite3_close(sqliteConnection) // ignore result code
throw DatabaseError(resultCode: code)
}
if let sqliteConnection = sqliteConnection {
return sqliteConnection
}
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
}
// MARK: - Database Setup
/// This method must be called after database initialization
func setUp() throws {
setupBusyMode()
setupDoubleQuotedStringLiterals()
try setupForeignKeys()
setupDefaultFunctions()
setupDefaultCollations()
setupAuthorizer()
observationBroker.installCommitAndRollbackHooks()
try activateExtendedCodes()
#if SQLITE_HAS_CODEC
try validateSQLCipher()
#endif
// Last step before we can start accessing the database.
try configuration.setUp(self)
try validateFormat()
configuration.SQLiteConnectionDidOpen?()
}
private func setupDoubleQuotedStringLiterals() {
if configuration.acceptsDoubleQuotedStringLiterals {
enableDoubleQuotedStringLiterals(sqliteConnection)
} else {
disableDoubleQuotedStringLiterals(sqliteConnection)
}
}
private func setupForeignKeys() throws {
// Foreign keys are disabled by default with SQLite3
if configuration.foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = ON")
}
}
private func setupBusyMode() {
let busyMode = configuration.readonly
? configuration.readonlyBusyMode ?? configuration.busyMode
: configuration.busyMode
switch busyMode {
case .immediateError:
break
case .timeout(let duration):
let milliseconds = Int32(duration * 1000)
sqlite3_busy_timeout(sqliteConnection, milliseconds)
case .callback(let callback):
busyCallback = callback
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_busy_handler(
sqliteConnection,
{ (dbPointer, numberOfTries) in
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
let callback = db.busyCallback!
return callback(Int(numberOfTries)) ? 1 : 0
},
dbPointer)
}
}
private func setupDefaultFunctions() {
add(function: .capitalize)
add(function: .lowercase)
add(function: .uppercase)
if #available(OSX 10.11, watchOS 3.0, *) {
add(function: .localizedCapitalize)
add(function: .localizedLowercase)
add(function: .localizedUppercase)
}
}
private func setupDefaultCollations() {
add(collation: .unicodeCompare)
add(collation: .caseInsensitiveCompare)
add(collation: .localizedCaseInsensitiveCompare)
add(collation: .localizedCompare)
add(collation: .localizedStandardCompare)
}
private func setupAuthorizer() {
// SQLite authorizer is set only once per database connection.
//
// This is because authorizer changes have SQLite invalidate statements,
// with undesired side effects. See:
//
// - DatabaseCursorTests.testIssue583()
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(
sqliteConnection,
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
let db = Unmanaged<Database>.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue()
guard let authorizer = db._authorizer else {
return SQLITE_OK
}
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
},
dbPointer)
}
private func activateExtendedCodes() throws {
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
#if SQLITE_HAS_CODEC
private func validateSQLCipher() throws {
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
//
// > In order to avoid situations where SQLite might be used
// > improperly at runtime, we strongly recommend that
// > applications institute a runtime test to ensure that the
// > application is actually using SQLCipher on the active
// > connection.
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
GRDB is not linked against SQLCipher. \
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
""")
}
}
#endif
private func validateFormat() throws {
// Users are surprised when they open a picture as a database and
// see no error (https://github.com/groue/GRDB.swift/issues/54).
//
// So let's fail early if file is not a database, or encrypted with
// another passphrase.
try makeStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
}
// MARK: - Database Closing
/// Closes a connection with `sqlite3_close`. This method is intended for
/// the public `close()` function. It may fail.
func close() throws {
SchedulingWatchdog.preconditionValidQueue(self)
guard let sqliteConnection = sqliteConnection else {
// Already closed
return
}
configuration.SQLiteConnectionWillClose?(sqliteConnection)
internalStatementCache.clear()
publicStatementCache.clear()
// https://www.sqlite.org/c3ref/close.html
// > If the database connection is associated with unfinalized prepared
// > statements or unfinished sqlite3_backup objects then
// > sqlite3_close() will leave the database connection open and
// > return SQLITE_BUSY.
let code = sqlite3_close(sqliteConnection)
guard code == SQLITE_OK else {
if let log = Self.logError {
if code == SQLITE_BUSY {
// Let the user know about unfinalized statements that did
// prevent the connection from closing properly.
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))")
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
}
}
}
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
self.sqliteConnection = nil
configuration.SQLiteConnectionDidClose?()
}
/// Closes a connection with `sqlite3_close_v2`. This method is intended for
/// deallocated connections.
func close_v2() {
SchedulingWatchdog.preconditionValidQueue(self)
guard let sqliteConnection = sqliteConnection else {
// Already closed
return
}
configuration.SQLiteConnectionWillClose?(sqliteConnection)
internalStatementCache.clear()
publicStatementCache.clear()
// https://www.sqlite.org/c3ref/close.html
// > If sqlite3_close_v2() is called with unfinalized prepared
// > statements and/or unfinished sqlite3_backups, then the database
// > connection becomes an unusable "zombie" which will automatically
// > be deallocated when the last prepared statement is finalized or the
// > last sqlite3_backup is finished.
// >
// > The sqlite3_close_v2() interface is intended for use with host
// > languages that are garbage collected, and where the order in which
// > destructors are called is arbitrary.
let code = sqlite3_close_v2(sqliteConnection)
if code != SQLITE_OK, let log = Self.logError {
// A rare situation where GRDB doesn't fatalError on
// unprocessed errors.
let message = String(cString: sqlite3_errmsg(sqliteConnection))
log(ResultCode(rawValue: code), "could not close database: \(message)")
}
self.sqliteConnection = nil
configuration.SQLiteConnectionDidClose?()
}
// MARK: - Limits
/// The maximum number of arguments accepted by an SQLite statement.
///
/// For example, requests such as the one below must make sure the `ids`
/// array does not contain more than `maximumStatementArgumentCount`
/// elements:
///
/// let ids: [Int] = ...
/// try dbQueue.write { db in
/// try Player.deleteAll(db, keys: ids)
/// }
///
/// See <https://www.sqlite.org/limits.html>
/// and `SQLITE_LIMIT_VARIABLE_NUMBER`.
public var maximumStatementArgumentCount: Int {
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
}
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
/// }
/// db.add(function: fn)
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
public func add(function: DatabaseFunction) {
functions.update(with: function)
function.install(in: self)
}
/// Remove an SQL function.
public func remove(function: DatabaseFunction) {
functions.remove(function)
function.uninstall(in: self)
}
// MARK: - Collations
/// Add or redefine a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.add(collation: collation)
/// try db.execute(sql: "CREATE TABLE files (name TEXT COLLATE localized_standard")
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
let collationPointer = Unmanaged.passUnretained(collation).toOpaque()
let code = sqlite3_create_collation_v2(
sqliteConnection,
collation.name,
SQLITE_UTF8,
collationPointer,
{ (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
return Int32(collation.function(length1, buffer1, length2, buffer2).rawValue)
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
}
}
/// Remove a collation.
public func remove(collation: DatabaseCollation) {
collations.remove(collation)
sqlite3_create_collation_v2(
sqliteConnection,
collation.name,
SQLITE_UTF8,
nil, nil, nil)
}
// MARK: - Read-Only Access
func beginReadOnly() throws {
if configuration.readonly { return }
if _readOnlyDepth == 0 {
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
}
_readOnlyDepth += 1
}
func endReadOnly() throws {
if configuration.readonly { return }
_readOnlyDepth -= 1
if _readOnlyDepth == 0 {
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
}
}
/// Grants read-only access, starting SQLite 3.8.0
func readOnly<T>(_ block: () throws -> T) throws -> T {
try beginReadOnly()
return try throwingFirstError(
execute: block,
finally: endReadOnly)
}
// MARK: - Snapshots
#if SQLITE_ENABLE_SNAPSHOT
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &snapshot) {
sqlite3_snapshot_get(sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
if let snapshot = snapshot {
return snapshot
} else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
}
}
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
let secondSnapshot = try takeVersionSnapshot()
defer {
sqlite3_snapshot_free(secondSnapshot)
}
let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot)
assert(cmp <= 0, "Unexpected snapshot ordering")
return cmp < 0
}
#endif
// MARK: - Authorizer
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
SchedulingWatchdog.preconditionValidQueue(self)
let old = self._authorizer
self._authorizer = authorizer
defer { self._authorizer = old }
return try block()
}
// MARK: - Recording of the selected region
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
if region.isFullDatabase {
return try block()
}
let oldFlag = self._isRecordingSelectedRegion
let oldRegion = self._selectedRegion
_isRecordingSelectedRegion = true
_selectedRegion = DatabaseRegion()
defer {
region.formUnion(_selectedRegion)
_isRecordingSelectedRegion = oldFlag
if _isRecordingSelectedRegion {
_selectedRegion = oldRegion.union(_selectedRegion)
} else {
_selectedRegion = oldRegion
}
}
return try block()
}
// MARK: - Trace
/// Registers a tracing function.
///
/// For example:
///
/// // Trace all SQL statements executed by the database
/// var configuration = Configuration()
/// configuration.prepareDatabase { db in
/// db.trace(options: .statement) { event in
/// print("SQL: \(event)")
/// }
/// }
/// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
///
/// Pass an empty options set in order to stop database tracing:
///
/// // Stop tracing
/// db.trace(options: [])
///
/// See <https://www.sqlite.org/c3ref/trace_v2.html> for more information.
///
/// - parameter options: The set of desired event kinds. Defaults to
/// `.statement`, which notifies all executed database statements.
/// - parameter trace: the tracing function.
public func trace(options: TracingOptions = .statement, _ trace: ((TraceEvent) -> Void)? = nil) {
SchedulingWatchdog.preconditionValidQueue(self)
self.trace = trace
if options.isEmpty || trace == nil {
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
#elseif os(Linux)
sqlite3_trace(sqliteConnection, nil)
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
} else {
sqlite3_trace(sqliteConnection, nil, nil)
}
#endif
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
// It is available from macOS 10.12, tvOS 10.0, watchOS 3.0
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
return SQLITE_OK
}, dbPointer)
#elseif os(Linux)
setupTrace_v1()
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
return SQLITE_OK
}, dbPointer)
} else {
setupTrace_v1()
}
#endif
}
#if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS))
private func setupTrace_v1() {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map(String.init(cString:)) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql))))
}, dbPointer)
}
#endif
// Precondition: configuration.trace != nil
private func trace_v2(
_ mask: CInt,
_ p: UnsafeMutableRawPointer?,
_ x: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
{
guard let trace = trace else { return }
switch mask {
case SQLITE_TRACE_STMT:
if let sqliteStatement = p, let unexpandedSQL = x {
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql))
trace(TraceEvent.statement(statement))
}
case SQLITE_TRACE_PROFILE:
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql))
let duration = TimeInterval(durationP.pointee) / 1.0e9
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
trace(TraceEvent.profile(statement: statement, duration: duration))
#elseif os(Linux)
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
trace(TraceEvent.profile(statement: statement, duration: duration))
}
#endif
}
default:
break
}
}
// MARK: - WAL Checkpoints
/// Runs a WAL checkpoint.
///
/// See <https://www.sqlite.org/wal.html> and
/// <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html> for
/// more information.
///
/// - parameter kind: The checkpoint mode (default passive)
/// - parameter dbName: The database name (default "main")
/// - returns: A tuple:
/// - `walFrameCount`: the total number of frames in the log file
/// - `checkpointedFrameCount`: the total number of checkpointed frames
/// in the log file
@discardableResult
public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws
-> (walFrameCount: Int, checkpointedFrameCount: Int)
{
SchedulingWatchdog.preconditionValidQueue(self)
var walFrameCount: CInt = -1
var checkpointedFrameCount: CInt = -1
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue,
&walFrameCount, &checkpointedFrameCount)
switch code {
case SQLITE_OK:
return (walFrameCount: Int(walFrameCount), checkpointedFrameCount: Int(checkpointedFrameCount))
case SQLITE_MISUSE:
throw DatabaseError(resultCode: code)
default:
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
}
// MARK: - Interrupt
// See <https://www.sqlite.org/c3ref/interrupt.html>
func interrupt() {
sqlite3_interrupt(sqliteConnection)
}
// MARK: - Database Suspension
/// When this notification is posted, databases which were opened with the
/// `Configuration.observesSuspensionNotifications` flag are suspended.
///
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public static let suspendNotification = Notification.Name("GRDB.Database.Suspend")
/// When this notification is posted, databases which were opened with the
/// `Configuration.observesSuspensionNotifications` flag are resumed.
///
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public static let resumeNotification = Notification.Name("GRDB.Database.Resume")
/// Suspends the database. A suspended database prevents database locks in
/// order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
///
/// This method can be called from any thread.
///
/// During suspension, any lock is released as soon as possible, and
/// lock acquisition is prevented. All database accesses may throw a
/// DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except
/// reads in WAL mode.
///
/// Suspension ends with resume().
func suspend() {
$isSuspended.update { isSuspended in
if isSuspended {
return
}
// Prevent future lock acquisition
isSuspended = true
// Interrupt the database because this may trigger an
// SQLITE_INTERRUPT error which may itself abort a transaction and
// release a lock. See <https://www.sqlite.org/c3ref/interrupt.html>
interrupt()
// Now what about the eventual remaining lock? We'll issue a
// rollback on next database access which requires a lock, in
// checkForSuspensionViolation(from:).
}
}
/// Resumes the database. A resumed database stops preventing database locks
/// in order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
///
/// This method can be called from any thread.
///
/// See suspend().
func resume() {
isSuspended = false
}
/// Support for checkForSuspensionViolation(from:)
private func journalMode() throws -> String {
if let journalMode = journalModeCache {
return journalMode
}
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
var statement: SQLiteStatement? = nil
let sql = "PRAGMA journal_mode"
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
sqlite3_step(statement)
guard let cString = sqlite3_column_text(statement, 0) else {
throw DatabaseError(resultCode: lastErrorCode, message: lastErrorMessage, sql: sql)
}
let journalMode = String(cString: cString)
journalModeCache = journalMode
return journalMode
}
/// Throws SQLITE_ABORT for suspended databases, if statement would lock
/// the database, in order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
func checkForSuspensionViolation(from statement: Statement) throws {
try $isSuspended.read { isSuspended in
guard isSuspended else {
return
}
if try journalMode() == "wal" && statement.isReadonly {
// In WAL mode, accept read-only statements:
// - SELECT ...
// - BEGIN DEFERRED TRANSACTION
//
// Those are not read-only:
// - INSERT ...
// - BEGIN IMMEDIATE TRANSACTION
return
}
if statement.releasesDatabaseLock {
// Accept statements that release locks:
// - COMMIT
// - ROLLBACK
// - ROLLBACK TRANSACTION TO SAVEPOINT
// - RELEASE SAVEPOINT
return
}
// Attempt at releasing an eventual lock with ROLLBACk,
// as explained in Database.suspend().
//
// Use sqlite3_exec instead of `try? rollback()` in order to avoid
// an infinite loop in checkForSuspensionViolation(from:)
_ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil)
throw DatabaseError(
resultCode: .SQLITE_ABORT,
message: "Database is suspended",
sql: statement.sql,
arguments: statement.arguments)
}
}
// MARK: - Transactions & Savepoint
/// Throws SQLITE_ABORT if called from a transaction-wrapping method and
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or a
/// `ON CONFLICT ROLLBACK` clause.
///
/// try db.inTransaction {
/// do {
/// // Aborted by sqlite3_interrupt or any other
/// // SQLite error which leaves transaction
/// ...
/// } catch { ... }
///
/// // <- Here we're inside an aborted transaction.
/// try checkForAbortedTransaction(...) // throws
/// ...
///
/// return .commit
/// }
func checkForAbortedTransaction(
sql: @autoclosure () -> String? = nil,
arguments: @autoclosure () -> StatementArguments? = nil)
throws
{
if isInsideTransactionBlock && sqlite3_get_autocommit(sqliteConnection) != 0 {
throw DatabaseError(
resultCode: .SQLITE_ABORT,
message: "Transaction was aborted",
sql: sql(),
arguments: arguments())
}
}
/// Executes a block inside a database transaction.
///
/// try dbQueue.inDatabase do {
/// try db.inTransaction {
/// try db.execute(sql: "INSERT ...")
/// return .commit
/// }
/// }
///
/// If the block throws an error, the transaction is rollbacked and the
/// error is rethrown.
///
/// This method is not reentrant: you can't nest transactions.
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .commit or .rollback.
/// - throws: The error thrown by the block.
public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws {
// Begin transaction
try beginTransaction(kind)
let wasInsideTransactionBlock = isInsideTransactionBlock
isInsideTransactionBlock = true
defer {
isInsideTransactionBlock = wasInsideTransactionBlock
}
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
let needsRollback: Bool
do {
let completion = try block()
switch completion {
case .commit:
// In case of aborted transaction, throw SQLITE_ABORT instead
// of the generic SQLITE_ERROR "cannot commit - no transaction is active"
try checkForAbortedTransaction()
// Leave transaction block now, so that transaction observers
// can execute statements without getting errors from
// checkForAbortedTransaction().
isInsideTransactionBlock = wasInsideTransactionBlock
try commit()
needsRollback = false
case .rollback:
needsRollback = true
}
} catch {
firstError = error
needsRollback = true
}
if needsRollback {
do {
try rollback()
} catch {
if firstError == nil {
firstError = error
}
}
}
if let firstError = firstError {
throw firstError
}
}
/// Runs the block with an isolation level equal or greater than
/// snapshot isolation.
func isolated<T>(readOnly: Bool = false, _ block: () throws -> T) throws -> T {
var result: T?
try inSavepoint {
if readOnly {
result = try self.readOnly(block)
} else {
result = try block()
}
return .commit
}
return result!
}
/// Executes a block inside a savepoint.
///
/// try dbQueue.inDatabase do {
/// try db.inSavepoint {
/// try db.execute(sql: "INSERT ...")
/// return .commit
/// }
/// }
///
/// If the block throws an error, the savepoint is rollbacked and the
/// error is rethrown.
///
/// This method is reentrant: you can nest savepoints.
///
/// - parameter block: A block that executes SQL statements and return
/// either .commit or .rollback.
/// - throws: The error thrown by the block.
public func inSavepoint(_ block: () throws -> TransactionCompletion) throws {
if !isInsideTransaction {
// By default, top level SQLite savepoints open a
// deferred transaction.
//
// But GRDB database configuration mandates a default transaction
// kind that we have to honor.
//
// Besides, starting some (?) SQLCipher/SQLite version, SQLite has a
// bug. Returning 1 from `sqlite3_commit_hook` does not leave the
// database in the autocommit mode, as expected after a rollback.
// This bug only happens, as far as we know, when a transaction is
// started with a savepoint:
//
// SAVEPOINT test;
// CREATE TABLE t(a);
// -- Rollbacked with sqlite3_commit_hook:
// RELEASE SAVEPOINT test;
// -- Not in the autocommit mode here!
//
// For those two reasons, we open a transaction instead of a
// top-level savepoint.
try inTransaction(configuration.defaultTransactionKind, block)
return
}
// Begin savepoint
//
// We use a single name for savepoints because there is no need
// using unique savepoint names. User could still mess with them
// with raw SQL queries, but let's assume that it is unlikely that
// the user uses "grdb" as a savepoint name.
try execute(sql: "SAVEPOINT grdb")
let wasInsideTransactionBlock = isInsideTransactionBlock
isInsideTransactionBlock = true
defer {
isInsideTransactionBlock = wasInsideTransactionBlock
}
// Now that savepoint has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
let needsRollback: Bool
do {
let completion = try block()
switch completion {
case .commit:
// In case of aborted transaction, throw SQLITE_ABORT instead
// of the generic SQLITE_ERROR "cannot commit - no transaction is active"
try checkForAbortedTransaction()
// Leave transaction block now, so that transaction observers
// can execute statements without getting errors from
// checkForAbortedTransaction().
isInsideTransactionBlock = wasInsideTransactionBlock
try execute(sql: "RELEASE SAVEPOINT grdb")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
needsRollback = false
case .rollback:
needsRollback = true
}
} catch {
firstError = error
needsRollback = true
}
if needsRollback {
do {
// Rollback, and release the savepoint.
// Rollback alone is not enough to clear the savepoint from
// the SQLite savepoint stack.
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
try execute(sql: "RELEASE SAVEPOINT grdb")
} catch {
if firstError == nil {
firstError = error
}
}
}
if let firstError = firstError {
throw firstError
}
}
/// Begins a database transaction.
///
/// - parameter kind: The transaction type (default nil). If nil, the
/// transaction type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
/// for more information.
/// - throws: The error thrown by the block.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
let kind = kind ?? configuration.defaultTransactionKind
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
}
/// Rollbacks a database transaction.
public func rollback() throws {
// The SQLite documentation contains two related but distinct techniques
// to handle rollbacks and errors:
//
// https://www.sqlite.org/lang_transaction.html#immediate
//
// > Response To Errors Within A Transaction
// >
// > If certain kinds of errors occur within a transaction, the
// > transaction may or may not be rolled back automatically.
// > The errors that can cause an automatic rollback include:
// >
// > - SQLITE_FULL: database or disk full
// > - SQLITE_IOERR: disk I/O error
// > - SQLITE_BUSY: database in use by another process
// > - SQLITE_NOMEM: out or memory
// >
// > [...] It is recommended that applications respond to the
// > errors listed above by explicitly issuing a ROLLBACK
// > command. If the transaction has already been rolled back
// > automatically by the error response, then the ROLLBACK
// > command will fail with an error, but no harm is caused
// > by this.
//
// https://sqlite.org/c3ref/get_autocommit.html
//
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
// > the given database connection is or is not in autocommit mode,
// > respectively.
// >
// > [...] If certain kinds of errors occur on a statement within a
// > multi-statement transaction (errors including SQLITE_FULL,
// > SQLITE_IOERR, SQLITE_NOMEM, SQLITE_BUSY, and SQLITE_INTERRUPT) then
// > the transaction might be rolled back automatically. The only way to
// > find out whether SQLite automatically rolled back the transaction
// > after an error is to use this function.
//
// The second technique is more robust, because we don't have to guess
// which rollback errors should be ignored, and which rollback errors
// should be exposed to the library user.
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
}
/// Commits a database transaction.
public func commit() throws {
try execute(sql: "COMMIT TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
}
// MARK: - Memory Management
func releaseMemory() {
sqlite3_db_release_memory(sqliteConnection)
schemaCache.clear()
internalStatementCache.clear()
publicStatementCache.clear()
}
// MARK: - Erasing
func erase() throws {
#if SQLITE_HAS_CODEC
// SQLCipher does not support the backup API:
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// So we'll drop all database objects one after the other.
// Prevent foreign keys from messing with drop table statements
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
if foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = OFF")
}
try throwingFirstError(
execute: {
// Remove all database objects, one after the other
try inTransaction {
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
while let row = try Row.fetchOne(self, sql: sql) {
let type: String = row["type"]
let name: String = row["name"]
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
}
return .commit
}
},
finally: {
// Restore foreign keys if needed
if foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = ON")
}
})
#else
try DatabaseQueue().backup(to: self)
#endif
}
// MARK: - Backup
/// Copies the database contents into another database.
///
/// The `backup` method blocks the current thread until the destination
/// database contains the same contents as the source database.
///
/// Usage:
///
/// let source: DatabaseQueue = ...
/// let destination: DatabaseQueue = ...
/// try source.write { sourceDb in
/// try destination.barrierWriteWithoutTransaction { destDb in
/// try sourceDb.backup(to: destDb)
/// }
/// }
///
///
/// When you're after progress reporting during backup, you'll want to
/// perform the backup in several steps. Each step copies the number of
/// _database pages_ you specify. See <https://www.sqlite.org/c3ref/backup_finish.html>
/// for more information:
///
/// // Backup with progress reporting
/// try sourceDb.backup(
/// to: destDb,
/// pagesPerStep: ...)
/// { backupProgress in
/// print("Database backup progress:", backupProgress)
/// }
///
/// The `progress` callback will be called at least once—when
/// `backupProgress.isCompleted == true`. If the callback throws
/// when `backupProgress.isCompleted == false`, the backup is aborted
/// and the error is rethrown. If the callback throws when
/// `backupProgress.isCompleted == true`, backup completion is
/// unaffected and the error is silently ignored.
///
/// See also `DatabaseReader.backup()`.
///
/// - parameters:
/// - destDb: The destination database.
/// - pagesPerStep: The number of database pages copied on each backup
/// step. By default, all pages are copied in one single step.
/// - progress: An optional function that is notified of the backup
/// progress.
/// - throws: The error thrown by `progress` if the backup is abandoned, or
/// any `DatabaseError` that would happen while performing the backup.
public func backup(
to destDb: Database,
pagesPerStep: Int32 = -1,
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
throws
{
try backupInternal(
to: destDb,
pagesPerStep: pagesPerStep,
afterBackupStep: progress)
}
func backupInternal(
to destDb: Database,
pagesPerStep: Int32 = -1,
afterBackupInit: (() -> Void)? = nil,
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
throws
{
guard let backup = sqlite3_backup_init(destDb.sqliteConnection, "main", sqliteConnection, "main") else {
throw DatabaseError(resultCode: destDb.lastErrorCode, message: destDb.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError()
}
afterBackupInit?()
do {
backupLoop: while true {
let rc = sqlite3_backup_step(backup, pagesPerStep)
let totalPageCount = Int(sqlite3_backup_pagecount(backup))
let remainingPageCount = Int(sqlite3_backup_remaining(backup))
let progress = DatabaseBackupProgress(
remainingPageCount: remainingPageCount,
totalPageCount: totalPageCount,
isCompleted: rc == SQLITE_DONE)
switch rc {
case SQLITE_DONE:
try? afterBackupStep?(progress)
break backupLoop
case SQLITE_OK:
try afterBackupStep?(progress)
case let code:
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
}
}
} catch {
sqlite3_backup_finish(backup)
throw error
}
switch sqlite3_backup_finish(backup) {
case SQLITE_OK:
break
case let code:
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
}
// The schema of the destination database has changed:
destDb.clearSchemaCache()
}
}
#if SQLITE_HAS_CODEC
extension Database {
// MARK: - Encryption
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.usePassphrase("secret")
/// }
public func usePassphrase(_ passphrase: String) throws {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try usePassphrase(data)
}
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.usePassphrase(passphraseData)
/// }
public func usePassphrase(_ passphrase: Data) throws {
let code = passphrase.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: String) throws {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try changePassphrase(data)
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: Data) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
//
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
// > favor of attaching a new database with the desired encryption
// > options and using sqlcipher_export() to migrate the contents and
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
let code = passphrase.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
}
}
#endif
extension Database {
// MARK: - Database-Related Types
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try
/// to access the database while it is locked by another connection.
///
/// The BusyMode enum describes the behavior of GRDB when such a situation
/// occurs:
///
/// - .immediateError: The SQLITE_BUSY error is immediately returned to the
/// connection that tries to access the locked database.
///
/// - .timeout: The SQLITE_BUSY error will be returned only if the database
/// remains locked for more than the specified duration.
///
/// - .callback: Perform your custom lock handling.
///
/// To set the busy mode of a database, use Configuration:
///
/// // Wait 1 second before failing with SQLITE_BUSY
/// let configuration = Configuration(busyMode: .timeout(1))
/// let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
///
/// Relevant SQLite documentation:
///
/// - <https://www.sqlite.org/c3ref/busy_timeout.html>
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
/// - <https://www.sqlite.org/lang_transaction.html>
/// - <https://www.sqlite.org/wal.html>
public enum BusyMode {
/// The SQLITE_BUSY error is immediately returned to the connection that
/// tries to access the locked database.
case immediateError
/// The SQLITE_BUSY error will be returned only if the database remains
/// locked for more than the specified duration (in seconds).
case timeout(TimeInterval)
/// A custom callback that is called when a database is locked.
/// See <https://www.sqlite.org/c3ref/busy_handler.html>
case callback(BusyCallback)
}
/// The available [checkpoint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html).
public enum CheckpointMode: Int32 {
/// The `SQLITE_CHECKPOINT_PASSIVE` mode
case passive = 0
/// The `SQLITE_CHECKPOINT_FULL` mode
case full = 1
/// The `SQLITE_CHECKPOINT_RESTART` mode
case restart = 2
/// The `SQLITE_CHECKPOINT_TRUNCATE` mode
case truncate = 3
}
/// A built-in SQLite collation.
///
/// See <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// Creates a built-in collation name.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// The `BINARY` built-in SQL collation
public static let binary = CollationName(rawValue: "BINARY")
/// The `NOCASE` built-in SQL collation
public static let nocase = CollationName(rawValue: "NOCASE")
/// The `RTRIM` built-in SQL collation
public static let rtrim = CollationName(rawValue: "RTRIM")
}
/// An SQL column type.
///
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// }
///
/// See <https://www.sqlite.org/datatype3.html>
public struct ColumnType: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
/// Creates an SQL column type.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// The `TEXT` SQL column type
public static let text = ColumnType(rawValue: "TEXT")
/// The `INTEGER` SQL column type
public static let integer = ColumnType(rawValue: "INTEGER")
/// The `DOUBLE` SQL column type
public static let double = ColumnType(rawValue: "DOUBLE")
/// The `REAL` SQL column type
public static let real = ColumnType(rawValue: "REAL")
/// The `NUMERIC` SQL column type
public static let numeric = ColumnType(rawValue: "NUMERIC")
/// The `BOOLEAN` SQL column type
public static let boolean = ColumnType(rawValue: "BOOLEAN")
/// The `BLOB` SQL column type
public static let blob = ColumnType(rawValue: "BLOB")
/// The `DATE` SQL column type
public static let date = ColumnType(rawValue: "DATE")
/// The `DATETIME` SQL column type
public static let datetime = ColumnType(rawValue: "DATETIME")
/// The `ANY` SQL column type
public static let any = ColumnType(rawValue: "ANY")
}
/// An SQLite conflict resolution.
///
/// See <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String {
/// The `ROLLBACK` conflict resolution
case rollback = "ROLLBACK"
/// The `ABORT` conflict resolution
case abort = "ABORT"
/// The `FAIL` conflict resolution
case fail = "FAIL"
/// The `IGNORE` conflict resolution
case ignore = "IGNORE"
/// The `REPLACE` conflict resolution
case replace = "REPLACE"
}
/// A foreign key action.
///
/// See <https://www.sqlite.org/foreignkeys.html>
public enum ForeignKeyAction: String {
/// The `CASCADE` foreign key action
case cascade = "CASCADE"
/// The `RESTRICT` foreign key action
case restrict = "RESTRICT"
/// The `SET NULL` foreign key action
case setNull = "SET NULL"
/// The `SET DEFAULT` foreign key action
case setDefault = "SET DEFAULT"
}
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
/// An option for `Database.trace(options:_:)`
public struct TracingOptions: OptionSet {
/// The raw "Trace Event Code".
///
/// See <https://www.sqlite.org/c3ref/c_trace.html>
public let rawValue: CInt
/// Creates a `TracingOptions` from a raw "Trace Event Code".
///
/// See:
/// - <https://www.sqlite.org/c3ref/c_trace.html>
/// - `Database.trace(options:_:)`
public init(rawValue: CInt) {
self.rawValue = rawValue
}
/// Reports executed statements.
///
/// See `Database.trace(options:_:)`
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// Reports executed statements and the estimated duration that the
/// statement took to run.
///
/// See `Database.trace(options:_:)`
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#elseif os(Linux)
#else
/// Reports executed statements and the estimated duration that the
/// statement took to run.
///
/// See `Database.trace(options:_:)`
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#endif
}
/// An event reported by `Database.trace(options:_:)`
public enum TraceEvent: CustomStringConvertible {
/// Information about a statement reported by `Database.trace(options:_:)`
public struct Statement {
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
}
let impl: Impl
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// The executed SQL, where bound parameters are not expanded.
///
/// For example:
///
/// UPDATE player SET score = ? WHERE id = ?
public var sql: String { _sql }
#elseif os(Linux)
#else
/// The executed SQL, where bound parameters are not expanded.
///
/// For example:
///
/// UPDATE player SET score = ? WHERE id = ?
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public var sql: String { _sql }
#endif
var _sql: String {
switch impl {
case .trace_v1:
// Likely a GRDB bug
fatalError("Not get statement SQL")
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
if let unexpandedSQL = unexpandedSQL {
return String(cString: unexpandedSQL)
.trimmingCharacters(in: .sqlStatementSeparators)
} else {
return String(cString: sqlite3_sql(sqliteStatement))
.trimmingCharacters(in: .sqlStatementSeparators)
}
}
}
/// The executed SQL, where bound parameters are expanded.
///
/// For example:
///
/// UPDATE player SET score = 1000 WHERE id = 1
public var expandedSQL: String {
switch impl {
case let .trace_v1(expandedSQL):
return expandedSQL
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql):
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
defer { sqlite3_free(cString) }
return String(cString: cString)
.trimmingCharacters(in: .sqlStatementSeparators)
}
}
}
/// An event reported by `TracingOptions.statement`.
case statement(Statement)
/// An event reported by `TracingOptions.profile`.
case profile(statement: Statement, duration: TimeInterval)
public var description: String {
switch self {
case let .statement(statement):
return statement.expandedSQL
case let .profile(statement: statement, duration: duration):
let durationString = String(format: "%.3f", duration)
return "\(durationString)s \(statement.expandedSQL)"
}
}
}
/// Confirms or cancels the changes performed by a transaction or savepoint.
@frozen
public enum TransactionCompletion {
/// Confirms changes
case commit
/// Cancel changes
case rollback
}
/// An SQLite transaction kind. See <https://www.sqlite.org/lang_transaction.html>
public enum TransactionKind: String {
/// The `DEFERRED` transaction kind
case deferred = "DEFERRED"
/// The `IMMEDIATE` transaction kind
case immediate = "IMMEDIATE"
/// The `EXCLUSIVE` transaction kind
case exclusive = "EXCLUSIVE"
}
/// An SQLite threading mode. See <https://www.sqlite.org/threadsafe.html>.
enum ThreadingMode {
case `default`
case multiThread
case serialized
var SQLiteOpenFlags: Int32 {
switch self {
case .`default`:
return 0
case .multiThread:
return SQLITE_OPEN_NOMUTEX
case .serialized:
return SQLITE_OPEN_FULLMUTEX
}
}
}
}
| 38.650255 | 164 | 0.588667 |
bb82058d74b3ea769e35daa830460739d8ae5bf9 | 272 | //
// FAQCell.swift
// Nudge
//
// Created by Jonah Starling on 2/22/17.
// Copyright © 2017 In The Belly. All rights reserved.
//
import UIKit
class FAQCell: UITableViewCell {
@IBOutlet var faqTitle: UILabel!
@IBOutlet var faqResponse: UILabel!
}
| 16 | 55 | 0.658088 |
f43d49007b6522043b2c8455a8236a020a244c3f | 269 | //
// AppDelegate.swift
// AppboosterSDKExample
//
// Created by Appbooster on 22.07.2020.
// Copyright © 2020 Appbooster. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| 15.823529 | 55 | 0.736059 |
cc7dc346ed285d8acc5b309f0eb24900cd883165 | 2,504 | extension AST {
public struct Group: Hashable {
public let kind: Located<Kind>
public let child: AST
public let location: SourceLocation
public init(
_ kind: Located<Kind>, _ child: AST, _ r: SourceLocation
) {
self.kind = kind
self.child = child
self.location = r
}
public enum Kind: Hashable {
// (...)
case capture
// (?<name>...) (?'name'...) (?P<name>...)
case namedCapture(Located<String>)
// (?:...)
case nonCapture
// (?|...)
case nonCaptureReset
// (?>...)
case atomicNonCapturing // TODO: is Oniguruma capturing?
// (?=...)
case lookahead
// (?!...)
case negativeLookahead
// (?*...)
case nonAtomicLookahead
// (?<=...)
case lookbehind
// (?<!...)
case negativeLookbehind
// (?<*...)
case nonAtomicLookbehind
// (*sr:...)
case scriptRun
// (*asr:...)
case atomicScriptRun
// (?iJmnsUxxxDPSWy{..}-iJmnsUxxxDPSW:)
// Isolated options are written as e.g (?i), and implicitly form a group
// containing all the following elements of the current group.
case changeMatchingOptions(MatchingOptionSequence, isIsolated: Bool)
// NOTE: Comments appear to be groups, but are not parsed
// the same. They parse more like quotes, so are not
// listed here.
}
}
}
extension AST.Group.Kind {
public var isCapturing: Bool {
switch self {
case .capture, .namedCapture: return true
default: return false
}
}
/// Whether this is a group with an implicit scope, e.g isolated matching
/// options implicitly become parent groups for the rest of the elements in
/// the current group:
///
/// (a(?i)bc)de -> (a(?i:bc))de
///
public var hasImplicitScope: Bool {
switch self {
case .changeMatchingOptions(_, let isIsolated):
return isIsolated
default:
return false
}
}
}
extension AST.Group {
/// If this group is a lookaround assertion, return its direction
/// and whether it is positive or negative. Otherwise returns
/// `nil`.
public var lookaroundKind: (forwards: Bool, positive: Bool)? {
switch self.kind.value {
case .lookahead: return (true, true)
case .negativeLookahead: return (true, false)
case .lookbehind: return (false, true)
case .negativeLookbehind: return (false, false)
default: return nil
}
}
}
| 23.401869 | 78 | 0.590655 |
502594c265d7508a1c9ef1cac0a50b61cfffc5c0 | 1,538 | // StubRegisterMock.swift
/*
MIT License
Copyright (c) 2019 Jordhan Leoture
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.
*/
@testable import MockSwift
class StubRegisterMock: StubRegister {
var recordedStubReturn: Any?
var recordedStubReceived: [Any] = []
func recordedStub<ReturnType>(for returnType: ReturnType.Type) -> ReturnType? {
recordedStubReceived.append(returnType)
return recordedStubReturn as? ReturnType
}
var recordReceived: [Stub] = []
func record(_ stub: Stub) {
recordReceived.append(stub)
}
}
| 37.512195 | 81 | 0.773732 |
480b7e9bb392d83da8f741393adafacb81b8f719 | 1,244 | //
// Page.swift
// Copyright © 2017 Oxagile. All rights reserved.
//
import Foundation
import XCTest
/**
Example Class for common Page
*/
class Page {
var isPageLoaded = false
/**
Should be overridden by any Page with logic for waiting all animation completed
*/
func waitForPageLoaded() -> Bool {
return false
}
/**
Can be used when it's needed to relaunch app from particular page and return it
*/
func relaunchApp<T: Page>(_ type: T.Type) -> T {
Container.app.launchArguments.removeAll()
Container.app.launch()
return type.init()
}
/**
Initialiser where parameter isPageLoaded is set to true or false depending on the result of waitForPageLoaded() method
*/
required init() {
isPageLoaded = waitForPageLoaded()
}
/**
Can be used when we go to external applications
*/
func isApplicationInBackground() -> Bool {
return UIApplication.shared.applicationState == .background
}
/*
Take a screenshot of an app's first window
*/
func takeScreenshot() -> Data {
return Container.app.windows.firstMatch.screenshot().pngRepresentation
}
}
| 23.037037 | 123 | 0.623794 |
0a395115d2256d52f3e3cf1ab9e731c659fae375 | 2,326 | // MIT License
//
// Copyright (c) 2020 Declarative Hub
//
// 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 Mockingbird
extension Spacer: UIKitNodeResolvable {
private class Node: UIKitNode {
var hierarchyIdentifier: String {
"Spacer"
}
var view: Spacer!
var context: Context!
var isSpacer: Bool {
true
}
var minLenght: CGFloat {
return view.minLength ?? context.environment.padding
}
func update(view: Spacer, context: Context) {
self.view = view
self.context = context
}
func layoutSize(fitting targetSize: CGSize, pass: LayoutPass) -> CGSize {
switch context.environment._layoutAxis {
case .horizontal:
return CGSize(width: minLenght, height: 0)
case .vertical:
return CGSize(width: 0, height: minLenght)
default:
return CGSize(width: minLenght, height: minLenght)
}
}
func layout(in container: Container, bounds: Bounds, pass: LayoutPass) {
}
}
func resolve(context: Context, cachedNode: AnyUIKitNode?) -> AnyUIKitNode {
return (cachedNode as? Node) ?? Node()
}
}
| 33.710145 | 81 | 0.659501 |
5bbccc19a5dfabf82a3d5004dbf1e59b4e8d8f48 | 94,567 | // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t.ast
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.ast
// REQUIRES: objc_interop
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
enum ErrorEnum : Error {
case failed
}
@objc class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc protocol Protocol_ObjC1 {}
@objc protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc extension PlainStruct { } // expected-error{{'@objc' can only be applied to an extension of a class}}{{1-7=}}
class FáncyName {}
@objc (FancyName) extension FáncyName {}
@objc
var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_getterSetter: Int {
@objc
get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
return 0
}
@objc
set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
@objc
didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var instanceVar3: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
}
}
class subject_staticVar1 {
@objc
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc
class var staticVar2: Int { return 42 }
}
@objc
func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
@objc
func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc // expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc
class subject_class1 { // no-error
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no-error
}
@objc
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc
var subject_instanceVar: Int // no-error
@objc
init(foo: Int) {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc var extProp: Int { return 0 } // expected-error{{members of extensions of generic classes cannot be declared @objc}}
@objc func extFoo() {} // expected-error{{members of extensions of generic classes cannot be declared @objc}}
}
@objc
enum subject_enum: Int {
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2)
case subject_enumElement2
@objc(subject_enumElement3)
case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-30=}}
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
@nonobjc // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}}
case subject_enumElement7
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
enum subject_enum2 {
@objc(subject_enum2Element1)
case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-31=}}
}
@objc
protocol subject_protocol1 {
@objc
var subject_instanceVar: Int { get }
@objc
func subject_instanceFunc()
}
@objc protocol subject_protocol2 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc protocol subject_protocol3 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc
var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
@objc
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc
protocol subject_containerObjCProtocol2 {
init(a: Int)
@objc init(a: Double)
func func1() -> Int
@objc func func1_() -> Int
var instanceVar1: Int { get set }
@objc var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc func dynamicSelf1_() -> Self { return self }
@objc func genericParams<T: NSObject>() -> [T] { return [] }
// expected-error@-1{{method cannot be marked @objc because it has generic parameters}}
@objc func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias AnotherNSCoding = NSCoding
typealias MetaNSCoding1 = NSCoding.Protocol
typealias MetaNSCoding2 = AnotherNSCoding.Protocol
@objc func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias Composition = NSCopying & NSCoding
@objc func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias NSCodingExistential = NSCoding.Type
@objc func inoutFunc(a: inout Int) {}
// expected-error@-1{{method cannot be marked @objc because inout parameters cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func genericContext1<T>(_: T) {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}}
class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc
func f() {} // no-error
}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc func foo() {} // okay
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc func foo() {} // okay
}
@objc(CustomNameForSubclassOfGeneric) // okay
class ConcreteSubclassOfGeneric3 : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric3 {
@objc func foo() {} // okay
}
class subject_subscriptIndexed1 {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc
subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc
subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid2 {
@objc
subscript(a: PlainClass) -> Int {
// expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc
subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc
subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc
subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc
subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc
subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc
subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_propertyInvalid1 {
@objc
let plainStruct = PlainStruct() // expected-error {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
}
//===--- Tests for @objc inference.
@objc
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc func func7_(a: PlainClass) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc func func7m_(a: PlainClass.Type) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc func func8_() -> PlainClass {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc func func8m_() -> PlainClass.Type {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc func func9_(a: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc func func10_() -> PlainStruct {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc func func11_(a: PlainEnum) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc func func12_(a: PlainProtocol) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc func func14_(a: Protocol_Class1) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc func func16_(a: AnyObject) {} // no-error
func func17(a: @escaping () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) {
@objc func func17_(a: @escaping () -> ()) {}
func func18(a: @escaping (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int)
@objc func func18_(a: @escaping (Int) -> (), b: Int) {}
func func19(a: @escaping (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) {
@objc func func19_(a: @escaping (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
@objc func func_UnnamedParam1(_: Int) {} // no-error
@objc func func_UnnamedParam2(_: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var intstanceVar4: Int {
// CHECK: @objc var intstanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var intstanceVar5: Int {
// CHECK: @objc var intstanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @objc @_hasStorage var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get
didSet {}
// CHECK-NEXT: {{^}} @objc set
}
@objc var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc @_hasStorage var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get
didSet {}
// CHECK-NEXT: {{^}} @objc set
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: Unicode.Scalar
// CHECK-LABEL: @objc var var_Char: Unicode.Scalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple1: ()
@objc var var_tuple1_: ()
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple2: Void
@objc var var_tuple2_: Void
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc var var_tuple4_: (Int, Int)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc var var_PlainClass_: PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc var var_PlainStruct_: PlainStruct
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc var var_PlainEnum_: PlainEnum
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc var var_PlainProtocol_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc var var_ProtocolClass_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc var var_PlainClassMetatype_: PlainClass.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc var var_PlainStructMetatype_: PlainStruct.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc var var_PlainEnumMetatype_: PlainEnum.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc var var_PlainExistentialMetatype_: PlainProtocol.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc var var_ProtocolClassMetatype_: Protocol_Class1.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: Any
// CHECK-LABEL: @objc var var_Existential0: Any
@objc var var_Existential0_: Any
var var_Existential1: PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc var var_Existential1_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential2: PlainProtocol & PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc var var_Existential2_: PlainProtocol & PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential3: PlainProtocol & Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1
@objc var var_Existential3_: PlainProtocol & Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential4: PlainProtocol & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1
@objc var var_Existential4_: PlainProtocol & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential5: Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc var var_Existential5_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential6: Protocol_Class1 & Protocol_Class2
// CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2
@objc var var_Existential6_: Protocol_Class1 & Protocol_Class2
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential7: Protocol_Class1 & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1
@objc var var_Existential7_: Protocol_Class1 & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential8: Protocol_ObjC1
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc var var_Existential8_: Protocol_ObjC1 // no-error
var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
@objc var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error
var var_ExistentialMetatype0: Any.Type
var var_ExistentialMetatype1: PlainProtocol.Type
var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type
var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
var var_ExistentialMetatype5: (Protocol_Class1).Type
var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
var var_ExistentialMetatype8: Protocol_ObjC1.Type
var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: Protocol_ObjC1?
var var_Optional9: Protocol_ObjC1.Type?
var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional5: AnyObject?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional7: String?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail10: PlainProtocol?
var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type
var var_Optional_fail23: NSRange? // a bridged struct imported from C
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int
var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: Protocol_ObjC1?
weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)?
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: Protocol_ObjC1
unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject]
@objc var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc var var_ArrayType3_: [PlainStruct]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject]
@objc var var_ArrayType4_: [(AnyObject) -> AnyObject]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc var var_ArrayType7_: [PlainClass]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc var var_ArrayType8_: [PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1]
@objc var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
@objc var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: @objc var var_ArrayType11: [Any]
@objc var var_ArrayType11_: [Any]
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc var var_ArrayType13_: [Any?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc var var_ArrayType15_: [AnyObject?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]]
@objc var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]]
@objc var var_ArrayType17_: [[(AnyObject) -> AnyObject]]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc var var_GP_Unconstrained_: GP_Unconstrained
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc var var_GP_PlainClass_: GP_PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc var var_GP_PlainProtocol_: GP_PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc var var_GP_Class_ObjC_: GP_Class_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc var var_GP_Protocol_Class_: GP_Protocol_Class
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Unconstrained_() -> GP_Unconstrained {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc func func_GP_Class_ObjC__() -> GP_Class_ObjC {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc @_hasInitialValue var v1: Int
}
@objc
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc
var intstanceVar1: Int {
// CHECK: @objc var intstanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc @_hasInitialValue class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @objc @IBOutlet @_implicitly_unwrapped_optional @_hasInitialValue weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// expected-error@-2 {{@IBOutlet property has non-optional type 'PlainStruct'}}
// expected-note@-3 {{add '?' to form the optional type 'PlainStruct?'}}
// expected-note@-4 {{add '!' to form an implicitly unwrapped optional}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @IBAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBAction {
class HasIBAction {
@IBAction func goodAction(_ sender: AnyObject?) { }
// CHECK: {{^}} @objc @IBAction func goodAction(_ sender: AnyObject?) {
@IBAction func badAction(_ sender: PlainStruct?) { }
// expected-error@-1{{argument to @IBAction method cannot have non-object type 'PlainStruct?'}}
}
//===---
//===--- @IBInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBInspectable {
class HasIBInspectable {
@IBInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @IBInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @GKInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasGKInspectable {
class HasGKInspectable {
@GKInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @GKInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @objc @NSManaged dynamic var goodManaged: Class_ObjC1 {
// CHECK-NEXT: {{^}} @objc get
// CHECK-NEXT: {{^}} @objc set
// CHECK-NEXT: {{^}} }
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3{{'dynamic' property 'badManaged' must also be '@objc'}}
// CHECK-LABEL: {{^}} @NSManaged var badManaged: PlainStruct {
// CHECK-NEXT: {{^}} get
// CHECK-NEXT: {{^}} set
// CHECK-NEXT: {{^}} }
}
//===---
//===--- Pointer argument types
//===---
@objc class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2)
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice)
init(foo: ()) { }
@objc(initWithIntent)
init(bar _: ()) { }
@objc(initForMurder)
init() { }
@objc(isFoo)
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error{{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:)
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:)
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::)
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc
enum BadEnum2: Int {
@objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(realDealloc) // expected-error{{'@objc' deinitializer cannot have a name}}
deinit { }
@objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc var prop: Int {
@objc(property) get { return _prop }
@objc(setProperty:) set { _prop = newValue }
}
var prop2: Int {
@objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}}
@objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}}
}
var prop3: Int {
@objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-25=}}
}
@objc
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) get {
return c
}
@objc(setAtClass:class:) set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo)
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo)
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc class ClosureArguments {
// CHECK: @objc func foo
@objc func foo(f: (Int) -> ()) {}
// CHECK: @objc func bar
@objc func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc func bas(f: (NotObjCEnum) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: (Int) -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: (NotObjCEnum) -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) (Int) -> ()
typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
class func initialize() {}
}
@objc class Load2 {
class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
class func initialize() {} // expected-error{{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
@objc class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
@objc(initialize) class func barnitialize() {} // expected-error{{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
@objc var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc init(degrees: Double) throws { }
// Errors
@objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc func fooWithErrorEnum1(x: ErrorEnum) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum)
func fooWithErrorEnum2(x: ErrorEnum) {}
@objc func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol-constrained type containing 'Error' cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1)
func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { }
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"ImplicitClassThrows1"
@objc class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl{{.*}}"methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl{{.*}}"methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int)
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl{{.*}}"init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
// CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange
func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() }
@objc func methodReturnsBridgedValueType2() throws -> NSRange {
return NSRange()
}
// expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}}
// CHECK: {{^}} @objc func methodReturnsError() throws -> Error
func methodReturnsError() throws -> Error { return ErrorEnum.failed }
// CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int)
func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) {
func add(x: Int) -> (Int) -> Int {
return { x + $0 }
}
}
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"SubclassImplicitClassThrows1"
@objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int))
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}}
@objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}}
@objc func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc func method3(_ x: Int, closure: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}}
@objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}}
@objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}}
@objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc init(fn: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) func method4(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
@objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method8:fn1:error:fn2:)
func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method9AndReturnError:s:fn1:fn2:)
func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
@objc protocol ProtocolThrowsObjCName {
@objc optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }}
// expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}}
}
@objc class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc extension PlainClass {
// CHECK-LABEL: @objc final func objc_ext_objc_okay(_: Int) {
final func objc_ext_objc_okay(_: Int) { }
final func objc_ext_objc_not_okay(_: PlainStruct) { }
// expected-error@-1{{method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) {
@nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { }
}
@objc class ObjC_Class1 : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
// CHECK-LABEL: @objc class OperatorInClass
@objc class OperatorInClass {
// CHECK: {{^}} static func == (lhs: OperatorInClass, rhs: OperatorInClass) -> Bool
static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool {
return true
}
// CHECK: {{^}} @objc static func + (lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass
@objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}}
return lhs
}
} // CHECK: {{^}$}}
@objc protocol OperatorInProtocol {
static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols must not have operator requirements}}
}
class AdoptsOperatorInProtocol : OperatorInProtocol {
static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {}
// expected-error@-1 {{operator methods cannot be declared @objc}}
}
//===--- @objc inference for witnesses
@objc protocol InferFromProtocol {
@objc(inferFromProtoMethod1:)
optional func method1(value: Int)
}
// Infer when in the same declaration context.
// CHECK-LABEL: ClassInfersFromProtocol1
class ClassInfersFromProtocol1 : InferFromProtocol{
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
// Infer when in a different declaration context of the same class.
// CHECK-LABEL: ClassInfersFromProtocol2a
class ClassInfersFromProtocol2a {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
extension ClassInfersFromProtocol2a : InferFromProtocol { }
// Infer when in a different declaration context of the same class.
class ClassInfersFromProtocol2b : InferFromProtocol { }
// CHECK-LABEL: ClassInfersFromProtocol2b
extension ClassInfersFromProtocol2b {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
// Don't infer when there is a signature mismatch.
// CHECK-LABEL: ClassInfersFromProtocol3
class ClassInfersFromProtocol3 : InferFromProtocol {
}
extension ClassInfersFromProtocol3 {
// CHECK: {{^}} func method1(value: String)
func method1(value: String) { }
}
// Inference for subclasses.
class SuperclassImplementsProtocol : InferFromProtocol { }
class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol {
}
extension SubclassInfersFromProtocol2 {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
@objc class NeverReturningMethod {
@objc func doesNotReturn() -> Never {}
}
// SR-5025
class User: NSObject {
}
@objc extension User {
var name: String {
get {
return "No name"
}
set {
// Nothing
}
}
var other: String {
unsafeAddress { // expected-error{{addressors are not allowed to be marked @objc}}
}
}
}
// 'dynamic' methods cannot be @inlinable.
class BadClass {
@inlinable @objc dynamic func badMethod1() {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to 'dynamic' declarations}}
}
@objc
protocol ObjCProtocolWithWeakProperty {
weak var weakProp: AnyObject? { get set } // okay
}
@objc
protocol ObjCProtocolWithUnownedProperty {
unowned var unownedProp: AnyObject { get set } // okay
}
// rdar://problem/46699152: errors about read/modify accessors being implicitly
// marked @objc.
@objc class MyObjCClass: NSObject {}
@objc
extension MyObjCClass {
@objc
static var objCVarInObjCExtension: Bool {
get {
return true
}
set {}
}
}
| 40.604122 | 350 | 0.716296 |
e9cd4c05c25e3a124d58508f8e27c5615af7b710 | 4,363 | //
// AsyncSequence+SwitchToLatest.swift
//
//
// Created by Thibault Wittemberg on 04/01/2022.
//
public extension AsyncSequence where Element: AsyncSequence {
/// Republishes elements sent by the most recently received async sequence.
///
/// ```
/// let sourceSequence = AsyncSequences.From([1, 2, 3])
/// let mappedSequence = sourceSequence.map { element in ["a\(element)", "b\(element)"].asyncElements }
/// let switchedSequence = mappedSequence.switchToLatest()
///
/// for try await element in switchedSequence {
/// print(element)
/// }
///
/// // will print:
/// a3, b3
/// ```
///
/// - Returns: The async sequence that republishes elements sent by the most recently received async sequence.
func switchToLatest() -> AsyncSwitchToLatestSequence<Self> {
AsyncSwitchToLatestSequence<Self>(self)
}
}
public struct AsyncSwitchToLatestSequence<UpstreamAsyncSequence: AsyncSequence>: AsyncSequence where UpstreamAsyncSequence.Element: AsyncSequence {
public typealias Element = UpstreamAsyncSequence.Element.Element
public typealias AsyncIterator = Iterator
let upstreamAsyncSequence: UpstreamAsyncSequence
public init(_ upstreamAsyncSequence: UpstreamAsyncSequence) {
self.upstreamAsyncSequence = upstreamAsyncSequence
}
public func makeAsyncIterator() -> AsyncIterator {
Iterator(upstreamIterator: self.upstreamAsyncSequence.makeAsyncIterator())
}
final class UpstreamIteratorManager {
var upstreamIterator: UpstreamAsyncSequence.AsyncIterator
var currentChildIterator: UpstreamAsyncSequence.Element.AsyncIterator?
var hasStarted = false
var currentTask: Task<Element?, Error>?
init(upstreamIterator: UpstreamAsyncSequence.AsyncIterator) {
self.upstreamIterator = upstreamIterator
}
func setCurrentTask(task: Task<Element?, Error>) {
self.currentTask = task
}
/// iterates over the upstream sequence and maintain the current async iterator while cancelling the current .next() task for each new element
func startUpstreamIterator() async throws {
guard !self.hasStarted else { return }
self.hasStarted = true
let firstChildSequence = try await self.upstreamIterator.next()
self.currentChildIterator = firstChildSequence?.makeAsyncIterator()
Task {
while let nextChildSequence = try await self.upstreamIterator.next() {
self.currentChildIterator = nextChildSequence.makeAsyncIterator()
self.currentTask?.cancel()
self.currentTask = nil
}
}
}
func nextOnCurrentChildIterator() async throws -> Element? {
let nextElement = try await self.currentChildIterator?.next()
return nextElement
}
}
public struct Iterator: AsyncIteratorProtocol {
let upstreamIteratorManager: UpstreamIteratorManager
init(upstreamIterator: UpstreamAsyncSequence.AsyncIterator) {
self.upstreamIteratorManager = UpstreamIteratorManager(upstreamIterator: upstreamIterator)
}
public mutating func next() async throws -> Element? {
guard !Task.isCancelled else { return nil }
var noValueHasBeenEmitted = true
var emittedElement: Element?
var currentTask: Task<Element?, Error>
try await self.upstreamIteratorManager.startUpstreamIterator()
let localUpstreamIteratorManager = self.upstreamIteratorManager
while noValueHasBeenEmitted {
currentTask = Task {
do {
return try await localUpstreamIteratorManager.nextOnCurrentChildIterator()
} catch is CancellationError {
return nil
} catch {
throw error
}
}
localUpstreamIteratorManager.setCurrentTask(task: currentTask)
emittedElement = try await currentTask.value
noValueHasBeenEmitted = (emittedElement == nil && currentTask.isCancelled)
}
return emittedElement
}
}
}
| 37.290598 | 150 | 0.642906 |
20bda1de104c087d06887aa7e3214cb17e4a710b | 275 | //
// Optional+Casted.swift
// AdditionalSwift
//
// Created by Stephen Martinez on 4/8/21.
// Copyright © 2021 Stephen L. Martinez. All rights reserved.
//
public extension Optional {
static func casted<T>(from value: T) -> Self {
value as? Wrapped
}
}
| 19.642857 | 62 | 0.647273 |
08b98ff4f839f85e44842e552f61398f18a77e4d | 205 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( [ {
for {
struct A {
class
case ,
| 20.5 | 87 | 0.731707 |
3821007bda09d92ece0e4e2db0e5ab16b48b4e59 | 197 | //
// PromotionModel.swift
// DribbleSample
//
// Created by Sungwook Baek on 2021/04/16.
//
import Foundation
struct PromotionSectionModel: Hashable, Decodable {
let photoLinks: String
}
| 15.153846 | 51 | 0.720812 |
90f419e05263510316b315f050126ac73617411e | 11,213 | /* file: valid_selected_instance_representation.swift generated: Mon Jan 3 16:32:52 2022 */
/* This file was generated by the EXPRESS to Swift translator "exp2swift",
derived from STEPcode (formerly NIST's SCL).
exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23
WARNING: You probably don't want to edit it since your modifications
will be lost if exp2swift is used to regenerate it.
*/
import SwiftSDAIcore
extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF {
//MARK: -FUNCTION DEFINITION in EXPRESS
/*
FUNCTION valid_selected_instance_representation(
pd : product_definition_or_assembly_relationship
) : LOGICAL;
LOCAL
properties : SET OF property_definition := bag_to_set( QUERY ( prd <* USEDIN(
pd, 'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.'
+ 'PROPERTY_DEFINITION.DEFINITION' ) | ( prd.name =
'occurrence selection' ) ) );
property_definition_representations : SET OF property_definition_representation := bag_to_set(
QUERY ( pdr <* USEDIN( properties[1],
'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.'
+ 'PROPERTY_DEFINITION_REPRESENTATION.DEFINITION' ) | ( pdr.
used_representation.name = 'selection criteria' ) ) );
selected_representation : representation;
END_LOCAL;
IF SIZEOF( properties ) <> 1 THEN
RETURN( FALSE );
END_IF;
IF SIZEOF( property_definition_representations ) <> 1 THEN
RETURN( FALSE );
END_IF;
selected_representation := property_definition_representations[1]\property_definition_representation.
used_representation;
IF ( SIZEOF( selected_representation\representation.items ) < 1 ) OR ( SIZEOF( selected_representation\
representation.items ) > 2 ) THEN
RETURN( FALSE );
END_IF;
IF SIZEOF( QUERY ( i <* selected_representation\representation.items | ( ( SIZEOF( [
'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.MEASURE_REPRESENTATION_ITEM' ,
'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.VALUE_RANGE' ] * TYPEOF( i ) ) = 1 ) AND ( i.name =
'selection quantity' ) ) ) ) <> 1 THEN
RETURN( FALSE );
END_IF;
IF SIZEOF( QUERY ( i <* selected_representation\representation.items | ( (
'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.DESCRIPTIVE_REPRESENTATION_ITEM' IN TYPEOF( i ) )
AND ( i.name = 'selection control' ) ) ) ) > 1 THEN
RETURN( FALSE );
END_IF;
IF ( SIZEOF( QUERY ( i <* selected_representation\representation.items | ( (
'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.DESCRIPTIVE_REPRESENTATION_ITEM' IN TYPEOF( i ) )
AND ( i.name = 'selection control' ) ) ) ) = 0 ) AND ( SIZEOF( QUERY ( i <* selected_representation\
representation.items | ( ( i.name = 'selection quantity' ) AND ( SIZEOF( [
'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.QUALIFIED_REPRESENTATION_ITEM' ,
'AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.VALUE_RANGE' ] * TYPEOF( i ) ) = 0 ) ) ) ) > 0 )
THEN
RETURN( FALSE );
END_IF;
RETURN( TRUE );
END_FUNCTION; -- valid_selected_instance_representation (line:47695 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
public static
func VALID_SELECTED_INSTANCE_REPRESENTATION(
_ PD: sPRODUCT_DEFINITION_OR_ASSEMBLY_RELATIONSHIP? )
-> SDAI.LOGICAL {
// CACHE LOOKUP
let _params = SDAI.ParameterList( PD )
if case .available(let _cached_value) = _valid_selected_instance_representation__cache.cachedValue(params: _params) {
return _cached_value as! SDAI.LOGICAL
}
var PD = PD; SDAI.TOUCH(var: &PD)
//LOCAL
var PROPERTIES: SDAI.SET<ePROPERTY_DEFINITION>? = SDAI.SET<ePROPERTY_DEFINITION>(generic: /*SDAI.SET<
gINTYPE>*/BAG_TO_SET(
SDAI.USEDIN(T: PD,
ROLE: \AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF
.ePROPERTY_DEFINITION.DEFINITION)
.QUERY{ PRD in
let _TEMP1 = /*runtime*/PRD.NAME
let _TEMP2 = SDAI.FORCE_OPTIONAL(/*runtime*/_TEMP1)
.==. SDAI.FORCE_OPTIONAL(SDAI.STRING(
"occurrence selection"))
return _TEMP2 })); SDAI.TOUCH(var: &PROPERTIES)
var PROPERTY_DEFINITION_REPRESENTATIONS: SDAI.SET<ePROPERTY_DEFINITION_REPRESENTATION>? =
SDAI.SET<ePROPERTY_DEFINITION_REPRESENTATION>(generic: /*SDAI.SET<gINTYPE>*/BAG_TO_SET(
SDAI.USEDIN(T: PROPERTIES?[1], ROLE: \AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF
.ePROPERTY_DEFINITION_REPRESENTATION.DEFINITION)
.QUERY{ PDR in
let _TEMP1 = /*runtime*/PDR.USED_REPRESENTATION
let _TEMP2 = /*runtime*/SDAI.FORCE_OPTIONAL(_TEMP1)?.NAME
let _TEMP3 = SDAI.FORCE_OPTIONAL(/*runtime*/_TEMP2) .==. SDAI.FORCE_OPTIONAL(SDAI.STRING(
"selection criteria"))
return _TEMP3 })); SDAI.TOUCH(var: &PROPERTY_DEFINITION_REPRESENTATIONS)
var SELECTED_REPRESENTATION: eREPRESENTATION?
//END_LOCAL
let _TEMP1 = SDAI.SIZEOF(PROPERTIES)
let _TEMP2 = _TEMP1 .!=. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(1))
if SDAI.IS_TRUE( _TEMP2 ) {
return _valid_selected_instance_representation__cache.updateCache(params: _params, value: SDAI.UNWRAP(
SDAI.LOGICAL(SDAI.FALSE)))
}
let _TEMP3 = SDAI.SIZEOF(PROPERTY_DEFINITION_REPRESENTATIONS)
let _TEMP4 = _TEMP3 .!=. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(1))
if SDAI.IS_TRUE( _TEMP4 ) {
return _valid_selected_instance_representation__cache.updateCache(params: _params, value: SDAI.UNWRAP(
SDAI.LOGICAL(SDAI.FALSE)))
}
let _TEMP5 = PROPERTY_DEFINITION_REPRESENTATIONS?[1]
let _TEMP6 = _TEMP5?.GROUP_REF(ePROPERTY_DEFINITION_REPRESENTATION.self)
let _TEMP7 = _TEMP6?.USED_REPRESENTATION
SELECTED_REPRESENTATION = _TEMP7
let _TEMP8 = SELECTED_REPRESENTATION?.GROUP_REF(eREPRESENTATION.self)
let _TEMP9 = _TEMP8?.ITEMS
let _TEMP10 = SDAI.SIZEOF(_TEMP9)
let _TEMP11 = _TEMP10 < SDAI.FORCE_OPTIONAL(SDAI.INTEGER(1))
let _TEMP12 = SELECTED_REPRESENTATION?.GROUP_REF(eREPRESENTATION.self)
let _TEMP13 = _TEMP12?.ITEMS
let _TEMP14 = SDAI.SIZEOF(_TEMP13)
let _TEMP15 = _TEMP14 > SDAI.FORCE_OPTIONAL(SDAI.INTEGER(2))
let _TEMP16 = _TEMP11 || _TEMP15
if SDAI.IS_TRUE( _TEMP16 ) {
return _valid_selected_instance_representation__cache.updateCache(params: _params, value: SDAI.UNWRAP(
SDAI.LOGICAL(SDAI.FALSE)))
}
let _TEMP17 = SELECTED_REPRESENTATION?.GROUP_REF(eREPRESENTATION.self)
let _TEMP18 = _TEMP17?.ITEMS
let _TEMP19 = _TEMP18?.QUERY{ I in
let _TEMP1 = ([SDAI.AIE(SDAI.STRING(
"AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.MEASURE_REPRESENTATION_ITEM")),
SDAI.AIE(SDAI.STRING("AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.VALUE_RANGE"))]
as [SDAI.AggregationInitializerElement<SDAI.STRING>])
let _TEMP2 = SDAI.TYPEOF(I)
let _TEMP3 = SDAI.FORCE_OPTIONAL(_TEMP1) * SDAI.FORCE_OPTIONAL(_TEMP2)
let _TEMP4 = SDAI.SIZEOF(_TEMP3)
let _TEMP5 = _TEMP4 .==. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(1))
let _TEMP6 = I.NAME
let _TEMP7 = SDAI.FORCE_OPTIONAL(_TEMP6) .==. SDAI.FORCE_OPTIONAL(SDAI.STRING("selection quantity"))
let _TEMP8 = _TEMP5 && _TEMP7
return _TEMP8 }
let _TEMP20 = SDAI.SIZEOF(_TEMP19)
let _TEMP21 = _TEMP20 .!=. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(1))
if SDAI.IS_TRUE( _TEMP21 ) {
return _valid_selected_instance_representation__cache.updateCache(params: _params, value: SDAI.UNWRAP(
SDAI.LOGICAL(SDAI.FALSE)))
}
let _TEMP22 = SELECTED_REPRESENTATION?.GROUP_REF(eREPRESENTATION.self)
let _TEMP23 = _TEMP22?.ITEMS
let _TEMP24 = _TEMP23?.QUERY{ I in
let _TEMP1 = SDAI.TYPEOF(I, IS: eDESCRIPTIVE_REPRESENTATION_ITEM.self)
let _TEMP2 = I.NAME
let _TEMP3 = SDAI.FORCE_OPTIONAL(_TEMP2) .==. SDAI.FORCE_OPTIONAL(SDAI.STRING("selection control"))
let _TEMP4 = _TEMP1 && _TEMP3
return _TEMP4 }
let _TEMP25 = SDAI.SIZEOF(_TEMP24)
let _TEMP26 = _TEMP25 > SDAI.FORCE_OPTIONAL(SDAI.INTEGER(1))
if SDAI.IS_TRUE( _TEMP26 ) {
return _valid_selected_instance_representation__cache.updateCache(params: _params, value: SDAI.UNWRAP(
SDAI.LOGICAL(SDAI.FALSE)))
}
let _TEMP27 = SELECTED_REPRESENTATION?.GROUP_REF(eREPRESENTATION.self)
let _TEMP28 = _TEMP27?.ITEMS
let _TEMP29 = _TEMP28?.QUERY{ I in
let _TEMP1 = SDAI.TYPEOF(I, IS: eDESCRIPTIVE_REPRESENTATION_ITEM.self)
let _TEMP2 = I.NAME
let _TEMP3 = SDAI.FORCE_OPTIONAL(_TEMP2) .==. SDAI.FORCE_OPTIONAL(SDAI.STRING("selection control"))
let _TEMP4 = _TEMP1 && _TEMP3
return _TEMP4 }
let _TEMP30 = SDAI.SIZEOF(_TEMP29)
let _TEMP31 = _TEMP30 .==. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(0))
let _TEMP32 = SELECTED_REPRESENTATION?.GROUP_REF(eREPRESENTATION.self)
let _TEMP33 = _TEMP32?.ITEMS
let _TEMP34 = _TEMP33?.QUERY{ I in
let _TEMP1 = I.NAME
let _TEMP2 = SDAI.FORCE_OPTIONAL(_TEMP1) .==. SDAI.FORCE_OPTIONAL(SDAI.STRING("selection quantity"))
let _TEMP3 = ([SDAI.AIE(SDAI.STRING(
"AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.QUALIFIED_REPRESENTATION_ITEM")),
SDAI.AIE(SDAI.STRING("AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.VALUE_RANGE"))]
as [SDAI.AggregationInitializerElement<SDAI.STRING>])
let _TEMP4 = SDAI.TYPEOF(I)
let _TEMP5 = SDAI.FORCE_OPTIONAL(_TEMP3) * SDAI.FORCE_OPTIONAL(_TEMP4)
let _TEMP6 = SDAI.SIZEOF(_TEMP5)
let _TEMP7 = _TEMP6 .==. SDAI.FORCE_OPTIONAL(SDAI.INTEGER(0))
let _TEMP8 = _TEMP2 && _TEMP7
return _TEMP8 }
let _TEMP35 = SDAI.SIZEOF(_TEMP34)
let _TEMP36 = _TEMP35 > SDAI.FORCE_OPTIONAL(SDAI.INTEGER(0))
let _TEMP37 = _TEMP31 && _TEMP36
if SDAI.IS_TRUE( _TEMP37 ) {
return _valid_selected_instance_representation__cache.updateCache(params: _params, value: SDAI.UNWRAP(
SDAI.LOGICAL(SDAI.FALSE)))
}
return _valid_selected_instance_representation__cache.updateCache(params: _params, value: SDAI.UNWRAP(
SDAI.LOGICAL(SDAI.TRUE)))
}
}
//MARK: - function result cache
private var _valid_selected_instance_representation__cache = SDAI.FunctionResultCache(
controller: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.schemaDefinition)
| 49.179825 | 121 | 0.65433 |
71ab0a61183a7372e2bd6783e93c47a42dd52c27 | 4,521 | //
// AppDelegate.swift
// Headlines
//
// Created by Daniel Morgz on 18/01/2016.
// Copyright © 2016 Daniel Morgan. All rights reserved.
//
import UIKit
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var uiRealm: Realm!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Test getting our articles
self.setupRealm()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//MARK testing and temp methods
func listAllFonts() {
for family: String in UIFont.familyNames()
{
print("\(family)")
for names: String in UIFont.fontNamesForFamilyName(family)
{
print("== \(names)")
}
}
}
//MARK: Realm
func setupRealm() {
self.realmMigrations()
self.uiRealm = try! Realm()
// for swift 2.0 Xcode 7
print("Realm DB Path:"+"\n"+self.uiRealm.path+"\n") //Print out the path to the realm db so we can easily fire up a realm browser to look at data
}
//If you make a change that needs a migration then bump the schema version otherwise you'll see an ERRRRRRRRROR
func realmMigrations() {
// Inside your application(application:didFinishLaunchingWithOptions:)
let config = Realm.Configuration(
// Set the new schema version. This must be greater than the previously used
// version (if you've never set a schema version before, the version is 0).
schemaVersion: 7,
// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
// We haven’t migrated anything yet, so oldSchemaVersion == 0
if (oldSchemaVersion < 1) {
// Nothing to do!
// Realm will automatically detect new properties and removed properties
// And will update the schema on disk automatically
}
})
// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config
}
}
extension UIViewController {
var uiRealm:Realm {
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
return delegate.uiRealm
}
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
| 39.657895 | 285 | 0.666445 |
ed33b5a5760193eb4f6507133dd052bb197fb6e9 | 1,924 | //
// ProductListViewModel.swift
// MGLoadMore
//
// Created by Tuan Truong on 4/5/19.
// Copyright © 2019 Sun Asterisk. All rights reserved.
//
import MGArchitecture
import RxSwift
import RxCocoa
struct ProductListViewModel {
let navigator: ProductListNavigatorType
let useCase: ProductListUseCaseType
}
// MARK: - ViewModelType
extension ProductListViewModel: ViewModelType {
struct Input {
let loadTrigger: Driver<Void>
let reloadTrigger: Driver<Void>
let loadMoreTrigger: Driver<Void>
let selectProductTrigger: Driver<IndexPath>
}
struct Output {
let error: Driver<Error>
let isLoading: Driver<Bool>
let isReloading: Driver<Bool>
let isLoadingMore: Driver<Bool>
let productList: Driver<[Product]>
let selectedProduct: Driver<Void>
let isEmpty: Driver<Bool>
}
func transform(_ input: Input) -> Output {
let result = getPage(
loadTrigger: input.loadTrigger,
reloadTrigger: input.reloadTrigger,
loadMoreTrigger: input.loadMoreTrigger,
getItems: useCase.getProductList)
let (page, error, isLoading, isReloading, isLoadingMore) = result.destructured
let productList = page
.map { $0.items }
let selectedProduct = select(trigger: input.selectProductTrigger, items: productList)
.do(onNext: navigator.toProductDetail)
.mapToVoid()
let isEmpty = checkIfDataIsEmpty(trigger: Driver.merge(isLoading, isReloading), items: productList)
return Output(
error: error,
isLoading: isLoading,
isReloading: isReloading,
isLoadingMore: isLoadingMore,
productList: productList,
selectedProduct: selectedProduct,
isEmpty: isEmpty
)
}
}
| 29.151515 | 107 | 0.629938 |
20e30ab008f9c4b9367afbe93a819ebbcab9f2a8 | 1,070 | //
// ChartGrid.swift
// CardioBot
//
// Created by Majid Jabrayilov on 7/4/20.
// Copyright © 2020 Majid Jabrayilov. All rights reserved.
//
import SwiftUI
struct ChartGrid: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: rect.width, y: 0))
path.move(to: CGPoint(x: 0, y: rect.height))
path.addLine(to: CGPoint(x: rect.width, y: rect.height))
path.move(to: CGPoint(x: 0, y: rect.height / 2))
path.addLine(to: CGPoint(x: rect.width, y: rect.height / 2))
}
}
}
#if DEBUG
struct BarChartGrid_Previews: PreviewProvider {
static var previews: some View {
ChartGrid()
.stroke(
style: StrokeStyle(
lineWidth: 1,
lineCap: .round,
lineJoin: .round,
miterLimit: 0,
dash: [1, 8],
dashPhase: 0
)
)
}
}
#endif
| 24.883721 | 72 | 0.499065 |
87f4cf3f37b271e3e60e7dd1c0b868941b5be28d | 2,705 | //
// LoginViewController.swift
// My-Simple-Instagram
//
// Created by Luigi Aiello on 30/10/17.
// Copyright © 2017 Luigi Aiello. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
//MARK:- Outlets
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var loginIndicator: UIActivityIndicatorView!
//MARK:- Override
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK:- Setup
private func setup() {
let authURL = String(format: "%@?client_id=%@&redirect_uri=%@&response_type=token&scope=%@&DEBUG=True", arguments: [AppConfig.INSTAGRAM_AUTHURL, AppConfig.INSTAGRAM_CLIENT_ID, AppConfig.INSTAGRAM_REDIRECT_URI, AppConfig.INSTAGRAM_SCOPE])
let urlRequest = URLRequest.init(url: URL.init(string: authURL)!)
webView.delegate = self
webView.loadRequest(urlRequest)
}
// MARK:- Helpers
func checkRequestForCallbackURL(request: URLRequest) -> Bool {
let requestURLString = (request.url?.absoluteString)! as String
//APILOL.INSTAGRAM_REDIRECT_URI
if requestURLString.hasPrefix(AppConfig.INSTAGRAM_REDIRECT_URI) {
let range: Range<String.Index> = requestURLString.range(of: "#access_token=")!
let newStr = String(requestURLString[range.upperBound...])
handleAuth(authToken: newStr)
return false;
}
return true
}
func handleAuth(authToken: String) {
print("Token: \(authToken)")
Config.store(token: authToken)
let mainStoryboard = UIStoryboard(name: "Gallery", bundle: Bundle.main)
let controller: NavigationController = mainStoryboard.instantiateViewController(withIdentifier: "NavigationController") as! NavigationController
self.present(controller, animated: true, completion: nil)
}
}
// MARK:- WebView Delegate
extension LoginViewController: UIWebViewDelegate {
func webView(_ webView: UIWebView,
shouldStartLoadWith request:URLRequest,
navigationType: UIWebViewNavigationType) -> Bool {
return checkRequestForCallbackURL(request: request)
}
func webViewDidStartLoad(_ webView: UIWebView) {
loginIndicator.isHidden = false
loginIndicator.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
loginIndicator.isHidden = true
loginIndicator.stopAnimating()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
webViewDidFinishLoad(webView)
}
}
| 34.679487 | 245 | 0.676895 |
e8d2c227c204a442525f18faaa5bc5df8eb01ae4 | 3,550 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 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 Swift project authors
*/
import Foundation
import XCTest
@testable import SwiftDocC
import Markdown
class HasOnlyKnownArgumentsTests: XCTestCase {
/// No diagnostics when there are two allowed arguments, one of which is optional and unused.
func testValidDirective() throws {
let source = "@dir(foo: x)"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems: [Problem] = []
_ = Semantic.Analyses.HasOnlyKnownArguments<Intro>(severityIfFound: .error, allowedArguments: ["foo", "bar"]).analyze(directive, children: directive.children, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertTrue(problems.isEmpty)
}
/// When there are no allowed arguments, diagnose for any provided argument.
func testNoArguments() throws {
let source = "@dir(foo: x, bar: x)"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems: [Problem] = []
_ = Semantic.Analyses.HasOnlyKnownArguments<Intro>(severityIfFound: .error, allowedArguments: []).analyze(directive, children: directive.children, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertEqual(problems.count, 2)
}
/// When there are arguments that aren't allowed, diagnose.
func testInvalidArguments() throws {
let source = "@dir(foo: x, bar: x, baz: x)"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems: [Problem] = []
_ = Semantic.Analyses.HasOnlyKnownArguments<Intro>(severityIfFound: .error, allowedArguments: ["foo", "bar"]).analyze(directive, children: directive.children, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertEqual(problems.count, 1)
}
func testInvalidArgumentsWithSuggestions() throws {
let source = "@dir(foo: x, bar: x, baz: x)"
let document = Document(parsing: source, options: .parseBlockDirectives)
let directive = document.child(at: 0)! as! BlockDirective
let (bundle, context) = try testBundleAndContext(named: "TestBundle")
var problems: [Problem] = []
_ = Semantic.Analyses.HasOnlyKnownArguments<Intro>(severityIfFound: .error, allowedArguments: ["foo", "bar", "woof", "bark"]).analyze(directive, children: directive.children, source: nil, for: bundle, in: context, problems: &problems)
XCTAssertEqual(problems.count, 1)
guard let first = problems.first else { return }
XCTAssertEqual("error: Unknown argument 'baz' in Intro. These arguments are currently unused but allowed: 'bark', 'woof'.", first.diagnostic.localizedDescription)
}
}
| 47.972973 | 242 | 0.677183 |
f4f7c4292248ccaa7a4f699f44b059a9074273d8 | 1,087 | //
// DecimalTrans.swift
// HexConverter
//
// Created by lip on 17/1/12.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
class DecimalTrans: HexTransView {
override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = textField.text ?? "0"
switch string {
case ".":
if text.contains(".") {
return false
}
return true
default:
return true
}
}
// 重写父类监听方法
override func textFieldValueChange(tf: UITextField) {
super.textFieldValueChange(tf: tf)
let text = tf.text ?? "--"
if text != "" {
decimalRes = text
binaryRes = decimalTransCore(decimal: text, targethex: 2) ?? "--"
octalRes = decimalTransCore(decimal: text, targethex: 8) ?? "--"
sixteenRes = decimalTransCore(decimal: text, targethex: 16) ?? "--"
tableView?.reloadData()
}
}
}
| 24.155556 | 138 | 0.547378 |
2879a4b65d5520bcac70d3d4edd375e02176425a | 4,133 | import XCTest
import Quick
import Nimble
private enum AfterEachType {
case OuterOne
case OuterTwo
case OuterThree
case InnerOne
case InnerTwo
case NoExamples
}
private var afterEachOrder = [AfterEachType]()
class FunctionalTests_AfterEachSpec: QuickSpec {
override func spec() {
describe("afterEach ordering") {
afterEach { afterEachOrder.append(AfterEachType.OuterOne) }
afterEach { afterEachOrder.append(AfterEachType.OuterTwo) }
afterEach { afterEachOrder.append(AfterEachType.OuterThree) }
it("executes the outer afterEach closures once, but not before this closure [1]") {
// No examples have been run, so no afterEach will have been run either.
// The list should be empty.
expect(afterEachOrder).to(beEmpty())
}
it("executes the outer afterEach closures a second time, but not before this closure [2]") {
// The afterEach for the previous example should have been run.
// The list should contain the afterEach for that example, executed from top to bottom.
expect(afterEachOrder).to(equal([AfterEachType.OuterOne, AfterEachType.OuterTwo, AfterEachType.OuterThree]))
}
context("when there are nested afterEach") {
afterEach { afterEachOrder.append(AfterEachType.InnerOne) }
afterEach { afterEachOrder.append(AfterEachType.InnerTwo) }
it("executes the outer and inner afterEach closures, but not before this closure [3]") {
// The afterEach for the previous two examples should have been run.
// The list should contain the afterEach for those example, executed from top to bottom.
expect(afterEachOrder).to(equal([
AfterEachType.OuterOne, AfterEachType.OuterTwo, AfterEachType.OuterThree,
AfterEachType.OuterOne, AfterEachType.OuterTwo, AfterEachType.OuterThree
]))
}
}
context("when there are nested afterEach without examples") {
afterEach { afterEachOrder.append(AfterEachType.NoExamples) }
}
}
#if _runtime(_ObjC) && !SWIFT_PACKAGE
describe("error handling when misusing ordering") {
it("should throw an exception when including afterEach in it block") {
expect {
afterEach { }
}.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal(NSExceptionName.internalInconsistencyException))
expect(exception.reason).to(equal("'afterEach' cannot be used inside 'it', 'afterEach' may only be used inside 'context' or 'describe'. "))
})
}
}
#endif
}
}
final class AfterEachTests: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (AfterEachTests) -> () throws -> Void)] {
return [
("testAfterEachIsExecutedInTheCorrectOrder", testAfterEachIsExecutedInTheCorrectOrder)
]
}
func testAfterEachIsExecutedInTheCorrectOrder() {
afterEachOrder = []
qck_runSpec(FunctionalTests_AfterEachSpec.self)
let expectedOrder = [
// [1] The outer afterEach closures are executed from top to bottom.
AfterEachType.OuterOne, AfterEachType.OuterTwo, AfterEachType.OuterThree,
// [2] The outer afterEach closures are executed from top to bottom.
AfterEachType.OuterOne, AfterEachType.OuterTwo, AfterEachType.OuterThree,
// [3] The inner afterEach closures are executed from top to bottom,
// then the outer afterEach closures are executed from top to bottom.
AfterEachType.InnerOne, AfterEachType.InnerTwo,
AfterEachType.OuterOne, AfterEachType.OuterTwo, AfterEachType.OuterThree
]
XCTAssertEqual(afterEachOrder, expectedOrder)
afterEachOrder = []
}
}
| 43.968085 | 163 | 0.629083 |
0e3f3fc3aed6bb4e42d4f5d87a2e718dbd6ab910 | 515 | //Created on 2018/12/11 by LCD :https://github.com/liucaide .
import Foundation
public struct CaamDau<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
public var build: Base {
return base
}
}
public protocol CaamDauCompatible {
associatedtype CompatibleType
var cd: CompatibleType { get }
}
extension CaamDauCompatible {
public var cd: CaamDau<Self> {
return CaamDau(self)
}
}
extension NSObject: CaamDauCompatible {}
| 17.758621 | 63 | 0.658252 |
8fcc6eab85adb2dd0299e9fbb8979a0acfee98eb | 10,308 | //
// JSONValidator.swift
// MappableObjectGeneratorTests
//
// Created by Werner Altewischer on 09/03/2018.
//
import Foundation
struct ValidationError: CustomStringConvertible {
let code: Int
let message: String
init(code: Int = 0, message: String) {
self.code = code
self.message = message
}
var description: String {
return self.message
}
}
struct ValidationErrors: CustomStringConvertible {
private let errors: [NamedKeyPath: ([ValidationError], Any?)]
fileprivate init(_ errors: [NamedKeyPath: ([ValidationError], Any?)]) {
self.errors = errors
}
var errorKeyPaths: [NamedKeyPath] {
return Array(errors.keys)
}
func errors(for keyPath: NamedKeyPath) -> [ValidationError] {
return errors[keyPath]?.0 ?? []
}
func value(for keyPath: NamedKeyPath) -> Any? {
return errors[keyPath]?.1
}
var description: String {
var s = "[\n"
for keyPath in errorKeyPaths {
let errors = self.errors(for: keyPath)
let value = self.value(for: keyPath)
let valueString = value.map{ let s = String(describing: $0); return $0 is String ? "\"\(s)\"" : s } ?? "nil"
if !errors.isEmpty {
s.append("\(type(of: keyPath.keyPath).rootType).\(keyPath.name)(\(valueString)): \(errors)\n")
}
}
s.append("]")
return s
}
}
struct NamedKeyPath: Hashable {
static func ==(lhs: NamedKeyPath, rhs: NamedKeyPath) -> Bool {
return lhs.keyPath == rhs.keyPath
}
let keyPath: AnyKeyPath
let name: String
public var hashValue: Int {
return keyPath.hashValue
}
}
enum ValidationResult {
case valid
case invalid(ValidationErrors)
}
fileprivate let kURIPattern: NSRegularExpression = (try? NSRegularExpression(pattern: "^((?<=\\()[A-Za-z][A-Za-z0-9\\+\\.\\-]*:([A-Za-z0-9\\.\\-_~:/\\?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]|%[A-Fa-f0-9]{2})+(?=\\)))|([A-Za-z][A-Za-z0-9\\+\\.\\-]*:([A-Za-z0-9\\.\\-_~:/\\?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]|%[A-Fa-f0-9]{2})+)$", options: NSRegularExpression.Options(rawValue: 0)))!
fileprivate let kEmailPattern: NSRegularExpression = (try? NSRegularExpression(pattern: "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}$", options: NSRegularExpression.Options(rawValue: 0)))!
fileprivate let kHostnamePattern: NSRegularExpression = (try? NSRegularExpression(pattern: "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$", options: NSRegularExpression.Options(rawValue: 0)))!
fileprivate let kIPV4Pattern: NSRegularExpression = (try? NSRegularExpression(pattern: "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", options: NSRegularExpression.Options(rawValue: 0)))!
class ObjectValidator<T> {
private let object: T
private var errors = [NamedKeyPath: ([ValidationError], Any?)]()
init(object: T) {
self.object = object
}
@discardableResult
func withKeyPath<F>(_ keyPath: KeyPath<T, F?>, name: String = "", required: Bool = false) -> ObjectFieldValidator<T, F>? {
let namedKeyPath = NamedKeyPath(keyPath: keyPath, name: name)
if let value = object[keyPath: keyPath] {
return ObjectFieldValidator<T, F>(objectValidator: self, keyPath: namedKeyPath, value: value)
} else if required {
addError(keyPath: namedKeyPath, message: "Value is required")
}
return nil
}
@discardableResult
func evaluate() -> ValidationResult {
if errors.isEmpty {
return ValidationResult.valid
} else {
return ValidationResult.invalid(ValidationErrors(errors))
}
}
fileprivate func addError(keyPath: NamedKeyPath, code: Int = 0, value: Any? = nil, message: String) {
var errorArray = errors[keyPath, default: ([ValidationError](), nil)].0
errorArray.append(ValidationError(code: code, message: message))
errors[keyPath] = (errorArray, value)
}
}
class ObjectFieldValidator<T, F> {
let value: F
let keyPath: NamedKeyPath
let objectValidator: ObjectValidator<T>
init(objectValidator: ObjectValidator<T>, keyPath: NamedKeyPath, value: F) {
self.objectValidator = objectValidator
self.value = value
self.keyPath = keyPath
}
func addError(code: Int = 0, message: String) {
self.objectValidator.addError(keyPath: keyPath, code: code, value: value, message: message)
}
}
extension ObjectFieldValidator where F == String {
@discardableResult
func validateMinLength(_ minLength: Int) -> ObjectFieldValidator<T, F> {
if value.count < minLength {
addError(message: "Length should be >= \(minLength)")
}
return self
}
@discardableResult
func validateMaxLength(_ maxLength: Int) -> ObjectFieldValidator<T, F> {
if value.count > maxLength {
addError(message: "Length should be <= \(maxLength)")
}
return self
}
@discardableResult
func validateIPV4Address() -> ObjectFieldValidator<T, F> {
if !matchesRegex(string: value, regex: kIPV4Pattern) {
addError(message: "Not a valid IPV4 address")
}
return self
}
@discardableResult
func validateIPV6Address() -> ObjectFieldValidator<T, F> {
var buf = UnsafeMutablePointer<Int8>.allocate(capacity: Int(INET6_ADDRSTRLEN))
if inet_pton(AF_INET6, value, &buf) != 1 {
addError(message: "Not a valid IPV6 address")
}
return self
}
@discardableResult
func validateEmailAddress() -> ObjectFieldValidator<T, F> {
if !matchesRegex(string: value, regex: kEmailPattern) {
addError(message: "Not a valid email address")
}
return self
}
@discardableResult
func validateHostName() -> ObjectFieldValidator<T, F> {
if !matchesRegex(string: value, regex: kHostnamePattern) {
addError(message: "Not a valid host name")
}
return self
}
@discardableResult
func validateURI() -> ObjectFieldValidator<T, F> {
if !matchesRegex(string: value, regex: kURIPattern) {
addError(message: "Not a valid URI")
}
return self
}
@discardableResult
func validatePattern(_ pattern: String) -> ObjectFieldValidator<T, F> {
do {
let expression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0))
if !matchesRegex(string: value, regex: expression) {
addError(message: "Does not match pattern: \"\(pattern)\"")
}
} catch let error {
addError(message: "Pattern is not a valid regular expression: \"\(pattern)\": \(error)")
}
return self
}
private func matchesRegex(string: String, regex: NSRegularExpression, fullMatch: Bool = false) -> Bool {
let nsString = string as NSString
let range = NSMakeRange(0, nsString.length)
let result = regex.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range)
let matchCount = result.count
if matchCount == 0 {
return false
}
if fullMatch {
if matchCount != 1 {
return false
}
let foundRange = result[0].range
if foundRange.location != 0 || foundRange.length != nsString.length {
return false
}
}
return true
}
}
extension ObjectFieldValidator where F: Numeric & Comparable {
@discardableResult
func validateMinimum(_ minimum: F, exclusive: Bool = false) -> ObjectFieldValidator<T, F> {
if exclusive && value <= minimum {
addError(message: "Value should be > \(minimum)")
} else if !exclusive && value < minimum {
addError(message: "Value should be >= \(minimum)")
}
return self;
}
@discardableResult
func validateMaximum(_ maximum: F, exclusive: Bool = false) -> ObjectFieldValidator<T, F> {
if exclusive && value >= maximum {
addError(message: "Value should be < \(maximum)")
} else if !exclusive && value > maximum {
addError(message: "Value should be <= \(maximum)")
}
return self;
}
}
extension ObjectFieldValidator where F: BinaryInteger {
@discardableResult
func validateMultipleOf(_ divisor: F) -> ObjectFieldValidator<T, F> {
if divisor != 0 && value % divisor != 0 {
addError(message: "Value should be a multiple of \(divisor)")
}
return self;
}
}
extension ObjectFieldValidator where F: BinaryFloatingPoint {
@discardableResult
func validateMultipleOf(_ divisor: F) -> ObjectFieldValidator<T, F> {
if divisor != 0.0 {
let result = value / divisor
if result != floor(result) {
addError(message: "Value should be a multiple of \(divisor)")
}
}
return self;
}
}
extension ObjectFieldValidator where F: Collection {
@discardableResult
func validateMinItems(_ minItems: Int) -> ObjectFieldValidator<T, F> {
if value.count < minItems {
addError(message: "Size of collection should be >= \(minItems)")
}
return self;
}
@discardableResult
func validateMaxItems(_ maxItems: Int) -> ObjectFieldValidator<T, F> {
if value.count > maxItems {
addError(message: "Size of collection should be <= \(maxItems)")
}
return self;
}
}
extension ObjectFieldValidator where F: Collection, F.Element: Hashable {
@discardableResult
func validateUniqueItems() -> ObjectFieldValidator<T, F> {
let set = Set(value)
if set.count != value.count {
addError(message: "All items should be unique")
}
return self
}
}
| 33.359223 | 368 | 0.595169 |
db87b0d066d3a53c30753c8cc63bf1646ed0e9d4 | 4,446 | //
// FileSystem.swift
// Outlander
//
// Created by Joseph McBride on 5/8/20.
// Copyright © 2020 Joe McBride. All rights reserved.
//
import Foundation
protocol FileSystem {
func contentsOf(_ directory: URL) -> [URL]
func fileExists(_ file: URL) -> Bool
func load(_ file: URL) -> Data?
func append(_ data: String, to fileUrl: URL) throws
func write(_ content: String, to fileUrl: URL)
func write(_ data: Data, to fileUrl: URL) throws
func foldersIn(directory: URL) -> [URL]
func access(_ handler: @escaping () -> Void)
func ensure(folder url: URL) throws
}
class LocalFileSystem: FileSystem {
let settings: ApplicationSettings
init(_ settings: ApplicationSettings) {
self.settings = settings
}
func contentsOf(_ directory: URL) -> [URL] {
var result: [URL] = []
access {
do {
result = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
} catch {
print("File load error: \(error)")
}
}
return result
}
func fileExists(_ file: URL) -> Bool {
file.checkFileExist()
}
func load(_ file: URL) -> Data? {
var data: Data?
access {
data = try? Data(contentsOf: file)
}
return data
}
func append(_ data: String, to fileUrl: URL) throws {
guard !data.isEmpty else {
return
}
try ensure(folder: fileUrl.deletingLastPathComponent())
try access {
try data.appendLine(to: fileUrl)
}
}
func append(_ data: Data, to fileUrl: URL) throws {
guard data.count != 0 else {
return
}
try ensure(folder: fileUrl.deletingLastPathComponent())
access {
try? data.write(to: fileUrl)
}
}
func write(_ content: String, to fileUrl: URL) {
guard !content.isEmpty else {
return
}
access {
do {
try content.write(to: fileUrl, atomically: true, encoding: .utf8)
} catch {}
}
}
func write(_ data: Data, to fileUrl: URL) throws {
guard data.count != 0 else {
return
}
try access {
try data.write(to: fileUrl)
}
}
func foldersIn(directory: URL) -> [URL] {
var directories: [URL] = []
access {
guard let items = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [URLResourceKey.isDirectoryKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles, .skipsPackageDescendants]) else {
return
}
for item in items {
if item.hasDirectoryPath {
directories.append(item)
}
}
}
return directories.sorted(by: { $0.absoluteString < $1.absoluteString })
}
func access(_ handler: @escaping () -> Void) {
settings.paths.rootUrl.access(handler)
}
func access(_ handler: @escaping () throws -> Void) throws {
try settings.paths.rootUrl.accessThrow(handler)
}
func ensure(folder url: URL) throws {
try access {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
}
}
func remove(folder url: URL) throws {
try access {
try FileManager.default.removeItem(at: url)
}
}
}
extension URL {
func access(_ handler: @escaping () -> Void) {
if !startAccessingSecurityScopedResource() {
print("startAccessingSecurityScopedResource returned false. This directory might not need it, or this URL might not be a security scoped URL, or maybe something's wrong?")
}
handler()
stopAccessingSecurityScopedResource()
}
func accessThrow(_ handler: @escaping () throws -> Void) throws {
if !startAccessingSecurityScopedResource() {
print("startAccessingSecurityScopedResource returned false. This directory might not need it, or this URL might not be a security scoped URL, or maybe something's wrong?")
}
try handler()
stopAccessingSecurityScopedResource()
}
func checkFileExist() -> Bool {
FileManager.default.fileExists(atPath: path)
}
}
| 27.444444 | 244 | 0.58502 |
715748116190d7bb01cd44132e9e8a169fdf79e7 | 7,185 | //
// BaseCollectionViewController.swift
// Project
//
// Created by PFei_He on 16/5/10.
// Copyright © 2016年 PFei_He. All rights reserved.
//
// __________ __________ _________ ___________ ___________ __________ ___________
// | _______ \ | _______ \ / _______ \ |______ __|| _________| / _________||____ ____|
// | | \ || | \ || / \ | | | | | | / | |
// | |_______/ || |_______/ || | | | | | | |_________ | | | |
// | ________/ | _____ _/ | | | | _ | | | _________|| | | |
// | | | | \ \ | | | || | | | | | | | | |
// | | | | \ \ | \_______/ || \____/ | | |_________ | \_________ | |
// |_| |_| \_\ \_________/ \______/ |___________| \__________| |_|
//
//
// The framework design by https://github.com/PFei-He/Project-Swift
//
// 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 PFKitSwift
import SVProgressHUD
///调试模式
private var DEBUG_MODE = false
public class BaseCollectionViewController: UICollectionViewController {
///请求成功返回的结果
public var successResult: AnyObject? {
return _successResult
}
private var _successResult: AnyObject?
///请求失败返回的结果
public var failureResult: AnyObject? {
return _failureResult
}
private var _failureResult: AnyObject?
///请求返回的附加结果
public var additionalResults: AnyObject? {
return _additionalResults
}
private var _additionalResults: AnyObject?
///请求的发送者
public var sender: AnyObject? {
return _sender
}
private var _sender: AnyObject?
///请求是否成功
public var requestIsSuccess: Bool {
return _requestIsSuccess
}
private var _requestIsSuccess = Bool()
///所有的请求
private var requests = Array<BaseRequest>()
//MARK: - Life Cycle
deinit {
removeAllRequests()
}
// MARK: - Request Management
/**
初始化请求
- Note: 无
- Parameter requests: 所有的请求
- Returns: 无
*/
public func addRequests(requests: Array<BaseRequest>) {
self.requests = requests
for request in requests {
request.add(self)
}
}
/**
移除请求
- Note: 无
- Parameter requests: 所有的请求
- Returns: 无
*/
// public func removeRequests(requests: Array<BaseRequest>) {
// for request in requests {
// request.removeRequester(self)
// }
// }
///移除请求
private func removeAllRequests() {
for request in self.requests {
request.remove(self)
}
}
// MARK: - Notification Management
//请求开始通知
final func requestStartedNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request started with sender: \(notification.object!).")
print("[ PROJECT ][ DEBUG ] Requester: \(String(classForCoder)).")
}
//请求开始
requestStarted()
}
//请求结束通知
final func requestEndedNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request ended with sender: \(notification.object!).")
}
//请求结束
requestEnded()
}
//请求成功通知
final func requestSuccessNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request success with result: \(notification.object!).")
}
//处理请求结果
_successResult = notification.object
if notification.userInfo is Dictionary<String, AnyObject> {
var dictionary: Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
_additionalResults = dictionary.removeValueForKey("sender")
}
_sender = notification.userInfo?["sender"]
_requestIsSuccess = true
//请求成功
requestSuccess()
}
//请求失败通知
final func requestFailureNotification(notification: NSNotification) {
if DEBUG_MODE {//调试模式
print("[ PROJECT ][ DEBUG ] Request failure with result: \(notification.object!).")
}
//处理请求结果
_failureResult = notification.object
if notification.userInfo is Dictionary<String, AnyObject> {
var dictionary: Dictionary<String, AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
_additionalResults = dictionary.removeValueForKey("sender")
}
_sender = notification.userInfo?["sender"]
_requestIsSuccess = false
//请求失败
requestFailure()
}
// MARK: - Public Methods
/**
请求开始
- Note: 此方法已实现提示框的处理,如需自定义,请自行重写此方法
- Parameter 无
- Returns: 无
*/
public func requestStarted() {
//显示提示框
SVProgressHUD.showWithStatus("加载中")
}
/**
请求结束
- Note: 此方法已实现提示框的处理,如需自定义,请自行重写此方法
- Parameter 无
- Returns: 无
*/
public func requestEnded() {
if _requestIsSuccess {//请求成功
//移除提示框
SVProgressHUD.dismiss()
} else {//请求失败
//显示请求失败的提示框
SVProgressHUD.showErrorWithStatus("请求失败")
}
}
/**
请求成功
- Note: 无
- Parameter 无
- Returns: 无
*/
public func requestSuccess() {
// Override this method to process the request when request success.
}
/**
请求失败
- Note: 无
- Parameter 无
- Returns: 无
*/
public func requestFailure() {
// Override this method to process the request when request failure.
}
/**
调试模式
- Note: 无
- Parameter openOrNot: 是否打开调试模式
- Returns: 无
*/
public class func debugMode(openOrNot: Bool) {
DEBUG_MODE = openOrNot
}
}
| 29.567901 | 115 | 0.575365 |
d7c4f8a1850b6cee9139dc5536c24f18bab74988 | 641 | //
// FormButton.swift
// TouchForms
//
// Created by Adam Kirk on 7/23/15.
// Copyright (c) 2015 Adam Kirk. All rights reserved.
//
import UIKit
public typealias FormButtonAction = () -> Void
public class FormButton: UIButton {
public var action: FormButtonAction
public var label: String?
public init(label: String, _ action: FormButtonAction) {
self.action = action
self.label = label
super.init(frame: CGRectZero)
setTitle(label, forState: .Normal)
}
public required init?(coder aDecoder: NSCoder) {
self.action = {}
super.init(coder: aDecoder)
}
}
| 20.03125 | 60 | 0.638066 |
ddb27b727e604bb8964a94804a28f953a2ed3e13 | 410 | /// Errors that can be thrown while working with HTTP.
public struct HTTPError: Error {
public enum Reason {
case noContent
case noContentType
case unknownContentType
case maxBodySize
}
/// See `Debuggable`.
public let reason: Reason
/// Creates a new `HTTPError`.
public init(
_ reason: Reason
) {
self.reason = reason
}
}
| 20.5 | 54 | 0.592683 |
623b01c0aab737465d6a88334c9ef0898469de33 | 4,020 | //
// LocationViewController.swift
// PhotoMap
//
// Created by Pat Khai on 10/4/18.
// Copyright © 2018 Pat Khai. All rights reserved.
//
import UIKit
protocol LocationViewControllerDelegate : class {
func locationsPickedLocation(controller: LocationViewController, latitude: NSNumber, longitude: NSNumber)
}
class LocationViewController: UIViewController,UITableViewDataSource, UITableViewDelegate,UISearchBarDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
// TODO: Fill in actual CLIENT_ID and CLIENT_SECRET
let CLIENT_ID = "QA1L0Z0ZNA2QVEEDHFPQWK0I5F1DE3GPLSNW4BZEBGJXUCFL"
let CLIENT_SECRET = "W2AOE1TYC4MHK5SZYOUGX0J3LVRALMPB4CXT3ZH21ZCPUMCU"
var userInfo : AnyObject!
var results: NSArray = []
weak var delegate : LocationViewControllerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
searchBar.delegate = self
fetchLocations("")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell") as! LocationCell
cell.location = results[(indexPath as NSIndexPath).row] as! NSDictionary
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// This is the selected venue
let venue = results[(indexPath as NSIndexPath).row] as! NSDictionary
let lat = venue.value(forKeyPath: "location.lat") as! NSNumber
let lng = venue.value(forKeyPath: "location.lng") as! NSNumber
let latString = "\(lat)"
let lngString = "\(lng)"
print(latString + " " + lngString)
delegate.locationsPickedLocation(controller: self, latitude: lat, longitude: lng)
}
func locationsPickedLocation() {
self.navigationController?.popViewController(animated: true)
}
func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let newText = NSString(string: searchBar.text!).replacingCharacters(in: range, with: text)
fetchLocations(newText)
return true
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
fetchLocations(searchBar.text!)
}
func fetchLocations(_ query: String, near: String = "San Francisco") {
let baseUrlString = "https://api.foursquare.com/v2/venues/search?"
let queryString = "client_id=\(CLIENT_ID)&client_secret=\(CLIENT_SECRET)&v=20141020&near=\(near),CA&query=\(query)"
let url = URL(string: baseUrlString + queryString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)!
let request = URLRequest(url: url)
let session = URLSession(
configuration: URLSessionConfiguration.default,
delegate:nil,
delegateQueue:OperationQueue.main
)
let task : URLSessionDataTask = session.dataTask(with: request,completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! JSONSerialization.jsonObject(with: data, options:[]) as? NSDictionary {
NSLog("response: \(responseDictionary)")
self.results = responseDictionary.value(forKeyPath: "response.venues") as! NSArray
self.tableView.reloadData()
}
}
});
task.resume()
}
}
| 35.892857 | 135 | 0.659701 |
209963231da246f570e700736069d3d1732ef5f2 | 1,655 | //
// CLLocationCoordinate2D+AirMapTraffic.swift
// AirMapSDK
//
// Created by Adolfo Martinelli on 2/21/17.
// Copyright 2018 AirMap, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
extension Coordinate2D {
public var formattedString: String {
var latSeconds = Int(latitude * 3600)
let latDegrees = latSeconds / 3600
latSeconds = abs(latSeconds % 3600)
let latMinutes = latSeconds / 60
latSeconds %= 60
var longSeconds = Int(longitude * 3600)
let longDegrees = longSeconds / 3600
longSeconds = abs(longSeconds % 3600)
let longMinutes = longSeconds / 60
longSeconds %= 60
let north = AirMapTrafficServiceUtils.directionFromBearing(000)
let south = AirMapTrafficServiceUtils.directionFromBearing(180)
let east = AirMapTrafficServiceUtils.directionFromBearing(090)
let west = AirMapTrafficServiceUtils.directionFromBearing(270)
return String(format:"%d° %d' %d\" %@, %d° %d' %d\" %@",
abs(latDegrees),
latMinutes,
latSeconds, (latDegrees >= 0 ? north : south),
abs(longDegrees),
longMinutes,
longSeconds, (longDegrees >= 0 ? east : west) )
}
}
| 32.45098 | 76 | 0.708761 |
71889c37b051543a716ff6f681bfed8b3c503f6a | 3,886 | /// Copyright (c) 2021 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 SwiftUI
struct AddTodoView {
@State private var name: String = ""
@State private var description: String = ""
@State private var showNameRequiredWarning = false
let todoSaved: (String, String?) -> Void
}
// MARK: - View
extension AddTodoView: View {
var body: some View {
VStack {
dismissIndicator
title
inputFields
Spacer()
saveButton
}
.padding(.vertical, 30)
.alert(isPresented: $showNameRequiredWarning) {
.init(
title: .init("Name Required"),
message: .init("A Todo should have a name"),
dismissButton: .destructive(.init("OK"))
)
}
.background(Color(UIColor.systemGroupedBackground))
.edgesIgnoringSafeArea(.all)
}
}
private extension AddTodoView {
var dismissIndicator: some View {
RoundedRectangle(cornerRadius: 3)
.frame(width: 90, height: 6)
.foregroundColor(Color(UIColor.lightGray))
}
var title: some View {
HStack {
Text("Add New")
.font(.largeTitle).fontWeight(.semibold)
Spacer()
}
.padding(.horizontal)
}
var inputFields: some View {
List {
Section(header: Text("Name")) {
TextField("", text: $name)
.frame(height: 40)
}
Section(header: Text("Description")) {
TextEditor(text: $description)
.frame(height: 200)
}
}
.listStyle(GroupedListStyle())
}
var saveButton: some View {
Button {
guard !name.isEmpty else {
showNameRequiredWarning.toggle()
return
}
todoSaved(name, description)
} label: {
ZStack {
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.blue)
Text("Add Todo")
.font(.system(size: 22, weight: .semibold))
.foregroundColor(.white)
}
.frame(height: 44)
.padding(.horizontal, 20)
}
}
}
struct AddTodoView_Previews: PreviewProvider {
static var previews: some View {
AddTodoView { _, _ in }
}
}
| 31.593496 | 83 | 0.677046 |
282e63cdb914bfdf3d8dd9b298526f41d3ac36a3 | 4,485 | import UIKit
class ViewController: UITableViewController {
var tableData = [Int]()
var titleView: UIView?
var navTitle: UILabel?
var popoverViewController: PopOverSingle!
var popoverImageController: PopOverImage!
var width: CGFloat?
var height: CGFloat?
var selectedOption = Options.All
override func viewDidLoad() {
super.viewDidLoad()
//populating the data at initial state
self.tableData = self.selectedOption.getData()
self.width = (self.navigationController?.navigationBar.frame.width)!
self.height = (self.navigationController?.navigationBar.frame.height)!
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.popOverController(_:)))
titleView = UIView(frame: CGRect(origin: CGPoint(x: width! / 2, y: height! / 2), size: CGSize(width: width! / 2, height: height!)))
navTitle = UILabel(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: width! / 2 , height: height!)))
navTitle?.textAlignment = .Center
navTitle?.text = self.selectedOption.getTitleString()
titleView?.addSubview(navTitle!)
titleView!.addGestureRecognizer(tap)
self.navigationItem.titleView = titleView
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PopSegueID" {
popoverViewController = segue.destinationViewController as! PopOverSingle
popoverViewController.selectedOption = self.selectedOption
popoverViewController.delegate = self
popoverViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
popoverViewController.popoverPresentationController!.delegate = self
popoverViewController.popoverPresentationController?.sourceView = self.navigationController?.navigationBar.topItem?.titleView
popoverViewController.popoverPresentationController?.sourceRect = CGRect(x: self.titleView!.frame.width / 2, y: 0, width: 0, height: height!)
popoverViewController.popoverPresentationController?.permittedArrowDirections = .Up
} else if segue.identifier == "PopImageSegueID" {
popoverImageController = segue.destinationViewController as! PopOverImage
popoverImageController.modalPresentationStyle = UIModalPresentationStyle.Popover
popoverImageController.popoverPresentationController!.delegate = self
popoverImageController.popoverPresentationController?.sourceView = self.navigationController?.navigationBar.topItem?.titleView
popoverImageController.popoverPresentationController?.sourceRect = CGRect(x: self.titleView!.frame.width / 2, y: 0, width: 0, height: height!)
popoverImageController.popoverPresentationController?.permittedArrowDirections = .Up
}
}
func popOverController(sender: UITapGestureRecognizer) {
self.performSegueWithIdentifier("PopSegueID", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .None
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier("BasicCellID") as? BasicCell else { return UITableViewCell() }
cell.label.text = "\(self.tableData[indexPath.row])"
return cell
}
}
extension ViewController: UIPopoverPresentationControllerDelegate {
}
extension ViewController: PopOverSingleDelegate {
func popOverCellSelected(index: Int) {
self.selectedOption = Options(rawValue: index)!
self.tableData = self.selectedOption.getData()
self.navTitle!.text = self.selectedOption.getTitleString()
self.tableView.reloadData()
}
func popOverCellDisselected(index: Int) {
print("Dis ---- Selected \(index)")
}
}
| 47.210526 | 163 | 0.713266 |
2994173eac1693d36989d85d4d1b0b837d4bf727 | 590 | //
// Problem_20Tests.swift
// Problem 20Tests
//
// Created by sebastien FOCK CHOW THO on 2019-06-17.
// Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved.
//
import XCTest
@testable import Problem_20
class Problem_20Tests: XCTestCase {
func test() {
let input1 = Node(value: 3, next: Node(value: 7, next: Node(value: 8, next: Node(value: 10, next: nil))))
let input2 = Node(value: 99, next: Node(value: 1, next: Node(value: 8, next: Node(value: 10, next: nil))))
XCTAssert(commonNode(lhs: input1, rhs: input2)!.value == 8)
}
}
| 26.818182 | 114 | 0.642373 |
db85b43a3d860129de91ee828bdc63b82d59bfcb | 341 |
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
}
}
| 24.357143 | 142 | 0.797654 |
7612ad6347ad6fc97b0169033c12c425da8fce1c | 165 | //
// Links+CoreDataClass.swift
//
//
// Created by Vineet Ravi on 24/04/18.
//
//
import Foundation
import CoreData
public class Links: NSManagedObject {
}
| 10.3125 | 39 | 0.672727 |
fc8738a0bee7210314b12f539e03af07ff63aeea | 1,569 | //
// LibXMLNavigatingParserDOM.swift
// XMLParsable
//
// Created by Lawrence Lomax on 26/08/2014.
// Copyright (c) 2014 Lawrence Lomax. All rights reserved.
//
import Foundation
import swiftz_core
public final class LibXMLNavigatingParserDOM: XMLParsableType, XMLParsableFactoryType {
private let node: xmlNodePtr
private let context: LibXMLDOM.Context?
internal init (node: xmlNodePtr) {
self.node = node
}
internal init (context: LibXMLDOM.Context) {
self.context = context
self.node = context.rootNode
}
deinit {
self.context?.dispose()
}
public class func createWithData(data: NSData) -> Result<LibXMLNavigatingParserDOM> {
return { LibXMLNavigatingParserDOM(context: $0) } <^> LibXMLDOM.createWithData(data)
}
public class func createWithURL(url: NSURL) -> Result<LibXMLNavigatingParserDOM> {
return { LibXMLNavigatingParserDOM(context: $0) } <^> LibXMLDOM.createWithURL(url)
}
public func parseChildren(elementName: String) -> [LibXMLNavigatingParserDOM] {
let foundChildren = filter(LibXMLDOM.childrenOfNode(self.node)) { node in
LibXMLDOMGetElementType(node) == LibXMLElementType.ELEMENT_NODE && LibXMLDOMElementNameEquals(node, elementName)
}
return foundChildren.map { LibXMLNavigatingParserDOM(node: $0) }
}
public func parseText() -> String? {
let foundChild = firstPassing(LibXMLDOM.childrenOfNode(self.node)) { node in
return LibXMLDOMGetElementType(node) == LibXMLElementType.TEXT_NODE
}
return foundChild >>- LibXMLDOMGetText
}
}
| 30.764706 | 118 | 0.727215 |
1cca8ef05ec49a735b0bdf90a99630e19431263e | 3,506 | import Foundation
struct LocaleStore {
/// Result Enum
///
/// - Success: Returns Grouped By Alphabets Locale Info
/// - Error: Returns error
enum GroupedByAlphabetsFetchResults {
case success(response: [String: [LocaleInfo]])
case error(error: (title: String?, message: String?))
}
/// Result Enum
///
/// - Success: Returns Array of Locale Info
/// - Error: Returns error
enum FetchResults {
case success(response: [LocaleInfo])
case error(error: (title: String?, message: String?))
}
static func getInfo(completionHandler: @escaping (FetchResults) -> ()) {
let bundle = Bundle(for: LocalePickerViewController.self)
let path = "Countries.bundle/Data/CountryCodes"
guard let jsonPath = bundle.path(forResource: path, ofType: "json"),
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) else {
let error: (title: String?, message: String?) = (title: "ContryCodes Error", message: "No ContryCodes Bundle Access")
return completionHandler(FetchResults.error(error: error))
}
if let jsonObjects = (try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments)) as? Array<Any> {
var result: [LocaleInfo] = []
for jsonObject in jsonObjects {
guard let countryObj = jsonObject as? Dictionary<String, Any> else { continue }
guard let country = countryObj["name"] as? String,
let code = countryObj["code"] as? String,
let phoneCode = countryObj["dial_code"] as? String else {
continue
}
let new = LocaleInfo(country: country, code: code, phoneCode: phoneCode)
result.append(new)
}
return completionHandler(FetchResults.success(response: result))
}
let error: (title: String?, message: String?) = (title: "JSON Error", message: "Couldn't parse json to Info")
return completionHandler(FetchResults.error(error: error))
}
static func fetch(completionHandler: @escaping (GroupedByAlphabetsFetchResults) -> ()) {
LocaleStore.getInfo { result in
switch result {
case .success(let info):
/*
var header = Set<String>()
info.forEach {
let country = $0.country
header.insert(String(country[country.startIndex]))
}
*/
var data = [String: [LocaleInfo]]()
info.forEach {
let country = $0.country
let index = String(country[country.startIndex])
var value = data[index] ?? [LocaleInfo]()
value.append($0)
data[index] = value
}
data.forEach { key, value in
data[key] = value.sorted(by: { lhs, rhs in
return lhs.country < rhs.country
})
}
completionHandler(GroupedByAlphabetsFetchResults.success(response: data))
case .error(let error):
completionHandler(GroupedByAlphabetsFetchResults.error(error: error))
}
}
}
}
| 40.767442 | 155 | 0.543925 |
21a897d263f3c65e61d46cce82dcf7493ed17e97 | 4,571 | import UIKit
import SubstrateSdk
import SoraUI
import SnapKit
protocol AnalyticsValidatorsCellDelegate: AnyObject {
func didTapInfoButton(in cell: AnalyticsValidatorsCell)
}
final class AnalyticsValidatorsCell: UITableViewCell {
weak var delegate: AnalyticsValidatorsCellDelegate?
let iconView: PolkadotIconView = {
let view = PolkadotIconView()
view.backgroundColor = .clear
view.fillColor = R.color.colorWhite()!
return view
}()
let nameLabel: UILabel = {
let label = UILabel()
label.font = .p1Paragraph
label.textColor = R.color.colorWhite()
return label
}()
let progressView: RoundedView = {
let view = RoundedView()
view.fillColor = R.color.colorAccent()!
return view
}()
private var progressPercents: Double = 0.0
private var widthConstraint: Constraint?
let progressDescriptionLabel: UILabel = {
let label = UILabel()
label.font = .p3Paragraph
label.textColor = R.color.colorLightGray()
return label
}()
let infoButton: UIButton = {
let button = UIButton()
button.setImage(R.image.iconInfo(), for: .normal)
return button
}()
private lazy var progressStackView: UIStackView = {
UIView.hStack(
alignment: .center,
spacing: 8,
[progressView, progressDescriptionLabel]
)
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupLayout()
setupBackground()
infoButton.addTarget(self, action: #selector(tapInfoButton), for: .touchUpInside)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
progressPercents = 0
}
private enum Constants {
static let iconProgressSpacing: CGFloat = 12
static let progressValueSpacing: CGFloat = 8
}
override func layoutSubviews() {
super.layoutSubviews()
separatorInset = .init(top: 0, left: UIConstants.horizontalInset, bottom: 0, right: UIConstants.horizontalInset)
guard progressPercents > 0 else {
widthConstraint?.update(offset: 0)
progressStackView.setCustomSpacing(0, after: progressView)
return
}
let totalWidth = infoButton.frame.minX
- Constants.iconProgressSpacing
- iconView.frame.maxX
- Constants.iconProgressSpacing
- Constants.progressValueSpacing
- progressDescriptionLabel.bounds.width
progressStackView.setCustomSpacing(Constants.progressValueSpacing, after: progressView)
let progressViewWidth = totalWidth * CGFloat(progressPercents)
widthConstraint?.update(offset: progressViewWidth)
}
@objc
private func tapInfoButton() {
delegate?.didTapInfoButton(in: self)
}
private func setupLayout() {
let content = UIView.hStack(
alignment: .center,
spacing: Constants.iconProgressSpacing,
[
iconView,
.vStack(
alignment: .leading,
[
nameLabel,
progressStackView
]
),
infoButton
]
)
iconView.snp.makeConstraints { $0.size.equalTo(24) }
progressView.snp.makeConstraints { make in
make.height.equalTo(4)
widthConstraint = make.width.equalTo(progressPercents).constraint
}
contentView.addSubview(content)
content.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(UIConstants.horizontalInset)
make.top.bottom.equalToSuperview().inset(8)
}
}
private func setupBackground() {
backgroundColor = .clear
selectedBackgroundView = UIView()
selectedBackgroundView?.backgroundColor = R.color.colorHighlightedAccent()
}
func bind(viewModel: AnalyticsValidatorItemViewModel) {
if let icon = viewModel.icon {
iconView.bind(icon: icon)
}
nameLabel.text = viewModel.validatorName
progressDescriptionLabel.text = viewModel.progressFullDescription
progressPercents = viewModel.progressPercents
}
}
| 30.271523 | 120 | 0.623715 |
5d40da577121ffb7c6481831efe7b11e36696d81 | 9,030 | /* Copyright (c) 2018 PaddlePaddle Authors. 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 UIKit
import MetalKit
import CoreMedia
import paddle_mobile
import MetalPerformanceShaders
class FileReader {
let file: UnsafeMutablePointer<FILE>
let fileSize: Int
init(paramPath: String) throws {
guard let tmpFile = fopen(paramPath, "rb") else {
throw PaddleMobileError.loaderError(message: "open param file error" + paramPath)
}
file = tmpFile
fseek(file, 0, SEEK_END)
fileSize = ftell(file)
guard fileSize > 0 else {
throw PaddleMobileError.loaderError(message: "param file size is too small")
}
rewind(file)
}
func read<T>() -> UnsafeMutablePointer<T> {
let ptr = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T>.size * fileSize)
fread(ptr, fileSize, 1, file)
return ptr
}
deinit {
fclose(file)
}
}
enum Platform {
case GPU
}
let platformSupport: [(Platform, String)] = [(.GPU, "GPU")]
enum SupportModel: String{
case yolo = "yolo"
case mobilenet_combined = "mobilenet_combined"
case super_resolution = "superresoltion"
case mobilenet = "mobilenet"
static func supportedModels() -> [SupportModel] {
return [.super_resolution, .yolo, .mobilenet_combined, .mobilenet]
}
}
let netSupport: [SupportModel : Net] = [
.super_resolution : SuperResolutionNet.init(device: MetalHelper.shared.device),
.yolo : YoloNet.init(device: MetalHelper.shared.device),
.mobilenet_combined : MobileNetCombined.init(device: MetalHelper.shared.device),
.mobilenet : MobileNet.init(device: MetalHelper.shared.device)]
class ViewController: UIViewController {
@IBOutlet weak var resultTextView: UITextView!
@IBOutlet weak var selectImageView: UIImageView!
@IBOutlet weak var elapsedTimeLabel: UILabel!
@IBOutlet weak var modelPickerView: UIPickerView!
@IBOutlet weak var threadPickerView: UIPickerView!
@IBOutlet weak var videoView: UIView!
// var videoCapture: VideoCapture!
var selectImage: UIImage?
var inputPointer: UnsafeMutablePointer<Float32>?
var modelType: SupportModel = SupportModel.supportedModels()[0]
var toPredictTexture: MTLTexture?
var runner: Runner!
var platform: Platform = .GPU
var threadNum = 1
@IBAction func loadAct(_ sender: Any) {
runner = Runner.init(inNet: netSupport[modelType]!, commandQueue: MetalHelper.shared.queue)
if platform == .GPU {
// let filePath = Bundle.main.path(forResource: "mingren_input_data", ofType: nil)
// let fileReader = try! FileReader.init(paramPath: filePath!)
// let pointer: UnsafeMutablePointer<Float32> = fileReader.read()
//
//
// let buffer = MetalHelper.shared.device.makeBuffer(length: fileReader.fileSize, options: .storageModeShared)
//
// buffer?.contents().copyMemory(from: pointer, byteCount: fileReader.fileSize)
if self.toPredictTexture == nil {
// runner.getTexture(inBuffer: buffer!) { [weak self] (texture) in
// self?.toPredictTexture = texture
// }
runner.getTexture(image: selectImage!.cgImage!) { [weak self] (texture) in
self?.toPredictTexture = texture
}
}
} else {
fatalError( " unsupport " )
}
if runner.load() {
print(" load success ! ")
} else {
print(" load error ! ")
}
}
@IBAction func selectImageAct(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}
@IBAction func clearAct(_ sender: Any) {
runner.clear()
}
@IBAction func predictAct(_ sender: Any) {
let max = 1
switch platform {
case .GPU:
guard let inTexture = toPredictTexture else {
resultTextView.text = "请选择图片 ! "
return
}
let startDate = Date.init()
for i in 0..<max {
self.runner.predict(texture: inTexture) { [weak self] (success, resultHolder) in
guard let sSelf = self else {
fatalError()
}
if success, let inResultHolder = resultHolder {
if i == max - 1 {
let time = Date.init().timeIntervalSince(startDate)
print(inResultHolder.result.floatArr(count: inResultHolder.capacity).strideArray())
DispatchQueue.main.async {
sSelf.resultTextView.text = sSelf.runner.net.resultStr(res: resultHolder!)
sSelf.elapsedTimeLabel.text = "平均耗时: \(time/Double(max) * 1000.0) ms"
}
}
}
DispatchQueue.main.async {
resultHolder?.releasePointer()
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
modelPickerView.delegate = self
modelPickerView.dataSource = self
threadPickerView.delegate = self
threadPickerView.dataSource = self
if let image = UIImage.init(named: "classify-img-output.png") {
selectImage = image
selectImageView.image = image
} else {
print("请添加测试图片")
}
GlobalConfig.shared.computePrecision = .Float32
// if platform == .CPU {
// inputPointer = runner.preproccess(image: selectImage!.cgImage!)
// } else if platform == .GPU {
// runner.getTexture(image: selectImage!.cgImage!) {[weak self] (texture) in
// self?.toPredictTexture = texture
// }
// } else {
// fatalError( " unsupport " )
// }
// videoCapture = VideoCapture.init(device: MetalHelper.shared.device, orientation: .portrait, position: .back)
// videoCapture.fps = 30
// videoCapture.delegate = self
// videoCapture.setUp { (success) in
// DispatchQueue.main.async {
// if let preViewLayer = self.videoCapture.previewLayer {
// self.videoView.layer.addSublayer(preViewLayer)
// self.videoCapture.previewLayer?.frame = self.videoView.bounds
// }
// self.videoCapture.start()
// }
// }
}
}
extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
if pickerView == modelPickerView {
return 1
} else if pickerView == threadPickerView {
return 1
} else {
fatalError()
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == modelPickerView {
return SupportModel.supportedModels().count
} else if pickerView == threadPickerView {
return platformSupport.count
} else {
fatalError()
}
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == modelPickerView {
return SupportModel.supportedModels()[row].rawValue
} else if pickerView == threadPickerView {
return platformSupport[row].1
} else {
fatalError()
}
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == modelPickerView {
self.modelType = SupportModel.supportedModels()[row]
} else if pickerView == threadPickerView {
platform = platformSupport[row].0
} else {
fatalError()
}
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true){[weak self] in
guard let sSelf = self, let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else{
fatalError("no image")
}
sSelf.selectImage = image
sSelf.selectImageView.image = image
sSelf.runner.getTexture(image: image.cgImage!, getTexture: { (texture) in
sSelf.toPredictTexture = texture
})
}
}
}
var bool1 = false
extension ViewController: VideoCaptureDelegate{
func predictTexture(texture: MTLTexture){
runner.scaleTexture(input: texture) { (scaledTexture) in
self.runner.predict(texture: scaledTexture, completion: { (success, resultHolder) in
// print(resultHolder!.result![0])
resultHolder?.releasePointer()
})
}
}
}
| 31.684211 | 118 | 0.65526 |
e639129e27901c7eb3de3673022994de7f84d09c | 2,492 | //
// AppDelegate.swift
// FakeSwiftUI
//
// Created by youga on 02/24/2020.
// Copyright (c) 2020 youga. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow()
// window?.rootViewController = TextDemoViewController()
// window?.rootViewController = GradientTextDemoViewController()
// window?.rootViewController = ImageDemoViewController()
window?.rootViewController = GridDemoViewController()
window?.makeKeyAndVisible() // Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47.923077 | 285 | 0.747191 |
f4c9409182da36e73f54b97d3b49773dd19ea82d | 128 | extension MachineArray: CustomStringConvertible {
public var description: String {
return array.description
}
}
| 21.333333 | 49 | 0.71875 |
d686755f0009a61cd354137cde0e223524d77358 | 4,566 | //
// FileControlViewController.swift
// Sample
//
// Created by 1amageek on 2017/12/28.
// Copyright © 2017年 Stamp Inc. All rights reserved.
//
import UIKit
import FirebaseFirestore
import Pring
@objcMembers
class FileControlObject: Object {
dynamic var file: File?
dynamic var files: [File] = []
static func image(_ color: UIColor) -> UIImage {
let frame: CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
UIGraphicsBeginImageContext(frame.size)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(frame)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
class FileControlViewController: UIViewController {
var listener: ListenerRegistration?
var object: FileControlObject? {
didSet {
if let url: URL = object?.file?.downloadURL {
let data: Data = try! Data(contentsOf: url)
let image: UIImage = UIImage(data: data)!
self.imageView.image = image
self.imageView.setNeedsDisplay()
}
self.listener = object?.listen({ (object, error) in
if let url: URL = object?.file?.downloadURL {
let data: Data = try! Data(contentsOf: url)
let image: UIImage = UIImage(data: data)!
self.imageView.image = image
self.imageView.setNeedsDisplay()
self.collectionView.reloadData()
}
})
self.collectionView.reloadData()
}
}
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var collectionView: UICollectionView!
@IBAction func uploadAction(_ sender: Any) {
let object: FileControlObject = FileControlObject()
do {
let file: File = File(data: UIImageJPEGRepresentation(FileControlObject.image(UIColor.blue), 0.2)!, mimeType: .jpeg)
object.file = file
}
object.files = [UIColor.blue, UIColor.yellow, UIColor.red].map {
return File(data: UIImageJPEGRepresentation(FileControlObject.image($0), 0.2)!, name: UUID().uuidString, mimeType: .jpeg)
}
object.save { _, error in
print(object)
print(error)
self.object = object
}
}
@IBAction func updateAction(_ sender: Any) {
guard let object: FileControlObject = self.object else {
return
}
do {
let file: File = File(data: UIImageJPEGRepresentation(FileControlObject.image(UIColor.green), 0.2)!, mimeType: .jpeg)
object.file = file
}
object.files = [UIColor.purple, UIColor.brown, UIColor.orange].map {
return File(data: UIImageJPEGRepresentation(FileControlObject.image($0), 0.2)!, name: UUID().uuidString, mimeType: .jpeg)
}
object.update(nil) { (error) in
print(object)
print(error)
}
}
@IBAction func deleteAction(_ sender: Any) {
guard let object: FileControlObject = self.object else {
return
}
object.file = File.delete()
object.files = []
object.update()
}
@IBAction func deleteObjectAction(_ sender: Any) {
guard let object: FileControlObject = self.object else {
return
}
object.delete { (error) in
self.collectionView.reloadData()
}
}
}
extension FileControlViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.object?.files.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
if let file: File = self.object?.files[indexPath.item] {
if let url: URL = file.downloadURL {
let data: Data = try! Data(contentsOf: url)
let image: UIImage = UIImage(data: data)!
let imageView: UIImageView = UIImageView(image: image)
cell.backgroundView = imageView
cell.backgroundView?.setNeedsDisplay()
}
}
return cell
}
}
| 32.848921 | 136 | 0.606001 |
48968bdb5ec73b0d6488a70c2a2e006e3db3808f | 12,584 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
@_exported import AWSSDKSwiftCore
import Foundation
import NIO
/**
Client object for interacting with AWS ElasticsearchService service.
Amazon Elasticsearch Configuration Service Use the Amazon Elasticsearch Configuration API to create, configure, and manage Elasticsearch domains. For sample code that uses the Configuration API, see the Amazon Elasticsearch Service Developer Guide. The guide also contains sample code for sending signed HTTP requests to the Elasticsearch APIs. The endpoint for configuration service requests is region-specific: es.region.amazonaws.com. For example, es.us-east-1.amazonaws.com. For a current list of supported regions and endpoints, see Regions and Endpoints.
*/
public struct ElasticsearchService {
//MARK: Member variables
public let client: AWSClient
//MARK: Initialization
/// Initialize the ElasticsearchService client
/// - parameters:
/// - accessKeyId: Public access key provided by AWS
/// - secretAccessKey: Private access key provided by AWS
/// - sessionToken: Token provided by STS.AssumeRole() which allows access to another AWS account
/// - region: Region of server you want to communicate with
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - middlewares: Array of middlewares to apply to requests and responses
/// - eventLoopGroupProvider: EventLoopGroup to use. Use `useAWSClientShared` if the client shall manage its own EventLoopGroup.
public init(accessKeyId: String? = nil, secretAccessKey: String? = nil, sessionToken: String? = nil, region: AWSSDKSwiftCore.Region? = nil, endpoint: String? = nil, middlewares: [AWSServiceMiddleware] = [], eventLoopGroupProvider: AWSClient.EventLoopGroupProvider = .useAWSClientShared) {
self.client = AWSClient(
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
region: region,
service: "es",
serviceProtocol: ServiceProtocol(type: .restjson),
apiVersion: "2015-01-01",
endpoint: endpoint,
serviceEndpoints: ["fips": "es-fips.us-west-1.amazonaws.com"],
middlewares: middlewares,
possibleErrorTypes: [ElasticsearchServiceErrorType.self],
eventLoopGroupProvider: eventLoopGroupProvider
)
}
//MARK: API Calls
/// Attaches tags to an existing Elasticsearch domain. Tags are a set of case-sensitive key value pairs. An Elasticsearch domain may have up to 10 tags. See Tagging Amazon Elasticsearch Service Domains for more information.
@discardableResult public func addTags(_ input: AddTagsRequest) -> EventLoopFuture<Void> {
return client.send(operation: "AddTags", path: "/2015-01-01/tags", httpMethod: "POST", input: input)
}
/// Cancels a scheduled service software update for an Amazon ES domain. You can only perform this operation before the AutomatedUpdateDate and when the UpdateStatus is in the PENDING_UPDATE state.
public func cancelElasticsearchServiceSoftwareUpdate(_ input: CancelElasticsearchServiceSoftwareUpdateRequest) -> EventLoopFuture<CancelElasticsearchServiceSoftwareUpdateResponse> {
return client.send(operation: "CancelElasticsearchServiceSoftwareUpdate", path: "/2015-01-01/es/serviceSoftwareUpdate/cancel", httpMethod: "POST", input: input)
}
/// Creates a new Elasticsearch domain. For more information, see Creating Elasticsearch Domains in the Amazon Elasticsearch Service Developer Guide.
public func createElasticsearchDomain(_ input: CreateElasticsearchDomainRequest) -> EventLoopFuture<CreateElasticsearchDomainResponse> {
return client.send(operation: "CreateElasticsearchDomain", path: "/2015-01-01/es/domain", httpMethod: "POST", input: input)
}
/// Permanently deletes the specified Elasticsearch domain and all of its data. Once a domain is deleted, it cannot be recovered.
public func deleteElasticsearchDomain(_ input: DeleteElasticsearchDomainRequest) -> EventLoopFuture<DeleteElasticsearchDomainResponse> {
return client.send(operation: "DeleteElasticsearchDomain", path: "/2015-01-01/es/domain/{DomainName}", httpMethod: "DELETE", input: input)
}
/// Deletes the service-linked role that Elasticsearch Service uses to manage and maintain VPC domains. Role deletion will fail if any existing VPC domains use the role. You must delete any such Elasticsearch domains before deleting the role. See Deleting Elasticsearch Service Role in VPC Endpoints for Amazon Elasticsearch Service Domains.
@discardableResult public func deleteElasticsearchServiceRole() -> EventLoopFuture<Void> {
return client.send(operation: "DeleteElasticsearchServiceRole", path: "/2015-01-01/es/role", httpMethod: "DELETE")
}
/// Returns domain configuration information about the specified Elasticsearch domain, including the domain ID, domain endpoint, and domain ARN.
public func describeElasticsearchDomain(_ input: DescribeElasticsearchDomainRequest) -> EventLoopFuture<DescribeElasticsearchDomainResponse> {
return client.send(operation: "DescribeElasticsearchDomain", path: "/2015-01-01/es/domain/{DomainName}", httpMethod: "GET", input: input)
}
/// Provides cluster configuration information about the specified Elasticsearch domain, such as the state, creation date, update version, and update date for cluster options.
public func describeElasticsearchDomainConfig(_ input: DescribeElasticsearchDomainConfigRequest) -> EventLoopFuture<DescribeElasticsearchDomainConfigResponse> {
return client.send(operation: "DescribeElasticsearchDomainConfig", path: "/2015-01-01/es/domain/{DomainName}/config", httpMethod: "GET", input: input)
}
/// Returns domain configuration information about the specified Elasticsearch domains, including the domain ID, domain endpoint, and domain ARN.
public func describeElasticsearchDomains(_ input: DescribeElasticsearchDomainsRequest) -> EventLoopFuture<DescribeElasticsearchDomainsResponse> {
return client.send(operation: "DescribeElasticsearchDomains", path: "/2015-01-01/es/domain-info", httpMethod: "POST", input: input)
}
/// Describe Elasticsearch Limits for a given InstanceType and ElasticsearchVersion. When modifying existing Domain, specify the DomainName to know what Limits are supported for modifying.
public func describeElasticsearchInstanceTypeLimits(_ input: DescribeElasticsearchInstanceTypeLimitsRequest) -> EventLoopFuture<DescribeElasticsearchInstanceTypeLimitsResponse> {
return client.send(operation: "DescribeElasticsearchInstanceTypeLimits", path: "/2015-01-01/es/instanceTypeLimits/{ElasticsearchVersion}/{InstanceType}", httpMethod: "GET", input: input)
}
/// Lists available reserved Elasticsearch instance offerings.
public func describeReservedElasticsearchInstanceOfferings(_ input: DescribeReservedElasticsearchInstanceOfferingsRequest) -> EventLoopFuture<DescribeReservedElasticsearchInstanceOfferingsResponse> {
return client.send(operation: "DescribeReservedElasticsearchInstanceOfferings", path: "/2015-01-01/es/reservedInstanceOfferings", httpMethod: "GET", input: input)
}
/// Returns information about reserved Elasticsearch instances for this account.
public func describeReservedElasticsearchInstances(_ input: DescribeReservedElasticsearchInstancesRequest) -> EventLoopFuture<DescribeReservedElasticsearchInstancesResponse> {
return client.send(operation: "DescribeReservedElasticsearchInstances", path: "/2015-01-01/es/reservedInstances", httpMethod: "GET", input: input)
}
/// Returns a list of upgrade compatible Elastisearch versions. You can optionally pass a DomainName to get all upgrade compatible Elasticsearch versions for that specific domain.
public func getCompatibleElasticsearchVersions(_ input: GetCompatibleElasticsearchVersionsRequest) -> EventLoopFuture<GetCompatibleElasticsearchVersionsResponse> {
return client.send(operation: "GetCompatibleElasticsearchVersions", path: "/2015-01-01/es/compatibleVersions", httpMethod: "GET", input: input)
}
/// Retrieves the complete history of the last 10 upgrades that were performed on the domain.
public func getUpgradeHistory(_ input: GetUpgradeHistoryRequest) -> EventLoopFuture<GetUpgradeHistoryResponse> {
return client.send(operation: "GetUpgradeHistory", path: "/2015-01-01/es/upgradeDomain/{DomainName}/history", httpMethod: "GET", input: input)
}
/// Retrieves the latest status of the last upgrade or upgrade eligibility check that was performed on the domain.
public func getUpgradeStatus(_ input: GetUpgradeStatusRequest) -> EventLoopFuture<GetUpgradeStatusResponse> {
return client.send(operation: "GetUpgradeStatus", path: "/2015-01-01/es/upgradeDomain/{DomainName}/status", httpMethod: "GET", input: input)
}
/// Returns the name of all Elasticsearch domains owned by the current user's account.
public func listDomainNames() -> EventLoopFuture<ListDomainNamesResponse> {
return client.send(operation: "ListDomainNames", path: "/2015-01-01/domain", httpMethod: "GET")
}
/// List all Elasticsearch instance types that are supported for given ElasticsearchVersion
public func listElasticsearchInstanceTypes(_ input: ListElasticsearchInstanceTypesRequest) -> EventLoopFuture<ListElasticsearchInstanceTypesResponse> {
return client.send(operation: "ListElasticsearchInstanceTypes", path: "/2015-01-01/es/instanceTypes/{ElasticsearchVersion}", httpMethod: "GET", input: input)
}
/// List all supported Elasticsearch versions
public func listElasticsearchVersions(_ input: ListElasticsearchVersionsRequest) -> EventLoopFuture<ListElasticsearchVersionsResponse> {
return client.send(operation: "ListElasticsearchVersions", path: "/2015-01-01/es/versions", httpMethod: "GET", input: input)
}
/// Returns all tags for the given Elasticsearch domain.
public func listTags(_ input: ListTagsRequest) -> EventLoopFuture<ListTagsResponse> {
return client.send(operation: "ListTags", path: "/2015-01-01/tags/", httpMethod: "GET", input: input)
}
/// Allows you to purchase reserved Elasticsearch instances.
public func purchaseReservedElasticsearchInstanceOffering(_ input: PurchaseReservedElasticsearchInstanceOfferingRequest) -> EventLoopFuture<PurchaseReservedElasticsearchInstanceOfferingResponse> {
return client.send(operation: "PurchaseReservedElasticsearchInstanceOffering", path: "/2015-01-01/es/purchaseReservedInstanceOffering", httpMethod: "POST", input: input)
}
/// Removes the specified set of tags from the specified Elasticsearch domain.
@discardableResult public func removeTags(_ input: RemoveTagsRequest) -> EventLoopFuture<Void> {
return client.send(operation: "RemoveTags", path: "/2015-01-01/tags-removal", httpMethod: "POST", input: input)
}
/// Schedules a service software update for an Amazon ES domain.
public func startElasticsearchServiceSoftwareUpdate(_ input: StartElasticsearchServiceSoftwareUpdateRequest) -> EventLoopFuture<StartElasticsearchServiceSoftwareUpdateResponse> {
return client.send(operation: "StartElasticsearchServiceSoftwareUpdate", path: "/2015-01-01/es/serviceSoftwareUpdate/start", httpMethod: "POST", input: input)
}
/// Modifies the cluster configuration of the specified Elasticsearch domain, setting as setting the instance type and the number of instances.
public func updateElasticsearchDomainConfig(_ input: UpdateElasticsearchDomainConfigRequest) -> EventLoopFuture<UpdateElasticsearchDomainConfigResponse> {
return client.send(operation: "UpdateElasticsearchDomainConfig", path: "/2015-01-01/es/domain/{DomainName}/config", httpMethod: "POST", input: input)
}
/// Allows you to either upgrade your domain or perform an Upgrade eligibility check to a compatible Elasticsearch version.
public func upgradeElasticsearchDomain(_ input: UpgradeElasticsearchDomainRequest) -> EventLoopFuture<UpgradeElasticsearchDomainResponse> {
return client.send(operation: "UpgradeElasticsearchDomain", path: "/2015-01-01/es/upgradeDomain", httpMethod: "POST", input: input)
}
}
| 77.202454 | 560 | 0.767483 |
fbb0cebb2f0fdbef2d8ae9f3f46d2d31428f9dec | 304 | //
// RealmObject1.swift
// RealmBrowser-Swift
//
// Created by Max Baumbach on 02/04/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import RealmSwift
class Person: Object {
@objc dynamic var personName = ""
@objc dynamic var hungry = false
@objc dynamic var aCat: Cat?
}
| 16.888889 | 52 | 0.671053 |
3a9eed8aaa3be07530dc97756dc0bb1ec3398d3c | 4,515 | //
// SKDefine.swift
// StampKit
//
// Created by Sam Smallman on 22/02/2020.
// Copyright © 2020 Artifice Industries Ltd. All rights reserved.
//
import Foundation
import OSCKit
let StampKitVersion = "1.0.0"
// MARK: Bonjour (mDNS) Constants
let StampKitBonjourTCPServiceType: String = "_stamp._tcp."
let StampKitBonjourServiceDomain: String = "local."
public let StampKitPortNumber: Int = 24601
// MARK:- Heartbeat
let StampKitHeartbeatMaxAttempts: Int = 5
let StampKitHeartbeatInterval: TimeInterval = 5
let StampKitHeartbeatFailureInterval: TimeInterval = 1
// MARK:- SKTimelineDescription
let StampKitPasswordRequired: String = "SKPASSWORDREQUIRED"
// MARK:- SKStatusDescription
enum SKConnectionStatus: String {
case authorised
case unauthorised
}
/// SKTimelineHandler
///
/// - Parameter timeline: A `SKTimeline`
public typealias SKTimelineHandler = (_ timeline: SKTimeline) -> Void
public typealias SKTimelinesHandler = (_ timelines: [SKTimelineDescription]) -> Void
public typealias SKNoteHandler = (_ note: SKNoteDescription) -> Void
public typealias SKNotesHandler = (_ notes: [SKNoteDescription]) -> Void
internal typealias SKCompletionHandler = (SKData) -> Void
// MARK:- Address Pattern Parts
enum SKAddressParts: String {
case application = "/stamp"
case response = "/response"
case update = "/update"
case timelines = "/timelines"
case timeline = "/timeline"
case connect = "/connect"
case disconnect = "/disconnect"
case note = "/note"
case notes = "/notes"
case updates = "/updates"
case heartbeat = "/thump"
}
// MARK:- Timeline Password
enum SKTimelinePassword: String {
case authorised
case unauthorised
}
// MARK:- Note Colour
public enum SKNoteColour: String, Codable {
case green
case red
case yellow
case purple
case undefined
}
public enum SKResponseStatusCode: Int, Error, Codable {
enum ResponseType: String, Codable {
case success // The action requested by the client was received, understood, accepted, and processed successfully.
case clientError // The client errored.
case serverError // The server failed to fulfill an apparently valid request.
case undefined // The status code cannot be resolved.
}
// MARK: Success - 2xx
case ok = 200 // Successful Request
case created = 201 // Request has been fulfilled, resulting in the creation of a new resource.
case accepted = 202 // Request has been accepted for processing, but the processing has not been completed.
// MARK: Client Error - 4xx
case badRequest = 400 // The server cannot or will not process the request due to an apparent client error.
case unauthorized = 401 // Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.
case paymentRequired = 402 // The content available on the server requires payment.
case forbidden = 403 // The request was a valid request, but the server is refusing to respond to it.
case notFound = 404 // The requested resource could not be found but may be available in the future.
case methodNotAllowed = 405 // A request method is not supported for the requested resource. e.g. a GET request on a form which requires data to be presented via POST
case conflict = 409 // The request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates.
case gone = 410 // the resource requested is no longer available and will not be available again.
// MARK: Server Error - 5xx
case internalServerError = 500 // A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
case notImplemented = 501 // The server either does not recognize the request method, or it lacks the ability to fulfill the request.
case serviceUnavailable = 503 // The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state
case networkAuthenticationRequired = 511 // The client needs to authenticate to gain network access.
// The class (or group) which the status code belongs to.
var responseType: ResponseType {
switch self.rawValue {
case 200..<300: return .success
case 400..<500: return .clientError
case 500..<600: return .serverError
default: return .undefined
}
}
}
| 39.605263 | 170 | 0.724252 |
69187e16b7958a0dbf58355bdbde3b6ddedcd17b | 2,175 | //
// AppDelegate.swift
// TDDPorker
//
// Created by SakuiYoshimitsu on 2018/08/08.
// Copyright © 2018年 ysakui. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.276596 | 285 | 0.756322 |
38bd72279f5f00e443f77c43a982ee5b5a069833 | 575 | //
// Verification.swift
// VastParserSwift
//
// Created by 伊藤大司 on 7/10/20.
// Copyright © 2020 DJ110. All rights reserved.
//
import Foundation
public class Verification {
public var vendor: String? // required "company.com-omid TODO: Sampel does not have this parameter
public var javaScriptResource: [JavaScriptResource] = [] // 0+
public var executableResource: [ExecutableResource] = [] // 0+
public var trackingEvents: TrackingEvents? // 0-1
public var verificationParameters: VerificationParameters? // 0-1
}
| 25 | 103 | 0.676522 |
5dd49fb555f5c57a9d29f5359e2b06ea1d87e426 | 8,116 | //
// BUDNativeViewController.swift
// BUADVADemo_Swift
//
// Created by bytedance on 2020/11/6.
//
import Foundation
class BUDBannerViewController: ViewController {
private var _bannerView:BUNativeExpressBannerView?;
private lazy var _statusLabel = UILabel();
override func viewDidLoad() {
self.navigationItem.title = "Banner"
self.view.backgroundColor = .white;
creatView()
}
///load Portrait Ad
@objc func load320x50Ad(_ sender:UIButton) -> Void {
loadBannerWithSlotID(slotID: "900546833", size:CGSize.init(width: 320, height: 50))
}
///load Landscape Ad
@objc func load300x250Ad(_ sender:UIButton) -> Void {
loadBannerWithSlotID(slotID: "945509778", size:CGSize.init(width: 300, height: 250))
}
///show ad
@objc func showAd(_ sender:UIButton) -> Void {
if !(_bannerView==nil) {
self.view.addSubview(_bannerView!)
_statusLabel.text = "Tap left button to load Ad";
}
}
func loadBannerWithSlotID(slotID:String, size:CGSize) -> Void {
_bannerView?.removeFromSuperview()
_bannerView = nil;
var window = UIApplication.shared.delegate?.window
if window==nil {
window = UIApplication.shared.keyWindow;
}
if window==nil {
window = UIApplication.shared.windows.first
}
let bottom = (window!!).safeAreaInsets.bottom;
_bannerView = BUNativeExpressBannerView.init(slotID: slotID, rootViewController: self, adSize: size)
_bannerView?.frame = CGRect.init(x: (self.view.frame.size.width-size.width)/2.0, y: self.view.frame.size.height-size.height-bottom, width: size.width, height: size.height)
_bannerView?.delegate = self;
_bannerView?.loadAdData();
_statusLabel.text = "Loading......";
}
}
extension BUDBannerViewController:BUNativeExpressBannerViewDelegate {
/**
This method is called when bannerAdView ad slot loaded successfully.
@param bannerAdView : view for bannerAdView
*/
func nativeExpressBannerAdViewDidLoad(_ bannerAdView: BUNativeExpressBannerView) {
}
/**
This method is called when bannerAdView ad slot failed to load.
@param error : the reason of error
*/
func nativeExpressBannerAdView(_ bannerAdView: BUNativeExpressBannerView, didLoadFailWithError error: Error?) {
_statusLabel.text = "Ad loaded fail";
}
/**
This method is called when rendering a nativeExpressAdView successed.
*/
func nativeExpressBannerAdViewRenderSuccess(_ bannerAdView: BUNativeExpressBannerView) {
_statusLabel.text = "Ad loaded";
}
/**
This method is called when a nativeExpressAdView failed to render.
@param error : the reason of error
*/
func nativeExpressBannerAdViewRenderFail(_ bannerAdView: BUNativeExpressBannerView, error: Error?) {
_statusLabel.text = "Ad loaded fail";
}
/**
This method is called when bannerAdView ad slot showed new ad.
*/
func nativeExpressBannerAdViewWillBecomVisible(_ bannerAdView: BUNativeExpressBannerView) {
}
/**
This method is called when bannerAdView is clicked.
*/
func nativeExpressBannerAdViewDidClick(_ bannerAdView: BUNativeExpressBannerView) {
}
/**
This method is called when the user clicked dislike button and chose dislike reasons.
@param filterwords : the array of reasons for dislike.
*/
func nativeExpressBannerAdView(_ bannerAdView: BUNativeExpressBannerView, dislikeWithReason filterwords: [BUDislikeWords]?) {
_bannerView?.removeFromSuperview();
_bannerView = nil;
}
/**
This method is called when another controller has been closed.
@param interactionType : open appstore in app or open the webpage or view video ad details page.
*/
func nativeExpressBannerAdViewDidCloseOtherController(_ bannerAdView: BUNativeExpressBannerView, interactionType: BUInteractionType) {
}
}
///Exmple UI
extension BUDBannerViewController {
func creatView() -> Void {
let color = UIColor.init(red: 1.0, green: 0, blue: 23.0/255.0, alpha: 1);
let safeTop = Double(self.navigationController?.view.safeAreaInsets.top ?? 0.0)
_statusLabel.font = UIFont.init(name: "PingFang-SC", size: 16)
_statusLabel.textColor = color
_statusLabel.textAlignment = .center
_statusLabel.translatesAutoresizingMaskIntoConstraints = false
_statusLabel.text = "Tap left button to load Ad"
self.view.addSubview(_statusLabel);
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[_statusLabel]-20-|", options: NSLayoutConstraint.FormatOptions.init(), metrics: nil, views: ["_statusLabel":_statusLabel]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-top-[_statusLabel(25)]", options: NSLayoutConstraint.FormatOptions.init(), metrics: ["top":NSNumber.init(value:safeTop+100.0)], views: ["_statusLabel":_statusLabel]))
let load320x50Ad = UIButton(type:.custom)
load320x50Ad.layer.borderWidth = 0.5;
load320x50Ad.layer.cornerRadius = 8;
load320x50Ad.layer.borderColor = UIColor.lightGray.cgColor
load320x50Ad.translatesAutoresizingMaskIntoConstraints = false
load320x50Ad.addTarget(self, action: #selector(self.load320x50Ad), for: .touchUpInside)
load320x50Ad.setTitle("load 320x50 Banner", for: .normal)
load320x50Ad.setTitleColor(color, for: .normal)
self.view.addSubview(load320x50Ad)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[load320x50Ad]-170-|", options: NSLayoutConstraint.FormatOptions.init(), metrics: nil, views: ["load320x50Ad":load320x50Ad]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[_statusLabel]-20-[load320x50Ad(40)]", options: NSLayoutConstraint.FormatOptions.init(), metrics: nil, views: ["_statusLabel":_statusLabel,"load320x50Ad":load320x50Ad]))
let load300x250Ad = UIButton(type:.custom)
load300x250Ad.layer.borderWidth = 0.5;
load300x250Ad.layer.cornerRadius = 8;
load300x250Ad.layer.borderColor = UIColor.lightGray.cgColor
load300x250Ad.translatesAutoresizingMaskIntoConstraints = false
load300x250Ad.addTarget(self, action: #selector(self.load300x250Ad), for: .touchUpInside)
load300x250Ad.setTitle("load 300x250 Banner", for: .normal)
load300x250Ad.setTitleColor(color, for: .normal)
self.view.addSubview(load300x250Ad)
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[load300x250Ad]-170-|", options: NSLayoutConstraint.FormatOptions.init(), metrics: nil, views: ["load300x250Ad":load300x250Ad]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[load320x50Ad]-20-[load300x250Ad(40)]", options: NSLayoutConstraint.FormatOptions.init(), metrics: nil, views: ["load320x50Ad":load320x50Ad,"load300x250Ad":load300x250Ad]))
let showAd = UIButton(type:.custom)
showAd.layer.cornerRadius = 8;
showAd.translatesAutoresizingMaskIntoConstraints = false;
showAd.addTarget(self, action: #selector(self.showAd), for: .touchUpInside)
showAd.setTitle("showAd", for: .normal)
showAd.setTitleColor(.white, for: .normal)
showAd.setTitleColor(.blue, for: .highlighted)
showAd.backgroundColor = color;
self.view.addSubview(showAd);
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[showAd(80)]-40-|", options: NSLayoutConstraint.FormatOptions.init(), metrics: nil, views: ["showAd":showAd]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-top-[showAd(80)]", options: NSLayoutConstraint.FormatOptions.init(), metrics: ["top":NSNumber.init(value: safeTop+155.0)], views: ["showAd":showAd]))
}
}
| 47.461988 | 257 | 0.700099 |
f82eb08336193e572f0f6a0cdeacaae5a8c78a23 | 216 | //
// FetchTarget.swift
// RXSwift_MVVM
//
// Created by Amir Daliri on 6.07.2019.
// Copyright © 2019 AmirDaliri. All rights reserved.
//
import Foundation
enum FetchTarget: Int {
case albums = 0, posts
}
| 15.428571 | 53 | 0.675926 |
391921e6abb2b8c32e384b6a4fdacb44344079d4 | 3,814 | //
// Binary.swift
// HealthSoftware
//
// Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/Binary)
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
Pure binary content defined by a format other than FHIR.
A resource that represents the data of a single raw artifact as digital content accessible in its native format. A
Binary resource can contain any content, whether text, image, pdf, zip archive, etc.
*/
open class Binary: Resource {
override open class var resourceType: ResourceType { return .binary }
/// MimeType of the binary content
public var contentType: FHIRPrimitive<FHIRString>
/// Identifies another resource to use as proxy when enforcing access control
public var securityContext: Reference?
/// The actual content
public var data: FHIRPrimitive<Base64Binary>?
/// Designated initializer taking all required properties
public init(contentType: FHIRPrimitive<FHIRString>) {
self.contentType = contentType
super.init()
}
/// Convenience initializer
public convenience init(
contentType: FHIRPrimitive<FHIRString>,
data: FHIRPrimitive<Base64Binary>? = nil,
id: FHIRPrimitive<FHIRString>? = nil,
implicitRules: FHIRPrimitive<FHIRURI>? = nil,
language: FHIRPrimitive<FHIRString>? = nil,
meta: Meta? = nil,
securityContext: Reference? = nil)
{
self.init(contentType: contentType)
self.data = data
self.id = id
self.implicitRules = implicitRules
self.language = language
self.meta = meta
self.securityContext = securityContext
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case contentType; case _contentType
case data; case _data
case securityContext
}
/// Initializer for Decodable
public required init(from decoder: Decoder) throws {
let _container = try decoder.container(keyedBy: CodingKeys.self)
// Decode all our properties
self.contentType = try FHIRPrimitive<FHIRString>(from: _container, forKey: .contentType, auxiliaryKey: ._contentType)
self.data = try FHIRPrimitive<Base64Binary>(from: _container, forKeyIfPresent: .data, auxiliaryKey: ._data)
self.securityContext = try Reference(from: _container, forKeyIfPresent: .securityContext)
try super.init(from: decoder)
}
/// Encodable
public override func encode(to encoder: Encoder) throws {
var _container = encoder.container(keyedBy: CodingKeys.self)
// Encode all our properties
try contentType.encode(on: &_container, forKey: .contentType, auxiliaryKey: ._contentType)
try data?.encode(on: &_container, forKey: .data, auxiliaryKey: ._data)
try securityContext?.encode(on: &_container, forKey: .securityContext)
try super.encode(to: encoder)
}
// MARK: - Equatable & Hashable
public override func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? Binary else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return contentType == _other.contentType
&& data == _other.data
&& securityContext == _other.securityContext
}
public override func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(contentType)
hasher.combine(data)
hasher.combine(securityContext)
}
}
| 32.598291 | 119 | 0.731515 |
115f15e061c610f986afaec683369eda19b003da | 19,649 | // RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/class_differentiable_other_module.swift
import _Differentiation
// Verify that a type `T` conforms to `AdditiveArithmetic`.
func assertConformsToAdditiveArithmetic<T>(_: T.Type)
where T: AdditiveArithmetic {}
// Dummy protocol with default implementations for `AdditiveArithmetic` requirements.
// Used to test `Self : AdditiveArithmetic` requirements.
protocol DummyAdditiveArithmetic: AdditiveArithmetic {}
extension DummyAdditiveArithmetic {
static func == (lhs: Self, rhs: Self) -> Bool {
fatalError()
}
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
}
class Empty: Differentiable {}
func testEmpty() {
assertConformsToAdditiveArithmetic(Empty.TangentVector.self)
}
protocol DifferentiableWithNonmutatingMoveAlong: Differentiable {}
extension DifferentiableWithNonmutatingMoveAlong {
func move(along _: TangentVector) {}
}
class EmptyWithInheritedNonmutatingMoveAlong: DifferentiableWithNonmutatingMoveAlong {
typealias TangentVector = Empty.TangentVector
static func proof_that_i_have_nonmutating_move_along() {
let empty = EmptyWithInheritedNonmutatingMoveAlong()
empty.move(along: .init())
}
}
class EmptyWrapper<T: Differentiable & AnyObject>: Differentiable {}
func testEmptyWrapper() {
assertConformsToAdditiveArithmetic(Empty.TangentVector.self)
assertConformsToAdditiveArithmetic(EmptyWrapper<Empty>.TangentVector.self)
}
// Test structs with `let` stored properties.
// Derived conformances fail because `mutating func move` requires all stored
// properties to be mutable.
class ImmutableStoredProperties<T: Differentiable & AnyObject>: Differentiable {
var okay: Float
// expected-warning @+1 {{stored property 'nondiff' has no derivative because 'Int' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
let nondiff: Int
// expected-warning @+1 {{synthesis of the 'Differentiable.move(along:)' requirement for 'ImmutableStoredProperties' requires all stored properties not marked with `@noDerivative` to be mutable or have a non-mutating 'move(along:)'; use 'var' instead, or add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
let diff: Float
let letClass: Empty // No error on class-bound differentiable `let` with a non-mutating 'move(along:)'.
let letClassWithInheritedNonmutatingMoveAlong: EmptyWithInheritedNonmutatingMoveAlong
// expected-warning @+1 {{synthesis of the 'Differentiable.move(along:)' requirement for 'ImmutableStoredProperties' requires all stored properties not marked with `@noDerivative` to be mutable or have a non-mutating 'move(along:)'; use 'var' instead, or add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
let letClassGeneric: T // Error due to lack of non-mutating 'move(along:)'.
let letClassWrappingGeneric: EmptyWrapper<T> // No error on class-bound differentiable `let` with a non-mutating 'move(along:)'.
init(letClassGeneric: T) {
okay = 0
nondiff = 0
diff = 0
letClass = Empty()
self.letClassGeneric = letClassGeneric
self.letClassWrappingGeneric = EmptyWrapper<T>()
}
}
func testImmutableStoredProperties() {
_ = ImmutableStoredProperties<Empty>.TangentVector(
okay: 1,
letClass: Empty.TangentVector(),
letClassWithInheritedNonmutatingMoveAlong: Empty.TangentVector(),
letClassWrappingGeneric: EmptyWrapper<Empty>.TangentVector())
}
class MutableStoredPropertiesWithInitialValue: Differentiable {
var x = Float(1)
var y = Double(1)
}
// Test class with both an empty constructor and memberwise initializer.
class AllMixedStoredPropertiesHaveInitialValue: Differentiable {
// expected-warning @+1 {{synthesis of the 'Differentiable.move(along:)' requirement for 'AllMixedStoredPropertiesHaveInitialValue' requires all stored properties not marked with `@noDerivative` to be mutable or have a non-mutating 'move(along:)'; use 'var' instead, or add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
let x = Float(1)
var y = Float(1)
// Memberwise initializer should be `init(y:)` since `x` is immutable.
static func testMemberwiseInitializer() {
_ = AllMixedStoredPropertiesHaveInitialValue()
}
}
/*
class HasCustomConstructor: Differentiable {
var x = Float(1)
var y = Float(1)
// Custom constructor should not affect synthesis.
init(x: Float, y: Float, z: Bool) {}
}
*/
class Simple: Differentiable {
var w: Float
var b: Float
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
func testSimple() {
let simple = Simple(w: 1, b: 1)
let tangent = Simple.TangentVector(w: 1, b: 1)
simple.move(along: tangent)
}
// Test type with mixed members.
class Mixed: Differentiable {
var simple: Simple
var float: Float
init(simple: Simple, float: Float) {
self.simple = simple
self.float = float
}
}
func testMixed(_ simple: Simple, _ simpleTangent: Simple.TangentVector) {
let mixed = Mixed(simple: simple, float: 1)
let tangent = Mixed.TangentVector(simple: simpleTangent, float: 1)
mixed.move(along: tangent)
}
// Test type with manual definition of vector space types to `Self`.
final class VectorSpacesEqualSelf: Differentiable & DummyAdditiveArithmetic {
var w: Float
var b: Float
typealias TangentVector = VectorSpacesEqualSelf
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
/*
extension VectorSpacesEqualSelf : Equatable, AdditiveArithmetic {
static func == (lhs: VectorSpacesEqualSelf, rhs: VectorSpacesEqualSelf) -> Bool {
fatalError()
}
static var zero: VectorSpacesEqualSelf {
fatalError()
}
static func + (lhs: VectorSpacesEqualSelf, rhs: VectorSpacesEqualSelf) -> VectorSpacesEqualSelf {
fatalError()
}
static func - (lhs: VectorSpacesEqualSelf, rhs: VectorSpacesEqualSelf) -> VectorSpacesEqualSelf {
fatalError()
}
}
*/
// Test generic type with vector space types to `Self`.
class GenericVectorSpacesEqualSelf<T>: Differentiable
where T: Differentiable, T == T.TangentVector {
var w: T
var b: T
init(w: T, b: T) {
self.w = w
self.b = b
}
}
func testGenericVectorSpacesEqualSelf() {
let genericSame = GenericVectorSpacesEqualSelf<Double>(w: 1, b: 1)
let tangent = GenericVectorSpacesEqualSelf.TangentVector(w: 1, b: 1)
genericSame.move(along: tangent)
}
// Test nested type.
class Nested: Differentiable {
var simple: Simple
var mixed: Mixed
var generic: GenericVectorSpacesEqualSelf<Double>
init(
simple: Simple, mixed: Mixed, generic: GenericVectorSpacesEqualSelf<Double>
) {
self.simple = simple
self.mixed = mixed
self.generic = generic
}
}
func testNested(
_ simple: Simple, _ mixed: Mixed,
_ genericSame: GenericVectorSpacesEqualSelf<Double>
) {
_ = Nested(simple: simple, mixed: mixed, generic: genericSame)
}
// Test type that does not conform to `AdditiveArithmetic` but whose members do.
// Thus, `Self` cannot be used as `TangentVector` or `TangentVector`.
// Vector space structs types must be synthesized.
// Note: it would be nice to emit a warning if conforming `Self` to
// `AdditiveArithmetic` is possible.
class AllMembersAdditiveArithmetic: Differentiable {
var w: Float
var b: Float
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
// Test type whose properties are not all differentiable.
class DifferentiableSubset: Differentiable {
var w: Float
var b: Float
@noDerivative var flag: Bool
@noDerivative let technicallyDifferentiable: Float = .pi
init(w: Float, b: Float, flag: Bool) {
self.w = w
self.b = b
self.flag = flag
}
}
func testDifferentiableSubset() {
_ = DifferentiableSubset.TangentVector(w: 1, b: 1)
_ = DifferentiableSubset.TangentVector(w: 1, b: 1)
}
// Test nested type whose properties are not all differentiable.
class NestedDifferentiableSubset: Differentiable {
var x: DifferentiableSubset
var mixed: Mixed
@noDerivative var technicallyDifferentiable: Float
init(x: DifferentiableSubset, mixed: Mixed) {
self.x = x
self.mixed = mixed
technicallyDifferentiable = 0
}
}
// Test type that uses synthesized vector space types but provides custom
// method.
class HasCustomMethod: Differentiable {
var simple: Simple
var mixed: Mixed
var generic: GenericVectorSpacesEqualSelf<Double>
init(
simple: Simple, mixed: Mixed, generic: GenericVectorSpacesEqualSelf<Double>
) {
self.simple = simple
self.mixed = mixed
self.generic = generic
}
func move(along direction: TangentVector) {
print("Hello world")
simple.move(along: direction.simple)
mixed.move(along: direction.mixed)
generic.move(along: direction.generic)
}
}
// Test type with user-defined memberwise initializer.
class TF_25: Differentiable {
public var bar: Float
public init(bar: Float) {
self.bar = bar
}
}
// Test user-defined memberwise initializer.
class TF_25_Generic<T: Differentiable>: Differentiable {
public var bar: T
public init(bar: T) {
self.bar = bar
}
}
// Test initializer that is not a memberwise initializer because of stored property name vs parameter label mismatch.
class HasCustomNonMemberwiseInitializer<T: Differentiable>: Differentiable {
var value: T
init(randomLabel value: T) { self.value = value }
}
// Test type with generic environment.
class HasGenericEnvironment<Scalar: FloatingPoint & Differentiable>: Differentiable
{
var x: Float = 0
}
// Test type with generic members that conform to `Differentiable`.
class GenericSynthesizeAllStructs<T: Differentiable>: Differentiable {
var w: T
var b: T
init(w: T, b: T) {
self.w = w
self.b = b
}
}
// Test type in generic context.
class A<T: Differentiable> {
class B<U: Differentiable, V>: Differentiable {
class InGenericContext: Differentiable {
@noDerivative var a: A
var b: B
var t: T
var u: U
init(a: A, b: B, t: T, u: U) {
self.a = a
self.b = b
self.t = t
self.u = u
}
}
}
}
// Test extension.
class Extended {
var x: Float
init(x: Float) {
self.x = x
}
}
extension Extended: Differentiable {}
// Test extension of generic type.
class GenericExtended<T> {
var x: T
init(x: T) {
self.x = x
}
}
extension GenericExtended: Differentiable where T: Differentiable {}
// Test constrained extension of generic type.
class GenericConstrained<T> {
var x: T
init(x: T) {
self.x = x
}
}
extension GenericConstrained: Differentiable
where T: Differentiable {}
final class TF_260<T: Differentiable>: Differentiable & DummyAdditiveArithmetic
{
var x: T.TangentVector
init(x: T.TangentVector) {
self.x = x
}
}
// TF-269: Test crash when differentiation properties have no getter.
// Related to access levels and associated type inference.
// TODO(TF-631): Blocked by class type differentiation support.
// [AD] Unhandled instruction in adjoint emitter: %2 = ref_element_addr %0 : $TF_269, #TF_269.filter // user: %3
// [AD] Diagnosing non-differentiability.
// [AD] For instruction:
// %2 = ref_element_addr %0 : $TF_269, #TF_269.filter // user: %3
/*
public protocol TF_269_Layer: Differentiable & KeyPathIterable
where TangentVector: KeyPathIterable {
associatedtype Input: Differentiable
associatedtype Output: Differentiable
func applied(to input: Input) -> Output
}
public class TF_269 : TF_269_Layer {
public var filter: Float
public typealias Activation = @differentiable(reverse) (Output) -> Output
@noDerivative public let activation: @differentiable(reverse) (Output) -> Output
init(filter: Float, activation: @escaping Activation) {
self.filter = filter
self.activation = activation
}
// NOTE: `KeyPathIterable` derived conformances do not yet support class
// types.
public var allKeyPaths: [PartialKeyPath<TF_269>] {
[]
}
public func applied(to input: Float) -> Float {
return input
}
}
*/
// Test errors.
// expected-error @+1 {{class 'MissingInitializer' has no initializers}}
class MissingInitializer: Differentiable {
// expected-note @+1 {{stored property 'w' without initial value prevents synthesized initializers}}
var w: Float
// expected-note @+1 {{stored property 'b' without initial value prevents synthesized initializers}}
var b: Float
}
// Test manually customizing vector space types.
// These should fail. Synthesis is semantically unsupported if vector space
// types are customized.
final class TangentVectorWB: DummyAdditiveArithmetic, Differentiable {
var w: Float
var b: Float
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
// expected-error @+3 {{'Differentiable' requires the types 'VectorSpaceTypeAlias.TangentVector' (aka 'TangentVectorWB') and 'TangentVectorWB.TangentVector' be equivalent}}
// expected-note @+2 {{requirement specified as 'Self.TangentVector' == 'Self.TangentVector.TangentVector' [with Self = VectorSpaceTypeAlias]}}
// expected-error @+1 {{type 'VectorSpaceTypeAlias' does not conform to protocol 'Differentiable'}}
final class VectorSpaceTypeAlias: DummyAdditiveArithmetic, Differentiable {
var w: Float
var b: Float
typealias TangentVector = TangentVectorWB
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
// expected-error @+1 {{type 'VectorSpaceCustomStruct' does not conform to protocol 'Differentiable'}}
final class VectorSpaceCustomStruct: DummyAdditiveArithmetic, Differentiable {
var w: Float
var b: Float
struct TangentVector: AdditiveArithmetic, Differentiable {
var w: Float.TangentVector
var b: Float.TangentVector
typealias TangentVector = VectorSpaceCustomStruct.TangentVector
}
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
class StaticNoDerivative: Differentiable {
@noDerivative static var s: Bool = true
}
final class StaticMembersShouldNotAffectAnything: DummyAdditiveArithmetic,
Differentiable
{
static var x: Bool = true
static var y: Bool = false
}
class ImplicitNoDerivative: Differentiable {
var a: Float = 0
var b: Bool = true // expected-warning {{stored property 'b' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
}
class ImplicitNoDerivativeWithSeparateTangent: Differentiable {
var x: DifferentiableSubset
var b: Bool = true // expected-warning {{stored property 'b' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
init(x: DifferentiableSubset) {
self.x = x
}
}
// TF-1018: verify that `@noDerivative` warnings are always silenceable, even
// when the `Differentiable` conformance context is not the nominal type
// declaration.
class ExtensionDifferentiableNoDerivative<T> {
// expected-warning @+2 {{stored property 'x' has no derivative because 'T' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
// expected-warning @+1 {{stored property 'y' has no derivative because 'T' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
var x, y: T
// expected-warning @+1 {{stored property 'nondiff' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
var nondiff: Bool
init() { fatalError() }
}
extension ExtensionDifferentiableNoDerivative: Differentiable {}
class ExtensionDifferentiableNoDerivativeFixed<T> {
@noDerivative var x, y: T
@noDerivative var nondiff: Bool
init() { fatalError() }
}
extension ExtensionDifferentiableNoDerivativeFixed: Differentiable {}
class ConditionalDifferentiableNoDerivative<T> {
var x, y: T
// expected-warning @+1 {{stored property 'nondiff' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
var nondiff: Bool
init() { fatalError() }
}
extension ConditionalDifferentiableNoDerivative: Differentiable
where T: Differentiable {}
class ConditionalDifferentiableNoDerivativeFixed<T> {
var x, y: T
@noDerivative var nondiff: Bool
init() { fatalError() }
}
extension ConditionalDifferentiableNoDerivativeFixed: Differentiable
where T: Differentiable {}
// TF-265: Test invalid initializer (that uses a non-existent type).
class InvalidInitializer: Differentiable {
init(filterShape: (Int, Int, Int, Int), blah: NonExistentType) {} // expected-error {{cannot find type 'NonExistentType' in scope}}
}
// Test memberwise initializer synthesis.
final class NoMemberwiseInitializerExtended<T> {
var value: T
init(_ value: T) {
self.value = value
}
}
extension NoMemberwiseInitializerExtended: Equatable, AdditiveArithmetic,
DummyAdditiveArithmetic
where T: AdditiveArithmetic {}
extension NoMemberwiseInitializerExtended: Differentiable
where T: Differentiable & AdditiveArithmetic {}
// SR-12793: Test interaction with `@differentiable` and `@derivative` type-checking.
class SR_12793: Differentiable {
@differentiable(reverse)
var x: Float = 0
@differentiable(reverse)
func method() -> Float { x }
@derivative(of: method)
func vjpMethod() -> (value: Float, pullback: (Float) -> TangentVector) { fatalError() }
// Test usage of synthesized `TangentVector` type.
// This should not produce an error: "reference to invalid associated type 'TangentVector'".
func move(along direction: TangentVector) {}
}
// Test property wrappers.
@propertyWrapper
struct ImmutableWrapper<Value> {
private var value: Value
var wrappedValue: Value { value }
init(wrappedValue: Value) {
self.value = wrappedValue
}
}
@propertyWrapper
struct Wrapper<Value> {
var wrappedValue: Value
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue: Value) { self.wrappedValue = wrappedValue }
}
struct Generic<T> {}
extension Generic: Differentiable where T: Differentiable {}
class WrappedProperties: Differentiable {
// expected-warning @+1 {{synthesis of the 'Differentiable.move(along:)' requirement for 'WrappedProperties' requires 'wrappedValue' in property wrapper 'ImmutableWrapper' to be mutable or have a non-mutating 'move(along:)'; add an explicit '@noDerivative' attribute}}
@ImmutableWrapper var immutableInt: Generic<Int> = Generic()
// expected-warning @+1 {{stored property 'mutableInt' has no derivative because 'Generic<Int>' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
@Wrapper var mutableInt: Generic<Int> = Generic()
@Wrapper var float: Generic<Float> = Generic()
@ClassWrapper var float2: Generic<Float> = Generic()
// SR-13071: Test `@differentiable` wrapped property.
@differentiable(reverse) @Wrapper var float3: Generic<Float> = Generic()
@noDerivative @ImmutableWrapper var nondiff: Generic<Int> = Generic()
static func testTangentMemberwiseInitializer() {
_ = TangentVector(float: .init(), float2: .init(), float3: .init())
}
}
// Test derived conformances in disallowed contexts.
extension OtherFileNonconforming: Differentiable {}
// expected-error @-1 {{extension outside of file declaring class 'OtherFileNonconforming' prevents automatic synthesis of 'move(along:)' for protocol 'Differentiable'}}
extension GenericOtherFileNonconforming: Differentiable {}
// expected-error @-1 {{extension outside of file declaring generic class 'GenericOtherFileNonconforming' prevents automatic synthesis of 'move(along:)' for protocol 'Differentiable'}}
| 32.053834 | 338 | 0.732607 |
8a3c23794149622b8cbe2f7ea0305996a0219666 | 328 | //
// detailCell3.swift
// UniversiTeam2
//
// Created by Jin Seok Park on 2015. 7. 30..
// Copyright (c) 2015년 Jin Seok Park. All rights reserved.
//
import UIKit
class detailCell3: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var text: UILabel!
}
| 14.909091 | 59 | 0.637195 |
c11a484d1d33fdc25e1fbf584bba6a55b73dfa34 | 1,387 | //
// SensorType.swift
// GlucoseDirect
//
import Foundation
enum SensorType: String, Codable {
case unknown = "Unknown"
case libre1 = "Libre 1"
case libre2EU = "Libre 2 EU"
case libre2CA = "Libre 2 CA"
case libre2US = "Libre 2 US"
case libre3 = "Libre 3"
case libreProH = "Libre Pro/H"
case libreSense = "Libre Sense"
case libreUS14day = "Libre US 14d"
case virtual = "Virtual Sensor"
// MARK: Lifecycle
init() {
self = .unknown
}
init(_ patchInfo: Data) {
switch patchInfo[0] {
case 0xDF:
self = .libre1
case 0xA2:
self = .libre1
case 0xE5:
self = .libreUS14day
case 0x70:
self = .libreProH
case 0x9D:
self = .libre2EU
case 0x76:
self = patchInfo[3] == 0x02 ? .libre2US
: patchInfo[3] == 0x04 ? .libre2CA
: patchInfo[2] >> 4 == 7 ? .libreSense
: .unknown
default:
if patchInfo.count > 6 { // Libre 3's NFC A1 command ruturns 35 or 28 bytes
self = .libre3
} else {
self = .unknown
}
}
}
// MARK: Internal
var description: String {
self.rawValue
}
var localizedString: String {
LocalizedString(self.rawValue)
}
}
| 22.370968 | 87 | 0.509012 |
dda9c1874148f20bb7fcc68f3e1db44df661417b | 772 | import UIKit
import XCTest
import ForegroundNotification
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.733333 | 111 | 0.611399 |
72f6b74896f253c797ece447d82d5408a4f08e36 | 252 | //: [Previous](@previous)
import UIKit
import Dumpling
// Produce html
let html = Markdown().parse(text).renderHTML()
// Produce attributed string using build-in theme
let string = Markdown().parse(text).renderAttributedString()
//: [Next](@next)
| 18 | 60 | 0.722222 |
79844f2d6c8cadd08a6b7e6c69d4dd4ba34298ec | 1,501 | // Generated by msgbuilder 2020-05-15 06:20:49 +0000
import StdMsgs
extension gazebo_msgs {
public enum DeleteModel: ServiceProt {
public static let md5sum: String = "9ce56b4e9e54616de25d796dc972a262"
public static let datatype = "gazebo_msgs/DeleteModel"
public struct Request: ServiceRequestMessage {
public static let md5sum: String = "ea31c8eab6fc401383cf528a7c0984ba"
public static let datatype = "gazebo_msgs/DeleteModelRequest"
public typealias ServiceType = DeleteModel
public static let definition = """
string model_name # name of the Gazebo Model to be deleted
"""
public var model_name: String
public init(model_name: String) {
self.model_name = model_name
}
public init() {
model_name = String()
}
}
public struct Response: ServiceResponseMessage {
public static let md5sum: String = "2ec6f3eff0161f4257b808b12bc830c2"
public static let datatype = "gazebo_msgs/DeleteModelResponse"
public typealias ServiceType = DeleteModel
public static let definition = """
bool success # return true if deletion is successful
string status_message # comments if available
"""
public var success: Bool
public var status_message: String
public init(success: Bool, status_message: String) {
self.success = success
self.status_message = status_message
}
public init() {
success = Bool()
status_message = String()
}
}
}
} | 27.290909 | 78 | 0.698201 |
6233427946739339b62448e873e041e65e5a57a6 | 7,286 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import FBSimulatorControl
import Foundation
extension FBSimulatorState {
public var description: String {
return FBSimulatorStateStringFromState(self).rawValue
}
}
extension FBiOSTargetQuery {
static func parseUDIDToken(_ token: String) throws -> String {
if let _ = UUID(uuidString: token) {
return token
}
if token.characters.count != 40 {
throw ParseError.couldNotInterpret("UDID is not 40 characters long", token)
}
let nonDeviceUDIDSet = CharacterSet(charactersIn: "0123456789ABCDEFabcdef").inverted
if let range = token.rangeOfCharacter(from: nonDeviceUDIDSet) {
let invalidCharacters = token.substring(with: range)
throw ParseError.couldNotInterpret("UDID contains non-hex character '\(invalidCharacters)'", token)
}
return token
}
}
extension URL {
static func urlRelativeTo(_ basePath: String, component: String, isDirectory: Bool) -> URL {
let url = URL(fileURLWithPath: basePath)
return url.appendingPathComponent(component, isDirectory: isDirectory)
}
var bridgedAbsoluteString: String {
return absoluteString
}
}
public typealias ControlCoreValue = FBJSONSerializable & CustomStringConvertible
@objc open class ControlCoreLoggerBridge: NSObject {
let reporter: EventReporter
init(reporter: EventReporter) {
self.reporter = reporter
}
@objc open func log(_ level: Int32, string: String) {
let subject = FBEventReporterSubject(logString: string, level: level)
reporter.report(subject)
}
}
extension FBiOSTargetType: Accumulator {
public func append(_ other: FBiOSTargetType) -> FBiOSTargetType {
return self == FBiOSTargetType.all ? intersection(other) : union(other)
}
}
extension FBiOSTargetQuery {
public static func ofCount(_ count: Int) -> FBiOSTargetQuery {
return allTargets().ofCount(count)
}
public func ofCount(_ count: Int) -> FBiOSTargetQuery {
return range(NSRange(location: 0, length: count))
}
}
extension FBiOSTargetQuery: Accumulator {
public func append(_ other: FBiOSTargetQuery) -> Self {
let targetType = self.targetType.append(other.targetType)
return udids(Array(other.udids))
.names(Array(other.names))
.states(other.states)
.architectures(Array(other.architectures))
.targetType(targetType)
.osVersions(Array(other.osVersions))
.devices(Array(other.devices))
.range(other.range)
}
}
extension FBiOSTargetFormatKey {
public static var allFields: [FBiOSTargetFormatKey] {
return [
FBiOSTargetFormatKey.UDID,
FBiOSTargetFormatKey.name,
FBiOSTargetFormatKey.model,
FBiOSTargetFormatKey.osVersion,
FBiOSTargetFormatKey.state,
FBiOSTargetFormatKey.architecture,
FBiOSTargetFormatKey.processIdentifier,
FBiOSTargetFormatKey.containerApplicationProcessIdentifier,
]
}
}
extension FBArchitecture {
public static var allFields: [FBArchitecture] {
return [
.I386,
.X86_64,
.armv7,
.armv7s,
.arm64,
]
}
}
extension FBiOSTargetFormat: Accumulator {
public func append(_ other: FBiOSTargetFormat) -> Self {
return appendFields(other.fields)
}
}
extension FBSimulatorBootConfiguration: Accumulator {
public func append(_ other: FBSimulatorBootConfiguration) -> Self {
var configuration = self
if let locale = other.localizationOverride ?? self.localizationOverride {
configuration = configuration.withLocalizationOverride(locale)
}
if let framebuffer = other.framebuffer ?? self.framebuffer {
configuration = configuration.withFramebuffer(framebuffer)
}
if let scale = other.scale ?? self.scale {
configuration = configuration.withScale(scale)
}
configuration = configuration.withOptions(options.union(other.options))
return configuration
}
}
extension FBProcessOutputConfiguration: Accumulator {
public func append(_ other: FBProcessOutputConfiguration) -> Self {
var configuration = self
if other.stdOut is String {
configuration = try! configuration.withStdOut(other.stdOut)
}
if other.stdErr is String {
configuration = try! configuration.withStdErr(other.stdErr)
}
return configuration
}
}
extension IndividualCreationConfiguration {
public var simulatorConfiguration: FBSimulatorConfiguration {
var configuration = FBSimulatorConfiguration.default()
if let model = self.model {
configuration = configuration.withDeviceModel(model)
}
if let os = self.os {
configuration = configuration.withOSNamed(os)
}
if let auxDirectory = self.auxDirectory {
configuration = configuration.withAuxillaryDirectory(auxDirectory)
}
return configuration
}
}
extension Bool {
static func fallback(from: String?, to: Bool) -> Bool {
guard let from = from else {
return false
}
switch from.lowercased() {
case "1", "true": return true
case "0", "false": return false
default: return false
}
}
}
extension HttpRequest {
func getBoolQueryParam(_ key: String, _ fallback: Bool) -> Bool {
return Bool.fallback(from: query[key], to: fallback)
}
}
extension FBiOSTargetFutureType {
public var eventName: EventName {
switch self {
case FBiOSTargetFutureType.applicationLaunch:
return .launch
case FBiOSTargetFutureType.agentLaunch:
return .launch
case FBiOSTargetFutureType.testLaunch:
return .launchXCTest
default:
return EventName(rawValue: rawValue)
}
}
}
extension FBiOSTargetFuture {
public var eventName: EventName {
return type(of: self).futureType.eventName
}
public var printable: String {
let json = try! JSON.encode(FBiOSActionRouter.json(fromAction: self) as AnyObject)
return try! json.serializeToString(false)
}
}
extension FBProcessLaunchConfiguration: EnvironmentAdditive {}
extension FBTestLaunchConfiguration: EnvironmentAdditive {
func withEnvironmentAdditions(_ environmentAdditions: [String: String]) -> Self {
guard let appLaunchConf = self.applicationLaunchConfiguration else {
return self
}
return withApplicationLaunchConfiguration(appLaunchConf.withEnvironmentAdditions(environmentAdditions))
}
}
public typealias Writer = FBFileConsumer
public extension Writer {
func write(_ string: String) {
var output = string
if output.characters.last != "\n" {
output.append("\n" as Character)
}
guard let data = output.data(using: String.Encoding.utf8) else {
return
}
consumeData(data)
}
}
public typealias FileHandleWriter = FBFileWriter
public extension FileHandleWriter {
static var stdOutWriter: FileHandleWriter {
return FileHandleWriter.syncWriter(with: FileHandle.standardOutput)
}
static var stdErrWriter: FileHandleWriter {
return FileHandleWriter.syncWriter(with: FileHandle.standardError)
}
}
public typealias EventType = FBEventType
public typealias JSONKeys = FBJSONKey
| 28.460938 | 107 | 0.725226 |
1c5547d89c1f85ad8cc60dab710b71026c2a53ba | 8,026 | //===--------------- IncrementalCompilationTests.swift - Swift Testing ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
import XCTest
@_spi(Testing) import SwiftDriver
final class IncrementalCompilationTests: XCTestCase {
func testBuildRecordReading() throws {
let buildRecord = try! BuildRecord(contents: Inputs.buildRecord)
XCTAssertEqual(buildRecord.swiftVersion,
"Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7)")
XCTAssertEqual(buildRecord.argsHash, "abbbfbcaf36b93e58efaadd8271ff142")
try XCTAssertEqual(buildRecord.buildTime,
Date(legacyDriverSecsAndNanos: [1570318779, 32358000]))
try XCTAssertEqual(buildRecord.inputInfos,
[
VirtualPath(path: "/Volumes/AS/repos/swift-driver/sandbox/sandbox/sandbox/file2.swift"):
InputInfo(status: .needsCascadingBuild,
previousModTime: Date(legacyDriverSecsAndNanos: [1570318778, 0])),
VirtualPath(path: "/Volumes/AS/repos/swift-driver/sandbox/sandbox/sandbox/main.swift"):
InputInfo(status: .upToDate,
previousModTime: Date(legacyDriverSecsAndNanos: [1570083660, 0])),
VirtualPath(path: "/Volumes/gazorp.swift"):
InputInfo(status: .needsNonCascadingBuild,
previousModTime: Date(legacyDriverSecsAndNanos: [0, 0]))
])
}
func testReadBinarySourceFileDependencyGraph() throws {
let packageRootPath = URL(fileURLWithPath: #file).pathComponents
.prefix(while: { $0 != "Tests" }).joined(separator: "/").dropFirst()
let testInputPath = packageRootPath + "/TestInputs/Incremental/main.swiftdeps"
let graph = try SourceFileDependencyGraph(pathString: String(testInputPath))
XCTAssertEqual(graph.majorVersion, 1)
XCTAssertEqual(graph.minorVersion, 0)
XCTAssertEqual(graph.compilerVersionString, "Swift version 5.3-dev (LLVM f516ac602c, Swift c39f31febd)")
graph.verify()
var saw0 = false
var saw1 = false
var saw2 = false
graph.forEachNode { node in
switch (node.sequenceNumber, node.key.designator) {
case let (0, .sourceFileProvide(name: name)):
saw0 = true
XCTAssertEqual(node.key.aspect, .interface)
XCTAssertEqual(name, "main.swiftdeps")
XCTAssertEqual(node.fingerprint, "ec443bb982c3a06a433bdd47b85eeba2")
XCTAssertEqual(node.defsIDependUpon, [2])
XCTAssertTrue(node.isProvides)
case let (1, .sourceFileProvide(name: name)):
saw1 = true
XCTAssertEqual(node.key.aspect, .implementation)
XCTAssertEqual(name, "main.swiftdeps")
XCTAssertEqual(node.fingerprint, "ec443bb982c3a06a433bdd47b85eeba2")
XCTAssertEqual(node.defsIDependUpon, [])
XCTAssertTrue(node.isProvides)
case let (2, .topLevel(name: name)):
saw2 = true
XCTAssertEqual(node.key.aspect, .interface)
XCTAssertEqual(name, "a")
XCTAssertNil(node.fingerprint)
XCTAssertEqual(node.defsIDependUpon, [])
XCTAssertFalse(node.isProvides)
default:
XCTFail()
}
}
XCTAssertTrue(saw0)
XCTAssertTrue(saw1)
XCTAssertTrue(saw2)
}
func testReadComplexSourceFileDependencyGraph() throws {
let packageRootPath = URL(fileURLWithPath: #file).pathComponents
.prefix(while: { $0 != "Tests" }).joined(separator: "/").dropFirst()
let testInputPath = packageRootPath + "/TestInputs/Incremental/hello.swiftdeps"
let data = try Data(contentsOf: URL(fileURLWithPath: String(testInputPath)))
let graph = try SourceFileDependencyGraph(data: data)
XCTAssertEqual(graph.majorVersion, 1)
XCTAssertEqual(graph.minorVersion, 0)
XCTAssertEqual(graph.compilerVersionString, "Swift version 5.3-dev (LLVM 4510748e505acd4, Swift 9f07d884c97eaf4)")
graph.verify()
// Check that a node chosen at random appears as expected.
var foundNode = false
graph.forEachNode { node in
if case let .member(context: context, name: name) = node.key.designator,
node.sequenceNumber == 25
{
XCTAssertFalse(foundNode)
foundNode = true
XCTAssertEqual(node.key.aspect, .interface)
XCTAssertEqual(context, "5hello1BV")
XCTAssertEqual(name, "init")
XCTAssertEqual(node.defsIDependUpon, [])
XCTAssertFalse(node.isProvides)
}
}
XCTAssertTrue(foundNode)
// Check that an edge chosen at random appears as expected.
var foundEdge = false
graph.forEachArc { defNode, useNode in
if defNode.sequenceNumber == 0 && useNode.sequenceNumber == 10 {
switch (defNode.key.designator, useNode.key.designator) {
case let (.sourceFileProvide(name: defName),
.potentialMember(context: useContext)):
XCTAssertFalse(foundEdge)
foundEdge = true
XCTAssertEqual(defName, "/Users/owenvoorhees/Desktop/hello.swiftdeps")
XCTAssertEqual(defNode.fingerprint, "38b457b424090ac2e595be0e5f7e3b5b")
XCTAssertEqual(useContext, "5hello1AC")
XCTAssertEqual(useNode.fingerprint, "b83bbc0b4b0432dbfabff6556a3a901f")
default:
XCTFail()
}
}
}
XCTAssertTrue(foundEdge)
}
func testDateConversion() {
let sn = [0, 8000]
let d = try! Date(legacyDriverSecsAndNanos: sn)
XCTAssert(isCloseEnough(d.legacyDriverSecsAndNanos, sn))
}
func testReadAndWriteBuildRecord() throws {
let version = "Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7)"
let options = "abbbfbcaf36b93e58efaadd8271ff142"
let file2 = "/Volumes/AS/repos/swift-driver/sandbox/sandbox/sandbox/file2.swift"
let main = "/Volumes/AS/repos/swift-driver/sandbox/sandbox/sandbox/main.swift"
let gazorp = "/Volumes/gazorp.swift"
let inputString =
"""
version: "\(version)"
options: "\(options)"
build_time: [1570318779, 32357931]
inputs:
"\(file2)": !dirty [1570318778, 0]
"\(main)": [1570083660, 0]
"\(gazorp)": !private [0, 0]
"""
let buildRecord = try BuildRecord(contents: inputString)
XCTAssertEqual(buildRecord.swiftVersion, version)
XCTAssertEqual(buildRecord.argsHash, options)
XCTAssertEqual(buildRecord.inputInfos.count, 3)
XCTAssert(isCloseEnough(buildRecord.buildTime.legacyDriverSecsAndNanos,
[1570318779, 32357931]))
XCTAssertEqual(try! buildRecord.inputInfos[VirtualPath(path: file2 )]!.status,
.needsCascadingBuild)
XCTAssert(try! isCloseEnough(buildRecord.inputInfos[VirtualPath(path: file2 )]!
.previousModTime.legacyDriverSecsAndNanos,
[1570318778, 0]))
XCTAssertEqual(try! buildRecord.inputInfos[VirtualPath(path: gazorp)]!.status,
.needsNonCascadingBuild)
XCTAssertEqual(try! buildRecord.inputInfos[VirtualPath(path: gazorp)]!
.previousModTime.legacyDriverSecsAndNanos,
[0, 0])
XCTAssertEqual(try! buildRecord.inputInfos[VirtualPath(path: main )]!.status,
.upToDate)
XCTAssert(try! isCloseEnough( buildRecord.inputInfos[VirtualPath(path: main )]!
.previousModTime.legacyDriverSecsAndNanos,
[1570083660, 0]))
let outputString = try buildRecord.encode()
XCTAssertEqual(inputString, outputString)
}
/// The date conversions are not exact
func isCloseEnough(_ a: [Int], _ b: [Int]) -> Bool {
a[0] == b[0] && abs(a[1] - b[1]) <= 100
}
}
| 42.691489 | 118 | 0.663469 |
fcee9d1ad0fce70199132f3d76c51c14e40be6a0 | 577 | //
// WeatherSearchResultCell.swift
// WeatheriOS
//
// Created by 서상의 on 2020/12/29.
//
import WeatherUIKit
class WeatherSearchResultCell: TableViewCell {
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.textLabel?.textColor = .gray
self.backgroundColor = .clear
self.selectionStyle = .none
}
func setText(_ text: String) {
self.textLabel?.text = text
}
func setAttributedText(_ text: NSMutableAttributedString) {
self.textLabel?.attributedText = text
}
}
| 24.041667 | 63 | 0.672444 |
215d94fd1f4ad1bb5456059d2ade35b98d5f0ec1 | 8,329 | //
// Accessors.swift
// PMJSON
//
// Created by Kevin Ballard on 10/9/15.
// Copyright © 2016 Postmates.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
public extension JSON {
/// Returns `true` iff the receiver is `.null`.
var isNull: Bool {
switch self {
case .null: return true
default: return false
}
}
/// Returns `true` iff the receiver is `.bool`.
var isBool: Bool {
switch self {
case .bool: return true
default: return false
}
}
/// Returns `true` iff the receiver is `.string`.
var isString: Bool {
switch self {
case .string: return true
default: return false
}
}
/// Returns `true` iff the receiver is `.int64`.
var isInt64: Bool {
switch self {
case .int64: return true
default: return false
}
}
/// Returns `true` iff the receiver is `.double`.
var isDouble: Bool {
switch self {
case .double: return true
default: return false
}
}
/// Returns `true` iff the receiver is `.int64` or `.double`.
var isNumber: Bool {
switch self {
case .int64, .double: return true
default: return false
}
}
/// Returns `true` iff the receiver is `.object`.
var isObject: Bool {
switch self {
case .object: return true
default: return false
}
}
/// Returns `true` iff the receiver is `.array`.
var isArray: Bool {
switch self {
case .array: return true
default: return false
}
}
}
public extension JSON {
/// Returns the boolean value if the receiver is `.bool`, otherwise `nil`.
///
/// When setting, replaces the receiver with the given boolean value, or with
/// null if the value is `nil`.
var bool: Bool? {
get {
switch self {
case .bool(let b): return b
default: return nil
}
}
set {
self = newValue.map(JSON.bool) ?? nil
}
}
/// Returns the string value if the receiver is `.string`, otherwise `nil`.
///
/// When setting, replaces the receiver with the given string value, or with
/// null if the value is `nil`.
var string: String? {
get {
switch self {
case .string(let s): return s
default: return nil
}
}
set {
self = newValue.map(JSON.string) ?? nil
}
}
/// Returns the 64-bit integral value if the receiver is `.int64` or `.double`, otherwise `nil`.
/// If the receiver is `.double`, the value is truncated. If it does not fit in 64 bits, `nil` is returned.
///
/// When setting, replaces the receiver with the given integral value, or with
/// null if the value is `nil`.
var int64: Int64? {
get {
switch self {
case .int64(let i): return i
case .double(let d): return convertDoubleToInt64(d)
default: return nil
}
} set {
self = newValue.map(JSON.int64) ?? nil
}
}
/// Returns the integral value if the receiver is `.int64` or `.double`, otherwise `nil`.
/// If the receiver is `.double`, the value is truncated. If it does not fit in an `Int`, `nil` is returned.
/// If the receiver is `.int64` and the value does not fit in an `Int`, `nil` is returned.
///
/// When setting, replaces the receiver with the given integral value, or with
/// null if the value is `nil`.
var int: Int? {
get {
guard let value = self.int64 else { return nil}
let truncated = Int(truncatingBitPattern: value)
guard Int64(truncated) == value else { return nil }
return truncated
}
set {
self = newValue.map({ JSON.int64(Int64($0)) }) ?? nil
}
}
/// Returns the numeric value as a `Double` if the receiver is `.int64` or `.double`, otherwise `nil`.
///
/// When setting, replaces the receiver with the given double value, or with
/// null if the value is `nil`.
var double: Double? {
get {
switch self {
case .int64(let i): return Double(i)
case .double(let d): return d
default: return nil
}
}
set {
self = newValue.map(JSON.double) ?? nil
}
}
/// Returns the object dictionary if the receiver is `.object`, otherwise `nil`.
///
/// When setting, replaces the receiver with the given object value, or with
/// null if the value is `nil`.
var object: JSONObject? {
get {
switch self {
case .object(let obj): return obj
default: return nil
}
}
set {
self = newValue.map(JSON.object) ?? nil
}
}
/// Returns the array if the receiver is `.array`, otherwise `nil`.
///
/// When setting, replaces the receiver with the given array value, or with
/// null if the value is `nil`.
var array: JSONArray? {
get {
switch self {
case .array(let ary): return ary
default: return nil
}
}
set {
self = newValue.map(JSON.array) ?? nil
}
}
}
public extension JSON {
/// Returns the string value if the receiver is `.string`, coerces the value to a string if
/// the receiver is `.bool`, `.null`, `.int64`, or `.double`, or otherwise returns `nil`.
var asString: String? {
return try? toString()
}
/// Returns the 64-bit integral value if the receiver is `.int64` or `.double`, coerces the value
/// if the receiver is `.string`, otherwise returns `nil`.
/// If the receiver is `.double`, the value is truncated. If it does not fit in 64 bits, `nil` is returned.
/// If the receiver is `.string`, it must parse fully as an integral or floating-point number.
/// If it parses as a floating-point number, it is truncated. If it does not fit in 64 bits, `nil` is returned.
var asInt64: Int64? {
return try? toInt64()
}
/// Returns the integral value if the receiver is `.int64` or `.double`, coerces the value
/// if the receiver is `.string`, otherwise returns `nil`.
/// If the receiver is `.double`, the value is truncated. If it does not fit in an `Int`, `nil` is returned.
/// If the receiver is `.string`, it must parse fully as an integral or floating-point number.
/// If it parses as a floating-point number, it is truncated. If it does not fit in an `Int`, `nil` is returned.
var asInt: Int? {
return try? toInt()
}
/// Returns the double value if the receiver is `.int64` or `.double`, coerces the value
/// if the receiver is `.string`, otherwise returns `nil`.
/// If the receiver is `.string`, it must parse fully as a floating-point number.
var asDouble: Double? {
return try? toDouble()
}
}
public extension JSON {
/// If the receiver is `.object`, returns the result of subscripting the object.
/// Otherwise, returns `nil`.
subscript(key: String) -> JSON? {
return self.object?[key]
}
/// If the receiver is `.array` and the index is in range of the array, returns the result of subscripting the array.
/// Otherwise returns `nil`.
subscript(index: Int) -> JSON? {
guard let ary = self.array else { return nil }
guard index >= ary.startIndex && index < ary.endIndex else { return nil }
return ary[index]
}
}
internal func convertDoubleToInt64(_ d: Double) -> Int64? {
// Int64(Double(Int64.max)) asserts because it interprets it as out of bounds.
// Int64(Double(Int64.min)) works just fine.
if d >= Double(Int64.max) || d < Double(Int64.min) {
return nil
}
return Int64(d)
}
| 32.535156 | 121 | 0.568616 |
76ed00e4a7d16727cf07f9dd72cf48ad99051179 | 1,385 | struct LRecentTracksResponse : LastfmApiResponseWrapper {
let response: LRecentTracksResponseRecentTracks
enum CodingKeys : String, CodingKey {
case response = "recenttracks"
}
}
struct LRecentTracksResponseRecentTracks : LastfmApiResponse {
let entities: [LRecentTracksResponseTrack]
let attr: LAttr
enum CodingKeys : String, CodingKey {
case entities = "track"
case attr = "@attr"
}
}
struct LRecentTracksResponseTrack : Entity {
let name: String
let url: String
let artist: LRecentTracksResponseTrackArtist
let album: LRecentTracksResponseTrackAlbum
let date: LRecentTracksResponseTrackDate?
var type: EntityType {
get {
return .track
}
}
var value: String {
get {
return date?.text ?? "Scrobbling now"
}
}
}
struct LRecentTracksResponseTrackArtist : Codable {
let name: String
enum CodingKeys : String, CodingKey {
case name = "#text"
}
}
struct LRecentTracksResponseTrackAlbum : Codable {
let title: String
enum CodingKeys : String, CodingKey {
case title = "#text"
}
}
struct LRecentTracksResponseTrackDate : Codable {
let uts: String
let text: String
enum CodingKeys : String, CodingKey {
case uts
case text = "#text"
}
}
| 21.640625 | 62 | 0.636101 |
56c5f4e653b4eb3d5ac7d54edf274836a114fdc2 | 14,027 | //
// PermissionModelSet.swift
//
//
// Created by Jevon Mao on 2/6/21.
//
import Foundation
import SwiftUI
//MARK: - Storage
/**
The global shared storage for PermissionsSwiftUI
*/
public class PermissionStore: ObservableObject {
//MARK: Creating a new store
/**
Initalizes and returns a new instance of `PermissionStore`
The `PermissionStore` initliazer accepts no parameters, instead, set properties after intialization:
```
let store = PermissionStore()
store.mainTexts.headerText = "PermissionsSwiftUI is the best library"
*/
public init(){}
//a private singleton instance that allows read & write, but for this file's methods only
fileprivate static var mutableShared = PermissionStore()
//Read only singleton exposed to other parts of program
static var shared: PermissionStore {
get{
mutableShared
}
}
//MARK: All Permissions
///An array of permissions that configures the permissions to request
@Published public var permissions: [PermissionType] = []
/**
A global array of permissions that configures the permissions to request
- Warning: `permissionsToAsk` property is deprecated, renamed to `undeterminedPermissions`
*/
@available(iOS, deprecated: 13.0, obsoleted: 15.0, renamed: "undeterminedPermissions")
///An array of undetermined permissions filtered out from `permissions`
var permissionsToAsk: [PermissionType] {
return undeterminedPermissions
}
var undeterminedPermissions: [PermissionType] {
FilterPermissions.filterForShouldAskPermission(for: permissions)
}
var interactedPermissions: [PermissionType] {
//Filter for permissions that are not interacted
permissions.filter{!$0.currentPermission.interacted}
}
var isModalDismissalRestricted: Bool {
let store = PermissionStore.shared
let dismiss = store.restrictModalDismissal
if dismiss {
//interactedPermissions array not empty means some permissions are still not interacted
return !store.interactedPermissions.isEmpty
}
return false
}
var isAlertDismissalRestricted: Bool {
let store = PermissionStore.shared
let dismiss = store.restrictAlertDismissal
if dismiss {
//interactedPermissions array not empty means some permissions are still not interacted
return !store.interactedPermissions.isEmpty
}
return false
}
//MARK: Configuring View Texts
///The text for text label components, including header and descriptions
public var mainTexts = MainTexts()
/**
Encapsulates the surrounding texts and title
*/
public struct MainTexts: Equatable {
///Text to display for header text
public var headerText: String = "Need Permissions"
///Text to display for header description text
public var headerDescription: String = """
In order for you use certain features of this app, you need to give permissions. See description for each permission
"""
///Text to display for bottom part description text
public var bottomDescription: String = """
Permission are necessary for all the features and functions to work properly. If not allowed, you have to enable permissions in settings
"""
}
//MARK: Customizing Colors
///The color configuration for permission allow buttons
public var allButtonColors = AllButtonColors()
//MARK: Change Auto Dismiss Behaviors
///Whether to auto dismiss the modal after last permission is allowed
public var autoDismissModal: Bool = true
///Whether to auto dismiss the alert after last permission is allowed
public var autoDismissAlert: Bool = true
//MARK: Configure Auto Authorization Checking
///Whether to auto check for authorization status before showing, and show the view only if permission is in `notDetermined`
public var autoCheckModalAuth: Bool = true
///Whether to auto check for authorization status before showing, and show the view only if permission is in `notDetermined`
public var autoCheckAlertAuth: Bool = true
//MARK: Prevent Dismissal Before All Permissions Interacted
///Whether to prevent dismissal of modal view (along with an error haptic) before all permissions have been interacted (explict deny or allow)
public var restrictModalDismissal: Bool = true
///Whether to prevent dismissal of alert view (along with an error haptic) before all permissions have been interacted (explict deny or allow)
public var restrictAlertDismissal: Bool = true
//MARK: `onAppear` and `onDisappear` Executions
///Override point for executing action when PermissionsSwiftUI view appears
public var onAppear: (()->Void)?
///Override point for executing action when PermissionsSwiftUI view disappears
public var onDisappear: (()->Void)?
//MARK: Permission Components
///The displayed text and image icon for the camera permission
public var cameraPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "camera.fill")),
title: "Camera",
description: "Allow to use your camera", authorized: false)
///The displayed text and image icon for the location permission
public var locationPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "location.fill.viewfinder")),
title: "Location",
description: "Allow to access your location", authorized: false
)
///The displayed text and image icon for the location always permission
public var locationAlwaysPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "location.fill.viewfinder")),
title: "Location Always",
description: "Allow to access your location", authorized: false
)
///The displayed text and image icon for the photo library permission
public var photoPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "photo")),
title: "Photo Library",
description: "Allow to access your photos", authorized: false
)
///The displayed text and image icon for the microphone permission
public var microphonePermisson = JMPermission(
imageIcon: AnyView(Image(systemName: "mic.fill")),
title: "Microphone",
description: "Allow to record with microphone", authorized: false
)
///The displayed text and image icon for the notification center permission
public var notificationPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "bell.fill")),
title: "Notification",
description: "Allow to send notifications", authorized: false
)
///The displayed text and image icon for the calendar permission
public var calendarPermisson = JMPermission(
imageIcon: AnyView(Image(systemName: "calendar")),
title: "Calendar",
description: "Allow to access calendar", authorized: false
)
///The displayed text and image icon for the bluetooth permission
public var bluetoothPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "wave.3.left.circle.fill")),
title: "Bluetooth",
description: "Allow to use bluetooth", authorized: false
)
///The displayed text and image icon for the permission to track across apps and websites
public var trackingPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "person.circle.fill")),
title: "Tracking",
description: "Allow to track your data", authorized: false
)
///The displayed text and image icon for the contact permission
public var contactsPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "book.fill")),
title: "Contacts",
description: "Allow to access your contacts", authorized: false
)
///The displayed text and image icon for the motion permission
public var motionPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "hare.fill")),
title: "Motion",
description: "Allow to access your motion sensor data", authorized: false
)
///The displayed text and image icon for the reminders permission
public var remindersPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "list.bullet.rectangle")),
title: "Reminders",
description: "Allow to access your reminders", authorized: false
)
///The displayed text and image icon for the speech recognition permission
public var speechPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "rectangle.3.offgrid.bubble.left.fill")),
title: "Speech",
description: "Allow to access speech recognition", authorized: false
)
///The displayed text and image icon for the health permission
public var healthPermission = JMPermission(
imageIcon: AnyView(Image(systemName: "heart.fill")),
title: "Health",
description: "Allow to access your health information",
authorized: false)
}
// MARK: - Updating methods
extension PermissionStore{
//Used for unit testing, need to reset storage before each subtest
static func resetPermissionsModelStore(){
mutableShared = PermissionStore()
}
//inout enables caller to modify PermissionStore
func updateStore<T>(property:(inout PermissionStore, T)->Void, value:T){
//Closure passes back PermissionStore instance, and the generic value passed in method
property(&PermissionStore.mutableShared, value)
}
}
// MARK: - Button Customizations
/**
`AllButtonColors` encapsulates the color configuration for all states of the allow button
To customize button colors:
1. Define a new instance of the `AllButtonColors` struct
2. Add the `setAllowButtonColor(to colors:AllButtonColors)` modifier to your view
3. Pass in the `AllButtonColors` struct previously into the proper parameter
*/
public struct AllButtonColors: Equatable {
//MARK: Creating New Button Configs
/**
- parameters:
- buttonIdle: The button color configuration for the default, idle state
- buttonAllowed: The button color configuration for the highlighted, allowed state
- buttonDenied: The button color configuration for the user explicitly denied state
*/
public init(buttonIdle: ButtonColor, buttonAllowed: ButtonColor, buttonDenied: ButtonColor){
self.init()
self.buttonIdle = buttonIdle
self.buttonAllowed = buttonAllowed
self.buttonDenied = buttonDenied
}
/**
- parameters:
- buttonIdle: The button color configuration for the default, idle state
*/
public init(buttonIdle: ButtonColor){
self.init()
self.buttonIdle = buttonIdle
}
/**
- parameters:
- buttonAllowed: The button color configuration for the highlighted, allowed state
*/
public init(buttonAllowed: ButtonColor){
self.init()
self.buttonAllowed = buttonAllowed
}
/**
- parameters:
- buttonDenied: The button color configuration for the user explicitly denied state
*/
public init(buttonDenied: ButtonColor){
self.init()
self.buttonDenied = buttonDenied
}
/**
Initializes a new `AllbuttonColors` from the primary and tertiary colors
Both `primaryColor` and `tertiaryColor` are non-required parameters. Colors without a given initializer parameter will be displayed with the default color.
- parameters:
- primaryColor: The primary color, characterized by the default blue
- tertiaryColor: The tertiary color, characterized by the default alert red
*/
public init(primaryColor: Color?=nil, tertiaryColor: Color?=nil){
self.primaryColor = primaryColor ?? Color(.systemBlue)
self.tertiaryColor = tertiaryColor ?? Color(.systemRed)
self.buttonIdle = ButtonColor(foregroundColor: self.primaryColor,
backgroundColor: Color(.systemGray5))
self.buttonAllowed = ButtonColor(foregroundColor: Color(.white),
backgroundColor: self.primaryColor)
self.buttonDenied = ButtonColor(foregroundColor: Color(.white),
backgroundColor: self.tertiaryColor)
}
//MARK: Button Color States
var primaryColor: Color
var tertiaryColor: Color
///The button color configuration under idle status defined by a `ButtonColor` struct
public var buttonIdle: ButtonColor
///The button color configuration under allowed status defined by a `ButtonColor` struct
public var buttonAllowed: ButtonColor
///The button color configuration under denied status defined by a `ButtonColor` struct
public var buttonDenied: ButtonColor
}
/**
`ButtonColor` represents the color configuration for the allow button in a single state
Declared within parent struct `AllButtonColors` and should only be used within a `AllButtonColors` struct instance.
To customize
*/
public struct ButtonColor: Equatable {
// MARK: Creating New Button Color
/**
- parameters:
- foregroundColor: The color of type `Color` for the foreground text
- backgroundColor: The color of type `Color` for the background
*/
public init(foregroundColor: Color, backgroundColor: Color){
self.foregroundColor = foregroundColor
self.backgroundColor = backgroundColor
}
//MARK: Properties
///The color of type `Color` for the foreground text
public var foregroundColor: Color
///The color of type `Color` for the foreground text
public var backgroundColor: Color
}
| 43.562112 | 180 | 0.688601 |
697dedef2b85ca28f56893902fea640cbb4555e3 | 3,274 | //
// OperatorRemoveDuplicatesViewController.swift
// CombineOperatorsCore
//
// Copyright (c) 2020 cocoatoucher user on github.com (https://github.com/cocoatoucher/)
//
// 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 Combine
class OperatorRemoveDuplicatesViewController: BaseOperatorViewController {
override func setupOperator() {
operators = [Operator(name: "remove\nDuplicates", description: nil)]
operatorInfo = "Publishes only elements that don’t match the previous element."
operatorCode = """
let subject = PassthroughSubject<String?, Error>()
let removeDuplicates = subject.removeDuplicates()
removeDuplicates
.sink(
receiveValue: { value in
display(value)
}
)
"""
}
override func setupBindings() {
let subject1 = Subject(
title: "Subject",
inputValues: ["🌟", "✅", nil]
)
subjects = [subject1]
let removeDuplicates = subject1.trackedPublisher!.removeDuplicates()
subscription = removeDuplicates
.handleEvents(
receiveSubscription: { [weak self] _ in
guard let self = self else { return }
self.updateOperator(.subscription)
}, receiveCancel: { [weak self] in
guard let self = self else { return }
self.updateOperator(.cancel)
}, receiveRequest: { [weak self] _ in
guard let self = self else { return }
self.updateOperator(.request)
}
)
.sink(
receiveCompletion: { [weak self] completion in
guard let self = self else { return }
self.setCompletionFromOperator(completion: completion)
}, receiveValue: { [weak self] value in
guard let self = self else { return }
self.setValueFromOperator(value: value)
}
)
}
}
| 38.517647 | 89 | 0.597434 |
67fd5752ce95b98549f917ac55337b63540ac746 | 410 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import Foundation
import LoadingSystem
public final class LocalFeedLoader<AStore: Store>: LocalLoader<[FeedImage], AStore> where AStore.Local == LocalFeedImage {
public convenience init(store: AStore, currentDate: @escaping () -> Date) {
self.init(store: store, currentDate: currentDate) {
cache in
cache.feed.toModels()
}
}
}
| 25.625 | 122 | 0.731707 |
b999dd3b528574fb2bbda29793a9125df24e2ecd | 1,262 | //
// ListViewModelCollectionView.swift
// SwiftBoard
//
// Created by Matt Daw on 2014-11-17.
// Copyright (c) 2014 Matt Daw. All rights reserved.
//
import UIKit
class ListViewModelCollectionView: UICollectionView, ListViewModelDelegate {
var listViewModel: ListViewModel? { return nil }
var deferAnimations: Bool = true
// MARK: ListViewModelDelegate
func listViewModelItemMoved(fromIndex: Int, toIndex: Int) {
let op = MoveItemOperation(collectionView: self, fromIndex: fromIndex, toIndex: toIndex)
if deferAnimations {
NSOperationQueue.mainQueue().addOperation(op)
} else {
op.start()
}
}
func listViewModelItemAddedAtIndex(index: Int) {
let op = AddItemOperation(collectionView: self, index: index)
if deferAnimations {
NSOperationQueue.mainQueue().addOperation(op)
} else {
op.start()
}
}
func listViewModelItemRemovedAtIndex(index: Int) {
let op = RemoveItemOperation(collectionView: self, index: index)
if deferAnimations {
NSOperationQueue.mainQueue().addOperation(op)
} else {
op.start()
}
}
}
| 26.851064 | 96 | 0.618859 |
23667d46805b42fe0242ae184a2ff41ef512f8e8 | 25,753 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: google/api/http.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// Defines the HTTP configuration for an API service. It contains a list of
/// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method
/// to one or more HTTP REST API methods.
public struct Google_Api_Http {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// A list of HTTP configuration rules that apply to individual API methods.
///
/// **NOTE:** All service configuration rules follow "last one wins" order.
public var rules: [Google_Api_HttpRule] = []
/// When set to true, URL path parmeters will be fully URI-decoded except in
/// cases of single segment matches in reserved expansion, where "%2F" will be
/// left encoded.
///
/// The default behavior is to not decode RFC 6570 reserved characters in multi
/// segment matches.
public var fullyDecodeReservedExpansion: Bool = false
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
/// `HttpRule` defines the mapping of an RPC method to one or more HTTP
/// REST API methods. The mapping specifies how different portions of the RPC
/// request message are mapped to URL path, URL query parameters, and
/// HTTP request body. The mapping is typically specified as an
/// `google.api.http` annotation on the RPC method,
/// see "google/api/annotations.proto" for details.
///
/// The mapping consists of a field specifying the path template and
/// method kind. The path template can refer to fields in the request
/// message, as in the example below which describes a REST GET
/// operation on a resource collection of messages:
///
///
/// service Messaging {
/// rpc GetMessage(GetMessageRequest) returns (Message) {
/// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}";
/// }
/// }
/// message GetMessageRequest {
/// message SubMessage {
/// string subfield = 1;
/// }
/// string message_id = 1; // mapped to the URL
/// SubMessage sub = 2; // `sub.subfield` is url-mapped
/// }
/// message Message {
/// string text = 1; // content of the resource
/// }
///
/// The same http annotation can alternatively be expressed inside the
/// `GRPC API Configuration` YAML file.
///
/// http:
/// rules:
/// - selector: <proto_package_name>.Messaging.GetMessage
/// get: /v1/messages/{message_id}/{sub.subfield}
///
/// This definition enables an automatic, bidrectional mapping of HTTP
/// JSON to RPC. Example:
///
/// HTTP | RPC
/// -----|-----
/// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))`
///
/// In general, not only fields but also field paths can be referenced
/// from a path pattern. Fields mapped to the path pattern cannot be
/// repeated and must have a primitive (non-message) type.
///
/// Any fields in the request message which are not bound by the path
/// pattern automatically become (optional) HTTP query
/// parameters. Assume the following definition of the request message:
///
///
/// service Messaging {
/// rpc GetMessage(GetMessageRequest) returns (Message) {
/// option (google.api.http).get = "/v1/messages/{message_id}";
/// }
/// }
/// message GetMessageRequest {
/// message SubMessage {
/// string subfield = 1;
/// }
/// string message_id = 1; // mapped to the URL
/// int64 revision = 2; // becomes a parameter
/// SubMessage sub = 3; // `sub.subfield` becomes a parameter
/// }
///
///
/// This enables a HTTP JSON to RPC mapping as below:
///
/// HTTP | RPC
/// -----|-----
/// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))`
///
/// Note that fields which are mapped to HTTP parameters must have a
/// primitive type or a repeated primitive type. Message types are not
/// allowed. In the case of a repeated type, the parameter can be
/// repeated in the URL, as in `...?param=A¶m=B`.
///
/// For HTTP method kinds which allow a request body, the `body` field
/// specifies the mapping. Consider a REST update method on the
/// message resource collection:
///
///
/// service Messaging {
/// rpc UpdateMessage(UpdateMessageRequest) returns (Message) {
/// option (google.api.http) = {
/// put: "/v1/messages/{message_id}"
/// body: "message"
/// };
/// }
/// }
/// message UpdateMessageRequest {
/// string message_id = 1; // mapped to the URL
/// Message message = 2; // mapped to the body
/// }
///
///
/// The following HTTP JSON to RPC mapping is enabled, where the
/// representation of the JSON in the request body is determined by
/// protos JSON encoding:
///
/// HTTP | RPC
/// -----|-----
/// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })`
///
/// The special name `*` can be used in the body mapping to define that
/// every field not bound by the path template should be mapped to the
/// request body. This enables the following alternative definition of
/// the update method:
///
/// service Messaging {
/// rpc UpdateMessage(Message) returns (Message) {
/// option (google.api.http) = {
/// put: "/v1/messages/{message_id}"
/// body: "*"
/// };
/// }
/// }
/// message Message {
/// string message_id = 1;
/// string text = 2;
/// }
///
///
/// The following HTTP JSON to RPC mapping is enabled:
///
/// HTTP | RPC
/// -----|-----
/// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")`
///
/// Note that when using `*` in the body mapping, it is not possible to
/// have HTTP parameters, as all fields not bound by the path end in
/// the body. This makes this option more rarely used in practice of
/// defining REST APIs. The common usage of `*` is in custom methods
/// which don't use the URL at all for transferring data.
///
/// It is possible to define multiple HTTP methods for one RPC by using
/// the `additional_bindings` option. Example:
///
/// service Messaging {
/// rpc GetMessage(GetMessageRequest) returns (Message) {
/// option (google.api.http) = {
/// get: "/v1/messages/{message_id}"
/// additional_bindings {
/// get: "/v1/users/{user_id}/messages/{message_id}"
/// }
/// };
/// }
/// }
/// message GetMessageRequest {
/// string message_id = 1;
/// string user_id = 2;
/// }
///
///
/// This enables the following two alternative HTTP JSON to RPC
/// mappings:
///
/// HTTP | RPC
/// -----|-----
/// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")`
/// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")`
///
/// # Rules for HTTP mapping
///
/// The rules for mapping HTTP path, query parameters, and body fields
/// to the request message are as follows:
///
/// 1. The `body` field specifies either `*` or a field path, or is
/// omitted. If omitted, it indicates there is no HTTP request body.
/// 2. Leaf fields (recursive expansion of nested messages in the
/// request) can be classified into three types:
/// (a) Matched in the URL template.
/// (b) Covered by body (if body is `*`, everything except (a) fields;
/// else everything under the body field)
/// (c) All other fields.
/// 3. URL query parameters found in the HTTP request are mapped to (c) fields.
/// 4. Any body sent with an HTTP request can contain only (b) fields.
///
/// The syntax of the path template is as follows:
///
/// Template = "/" Segments [ Verb ] ;
/// Segments = Segment { "/" Segment } ;
/// Segment = "*" | "**" | LITERAL | Variable ;
/// Variable = "{" FieldPath [ "=" Segments ] "}" ;
/// FieldPath = IDENT { "." IDENT } ;
/// Verb = ":" LITERAL ;
///
/// The syntax `*` matches a single path segment. The syntax `**` matches zero
/// or more path segments, which must be the last part of the path except the
/// `Verb`. The syntax `LITERAL` matches literal text in the path.
///
/// The syntax `Variable` matches part of the URL path as specified by its
/// template. A variable template must not contain other variables. If a variable
/// matches a single path segment, its template may be omitted, e.g. `{var}`
/// is equivalent to `{var=*}`.
///
/// If a variable contains exactly one path segment, such as `"{var}"` or
/// `"{var=*}"`, when such a variable is expanded into a URL path, all characters
/// except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the
/// Discovery Document as `{var}`.
///
/// If a variable contains one or more path segments, such as `"{var=foo/*}"`
/// or `"{var=**}"`, when such a variable is expanded into a URL path, all
/// characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables
/// show up in the Discovery Document as `{+var}`.
///
/// NOTE: While the single segment variable matches the semantics of
/// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2
/// Simple String Expansion, the multi segment variable **does not** match
/// RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion
/// does not expand special characters like `?` and `#`, which would lead
/// to invalid URLs.
///
/// NOTE: the field paths in variables and in the `body` must not refer to
/// repeated fields or map fields.
public struct Google_Api_HttpRule {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Selects methods to which this rule applies.
///
/// Refer to [selector][google.api.DocumentationRule.selector] for syntax details.
public var selector: String = String()
/// Determines the URL pattern is matched by this rules. This pattern can be
/// used with any of the {get|put|post|delete|patch} methods. A custom method
/// can be defined using the 'custom' field.
public var pattern: Google_Api_HttpRule.OneOf_Pattern? = nil
/// Used for listing and getting information about resources.
public var get: String {
get {
if case .get(let v)? = pattern {return v}
return String()
}
set {pattern = .get(newValue)}
}
/// Used for updating a resource.
public var put: String {
get {
if case .put(let v)? = pattern {return v}
return String()
}
set {pattern = .put(newValue)}
}
/// Used for creating a resource.
public var post: String {
get {
if case .post(let v)? = pattern {return v}
return String()
}
set {pattern = .post(newValue)}
}
/// Used for deleting a resource.
public var delete: String {
get {
if case .delete(let v)? = pattern {return v}
return String()
}
set {pattern = .delete(newValue)}
}
/// Used for updating a resource.
public var patch: String {
get {
if case .patch(let v)? = pattern {return v}
return String()
}
set {pattern = .patch(newValue)}
}
/// The custom pattern is used for specifying an HTTP method that is not
/// included in the `pattern` field, such as HEAD, or "*" to leave the
/// HTTP method unspecified for this rule. The wild-card rule is useful
/// for services that provide content to Web (HTML) clients.
public var custom: Google_Api_CustomHttpPattern {
get {
if case .custom(let v)? = pattern {return v}
return Google_Api_CustomHttpPattern()
}
set {pattern = .custom(newValue)}
}
/// The name of the request field whose value is mapped to the HTTP body, or
/// `*` for mapping all fields not captured by the path pattern to the HTTP
/// body. NOTE: the referred field must not be a repeated field and must be
/// present at the top-level of request message type.
public var body: String = String()
/// Optional. The name of the response field whose value is mapped to the HTTP
/// body of response. Other response fields are ignored. When
/// not set, the response message will be used as HTTP body of response.
public var responseBody: String = String()
/// Additional HTTP bindings for the selector. Nested bindings must
/// not contain an `additional_bindings` field themselves (that is,
/// the nesting may only be one level deep).
public var additionalBindings: [Google_Api_HttpRule] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
/// Determines the URL pattern is matched by this rules. This pattern can be
/// used with any of the {get|put|post|delete|patch} methods. A custom method
/// can be defined using the 'custom' field.
public enum OneOf_Pattern: Equatable {
/// Used for listing and getting information about resources.
case get(String)
/// Used for updating a resource.
case put(String)
/// Used for creating a resource.
case post(String)
/// Used for deleting a resource.
case delete(String)
/// Used for updating a resource.
case patch(String)
/// The custom pattern is used for specifying an HTTP method that is not
/// included in the `pattern` field, such as HEAD, or "*" to leave the
/// HTTP method unspecified for this rule. The wild-card rule is useful
/// for services that provide content to Web (HTML) clients.
case custom(Google_Api_CustomHttpPattern)
#if !swift(>=4.1)
public static func ==(lhs: Google_Api_HttpRule.OneOf_Pattern, rhs: Google_Api_HttpRule.OneOf_Pattern) -> Bool {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch (lhs, rhs) {
case (.get, .get): return {
guard case .get(let l) = lhs, case .get(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.put, .put): return {
guard case .put(let l) = lhs, case .put(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.post, .post): return {
guard case .post(let l) = lhs, case .post(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.delete, .delete): return {
guard case .delete(let l) = lhs, case .delete(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.patch, .patch): return {
guard case .patch(let l) = lhs, case .patch(let r) = rhs else { preconditionFailure() }
return l == r
}()
case (.custom, .custom): return {
guard case .custom(let l) = lhs, case .custom(let r) = rhs else { preconditionFailure() }
return l == r
}()
default: return false
}
}
#endif
}
public init() {}
}
/// A custom pattern is used for defining custom HTTP verb.
public struct Google_Api_CustomHttpPattern {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// The name of this custom HTTP verb.
public var kind: String = String()
/// The path matched by this custom verb.
public var path: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "google.api"
extension Google_Api_Http: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".Http"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "rules"),
2: .standard(proto: "fully_decode_reserved_expansion"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeRepeatedMessageField(value: &self.rules) }()
case 2: try { try decoder.decodeSingularBoolField(value: &self.fullyDecodeReservedExpansion) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.rules.isEmpty {
try visitor.visitRepeatedMessageField(value: self.rules, fieldNumber: 1)
}
if self.fullyDecodeReservedExpansion != false {
try visitor.visitSingularBoolField(value: self.fullyDecodeReservedExpansion, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Google_Api_Http, rhs: Google_Api_Http) -> Bool {
if lhs.rules != rhs.rules {return false}
if lhs.fullyDecodeReservedExpansion != rhs.fullyDecodeReservedExpansion {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Google_Api_HttpRule: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".HttpRule"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "selector"),
2: .same(proto: "get"),
3: .same(proto: "put"),
4: .same(proto: "post"),
5: .same(proto: "delete"),
6: .same(proto: "patch"),
8: .same(proto: "custom"),
7: .same(proto: "body"),
12: .standard(proto: "response_body"),
11: .standard(proto: "additional_bindings"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.selector) }()
case 2: try {
if self.pattern != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {self.pattern = .get(v)}
}()
case 3: try {
if self.pattern != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {self.pattern = .put(v)}
}()
case 4: try {
if self.pattern != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {self.pattern = .post(v)}
}()
case 5: try {
if self.pattern != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {self.pattern = .delete(v)}
}()
case 6: try {
if self.pattern != nil {try decoder.handleConflictingOneOf()}
var v: String?
try decoder.decodeSingularStringField(value: &v)
if let v = v {self.pattern = .patch(v)}
}()
case 7: try { try decoder.decodeSingularStringField(value: &self.body) }()
case 8: try {
var v: Google_Api_CustomHttpPattern?
if let current = self.pattern {
try decoder.handleConflictingOneOf()
if case .custom(let m) = current {v = m}
}
try decoder.decodeSingularMessageField(value: &v)
if let v = v {self.pattern = .custom(v)}
}()
case 11: try { try decoder.decodeRepeatedMessageField(value: &self.additionalBindings) }()
case 12: try { try decoder.decodeSingularStringField(value: &self.responseBody) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.selector.isEmpty {
try visitor.visitSingularStringField(value: self.selector, fieldNumber: 1)
}
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch self.pattern {
case .get?: try {
guard case .get(let v)? = self.pattern else { preconditionFailure() }
try visitor.visitSingularStringField(value: v, fieldNumber: 2)
}()
case .put?: try {
guard case .put(let v)? = self.pattern else { preconditionFailure() }
try visitor.visitSingularStringField(value: v, fieldNumber: 3)
}()
case .post?: try {
guard case .post(let v)? = self.pattern else { preconditionFailure() }
try visitor.visitSingularStringField(value: v, fieldNumber: 4)
}()
case .delete?: try {
guard case .delete(let v)? = self.pattern else { preconditionFailure() }
try visitor.visitSingularStringField(value: v, fieldNumber: 5)
}()
case .patch?: try {
guard case .patch(let v)? = self.pattern else { preconditionFailure() }
try visitor.visitSingularStringField(value: v, fieldNumber: 6)
}()
default: break
}
if !self.body.isEmpty {
try visitor.visitSingularStringField(value: self.body, fieldNumber: 7)
}
if case .custom(let v)? = self.pattern {
try visitor.visitSingularMessageField(value: v, fieldNumber: 8)
}
if !self.additionalBindings.isEmpty {
try visitor.visitRepeatedMessageField(value: self.additionalBindings, fieldNumber: 11)
}
if !self.responseBody.isEmpty {
try visitor.visitSingularStringField(value: self.responseBody, fieldNumber: 12)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Google_Api_HttpRule, rhs: Google_Api_HttpRule) -> Bool {
if lhs.selector != rhs.selector {return false}
if lhs.pattern != rhs.pattern {return false}
if lhs.body != rhs.body {return false}
if lhs.responseBody != rhs.responseBody {return false}
if lhs.additionalBindings != rhs.additionalBindings {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Google_Api_CustomHttpPattern: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".CustomHttpPattern"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "kind"),
2: .same(proto: "path"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.kind) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.path) }()
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.kind.isEmpty {
try visitor.visitSingularStringField(value: self.kind, fieldNumber: 1)
}
if !self.path.isEmpty {
try visitor.visitSingularStringField(value: self.path, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
public static func ==(lhs: Google_Api_CustomHttpPattern, rhs: Google_Api_CustomHttpPattern) -> Bool {
if lhs.kind != rhs.kind {return false}
if lhs.path != rhs.path {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 39.62 | 140 | 0.664427 |
48a50eeb9e68614b458e7c49b70e24827589bbce | 2,542 | //
// ViewController.swift
// Example
//
// Created by GongXiang on 12/8/16.
// Updated by Pradeep Sakharelia on 15/05/19
// Copyright © 2016 Kevin. All rights reserved.
//
import UIKit
import Printer
private extension TextBlock {
static func plainText(_ content: String) -> TextBlock {
return TextBlock(content: content, predefined: .light)
}
}
class ViewController: UIViewController {
let pm = PrinterManager()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func touchPrint(sender: UIButton) {
guard let image = UIImage(named: "demo") else {
return
}
if pm.canPrint {
var receipt = Receipt(
.title("Restaurant"),
.blank,
.text(.init("Palo Alto Californlia 94301")),
.text(.init("378-0987893742")),
.blank,
.text(.init(content: Date().description, predefined: .alignment(.center))),
.blank,
.kv(key: "Merchant ID:", value: "iceu1390"),
.kv(key: "Terminal ID:", value: "29383"),
.blank,
.kv(key: "Transaction ID:", value: "0x000321"),
.text(.plainText("PURCHASE")),
.blank,
.kv(key: "Sub Total", value: "USD$ 25.09"),
.kv(key: "Tip", value: "3.78"),
.dividing,
.kv(key: "Total", value: "USD$ 28.87"),
.blank,
.blank,
.blank,
.text(.init(content: "Thanks for supporting", predefined: .alignment(.center))),
.text(.init(content: "local bussiness!", predefined: .alignment(.center))),
.blank,
.text(.init(content: "THANK YOU", predefined: .bold, .alignment(.center))),
.blank,
.blank,
.blank,
.qr("https://www.yuxiaor.com"),
.blank,
.blank
)
receipt.feedLinesOnTail = 2
receipt.feedPointsPerLine = 60
pm.print(receipt)
} else {
performSegue(withIdentifier: "ShowSelectPrintVC", sender: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? PrinterTableViewController {
vc.sectionTitle = "Choose Printer"
vc.printerManager = pm
}
}
}
| 29.218391 | 96 | 0.50118 |
acb6caf4d79700b7ed1d5047185d96076a24a957 | 1,437 | //
// LargeValueFormatter.swift
// ChartsZypDemo
// Copyright © 2016 dcg. All rights reserved.
//
import Foundation
import ChartsZyp
private let MAX_LENGTH = 5
@objc protocol Testing123 { }
public class LargeValueFormatter: NSObject, IValueFormatter, IAxisValueFormatter {
/// Suffix to be appended after the values.
///
/// **default**: suffix: ["", "k", "m", "b", "t"]
public var suffix = ["", "k", "m", "b", "t"]
/// An appendix text to be added at the end of the formatted value.
public var appendix: String?
public init(appendix: String? = nil) {
self.appendix = appendix
}
fileprivate func format(value: Double) -> String {
var sig = value
var length = 0
let maxLength = suffix.count - 1
while sig >= 1000.0 && length < maxLength {
sig /= 1000.0
length += 1
}
var r = String(format: "%2.f", sig) + suffix[length]
if let appendix = appendix {
r += appendix
}
return r
}
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return format(value: value)
}
public func stringForValue(
_ value: Double,
entry: ChartDataEntry,
dataSetIndex: Int,
viewPortHandler: ViewPortHandler?) -> String {
return format(value: value)
}
}
| 24.355932 | 82 | 0.559499 |
e8db949f068332637221fd0794aa8709249aba72 | 450 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let f={extension{
class C{let:=[{{
{
>{
class
case,
| 30 | 79 | 0.737778 |
e567027f2714410b8c1fa5f3a706aa558c9e3e20 | 833 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "NIOCronScheduler",
products: [
.library(
name: "NIOCronScheduler",
targets: ["NIOCronScheduler"]),
],
dependencies: [
// Event-driven network application framework for high performance protocol servers & clients, non-blocking.
.package(url: "https://github.com/apple/swift-nio.git", from: "2.0.0"),
// ⏱ Simple pure swift cron expressions parser
.package(url: "https://github.com/MihaelIsaev/SwifCron.git", from:"1.3.0"),
],
targets: [
.target(
name: "NIOCronScheduler",
dependencies: ["NIO", "SwifCron"]),
.testTarget(
name: "NIOCronSchedulerTests",
dependencies: ["NIOCronScheduler"]),
]
)
| 30.851852 | 116 | 0.593037 |
0a7a0af3ddaebe2173333c8923676984a5588628 | 6,116 | //
// SettingViewCell.swift
// ifanr
//
// Created by 梁亦明 on 16/8/4.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import Foundation
enum SettingCellType {
case `default`
case detailTitle
case `switch`
case image
func cellReuseIdentifier() -> String {
switch self {
case .default:
return "SettingDefault"
case .detailTitle:
return "SettingDetailTitle"
case .switch:
return "SettingSwitch"
case .image:
return "SettingImage"
}
}
}
class SettingViewCell: UITableViewCell, Reusable {
var cellType: SettingCellType = .default
class func cellWithTableView(_ tableView: UITableView) -> SettingViewCell {
var cell = tableView.dequeueReusableCell() as SettingViewCell?
if cell == nil {
cell = SettingViewCell(style: .default, reuseIdentifier: self.reuseIdentifier)
}
return cell!
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.black
selectionStyle = .none
switch reuseIdentifier! {
case SettingCellType.default.cellReuseIdentifier():
addSubview(titleLabel)
addSubview(detailLabel)
setupTitleLayout()
setupDetailTitleLayout()
case SettingCellType.detailTitle.cellReuseIdentifier():
addSubview(detailLabel)
setupDetailTitleLayout()
case SettingCellType.switch.cellReuseIdentifier():
addSubview(titleLabel)
addSubview(detailLabel)
addSubview(switchView)
setupTitleLayout()
setupDetailTitleLayout()
setupSwitchLayout()
case SettingCellType.image.cellReuseIdentifier():
addSubview(titleLabel)
addSubview(startView)
setupTitleLayout()
setupImageLayout()
default:
break
}
addSubview(lineView)
setupLineView()
}
var model: SettingModel! {
didSet {
switch model.type {
case .default, .switch:
self.titleLabel.text = model.title
self.detailLabel.text = model.detail
case .detailTitle:
detailLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 14)
self.detailLabel.text = model.detail
case .image:
titleLabel.text = model.title
}
}
}
convenience init(cellType: SettingCellType) {
self.init(style: .default, reuseIdentifier: cellType.cellReuseIdentifier())
self.cellType = cellType
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: 16)
titleLabel.textColor = UIColor.lightGray
return titleLabel
}()
fileprivate lazy var detailLabel: UILabel = {
let detailLable = UILabel()
detailLable.font = UIFont.customFont_FZLTXIHJW(fontSize: 12)
detailLable.textColor = UIColor.darkGray
return detailLable
}()
fileprivate lazy var switchView: UISwitch = {
let switchView = UISwitch()
return switchView
}()
fileprivate lazy var startView: UIView = {
var startView = UIView()
for i in 0 ..< 5 {
var startImageView = UIImageView(image: UIImage(named: "ic_start"))
startImageView.frame = CGRect(x: i*20, y: 0, width: 20, height: 20)
startImageView.contentMode = .scaleAspectFit
startView.addSubview(startImageView)
}
return startView
}()
fileprivate lazy var startImageView: UIImageView = {
var startImageView = UIImageView(image: UIImage(named: "ic_start"))
startImageView.contentMode = .scaleAspectFit
return startImageView
}()
fileprivate lazy var lineView: UIView = {
var lineView = UIView()
lineView.backgroundColor = UIColor.darkGray
return lineView
}()
}
extension SettingViewCell {
fileprivate func setupTitleLayout() {
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(UIConstant.UI_MARGIN_20)
make.right.equalTo(self).inset(UIConstant.UI_MARGIN_20)
make.top.equalTo(self).offset(UIConstant.UI_MARGIN_10)
make.height.equalTo(20)
}
}
fileprivate func setupDetailTitleLayout() {
self.detailLabel.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(UIConstant.UI_MARGIN_20)
make.right.equalTo(self).inset(UIConstant.UI_MARGIN_20)
make.bottom.equalTo(self).inset(UIConstant.UI_MARGIN_10)
make.height.equalTo(20)
}
}
fileprivate func setupLineView() {
self.lineView.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(UIConstant.UI_MARGIN_20)
make.right.equalTo(self).inset(UIConstant.UI_MARGIN_20)
make.height.equalTo(1)
make.bottom.equalTo(self).inset(1)
}
}
fileprivate func setupSwitchLayout() {
switchView.snp.makeConstraints { (make) in
make.right.equalTo(self).inset(UIConstant.UI_MARGIN_20)
make.centerY.equalTo(self.snp.centerY)
make.size.equalTo(CGSize(width: 49, height: 31))
}
}
fileprivate func setupImageLayout() {
startView.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(UIConstant.UI_MARGIN_20)
make.right.equalTo(self).inset(UIConstant.UI_MARGIN_20)
make.bottom.equalTo(self).inset(UIConstant.UI_MARGIN_10)
make.height.equalTo(20)
}
}
}
| 32.359788 | 90 | 0.610857 |
ef422c314c3e7157952b69ff9862697612fcd8b0 | 4,826 | //
// SocketExtensions.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 7/1/2016.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import StarscreamSocketIO
enum JSONError : Error {
case notArray
case notNSDictionary
}
extension Array {
func toJSON() throws -> Data {
return try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
}
}
extension CharacterSet {
static var allowedURLCharacterSet: CharacterSet {
return CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]\" {}").inverted
}
}
extension NSDictionary {
private static func keyValueToSocketIOClientOption(key: String, value: Any) -> SocketIOClientOption? {
switch (key, value) {
case let ("connectParams", params as [String: Any]):
return .connectParams(params)
case let ("cookies", cookies as [HTTPCookie]):
return .cookies(cookies)
case let ("extraHeaders", headers as [String: String]):
return .extraHeaders(headers)
case let ("forceNew", force as Bool):
return .forceNew(force)
case let ("forcePolling", force as Bool):
return .forcePolling(force)
case let ("forceWebsockets", force as Bool):
return .forceWebsockets(force)
case let ("handleQueue", queue as DispatchQueue):
return .handleQueue(queue)
case let ("log", log as Bool):
return .log(log)
case let ("logger", logger as SocketLogger):
return .logger(logger)
case let ("nsp", nsp as String):
return .nsp(nsp)
case let ("path", path as String):
return .path(path)
case let ("reconnects", reconnects as Bool):
return .reconnects(reconnects)
case let ("reconnectAttempts", attempts as Int):
return .reconnectAttempts(attempts)
case let ("reconnectWait", wait as Int):
return .reconnectWait(wait)
case let ("secure", secure as Bool):
return .secure(secure)
case let ("security", security as SSLSecurity):
return .security(security)
case let ("selfSigned", selfSigned as Bool):
return .selfSigned(selfSigned)
case let ("sessionDelegate", delegate as URLSessionDelegate):
return .sessionDelegate(delegate)
case let ("compress", compress as Bool):
return compress ? .compress : nil
default:
return nil
}
}
func toSocketConfiguration() -> SocketIOClientConfiguration {
var options = [] as SocketIOClientConfiguration
for (rawKey, value) in self {
if let key = rawKey as? String, let opt = NSDictionary.keyValueToSocketIOClientOption(key: key, value: value) {
options.insert(opt)
}
}
return options
}
}
extension String {
func toArray() throws -> [Any] {
guard let stringData = data(using: .utf16, allowLossyConversion: false) else { return [] }
guard let array = try JSONSerialization.jsonObject(with: stringData, options: .mutableContainers) as? [Any] else {
throw JSONError.notArray
}
return array
}
func toNSDictionary() throws -> NSDictionary {
guard let binData = data(using: .utf16, allowLossyConversion: false) else { return [:] }
guard let json = try JSONSerialization.jsonObject(with: binData, options: .allowFragments) as? NSDictionary else {
throw JSONError.notNSDictionary
}
return json
}
func urlEncode() -> String? {
return addingPercentEncoding(withAllowedCharacters: .allowedURLCharacterSet)
}
}
| 38 | 123 | 0.650642 |
50367092b2bbf02ab630f50f56df43f5cc4d4939 | 5,939 | //
// Copyright 2021 Wultra s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions
// and limitations under the License.
//
import Foundation
import PowerAuthShared
typealias D = PowerAuthDebug
public class TestManager: TestMonitor {
public struct TestResults {
let testsCount: Int
let failedTests: Int
let warnings: [String]
let errors: [String]
}
public let name: String
public let testCases: () throws -> [TestCase]
public var promptForInteraction: ((String) -> Void)?
public private(set) var lastResults: TestResults?
public init(name: String, tests: @escaping () throws -> [TestCase]) {
self.name = name
self.testCases = tests
self.promptForInteraction = nil
}
public func runAll() -> TestResults {
lastPromptDate = nil
D.verboseLevel = .all
D.print("======================================================")
D.print("=== Starting \(name) tests...")
D.print("======================================================")
let results = runTests()
lastResults = results
results.dumpResults()
return results
}
private func runTests() -> TestResults {
let tests: [TestCase]
do {
tests = try testCases()
} catch {
D.print("=== \(name): Failed to initialize test list: \(error.localizedDescription)")
return TestResults(testsCount: 0, failedTests: 0, warnings: [], errors: [])
}
var totalCount = 0
var totalFailures = 0
var allErrors = [String]()
var allWarnings = [String]()
tests.forEach { testCase in
resetCounters()
do {
D.print("=== \(name).\(testCase.name) - starting...")
currentTestIsInteractive = testCase.isInteractive
partialTests += 1
try testCase.run(with: self)
let isError = !errors.isEmpty || partialFailures > 0
if !isError {
D.print("=== \(name).\(testCase.name) - OK")
} else if !errors.isEmpty {
D.print("=== \(name).\(testCase.name) - FAILED")
}
} catch {
self.error("\(testCase.name): \(error.localizedDescription)")
}
// Keep partial results
totalCount += partialTests
totalFailures += partialFailures
allErrors.append(contentsOf: errors)
allWarnings.append(contentsOf: warnings)
}
return TestResults(testsCount: totalCount, failedTests: totalFailures, warnings: allWarnings, errors: allErrors)
}
// MARK: TestResult
public func error(_ message: String) {
D.print("=== FAIL: \(message)")
errors.append(message)
partialFailures += 1
}
public func warning(_ message: String) {
D.print("=== WARNING: \(message)")
warnings.append(message)
}
public func increaseTestCount() {
partialTests += 1
}
public func increaseFailedTestCount() {
partialFailures += 1
}
private var currentTestIsInteractive: Bool = true
private var lastPromptDate: Date?
public func promptForInteraction(_ message: String, wait: TestMonitorWait) {
guard currentTestIsInteractive else {
return
}
promptForInteraction?(message)
let padding = 12
let row = String(repeating: "*", count: message.count + padding)
let spc = String(repeating: " ", count: message.count + padding)
let pad = String(repeating: " ", count: padding/2)
print("")
print("*\(row)*")
print("*\(spc)*")
print("*\(pad)\(message)\(pad)*")
print("*\(spc)*")
print("*\(row)*")
print("")
Thread.sleep(forTimeInterval: wait.timeInterval)
lastPromptDate = Date()
}
public private(set) var errors = [String]()
public private(set) var warnings = [String]()
private var partialTests = 0
private var partialFailures = 0
private func resetCounters() {
partialTests = 0
partialFailures = 0
errors.removeAll()
warnings.removeAll()
}
}
extension TestMonitorWait {
/// Wait type converted to TimeInterval.
var timeInterval: TimeInterval {
switch self {
case .long:
return 5
case .short:
return 1
}
}
}
extension TestManager.TestResults {
func dumpResults() {
D.print("======================================================")
if testsCount == 0 {
D.print("=== FAILED: No test was executed for ")
} else if failedTests > 0 {
D.print("=== FAILED: Executed \(testsCount) tests, but \(failedTests) failed.")
} else {
D.print("=== OK: Executed \(testsCount) tests.")
}
errors.forEach { error in
D.print(" - ERROR: \(error)")
}
warnings.forEach { warn in
D.print(" - WARNING: \(warn)")
}
D.print("======================================================")
}
}
| 29.844221 | 120 | 0.527698 |
87f5305bb922d5e78fe7203e6bc2e0d18a7d6e46 | 3,352 | //
// SwiftUIExample.swift
// Example
//
// Created by june chen on 1/3/21.
// Copyright © 2021 Openpay. All rights reserved.
//
import Openpay
import SwiftUI
struct SwiftUIExample: View {
@ObservedObject var viewModel: SwiftUIViewModel
var body: some View {
NavigationView {
SwiftUICheckoutView(
alert: $viewModel.alert,
totalAmount: viewModel.totalAmountDisplayValue,
checkout: viewModel.checkout,
isLoading: $viewModel.isLoading
)
.navigationViewTitle("Checkout Page")
.openpayWebCheckoutView(checkoutItem: $viewModel.checkoutItem) { result in
viewModel.checkoutCompletion(result)
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
private struct SwiftUICheckoutView: View {
@Binding var alert: SwiftUIViewModel.Alert?
let totalAmount: String
let checkout: () -> Void
@Binding var isLoading: Bool
var body: some View {
ZStack {
VStack(spacing: 20) {
HStack {
BadgeView(colorTheme: .dynamic(light: .graniteOnAmber, dark: .amberOnGranite))
.frame(width: 75, height: 24)
Text("Total Amount: \(totalAmount)").font(.headline)
}
PaymentButtonView(
action: checkout,
colorTheme: .dynamic(light: .graniteOnAmber, dark: .amberOnGranite)
)
.frame(width: 218, height: 44)
.alert(item: $alert) { item -> Alert in
Alert(title: Text(item.title), message: Text(item.subtitle))
}
}
if #available(iOS 14.0, *) {
if isLoading {
ProgressView()
}
} else {
ActivityIndicator(isAnimating: $isLoading, style: .large)
}
}
}
}
private extension View {
func navigationViewTitle(_ titleKey: LocalizedStringKey) -> some View {
if #available(iOS 14.0, *) {
// AnyView can be removed when using Xcode 12 beta 5
return AnyView(navigationTitle(titleKey))
} else {
return AnyView(navigationBarTitle(titleKey))
}
}
}
struct ActivityIndicator: UIViewRepresentable {
@Binding var isAnimating: Bool
let style: UIActivityIndicatorView.Style
func makeUIView(context: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
return UIActivityIndicatorView(style: style)
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicator>) {
isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
}
}
struct SwiftUIExample_Previews: PreviewProvider {
static var previews: some View {
Group {
SwiftUIExample(viewModel: SwiftUIViewModel(paymentRepo: MockPaymentRepo(apiService: HTTPSAPIService(baseURL: URL(string: "https://merchant-server.test/")!))))
SwiftUIExample(viewModel: SwiftUIViewModel(paymentRepo: MockPaymentRepo(apiService: HTTPSAPIService(baseURL: URL(string: "https://merchant-server.test/")!))))
.preferredColorScheme(.dark)
}
}
}
| 32.543689 | 170 | 0.601432 |
906bfb2460906601ebae5c6d2b9918e77d7d6197 | 22,569 | //
// ImageDownloader.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// 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.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// Progress update block of downloader.
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
/// Completion block of downloader.
public typealias ImageDownloaderCompletionHandler = ((image: Image?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ())
/// Download task.
public struct RetrieveImageDownloadTask {
let internalTask: NSURLSessionDataTask
/// Downloader by which this task is intialized.
public private(set) weak var ownerDownloader: ImageDownloader?
/**
Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
*/
public func cancel() {
ownerDownloader?.cancelDownloadingTask(self)
}
/// The original request URL of this download task.
public var URL: NSURL? {
return internalTask.originalRequest?.URL
}
/// The relative priority of this download task.
/// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
/// The value for it is between 0.0~1.0. Default priority is value of 0.5.
/// See documentation on `priority` of `NSURLSessionTask` for more about it.
public var priority: Float {
get {
return internalTask.priority
}
set {
internalTask.priority = newValue
}
}
}
private let defaultDownloaderName = "default"
private let downloaderBarrierName = "com.onevcat.Kingfisher.ImageDownloader.Barrier."
private let imageProcessQueueName = "com.onevcat.Kingfisher.ImageDownloader.Process."
private let instance = ImageDownloader(name: defaultDownloaderName)
/**
The error code.
- BadData: The downloaded data is not an image or the data is corrupted.
- NotModified: The remote server responsed a 304 code. No image data downloaded.
- NotCached: The image rquested is not in cache but OnlyFromCache is activated.
- InvalidURL: The URL is invalid.
*/
public enum KingfisherError: Int {
case BadData = 10000
case NotModified = 10001
case InvalidStatusCode = 10002
case NotCached = 10003
case InvalidURL = 20000
}
/// Protocol of `ImageDownloader`.
@objc public protocol ImageDownloaderDelegate {
/**
Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter image: Downloaded image.
- parameter URL: URL of the original request URL.
- parameter response: The response object of the downloading process.
*/
optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: Image, forURL URL: NSURL, withResponse response: NSURLResponse)
}
/// Protocol indicates that an authentication challenge could be handled.
public protocol AuthenticationChallengeResponable: class {
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`.
*/
func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
}
extension AuthenticationChallengeResponable {
func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trustedHosts = downloader.trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) {
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
completionHandler(.UseCredential, credential)
return
}
}
completionHandler(.PerformDefaultHandling, nil)
}
}
/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
public class ImageDownloader: NSObject {
class ImageFetchLoad {
var callbacks = [CallbackPair]()
var responseData = NSMutableData()
var options: KingfisherOptionsInfo?
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
}
// MARK: - Public property
/// This closure will be applied to the image download request before it being sent. You can modify the request for some customizing purpose, like adding auth token to the header or do a url mapping.
public var requestModifier: (NSMutableURLRequest -> Void)?
/// The duration before the download is timeout. Default is 15 seconds.
public var downloadTimeout: NSTimeInterval = 15.0
/// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead.
public var trustedHosts: Set<String>?
/// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly.
public var sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() {
didSet {
session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue())
}
}
/// Whether the download requests should use pipeling or not. Default is false.
public var requestsUsePipeling = false
private let sessionHandler: ImageDownloaderSessionHandler
private var session: NSURLSession?
/// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
public weak var delegate: ImageDownloaderDelegate?
/// A responder for authentication challenge.
/// Downloader will forward the received authentication challenge for the downloading session to this responder.
public weak var authenticationChallengeResponder: AuthenticationChallengeResponable?
// MARK: - Internal property
let barrierQueue: dispatch_queue_t
let processQueue: dispatch_queue_t
typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHander: ImageDownloaderCompletionHandler?)
var fetchLoads = [NSURL: ImageFetchLoad]()
// MARK: - Public method
/// The default downloader.
public class var defaultDownloader: ImageDownloader {
return instance
}
/**
Init a downloader with name.
- parameter name: The name for the downloader. It should not be empty.
- returns: The downloader object.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
}
barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT)
processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_CONCURRENT)
sessionHandler = ImageDownloaderSessionHandler()
super.init()
// Provide a default implement for challenge responder.
authenticationChallengeResponder = sessionHandler
session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue())
}
func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? {
var fetchLoad: ImageFetchLoad?
dispatch_sync(barrierQueue, { () -> Void in
fetchLoad = self.fetchLoads[key]
})
return fetchLoad
}
}
// MARK: - Download method
extension ImageDownloader {
/**
Download an image with a URL.
- parameter URL: Target URL.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
public func downloadImageWithURL(URL: NSURL,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
return downloadImageWithURL(URL, options: nil, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Download an image with a URL and option.
- parameter URL: Target URL.
- parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
public func downloadImageWithURL(URL: NSURL,
options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
return downloadImageWithURL(URL,
retrieveImageTask: nil,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
internal func downloadImageWithURL(URL: NSURL,
retrieveImageTask: RetrieveImageTask?,
options: KingfisherOptionsInfo?,
progressBlock: ImageDownloaderProgressBlock?,
completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
{
if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelledBeforeDownloadStarting {
return nil
}
let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
// We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.HTTPShouldUsePipelining = requestsUsePipeling
self.requestModifier?(request)
// There is a possiblility that request modifier changed the url to `nil` or empty.
#if swift(>=2.3)
let isEmptyUrl = (request.URL == nil || request.URL!.absoluteString == nil || (request.URL!.absoluteString!.isEmpty))
#else
let isEmptyUrl = (request.URL == nil || request.URL!.absoluteString.isEmpty)
#endif
if isEmptyUrl {
completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidURL.rawValue, userInfo: nil), imageURL: nil, originalData: nil)
return nil
}
var downloadTask: RetrieveImageDownloadTask?
setupProgressBlock(progressBlock, completionHandler: completionHandler, forURL: request.URL!) {(session, fetchLoad) -> Void in
if fetchLoad.downloadTask == nil {
let dataTask = session.dataTaskWithRequest(request)
fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
fetchLoad.options = options
dataTask.priority = options?.downloadPriority ?? NSURLSessionTaskPriorityDefault
dataTask.resume()
// Hold self while the task is executing.
self.sessionHandler.downloadHolder = self
}
fetchLoad.downloadTaskCount += 1
downloadTask = fetchLoad.downloadTask
retrieveImageTask?.downloadTask = downloadTask
}
return downloadTask
}
// A single key may have multiple callbacks. Only download once.
internal func setupProgressBlock(progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?, forURL URL: NSURL, started: ((NSURLSession, ImageFetchLoad) -> Void)) {
dispatch_barrier_sync(barrierQueue, { () -> Void in
let loadObjectForURL = self.fetchLoads[URL] ?? ImageFetchLoad()
let callbackPair = (progressBlock: progressBlock, completionHander: completionHandler)
loadObjectForURL.callbacks.append(callbackPair)
self.fetchLoads[URL] = loadObjectForURL
if let session = self.session {
started(session, loadObjectForURL)
}
})
}
func cancelDownloadingTask(task: RetrieveImageDownloadTask) {
dispatch_barrier_sync(barrierQueue) { () -> Void in
if let URL = task.internalTask.originalRequest?.URL, imageFetchLoad = self.fetchLoads[URL] {
imageFetchLoad.downloadTaskCount -= 1
if imageFetchLoad.downloadTaskCount == 0 {
task.internalTask.cancel()
}
}
}
}
func cleanForURL(URL: NSURL) {
dispatch_barrier_sync(barrierQueue, { () -> Void in
self.fetchLoads.removeValueForKey(URL)
return
})
}
}
// MARK: - NSURLSessionDataDelegate
// See https://github.com/onevcat/Kingfisher/issues/235
/// Delegate class for `NSURLSessionTaskDelegate`.
/// The session object will hold its delegate until it gets invalidated.
/// If we use `ImageDownloader` as the session delegate, it will not be released.
/// So we need an additional handler to break the retain cycle.
class ImageDownloaderSessionHandler: NSObject, NSURLSessionDataDelegate, AuthenticationChallengeResponable {
// The holder will keep downloader not released while a data task is being executed.
// It will be set when the task started, and reset when the task finished.
var downloadHolder: ImageDownloader?
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
// If server response is not 200,201 or 304, inform the callback handler with InvalidStatusCode error.
// InvalidStatusCode error has userInfo which include statusCode and localizedString.
if let statusCode = (response as? NSHTTPURLResponse)?.statusCode, let URL = dataTask.originalRequest?.URL where statusCode != 200 && statusCode != 201 && statusCode != 304 {
callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidStatusCode.rawValue, userInfo: ["statusCode": statusCode, "localizedStringForStatusCode": NSHTTPURLResponse.localizedStringForStatusCode(statusCode)]), imageURL: URL, originalData: nil)
}
completionHandler(NSURLSessionResponseDisposition.Allow)
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
guard let downloader = downloadHolder else {
return
}
if let URL = dataTask.originalRequest?.URL, fetchLoad = downloader.fetchLoadForKey(URL) {
fetchLoad.responseData.appendData(data)
for callbackPair in fetchLoad.callbacks {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength)
})
}
}
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let URL = task.originalRequest?.URL {
if let error = error { // Error happened
callbackWithImage(nil, error: error, imageURL: URL, originalData: nil)
} else { //Download finished without error
processImageForTask(task, URL: URL)
}
}
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
internal func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
private func callbackWithImage(image: Image?, error: NSError?, imageURL: NSURL, originalData: NSData?) {
guard let downloader = downloadHolder else {
return
}
if let callbackPairs = downloader.fetchLoadForKey(imageURL)?.callbacks {
let options = downloader.fetchLoadForKey(imageURL)?.options ?? KingfisherEmptyOptionsInfo
downloader.cleanForURL(imageURL)
for callbackPair in callbackPairs {
dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in
callbackPair.completionHander?(image: image, error: error, imageURL: imageURL, originalData: originalData)
})
}
if downloader.fetchLoads.isEmpty {
downloadHolder = nil
}
}
}
private func processImageForTask(task: NSURLSessionTask, URL: NSURL) {
guard let downloader = downloadHolder else {
return
}
// We are on main queue when receiving this.
dispatch_async(downloader.processQueue, { () -> Void in
if let fetchLoad = downloader.fetchLoadForKey(URL) {
let options = fetchLoad.options ?? KingfisherEmptyOptionsInfo
if let image = Image.kf_imageWithData(fetchLoad.responseData, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) {
downloader.delegate?.imageDownloader?(downloader, didDownloadImage: image, forURL: URL, withResponse: task.response!)
if options.backgroundDecode {
self.callbackWithImage(image.kf_decodedImage(scale: options.scaleFactor), error: nil, imageURL: URL, originalData: fetchLoad.responseData)
} else {
self.callbackWithImage(image, error: nil, imageURL: URL, originalData: fetchLoad.responseData)
}
} else {
// If server response is 304 (Not Modified), inform the callback handler with NotModified error.
// It should be handled to get an image from cache, which is response of a manager object.
if let res = task.response as? NSHTTPURLResponse where res.statusCode == 304 {
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotModified.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
return
}
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
} else {
self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil)
}
})
}
}
| 45.871951 | 429 | 0.677123 |
f7fd199c7ad952ea4b8e9956b3adf225c6629596 | 4,688 | //
// Created by 和泉田 領一 on 2017/09/25.
// Copyright (c) 2017 CAPH TECH. All rights reserved.
//
import Foundation
struct FeedbackGenerator {
static func generate(configuration: FeedbackConfiguration,
repository: FeedbackEditingItemsRepositoryProtocol) throws -> Feedback {
guard let deviceName = repository.item(of: DeviceNameItem.self)?.deviceName,
let systemVersion = repository.item(of: SystemVersionItem.self)?.version
else { throw CTFeedbackError.unknown }
let appName = repository.item(of: AppNameItem.self)?.name ?? ""
let appVersion = repository.item(of: AppVersionItem.self)?.version ?? ""
let appBuild = repository.item(of: AppBuildItem.self)?.buildString ?? ""
let email = repository.item(of: UserEmailItem.self)?.email
let topic = repository.item(of: TopicItem.self)?.selected
let attachment = repository.item(of: AttachmentItem.self)?.media
let body = repository.item(of: BodyItem.self)?.bodyText ?? ""
let subject = configuration.subject ?? generateSubject(appName: appName, topic: topic)
let format = configuration.usesHTML ? generateHTML : generateString
let formattedBody = format(body,
deviceName,
systemVersion,
appName,
appVersion,
appBuild,
configuration.additionalDiagnosticContent)
return Feedback(email: email,
to: configuration.toRecipients,
cc: configuration.ccRecipients,
bcc: configuration.bccRecipients,
subject: subject,
body: formattedBody,
isHTML: configuration.usesHTML,
jpeg: attachment?.jpegData,
mp4: attachment?.videoData)
}
private static func generateSubject(appName: String, topic: TopicProtocol?) -> String {
return String(format: "%@: %@", appName, topic?.title ?? "")
}
private static func generateHTML(body: String,
deviceName: String,
systemVersion: String,
appName: String,
appVersion: String,
appBuild: String,
additionalDiagnosticContent: String?) -> String {
var platform = "iOS"
#if targetEnvironment(macCatalyst)
platform="macOS"
#endif
let format = """
<style>td {padding-right: 20px}</style>
<p>%@</p><br />
<table cellspacing=0 cellpadding=0>
<tr><td>Device:</td><td><b>%@</b></td></tr>
<tr><td>%@:</td><td><b>%@</b></td></tr>
<tr><td>App:</td><td><b>%@</b></td></tr>
<tr><td>Version:</td><td><b>%@</b></td></tr>
<tr><td>Build:</td><td><b>%@</b></td></tr>
</table>
"""
var content: String = String(format: format,
body.replacingOccurrences(of: "\n", with: "<br />"),
deviceName,
platform,
systemVersion,
appName,
appVersion,
appBuild)
if let additional = additionalDiagnosticContent { content.append(additional) }
return content
}
private static func generateString(body: String,
deviceName: String,
systemVersion: String,
appName: String,
appVersion: String,
appBuild: String,
additionalDiagnosticContent: String?) -> String {
var platform = "iOS"
#if targetEnvironment(macCatalyst)
platform="macOS"
#endif
var content: String
= String(format: "%@\n\n\nDevice: %@\n%@: %@\nApp: %@\nVersion: %@\nBuild: %@",
body,
deviceName,
platform,
systemVersion,
appName,
appVersion,
appBuild)
if let additional = additionalDiagnosticContent { content.append(additional) }
return content
}
}
| 43.813084 | 97 | 0.481869 |
111eda3368e873beef0c0d0b108c3ccf176ed05c | 846 | //
// TransientStorage.swift
// Swiftagram
//
// Created by Stefano Bertagno on 07/03/2020.
//
import Foundation
/// A `struct` holding reference to all transient `Secret`s.
/// - note: Use when only dealing with one-shot `Secret`s.
public struct TransientStorage: Storage {
/// Init.
public init() { }
/// The implementation does nothing.
/// - returns: `nil`.
public func find(matching identifier: String) -> Secret? { return nil }
/// The implementation does nothing.
/// - returns: An empty `Array`.
public func all() -> [Secret] { return [] }
/// The implementation does nothing.
public func store(_ response: Secret) { }
/// The implementation does nothing.
/// - returns: `nil`.
@discardableResult
public func remove(matching identifier: String) -> Secret? { return nil }
}
| 26.4375 | 77 | 0.644208 |
3990880ca33958184f59e3d603e72d29491ca8b3 | 24,884 | // Copyright 2020 Espressif Systems
//
// 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.
//
// DevicesViewController.swift
// ESPRainMaker
//
import Alamofire
import AWSAuthCore
import AWSCognitoIdentityProvider
import Foundation
import JWTDecode
import MBProgressHUD
import UIKit
class DevicesViewController: UIViewController {
// IB outlets
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var addButton: UIButton!
@IBOutlet var initialView: UIView!
@IBOutlet var emptyListIcon: UIImageView!
@IBOutlet var infoLabel: UILabel!
@IBOutlet var networkIndicator: UIView!
@IBOutlet var loadingIndicator: SpinnerView!
@IBOutlet var segmentControl: UISegmentedControl!
@IBOutlet var dropDownMenu: UIView!
@IBOutlet var segmentControlLeadingConstraint: NSLayoutConstraint!
@IBOutlet var groupMenuButton: UIButton!
let controlStoryBoard = UIStoryboard(name: "DeviceDetail", bundle: nil)
var user: AWSCognitoIdentityUser?
var pool: AWSCognitoIdentityUserPool?
var checkDeviceAssociation = false
private var currentPage = 0
private var absoluteSegmentPosition: [CGFloat] = []
// MARK: - Overriden Methods
override func viewDidLoad() {
super.viewDidLoad()
// Check if user session is valid
_ = User.shared.currentUser()
pool = AWSCognitoIdentityUserPool(forKey: Constants.AWSCognitoUserPoolsSignInProviderKey)
if user == nil {
user = pool?.currentUser()
}
// Get info of user from user default
if (UserDefaults.standard.value(forKey: Constants.userInfoKey) as? [String: Any]) != nil {
collectionView.isUserInteractionEnabled = false
collectionView.isHidden = false
// Fetch associated nodes from local storage
User.shared.associatedNodeList = ESPLocalStorage.shared.fetchNodeDetails()
if Configuration.shared.appConfiguration.supportGrouping {
NodeGroupManager.shared.nodeGroup = ESPLocalStorage.shared.fetchNodeGroups()
}
refreshDeviceList()
} else {
refresh()
}
dropDownMenu.dropShadow()
NotificationCenter.default.addObserver(self, selector: #selector(updateUIView), name: Notification.Name(Constants.uiViewUpdateNotification), object: nil)
// Register nib
collectionView.register(UINib(nibName: "DeviceGroupEmptyDeviceCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "deviceGroupEmptyDeviceCVC")
// Add gesture to hide Group DropDown menu
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideDropDown))
tapGesture.cancelsTouchesInView = false
tapGesture.delegate = self
view.addGestureRecognizer(tapGesture)
if !Configuration.shared.appConfiguration.supportGrouping {
segmentControl.isHidden = true
groupMenuButton.isHidden = true
} else {
configureSegmentControl()
}
if !Configuration.shared.appConfiguration.supportSchedule {
tabBarController?.viewControllers?.remove(at: 1)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkNetworkUpdate()
if User.shared.updateUserInfo {
User.shared.updateUserInfo = false
updateUserInfo()
}
if (UserDefaults.standard.value(forKey: Constants.userInfoKey) as? [String: Any]) != nil {
if User.shared.updateDeviceList {
refreshDeviceList()
}
}
setViewForNoNodes()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
addButton.setImage(UIImage(named: "add_icon"), for: .normal)
dropDownMenu.isHidden = true
NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name(Constants.networkUpdateNotification), object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name(Constants.localNetworkUpdateNotification), object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
NotificationCenter.default.addObserver(self, selector: #selector(appEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(checkNetworkUpdate), name: Notification.Name(Constants.networkUpdateNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(localNetworkUpdate), name: Notification.Name(Constants.localNetworkUpdateNotification), object: nil)
tabBarController?.tabBar.isHidden = false
}
// MARK: - Observer functions
@objc func hideDropDown() {
dropDownMenu.isHidden = true
}
@objc func reloadCollectionView() {
collectionView.reloadData()
}
@objc func appEnterForeground() {
refreshDeviceList()
}
@objc func checkNetworkUpdate() {
DispatchQueue.main.async {
if ESPNetworkMonitor.shared.isConnectedToNetwork {
self.networkIndicator.isHidden = true
} else {
self.networkIndicator.isHidden = false
}
}
}
@objc func localNetworkUpdate() {
collectionView.reloadData()
}
@objc func updateUIView() {
for subview in view.subviews {
subview.setNeedsDisplay()
}
}
@objc func refreshDeviceList() {
showLoader()
collectionView.isUserInteractionEnabled = false
User.shared.updateDeviceList = false
NetworkManager.shared.getNodes { nodes, error in
DispatchQueue.main.async {
self.loadingIndicator.isHidden = true
User.shared.associatedNodeList = nil
if error != nil {
self.unhideInitialView(error: error)
self.collectionView.isUserInteractionEnabled = true
return
}
User.shared.associatedNodeList = nodes
if Configuration.shared.appConfiguration.supportGrouping {
NodeGroupManager.shared.getNodeGroups { _, error in
DispatchQueue.main.async {
// Start local discovery if its enabled
if Configuration.shared.appConfiguration.supportLocalControl {
User.shared.startServiceDiscovery()
}
}
if error != nil {
Utility.showToastMessage(view: self.view, message: error!.description, duration: 5.0)
}
self.setupSegmentControl()
self.prepareView()
}
} else {
if Configuration.shared.appConfiguration.supportLocalControl {
User.shared.startServiceDiscovery()
}
self.prepareView()
}
}
}
}
// MARK: - IB Actions
@IBAction func clickedSegment(segment: UISegmentedControl) {
print(segment.selectedSegmentIndex)
if segment.selectedSegmentIndex > currentPage {
collectionView.scrollToItem(at: IndexPath(row: segment.selectedSegmentIndex, section: 0), at: .right, animated: true)
} else {
collectionView.scrollToItem(at: IndexPath(row: segment.selectedSegmentIndex, section: 0), at: .left, animated: true)
}
adjustSegmentControlFor(currentIndex: segment.selectedSegmentIndex)
currentPage = segment.selectedSegmentIndex
}
@IBAction func refreshClicked(_: Any) {
refreshDeviceList()
}
@IBAction func dropDownClicked(_: Any) {
dropDownMenu.isHidden = !dropDownMenu.isHidden
}
@IBAction func goToNodeGroups(_: Any) {
let controlStoryBoard = UIStoryboard(name: "NodeGrouping", bundle: nil)
let deviceTraitsVC = controlStoryBoard.instantiateViewController(withIdentifier: "nodeGroupsVC") as! NodeGroupsViewController
navigationController?.pushViewController(deviceTraitsVC, animated: true)
}
@IBAction func addNodeGroup(_: Any) {
let controlStoryBoard = UIStoryboard(name: "NodeGrouping", bundle: nil)
let deviceTraitsVC = controlStoryBoard.instantiateViewController(withIdentifier: "createGroupVC") as! NewNodeGroupViewController
navigationController?.pushViewController(deviceTraitsVC, animated: true)
}
@IBAction func addDeviceClicked(_: Any) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
tabBarController?.tabBar.isHidden = true
// Check if scan is enabled in ap
if Configuration.shared.espProvSetting.scanEnabled {
let scannerVC = mainStoryboard.instantiateViewController(withIdentifier: "scannerVC") as! ScannerViewController
navigationController?.pushViewController(scannerVC, animated: true)
} else {
// If scan is not enabled check supported transport
switch Configuration.shared.espProvSetting.transport {
case .ble:
// Go directly to BLE manual provisioing
goToBleProvision()
case .softAp:
// Go directly to SoftAP manual provisioing
goToSoftAPProvision()
default:
// If both BLE and SoftAP is supported. Present Action Sheet to give option to choose.
let actionSheet = UIAlertController(title: "", message: "Choose Provisioning Transport", preferredStyle: .actionSheet)
let bleAction = UIAlertAction(title: "BLE", style: .default) { _ in
self.goToBleProvision()
}
let softapAction = UIAlertAction(title: "SoftAP", style: .default) { _ in
self.goToSoftAPProvision()
}
actionSheet.addAction(bleAction)
actionSheet.addAction(softapAction)
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
}
}
// MARK: - Private Methods
private func goToBleProvision() {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let bleLandingVC = mainStoryboard.instantiateViewController(withIdentifier: "bleLandingVC") as! BLELandingViewController
navigationController?.pushViewController(bleLandingVC, animated: true)
}
private func goToSoftAPProvision() {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let softLandingVC = mainStoryboard.instantiateViewController(withIdentifier: "provisionLanding") as! ProvisionLandingViewController
navigationController?.pushViewController(softLandingVC, animated: true)
}
private func prepareView() {
if User.shared.associatedNodeList == nil || User.shared.associatedNodeList?.count == 0 {
setViewForNoNodes()
} else {
initialView.isHidden = true
collectionView.isHidden = false
addButton.isHidden = false
collectionView.reloadData()
}
collectionView.isUserInteractionEnabled = true
}
private func showLoader() {
loadingIndicator.isHidden = false
loadingIndicator.animate()
}
private func updateUserInfo() {
User.shared.getcognitoIdToken { idToken in
if idToken != nil {
self.getUserInfo(token: idToken!, provider: .cognito)
} else {
Utility.hideLoader(view: self.view)
self.refreshDeviceList()
}
}
}
private func refresh() {
user?.getDetails().continueOnSuccessWith { (_) -> AnyObject? in
DispatchQueue.main.async {
self.updateUserInfo()
}
return nil
}
}
private func setViewForNoNodes() {
if User.shared.associatedNodeList?.count == 0 || User.shared.associatedNodeList == nil {
infoLabel.text = "No Device Added"
emptyListIcon.image = UIImage(named: "no_device_icon")
infoLabel.textColor = .white
initialView.isHidden = false
collectionView.isHidden = true
addButton.isHidden = true
}
}
private func setupSegmentControl() {
segmentControlLeadingConstraint.constant = 0
segmentControl.layoutIfNeeded()
segmentControl.removeAllSegments()
absoluteSegmentPosition = []
var segmentPosition: CGFloat = 0
for i in 0 ... NodeGroupManager.shared.nodeGroup.count {
var stringBoundingbox: CGSize = .zero
if i == 0 {
stringBoundingbox = "All Devices".size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.5, weight: .semibold)])
segmentControl.insertSegment(withTitle: "All Devices", at: i, animated: false)
} else {
let groupName = NodeGroupManager.shared.nodeGroup[i - 1].group_name ?? ""
stringBoundingbox = (groupName as NSString).size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.5, weight: .semibold)])
segmentControl.insertSegment(withTitle: groupName, at: i, animated: false)
}
segmentPosition = segmentPosition + stringBoundingbox.width + 20
absoluteSegmentPosition.append(segmentPosition)
segmentControl.setWidth(stringBoundingbox.width + 20, forSegmentAt: i)
}
if currentPage > NodeGroupManager.shared.nodeGroup.count {
segmentControl.selectedSegmentIndex = NodeGroupManager.shared.nodeGroup.count
} else {
segmentControl.selectedSegmentIndex = currentPage
}
}
private func getFontWidthForString(text: NSString) -> CGSize {
return text.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.5, weight: .semibold)])
}
private func getUserInfo(token: String, provider: ServiceProvider) {
do {
let json = try decode(jwt: token)
User.shared.userInfo.username = json.body["cognito:username"] as? String ?? ""
User.shared.userInfo.email = json.body["email"] as? String ?? ""
User.shared.userInfo.userID = json.body["custom:user_id"] as? String ?? ""
User.shared.userInfo.loggedInWith = provider
User.shared.userInfo.saveUserInfo()
} catch {
print("error parsing token")
}
refreshDeviceList()
}
private func getSingleDeviceNodeCount(forNodeList: [Node]?) -> Int {
var singleDeviceNodeCount = 0
if let nodeList = forNodeList {
for item in nodeList {
if item.devices?.count == 1 {
singleDeviceNodeCount += 1
}
}
}
return singleDeviceNodeCount
}
// Helper method to customise UISegmentControl
private func configureSegmentControl() {
let currentBGColor = UIColor(hexString: "#8265E3")
segmentControl.removeBorder()
segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white as Any, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.0, weight: .regular)], for: .normal)
segmentControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white as Any, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.5, weight: .semibold), NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue], for: .selected)
segmentControl.changeUnderlineColor(color: currentBGColor)
let allDeviceSize = getFontWidthForString(text: "All Devices")
segmentControl.setWidth(allDeviceSize.width + 40, forSegmentAt: 0)
}
private func unhideInitialView(error: ESPNetworkError?) {
User.shared.associatedNodeList = ESPLocalStorage.shared.fetchNodeDetails()
if User.shared.associatedNodeList?.count == 0 || User.shared.associatedNodeList == nil {
infoLabel.text = "No devices to show\n" + (error?.description ?? "Something went wrong!!")
emptyListIcon.image = nil
infoLabel.textColor = .red
initialView.isHidden = false
collectionView.isHidden = true
addButton.isHidden = true
} else {
collectionView.reloadData()
initialView.isHidden = true
collectionView.isHidden = false
addButton.isHidden = false
Utility.showToastMessage(view: view, message: "Network error: \(error?.description ?? "Something went wrong!!")")
}
if Configuration.shared.appConfiguration.supportGrouping {
NodeGroupManager.shared.nodeGroup = ESPLocalStorage.shared.fetchNodeGroups()
setupSegmentControl()
prepareView()
}
}
private func preparePopover(contentController: UIViewController,
sender: UIView,
delegate: UIPopoverPresentationControllerDelegate?)
{
contentController.modalPresentationStyle = .popover
contentController.popoverPresentationController!.sourceView = sender
contentController.popoverPresentationController!.sourceRect = sender.bounds
contentController.preferredContentSize = CGSize(width: 182.0, height: 112.0)
contentController.popoverPresentationController!.delegate = delegate
}
private func adjustSegmentControlFor(currentIndex: Int) {
if absoluteSegmentPosition[currentIndex] > UIScreen.main.bounds.size.width - 100 {
UIView.animate(withDuration: 0.5) {
self.segmentControlLeadingConstraint.constant = UIScreen.main.bounds.size.width - 80 - 20 - self.absoluteSegmentPosition[currentIndex]
self.segmentControl.layoutIfNeeded()
}
} else {
if segmentControlLeadingConstraint.constant != 0 {
UIView.animate(withDuration: 0.5) {
self.segmentControlLeadingConstraint.constant = 0
self.segmentControl.layoutIfNeeded()
}
}
}
}
}
extension DevicesViewController: UICollectionViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let x = scrollView.contentOffset.x
let w = scrollView.bounds.size.width
let currentPage = Int(ceil(x / w))
self.currentPage = currentPage
segmentControl.selectedSegmentIndex = currentPage
adjustSegmentControlFor(currentIndex: currentPage)
}
}
extension DevicesViewController: UICollectionViewDataSource {
func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
if Configuration.shared.appConfiguration.supportGrouping {
if NodeGroupManager.shared.nodeGroup.count == 0 {
if User.shared.associatedNodeList == nil || User.shared.associatedNodeList?.count == 0 {
return 0
} else {
return 1
}
}
return NodeGroupManager.shared.nodeGroup.count + 1
}
return 1
}
func numberOfSections(in _: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item > 0 {
let group = NodeGroupManager.shared.nodeGroup[indexPath.item - 1]
if group.nodes?.count ?? 0 < 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "deviceGroupEmptyDeviceCVC", for: indexPath) as! DeviceGroupEmptyDeviceCollectionViewCell
cell.addDeviceButtonAction = {
let nodeGroupStoryBoard = UIStoryboard(name: "NodeGrouping", bundle: nil)
let editNodeGroupVC = nodeGroupStoryBoard.instantiateViewController(withIdentifier: "editNodeGroupVC") as! EditNodeGroupViewController
editNodeGroupVC.currentNodeGroup = group
self.navigationController?.pushViewController(editNodeGroupVC, animated: true)
}
return cell
}
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "deviceGroupCollectionViewCell", for: indexPath) as! DeviceGroupCollectionViewCell
cell.delegate = self
if indexPath.item == 0 {
cell.singleDeviceNodeCount = getSingleDeviceNodeCount(forNodeList: User.shared.associatedNodeList)
cell.datasource = User.shared.associatedNodeList ?? []
} else {
let nodeList = NodeGroupManager.shared.nodeGroup[indexPath.item - 1].nodeList
cell.singleDeviceNodeCount = getSingleDeviceNodeCount(forNodeList: nodeList)
cell.datasource = nodeList ?? []
}
let refreshControl = UIRefreshControl()
refreshControl.addTarget(cell, action: #selector(refreshDeviceList), for: .valueChanged)
refreshControl.tintColor = .clear
cell.collectionView.refreshControl = refreshControl
cell.refreshAction = {
refreshControl.endRefreshing()
self.refreshDeviceList()
}
cell.collectionView.reloadData()
return cell
}
}
extension DevicesViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt _: IndexPath) -> CGSize {
let frame = collectionView.frame
return CGSize(width: frame.width, height: frame.height)
}
func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, minimumInteritemSpacingForSectionAt _: Int) -> CGFloat {
return 0
}
func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, minimumLineSpacingForSectionAt _: Int) -> CGFloat {
return 0
}
func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, insetForSectionAt _: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
extension DevicesViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for _: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_: UIPopoverPresentationController) {}
func popoverPresentationControllerShouldDismissPopover(_: UIPopoverPresentationController) -> Bool {
return false
}
}
extension DevicesViewController: DeviceGroupCollectionViewCellDelegate {
func didSelectDevice(device: Device) {
let deviceTraitsVC = controlStoryBoard.instantiateViewController(withIdentifier: Constants.deviceTraitListVCIdentifier) as! DeviceTraitListViewController
deviceTraitsVC.device = device
Utility.hideLoader(view: view)
navigationController?.pushViewController(deviceTraitsVC, animated: true)
}
func didSelectNode(node: Node) {
let deviceStoryboard = UIStoryboard(name: "DeviceDetail", bundle: nil)
let destination = deviceStoryboard.instantiateViewController(withIdentifier: "nodeDetailsVC") as! NodeDetailsViewController
destination.currentNode = node
navigationController?.pushViewController(destination, animated: true)
}
}
extension DevicesViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view == groupMenuButton {
return false
}
return true
}
}
| 42.829604 | 278 | 0.658536 |
8ae31b5e60ba06aaabb7b39e3703c78926ee98da | 3,327 | //
// ViewController.swift
// AdvertisingSlider
//
// Created by Виталий Сероштанов on 28.10.2019.
// Copyright © 2019 Виталий Сероштанов. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var slider: AdvertisingSlider!
// Text source: https://en.wikipedia.org/wiki/Travel
fileprivate var titles = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.slider.dataSource = self
self.slider.delegate = self
self.slider.overViewColor = UIColor.black
self.slider.overViewAlpha = 0.2
self.slider.cornerRadius = 8
self.slider.pageControlInteraction = true
self.slider.font = UIFont.boldSystemFont(ofSize: 16)
self.slider.textRows = 5
self.slider.contentMode = .scaleAspectFill
//self.slider.moveToPage(3, animated: false)
}
@IBAction func fillSliderPressed(_ sender: Any) {
self.titles = ["The origin of the word \"travel\" is most likely lost to history.",
"The term \"travel\" may originate from the Old French word travail, which means 'work'",
"According to the Merriam Webster dictionary, the first known use of the word travel was in the 14th century.",
"It also states that the word comes from Middle English travailen, travelen (which means to torment, labor, strive, journey) and earlier from Old French travailler (which means to work strenuously, toil)",
"In English we still occasionally use the words \"travail\", which means struggle.",
"There's a big difference between simply being a tourist and being a true world traveler"]
self.slider.reloadData()
}
@IBAction func clearSliderPressed(_ sender: Any) {
self.titles = [String]()
self.slider.reloadData()
}
@IBAction func reloadDataPressed(_ sender: Any) {
if titles.count == 0 {return}
let itemNumber = titles.count / 2
self.titles.remove(at: itemNumber)
self.slider.reloadData()
}
}
extension ViewController : AdvertisingSliderDataSource {
func urlStringToDownload(image index: Int, slider: AdvertisingSlider) -> String? {
return "https://images.pexels.com/photos/1543793/pexels-photo-1543793.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
// if index == 3 {
// return "https://images.pexels.com/photos/1543793/pexels-photo-1543793.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
// }
// return nil
}
func pagesCount(forSlider: AdvertisingSlider) -> Int {
return self.titles.count
}
func imageForIndex(_ index: Int, slider: AdvertisingSlider) -> UIImage? {
return nil
// if index == 3 {return nil}
// print("Get image number \(index)")
// return UIImage.init(named: "\(index).jpg")!
}
func textForIndex(_ index: Int, slider: AdvertisingSlider) -> String {
return self.titles[index]
}
}
extension ViewController : AdvertisingSliderDelegate {
func didItemPressed(_ index: Int, slider: AdvertisingSlider) {
print("Item \(index) pressed")
}
func didPageChanged(_ index: Int, slider: AdvertisingSlider) {
print("Page changed on: \(index)")
}
}
| 35.774194 | 213 | 0.65254 |
9cedc90e6082e584f9f165bc1b2ed882fd3dddd8 | 10,038 | //
// InterpretAccount.swift
// swifttalk-server
//
// Created by Chris Eidhof on 13.12.18.
//
import Foundation
import Promise
import Database
import WebServer
import Base
extension ProfileFormData {
init(_ data: UserData) {
email = data.email
name = data.name
}
}
extension Route.Account {
func interpret<I: STResponse>() throws -> I where I.Env == STRequestEnvironment {
return .requireSession { try self.interpret(session: $0)}
}
private func interpret<I: STResponse>(session sess: Session) throws -> I where I.Env == STRequestEnvironment {
func editAccount(form: Form<ProfileFormData, STRequestEnvironment>, role: UserData.Role, cont: @escaping () -> Route) -> I {
func updateAndRedirect(_ user: Row<UserData>) -> I {
return .query(user.update()) { _ in
return .redirect(to: cont())
}
}
return .form(form, initial: ProfileFormData(sess.user.data), convert: { profile in
var u = sess.user
u.data.email = profile.email
u.data.name = profile.name
u.data.confirmedNameAndEmail = true
u.data.role = role
let errors = u.data.validate()
if errors.isEmpty {
return .left(u)
} else {
return .right(errors)
}
}, onPost: { user in
.onSuccess(promise: recurly.account(with: sess.user.id).promise, do: { _ in
.onSuccess(promise: recurly.updateAccount(accountCode: sess.user.id, email: user.data.email).promise, do: { (a: Account?) -> I in
updateAndRedirect(user)
}, else: {
.write(html: form.render(ProfileFormData(user.data), [(field: "", message: "An error occurred while updating your account profile. Please try again later.")]))
})
}, else: {
updateAndRedirect(user)
})
})
}
// todo use the form helper
func renderUpdatePaymentForm(error: RecurlyError?) -> I {
return .onSuccess(promise: sess.user.billingInfo.promise, do: { billingInfo in
let data = SubscriptionFormData(error: error)
let view: Node
if let b = billingInfo {
view = updatePaymentView(data: data, initial: b)
} else {
view = noBillingInfoView()
}
return .write(html: view)
})
}
func updatePaymentMethod(recurlyToken: String, threeDResultToken: String? = nil) -> I {
return .onSuccess(promise: sess.user.updateBillingInfo(token: recurlyToken, threeDResultToken: threeDResultToken).promise, do: { (response: RecurlyResult<BillingInfo>) -> I in
switch response {
case .success:
return .redirect(to: .account(.billing)) // todo show message?
case .error(let error):
log(error)
if let threeDActionToken = error.threeDActionToken {
let success = ThreeDSuccessRoute { threeDResultToken in
.account(.threeDSecureResponse(threeDResultToken: threeDResultToken, recurlyToken: recurlyToken))
}
let otherPaymentMethod = Route.account(.updatePayment)
return .redirect(to: .threeDSecureChallenge(threeDActionToken: threeDActionToken, success: success, otherPaymentMethod: otherPaymentMethod))
} else {
return renderUpdatePaymentForm(error: error)
}
}
})
}
switch self {
case .logout:
return I.query(sess.user.deleteSession(sess.sessionId)) {
return I.redirect(to: .home)
}
case let .register(couponCode, planCode, team):
let role: UserData.Role = team ? .teamManager : .user
return editAccount(form: registerForm(couponCode: couponCode, planCode: planCode, team: team), role: role) {
return sess.premiumAccess ? .home : .subscription(.new(couponCode: couponCode, planCode: planCode, team: team))
}
case .profile:
return editAccount(form: accountForm(), role: sess.user.data.role, cont: { .account(.profile) })
case .billing:
var user = sess.user
func renderBilling(recurlyToken: String) -> I {
let invoicesAndPDFs = sess.user.invoices.promise.map { invoices in
return invoices?.map { invoice in
(invoice, recurly.pdfURL(invoice: invoice, hostedLoginToken: recurlyToken))
}
}
let redemptions = sess.user.redemptions.promise.map { r in
r?.filter { $0.state == "active" }
}
let promise = zip(sess.user.currentSubscription.promise, invoicesAndPDFs, redemptions, sess.user.billingInfo.promise, recurly.coupons().promise).map(zip)
return .onSuccess(promise: promise, do: { p in
let (sub, invoicesAndPDFs, redemptions, billingInfo, coupons) = p
func cont(subAndAddOn: (Subscription, Plan.AddOn)?) throws -> I {
let redemptionsWithCoupon = try redemptions.map { (r) -> (Redemption, Coupon) in
let c = try coupons.first(where: { $0.matches(r.coupon_code) }) ?!
ServerError(privateMessage: "No coupon for \(r)!", publicMessage: "Something went wrong while loading your account details. Please contact us at \(email) to resolve this issue.")
return (r,c)
}
let result = billingView(subscription: subAndAddOn, invoices: invoicesAndPDFs, billingInfo: billingInfo, redemptions: redemptionsWithCoupon)
return .write(html: result)
}
if let s = sub, let p = Plan.all.first(where: { $0.plan_code == s.plan.plan_code }) {
return .onSuccess(promise: p.teamMemberAddOn.promise, do: { addOn in
try cont(subAndAddOn: (s, addOn))
})
} else {
return try cont(subAndAddOn: nil)
}
})
}
guard let t = sess.user.data.recurlyHostedLoginToken else {
return .onSuccess(promise: sess.user.account.promise, do: { acc in
user.data.recurlyHostedLoginToken = acc.hosted_login_token
return .query(user.update()) {
renderBilling(recurlyToken: acc.hosted_login_token)
}
}, else: {
if sess.teamMemberPremiumAccess {
return .write(html: billingLayout(teamMemberBillingContent()))
} else if sess.gifterPremiumAccess {
return .write(html: billingLayout(gifteeBillingContent()))
} else {
return .write(html: billingLayout(unsubscribedBillingContent()))
}
})
}
return renderBilling(recurlyToken: t)
case .updatePayment:
return .verifiedPost(do: { body in
let recurlyToken = try body["billing_info[token]"] ?!
ServerError(privateMessage: "No billing_info[token]")
return updatePaymentMethod(recurlyToken: recurlyToken)
}, or: {
renderUpdatePaymentForm(error: nil)
})
case let .threeDSecureResponse(threeDResultToken, recurlyToken):
return updatePaymentMethod(recurlyToken: recurlyToken, threeDResultToken: threeDResultToken)
case .teamMembers:
let signupLink = Route.signup(.teamMember(token: sess.user.data.teamToken)).url
return I.query(sess.user.teamMembers) { members in
return I.onSuccess(promise: sess.user.currentSubscription.promise, do: { sub in
guard let s = sub, let p = Plan.all.first(where: { $0.plan_code == s.plan.plan_code }) else {
throw ServerError(privateMessage: "Can't get sub or plan: \(String(describing: sub))")
}
return I.onSuccess(promise: p.teamMemberAddOn.promise, do: { addOn in
let prettyAmount: String?
if addOn.unit_amount_in_cents.usdCents > 0 {
prettyAmount = "\(addOn.unit_amount_in_cents.plainText) \(p.prettyInterval)"
} else {
prettyAmount = nil
}
return I.write(html: teamMembersView(teamMembers: members, price: prettyAmount, signupLink: signupLink))
})
})
}
case .invalidateTeamToken:
var user = sess.user
user.data.teamToken = UUID()
return .query(user.update()) { .redirect(to: .account(.teamMembers)) }
case .deleteTeamMember(let id):
return .verifiedPost { _ in
.query(sess.user.deleteTeamMember(teamMemberId: id, userId: sess.user.id)) {
let task = Task.syncTeamMembersWithRecurly(userId: sess.user.id).schedule(at: globals.currentDate().addingTimeInterval(5*60))
return .query(task) {
.redirect(to: .account(.teamMembers))
}
}
}
}
}
}
| 48.965854 | 210 | 0.534569 |
69a86412fd5a320ad13981621a1a23f7b14d32fb | 433 | //
// CreateAccountPwd1ViewController.swift
// W1assDropbox
//
// Created by Sophia KC on 16/10/16.
// Copyright © 2016 Sophia KC. All rights reserved.
//
import UIKit
class CreateAccountPwd1ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onTapWelcome(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| 17.32 | 57 | 0.655889 |
bb804fbfa99b49893a12f70c19e55540f6028a48 | 451 | import Foundation
import UIKit
import WebKit
extension WKWebView {
func evaluate(script: String, completionHandler: ((Any?, Error?) -> Swift.Void)? = nil) {
var finished = false
evaluateJavaScript(script) { result, error in
completionHandler?(result, error)
finished = true
}
while !finished {
RunLoop.current.run(mode: .default, before: Date.distantFuture)
}
}
}
| 23.736842 | 93 | 0.609756 |
728a5bde0e2337df1040d2460c982c048c8597b6 | 924 | //
// Affiliation.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
/** Represents many to many relationsip of affiliations between users and communities */
public struct Affiliation: Codable, Hashable {
public var userId: Int64
public var communityId: Int64
public init(userId: Int64, communityId: Int64) {
self.userId = userId
self.communityId = communityId
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case userId = "user_id"
case communityId = "community_id"
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(userId, forKey: .userId)
try container.encode(communityId, forKey: .communityId)
}
}
| 24.315789 | 88 | 0.695887 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.