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
e94937619706d9e18ad0b25713df8fa8e9d744ee
286
// // MSMsgChatViewController.swift // MushengMessageMoudle // // Created by dss on 2021/11/12. // import UIKit class MSMsgChatViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .cyan } }
15.052632
49
0.667832
4ab84af7d33e006dad035d9e9bfdb258757b6d7d
531
import Flutter import UIKit public class SwiftRepositoryCachePlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "repository_cache", binaryMessenger: registrar.messenger()) let instance = SwiftRepositoryCachePlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { result("iOS " + UIDevice.current.systemVersion) } }
35.4
104
0.781544
7ada1dfab4673ab02fb32af6d3ba3b7ac16f2b39
2,106
// // AppDelegate.swift // NextGrowingTextView // // Created by muukii on 12/19/2015. // Copyright (c) 2015 muukii. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { 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:. } }
45.782609
285
0.754036
0a1a91529d704bbf51183eb25962b7da3d8a7f6c
2,004
import Foundation import SafariServices @objc(CAPBrowserPlugin) public class CAPBrowserPlugin : CAPPlugin, SFSafariViewControllerDelegate { var vc: SFSafariViewController? @objc func open(_ call: CAPPluginCall) { guard let urlString = call.getString("url") else { call.error("Must provide a URL to open") return } if urlString.isEmpty { call.error("URL must not be empty") return } let toolbarColor = call.getString("toolbarColor") let url = URL(string: urlString) if let scheme = url?.scheme, ["http", "https"].contains(scheme.lowercased()) { DispatchQueue.main.async { self.vc = SFSafariViewController.init(url: url!) self.vc!.delegate = self let presentationStyle = call.getString("presentationStyle") if presentationStyle != nil && presentationStyle == "popover" && self.supportsPopover() { self.vc!.modalPresentationStyle = .popover self.setCenteredPopover(self.vc) } else { self.vc!.modalPresentationStyle = .fullScreen } if toolbarColor != nil { self.vc!.preferredBarTintColor = UIColor(fromHex: toolbarColor!) } self.bridge.presentVC(self.vc!, animated: true, completion: { call.success() }) } } else { call.error("Invalid URL") } } @objc func close(_ call: CAPPluginCall) { if vc == nil { call.success() } DispatchQueue.main.async { self.bridge.dismissVC(animated: true) { call.success() } } } @objc func prefetch(_ call: CAPPluginCall) { call.unimplemented() } public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { self.notifyListeners("browserFinished", data: [:]) vc = nil } public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) { self.notifyListeners("browserPageLoaded", data: [:]) } }
28.225352
124
0.646208
64d75827418e36dd83f20e323ea6882af20351c0
236
// // Created by Spritzer App on 2018-11-01. // import Foundation public class Pair<T, U> { var first: T var second: U public init(_ first: T, _ second: U){ self.first = first self.second = second } }
14.75
41
0.580508
0831714bdd724d950234112139ff740329abaadf
1,488
// // Pneumonia_Machine_LearningUITests.swift // Pneumonia_Machine_LearningUITests // // Created by Austin Heisey on 3/9/20. // Copyright © 2020 Austin Heisey. All rights reserved. // import XCTest class Pneumonia_Machine_LearningUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
33.818182
182
0.665995
d6d0ceb0eb4623369d08193c430ed1fc047afa37
1,822
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // import UIKit @available(*, deprecated, renamed: "ResizingHandleView") public typealias MSResizingHandleView = ResizingHandleView @objc(MSFResizingHandleView) open class ResizingHandleView: UIView { private struct Constants { static let markSize = CGSize(width: 36, height: 4) static let markCornerRadius: CGFloat = 2 } @objc public static let height: CGFloat = 20 private let markLayer: CALayer = { let markLayer = CALayer() markLayer.bounds.size = Constants.markSize markLayer.cornerRadius = Constants.markCornerRadius markLayer.backgroundColor = Colors.ResizingHandle.mark.cgColor return markLayer }() public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = Colors.ResizingHandle.background self.frame.size.height = ResizingHandleView.height autoresizingMask = .flexibleWidth setContentHuggingPriority(.required, for: .vertical) setContentCompressionResistancePriority(.required, for: .vertical) isUserInteractionEnabled = false layer.addSublayer(markLayer) } public required init?(coder aDecoder: NSCoder) { preconditionFailure("init(coder:) has not been implemented") } open override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: ResizingHandleView.height) } open override func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: size.width, height: ResizingHandleView.height) } open override func layoutSubviews() { super.layoutSubviews() markLayer.position = CGPoint(x: bounds.midX, y: bounds.midY) } }
32.535714
89
0.700878
d57b3add78b8c30e322ec236bdedf6a3a0248ef7
559
// // ChaCha20+Foundation.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 27/09/15. // Copyright © 2015 Marcin Krzyzanowski. All rights reserved. // import Foundation extension ChaCha20 { convenience public init?(key:String, iv:String) { guard let kkey = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes(), let iiv = iv.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.arrayOfBytes() else { return nil } self.init(key: kkey, iv: iiv) } }
31.055556
219
0.701252
f40a49d25566f28f4894cc1a291133efd4ad0c30
2,750
// // Date+Extensions.swift // // Copyright © 2014 Zeeshan Mian // // 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 // MARK: Date Extension extension Date { public func fromNow(style: DateComponentsFormatter.UnitsStyle = .abbreviated, format: String = "%@") -> String? { let formatter = DateComponentsFormatter() formatter.unitsStyle = style formatter.maximumUnitCount = 1 formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second] guard let timeString = formatter.string(from: self, to: Date()) else { return nil } let formatString = NSLocalizedString(format, comment: "Used to say how much time has passed (e.g. '2 hours ago').") return String(format: formatString, timeString) } /// Reset time to beginning of the day (`12 AM`) of `self` without changing the timezone. public func stripTime() -> Date { let calendar = Calendar.current let components = (calendar as NSCalendar).components([.year, .month, .day], from: self) return calendar.date(from: components) ?? self } // MARK: UTC private static let utcDateFormatter = DateFormatter().apply { $0.timeZone = .utc $0.dateFormat = "yyyy-MM-dd" } public var utc: Date { let dateString = Date.utcDateFormatter.string(from: self) Date.utcDateFormatter.timeZone = .current let date = Date.utcDateFormatter.date(from: dateString)! Date.utcDateFormatter.timeZone = .utc return date } } extension TimeZone { public static let utc = TimeZone(identifier: "UTC")! } extension Locale { public static let usa = Locale(identifier: "en_US") }
37.162162
123
0.693455
f9d9c205d97d3205a745026e4fc24aa4c84d363a
622
// // EventTableViewCell.swift // StarbucksApp // // Created by 신민희 on 2021/05/25. // import UIKit class EventTableViewCell: UITableViewCell { static let identifier = "EventTableViewCell" override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUI() { setBasic() setLayout() } func setBasic() { } func setLayout() { } }
18.848485
79
0.601286
16c16c72da9c936da418e01e09aab1b93bd6d496
1,267
// // MessageMainPullToRefresh.swift // DatingApp // // Created by Radley Hoang on 11/02/2022. // import SwiftUI struct PullToRefresh: View { var coordinateSpaceName: String var onRefresh: ()->Void @State var needRefresh: Bool = false var body: some View { GeometryReader { geo in if (geo.frame(in: .named(coordinateSpaceName)).midY > 50) { Spacer() .onAppear { needRefresh = true } } else if (geo.frame(in: .named(coordinateSpaceName)).maxY < 10) { Spacer() .onAppear { if needRefresh { needRefresh = false onRefresh() } } } HStack { Spacer() if needRefresh { ProgressView() } else { Text("Pull to refresh") .style(font: .lexendBold, size: 14, color: Asset.Colors.Global.gray777777.color) .offset(y: 20) } Spacer() } }.padding(.top, -50) } }
26.957447
104
0.415154
f9db5a032a146cac4af79974cb50e27a6da43d09
139
// // GHLabel.swift // // // Created by lvv.me on 2022/2/22. // import Foundation struct GHLabel: Decodable { var name: String }
10.692308
35
0.618705
799a8fe4900ae7e2eeb43373e22f20e20acc7fc4
672
import ImageIO import MobileCoreServices import UIKit extension UIImage: ImageViewable { public var bitmapView: UnsafePointer<UInt8> { return cgImage!.bitmapView } public var JPEGView: UnsafePointer<UInt8> { return (UIImageJPEGRepresentation(self, 1.0)! as NSData).bytes.bindMemory(to: UInt8.self, capacity: UIImageJPEGRepresentation(self, 1.0)!.count) } public var PNGView: UnsafePointer<UInt8> { return (UIImagePNGRepresentation(self)! as NSData).bytes.bindMemory(to: UInt8.self, capacity: UIImagePNGRepresentation(self)!.count) } } extension Image { public init(image: UIImage) { self.init(data: image.bitmapView, size: Size(size: image.size)) } }
26.88
146
0.764881
eb7c4dbe75006236f041ae4f4de5625546362fdc
1,859
// // Copyright © 2020 NHSX. All rights reserved. // import Localization import XCTest struct StartOnboardingScreen { var app: XCUIApplication func scrollTo(element: XCUIElement) { app.scrollTo(element: element) } var stepTitle: XCUIElement { app.staticTexts[localized: .start_onboarding_step_title] } var stepDescription1Header: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_header] } var stepDescription1Body: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_description] } var stepDescription2Header: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_header] } var stepDescription2Body: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_description] } var stepDescription3Header: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_header] } var stepDescription3Body: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_description] } var stepDescription4Header: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_header] } var stepDescription4Body: XCUIElement { app.staticTexts[localized: .start_onboarding_step_1_description] } var continueButton: XCUIElement { app.windows["MainWindow"].buttons[localized: .start_onboarding_button_title] } var ageConfirmationAcceptButton: XCUIElement { app.buttons[localized: .age_confirmation_alert_accept] } var ageConfirmationRejectButton: XCUIElement { app.buttons[localized: .age_confirmation_alert_reject] } func ageConfirmationAlertHandled(title: String) -> XCUIElement { app.staticTexts[title] } }
27.746269
84
0.703066
de53c9268acb4b2b10cf40b16fa43420367ce719
232
// // ChartData.swift // SubscMemo // // Created by Higashihara Yoki on 2021/05/01. // import SwiftUI protocol ChartData: Identifiable { var data: Double { get } var color: Color { get } var label: String { get } }
15.466667
46
0.637931
f827b2c52f4f8d9b9f2db34385a48359d568426f
247
// // SnapLikeCell.swift // SnapLikeCollectionView // // Created by Kei Fujikawa on 2018/12/03. // Copyright © 2018 kboy. All rights reserved. // public protocol SnapLikeCell: class { associatedtype Item var item: Item? { get set } }
19
47
0.684211
deb9615d1f722a47f4ecf90d6462ba4b97efe746
819
// // JsonParseUsageUITestsLaunchTests.swift // JsonParseUsageUITests // // Created by cemal tüysüz on 3.01.2022. // import XCTest class JsonParseUsageUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
24.818182
88
0.681319
644b9884017d1ed51754fdc7845663714f3ae8fb
14,203
// // DefaultSettings.swift // TastyImitationKeyboard // // Created by Alexei Baboulevitch on 11/2/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import UIKit class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView? @IBOutlet var effectsView: UIVisualEffectView? @IBOutlet var backButton: UIButton? @IBOutlet var settingsLabel: UILabel? @IBOutlet var pixelLine: UIView? override var darkMode: Bool { didSet { self.updateAppearance(darkMode) } } let cellBackgroundColorDark = UIColor.white.withAlphaComponent(CGFloat(0.25)) let cellBackgroundColorLight = UIColor.white.withAlphaComponent(CGFloat(1)) let cellLabelColorDark = UIColor.white let cellLabelColorLight = UIColor.black let cellLongLabelColorDark = UIColor.lightGray let cellLongLabelColorLight = UIColor.gray // TODO: these probably don't belong here, and also need to be localized var settingsList: [(String, [String])] { get { return [ ("General Settings", [kAutoCapitalization, kPeriodShortcut, kKeyboardClicks]), ("Extra Settings", [kSmallLowercase]) ] } } var settingsNames: [String:String] { get { return [ kAutoCapitalization: "Auto-Capitalization", kPeriodShortcut: "“.” Shortcut", kKeyboardClicks: "Keyboard Clicks", kSmallLowercase: "Allow Lowercase Key Caps" ] } } var settingsNotes: [String: String] { get { return [ kKeyboardClicks: "Please note that keyboard clicks will work only if “Allow Full Access” is enabled in the keyboard settings. Unfortunately, this is a limitation of the operating system.", kSmallLowercase: "Changes your key caps to lowercase when Shift is off, making it easier to tell what mode you are in." ] } } required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) { super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode) self.loadNib() } required init?(coder aDecoder: NSCoder) { fatalError("loading from nib not supported") } func loadNib() { let assets = Bundle(for: type(of: self)).loadNibNamed("DefaultSettings", owner: self, options: nil) if (assets?.count)! > 0 { if let rootView = assets?.first as? UIView { rootView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(rootView) let left = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0) let right = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0) let top = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) self.addConstraint(left) self.addConstraint(right) self.addConstraint(top) self.addConstraint(bottom) } } self.tableView?.register(DefaultSettingsTableViewCell.self, forCellReuseIdentifier: "cell") self.tableView?.estimatedRowHeight = 44; self.tableView?.rowHeight = UITableViewAutomaticDimension; // XXX: this is here b/c a totally transparent background does not support scrolling in blank areas self.tableView?.backgroundColor = UIColor.white.withAlphaComponent(0.01) self.updateAppearance(self.darkMode) } func numberOfSections(in tableView: UITableView) -> Int { return self.settingsList.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.settingsList[section].1.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == self.settingsList.count - 1 { return 50 } else { return 0 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.settingsList[section].0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? DefaultSettingsTableViewCell { let key = self.settingsList[indexPath.section].1[indexPath.row] if cell.sw.allTargets.count == 0 { cell.sw.addTarget(self, action: #selector(DefaultSettings.toggleSetting(_:)), for: UIControlEvents.valueChanged) } cell.sw.isOn = UserDefaults.standard.bool(forKey: key) cell.label.text = self.settingsNames[key] cell.longLabel.text = self.settingsNotes[key] cell.backgroundColor = (self.darkMode ? cellBackgroundColorDark : cellBackgroundColorLight) cell.label.textColor = (self.darkMode ? cellLabelColorDark : cellLabelColorLight) cell.longLabel.textColor = (self.darkMode ? cellLongLabelColorDark : cellLongLabelColorLight) cell.changeConstraints() return cell } else { assert(false, "this is a bad thing that just happened") return UITableViewCell() } } func updateAppearance(_ dark: Bool) { if dark { let blueColor = UIColor(red: 135/CGFloat(255), green: 206/CGFloat(255), blue: 250/CGFloat(255), alpha: 1) self.pixelLine?.backgroundColor = blueColor.withAlphaComponent(CGFloat(0.5)) self.backButton?.setTitleColor(blueColor, for: UIControlState()) self.settingsLabel?.textColor = UIColor.white if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { cell.backgroundColor = cellBackgroundColorDark let label = cell.viewWithTag(2) as? UILabel label?.textColor = cellLabelColorDark let longLabel = cell.viewWithTag(3) as? UITextView longLabel?.textColor = cellLongLabelColorDark } } } else { let blueColor = UIColor(red: 0/CGFloat(255), green: 122/CGFloat(255), blue: 255/CGFloat(255), alpha: 1) self.pixelLine?.backgroundColor = blueColor.withAlphaComponent(CGFloat(0.5)) self.backButton?.setTitleColor(blueColor, for: UIControlState()) self.settingsLabel?.textColor = UIColor.gray if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { cell.backgroundColor = cellBackgroundColorLight let label = cell.viewWithTag(2) as? UILabel label?.textColor = cellLabelColorLight let longLabel = cell.viewWithTag(3) as? UITextView longLabel?.textColor = cellLongLabelColorLight } } } } func toggleSetting(_ sender: UISwitch) { if let cell = sender.superview as? UITableViewCell { if let indexPath = self.tableView?.indexPath(for: cell) { let key = self.settingsList[indexPath.section].1[indexPath.row] UserDefaults.standard.set(sender.isOn, forKey: key) } } } } class DefaultSettingsTableViewCell: UITableViewCell { var sw: UISwitch var label: UILabel var longLabel: UITextView var constraintsSetForLongLabel: Bool var cellConstraints: [NSLayoutConstraint] override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.sw = UISwitch() self.label = UILabel() self.longLabel = UITextView() self.cellConstraints = [] self.constraintsSetForLongLabel = false super.init(style: style, reuseIdentifier: reuseIdentifier) self.sw.translatesAutoresizingMaskIntoConstraints = false self.label.translatesAutoresizingMaskIntoConstraints = false self.longLabel.translatesAutoresizingMaskIntoConstraints = false self.longLabel.text = nil self.longLabel.isScrollEnabled = false self.longLabel.isSelectable = false self.longLabel.backgroundColor = UIColor.clear self.sw.tag = 1 self.label.tag = 2 self.longLabel.tag = 3 self.addSubview(self.sw) self.addSubview(self.label) self.addSubview(self.longLabel) self.addConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addConstraints() { let margin: CGFloat = 8 let sideMargin = margin * 2 let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty if hasLongText { let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -sideMargin) let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: margin) let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: sideMargin) let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: sw, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) self.addConstraint(switchSide) self.addConstraint(switchTop) self.addConstraint(labelSide) self.addConstraint(labelCenter) let left = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: sideMargin) let right = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -sideMargin) let top = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: sw, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: margin) let bottom = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -margin) self.addConstraint(left) self.addConstraint(right) self.addConstraint(top) self.addConstraint(bottom) self.cellConstraints += [switchSide, switchTop, labelSide, labelCenter, left, right, top, bottom] self.constraintsSetForLongLabel = true } else { let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -sideMargin) let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: margin) let switchBottom = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: -margin) let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: sideMargin) let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: sw, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) self.addConstraint(switchSide) self.addConstraint(switchTop) self.addConstraint(switchBottom) self.addConstraint(labelSide) self.addConstraint(labelCenter) self.cellConstraints += [switchSide, switchTop, switchBottom, labelSide, labelCenter] self.constraintsSetForLongLabel = false } } // XXX: not in updateConstraints because it doesn't play nice with UITableViewAutomaticDimension for some reason func changeConstraints() { let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty if hasLongText != self.constraintsSetForLongLabel { self.removeConstraints(self.cellConstraints) self.cellConstraints.removeAll() self.addConstraints() } } }
47.983108
218
0.653524
39465f145527525b86d1993818a0ac2e9282b718
1,014
// // LoggerFormatterProtocol.swift // LoggerKit // // Created by Werck, Ayrton on 18-07-06. // Copyright (c) 2018 Nuglif. All rights reserved. // public struct LogMetaData { let level: LoggerLevel let category: LogCategoryProtocol let subSystem: String let userInfo: [String: Any]? let line: Int? let functionName: String? let fileName: String? public init(level: LoggerLevel, category: LogCategoryProtocol, subSystem: String, userInfo: [String: Any]? = nil, line: Int? = nil, functionName: String? = nil, fileName: String? = nil) { self.line = line self.functionName = functionName self.fileName = fileName self.level = level self.category = category self.userInfo = userInfo self.subSystem = subSystem } } public protocol LoggerFormatterProtocol { func format(message: String, details: LogMetaData) -> String }
26
64
0.607495
0afaa6770af1d4b36ca221e4cefb176c678a2376
2,991
import RxSugar import XCTest import UIKit import UIKit.UIGestureRecognizerSubclass struct TargetActionPair { let target: AnyObject let action: Selector } class TestGestureRecognizer: UIGestureRecognizer { var targetActionPair: TargetActionPair? var forceState: UIGestureRecognizer.State = .ended override var state: UIGestureRecognizer.State { get { return forceState } set { self.state = newValue } } override open func addTarget(_ target: Any, action: Selector) { targetActionPair = TargetActionPair(target: target as AnyObject, action: action) } func fireGestureEvent(_ state: UIGestureRecognizer.State) { guard let targetAction = self.targetActionPair else { return } forceState = state _ = targetAction.target.perform(targetAction.action, with: self) } } class TestTapGestureRecognizer: UITapGestureRecognizer { var targetActionPair: TargetActionPair? var forceState: UIGestureRecognizer.State = .ended override var state: UIGestureRecognizer.State { get { return forceState } set { self.state = newValue } } override func addTarget(_ target: Any, action: Selector) { targetActionPair = TargetActionPair(target: target as AnyObject, action: action) } func fireGestureEvent(_ state: UIGestureRecognizer.State) { guard let targetAction = self.targetActionPair else { return } forceState = state _ = targetAction.target.perform(targetAction.action, with: self) } } class UIGestureRecognizer_SugarTests: XCTestCase { func testGestureRecognizerDoesNotFilterEvents() { let testObject = TestGestureRecognizer() let eventStream = testObject.rxs.events var events: [String] = [] _ = eventStream.subscribe(onNext: { _ in events.append("event") }) testObject.fireGestureEvent(.possible) XCTAssertEqual(events, ["event"]) testObject.fireGestureEvent( .began) XCTAssertEqual(events, ["event", "event"]) testObject.fireGestureEvent(.changed) XCTAssertEqual(events, ["event", "event", "event"]) testObject.fireGestureEvent(.ended) XCTAssertEqual(events, ["event", "event", "event", "event"]) } func testTapGestureRecognizerSendsRecognizedEvents() { let testObject = TestTapGestureRecognizer() let eventStream = testObject.rxs.tap var events: [String] = [] _ = eventStream.subscribe(onNext: { _ in events.append("tap") }) testObject.fireGestureEvent(.ended) XCTAssertEqual(events, ["tap"]) testObject.fireGestureEvent( .possible) XCTAssertEqual(events, ["tap"]) testObject.fireGestureEvent(.changed) XCTAssertEqual(events, ["tap"]) testObject.fireGestureEvent(.ended) XCTAssertEqual(events, ["tap", "tap"]) } }
33.233333
88
0.661317
1ea0ac979eec9bdbf0f1a479013d1b8dcbed8efe
7,244
// // ViewController.swift // Example // // Created by Luong Van Lam on 6/11/18. // Copyright © 2018 lamlv. All rights reserved. // import AzCall import AzCore import UIKit class ViewController: UIViewController { @IBOutlet var tableView: UITableView! @IBOutlet var indicator: UIActivityIndicatorView! @IBOutlet var loadingView: UIView! enum SectionIndex: Int { case rtcVideoCall = 0 case rtcAudioCall = 1 case freeSwitchCall = 2 var title: String? { let data = ["WebRTC Video Call", "WebRTC Audio Call", "Free Switch Call"] return data[hashValue] } } override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") let attr = NSAttributedString(string: "Sign Out", attributes: [ NSAttributedStringKey.foregroundColor: UIColor.blue ]) let btnSignOut = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 40)) btnSignOut.setAttributedTitle(attr, for: .normal) btnSignOut.sizeToFit() btnSignOut.addTarget(self, action: #selector(signOutOnClick), for: .touchUpInside) btnSignOut.tintColor = UIColor.blue navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btnSignOut) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard AzStackManager.shared.networkManager.socketIsConnected == false else { return } if AzStackManager.shared.userId != "", AzStackManager.shared.userCredentials != "" { startAuth(userId: AzStackManager.shared.userId, credentials: AzStackManager.shared.userCredentials) } else { showInputName() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func showInputName() { guard AzStackManager.shared.networkManager.socketIsConnected == false else { return } let alert = UIAlertController(title: "User Information", message: "Select your user to work with AzStack", preferredStyle: .alert) alert.addTextField(configurationHandler: { textfield in textfield.placeholder = "Input your AzStack's userId" }) alert.addTextField(configurationHandler: { textfield in textfield.placeholder = "Input your credentials" }) let saveAction = UIAlertAction(title: "Save", style: .default, handler: { _ in let userId = alert.textFields?[0].text ?? "" let credentials = alert.textFields?[1].text ?? "" self.startAuth(userId: userId, credentials: credentials) }) alert.addAction(saveAction) present(alert, animated: true, completion: nil) } func showAlert(with msg: String) { let alert = UIAlertController(title: "Error", message: msg, preferredStyle: .alert) let action = UIAlertAction(title: "Confirm", style: .default, handler: { _ in alert.dismiss(animated: true, completion: nil) }) alert.addAction(action) present(alert, animated: true, completion: nil) } func startAuth(userId: String, credentials: String) { self.indicator.startAnimating() self.loadingView.isHidden = false AzStackManager.shared.connectWithAzStack( userId: userId, userCredentials: credentials, fullname: "Demo User - \(userId)", additionInfo: nil, completion: { result in DispatchQueue.main.async { self.indicator.stopAnimating() self.loadingView.isHidden = true if let err = result.error { self.showAlert(with: err.localizedDescription) } else { self.title = result.userId self.loadingView.isHidden = true } } } ) } @objc func signOutOnClick() { AzStackManager.shared.logOut({ error in guard error == nil else { return self.showAlert(with: error!.localizedDescription) } self.showInputName() }) } } // MARK: - UITableViewDelegate extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let sectionIndex = SectionIndex(rawValue: indexPath.section) else { fatalError() } switch sectionIndex { case .rtcVideoCall: selectUserForRtcCall(true) case .rtcAudioCall: selectUserForRtcCall(false) case .freeSwitchCall: AzCallManager.shared.showFreeSwitchCall(true, completionPresent: nil) } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func selectUserForRtcCall(_ hasVideo: Bool) { let alert = UIAlertController(title: "Partner AzUsreId", message: "Select your friend id to make a call", preferredStyle: .alert) alert.addTextField(configurationHandler: { textfield in textfield.placeholder = "Partner's AzUserId" }) let confirm = UIAlertAction(title: "Confirm", style: .default, handler: { _ in guard let azUserId = alert.textFields?.first?.text, azUserId != "" else { return } self.showRtcCall(with: azUserId, hasVideo: hasVideo) }) let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { _ in alert.dismiss(animated: true, completion: nil) }) alert.addAction(confirm) alert.addAction(cancel) present(alert, animated: true, completion: nil) } func showRtcCall(with azUserId: String, hasVideo: Bool) { AzCallManager.shared.startRtcCallWith( azUserId, hasVideo: hasVideo, animatedPresent: false, completionPresent: nil ) } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return SectionIndex.freeSwitchCall.rawValue + 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let section = SectionIndex(rawValue: indexPath.section) else { fatalError() } let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = section.title return cell } }
33.229358
138
0.59608
c16002fe91d085bb3e07bcfc176ea3c2c1e622ec
3,011
// // ImagePicker.swift // Podpishis // // Created by Анастасия Зубехина on 23.12.2019. // Copyright © 2019 Zirkel. All rights reserved. // import UIKit protocol ImagePickerDelegate: AnyObject { func didSelect(image: UIImage?) } open class ImagePicker: NSObject { private let imagePicker: UIImagePickerController private weak var presentationController: UIViewController? private weak var delegate: ImagePickerDelegate? init(_ presentationController: UIViewController, _ delegate: ImagePickerDelegate) { imagePicker = UIImagePickerController() super.init() self.presentationController = presentationController self.delegate = delegate imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.mediaTypes = ["public.image"] } func present(cameraTitle: String = "Camera", photoTitle: String = "Photo", cancelTitle: String = "Cancel") { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if let cameraAction = action(for: .camera, title: cameraTitle) { alertController.addAction(cameraAction) } if let photoLibraryAction = action(for: .photoLibrary, title: photoTitle) { alertController.addAction(photoLibraryAction) } alertController.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: nil)) presentationController?.present(alertController, animated: true) } func openPicker(by type: UIImagePickerController.SourceType) { imagePicker.sourceType = type presentationController?.present(imagePicker, animated: true) } func action(for type: UIImagePickerController.SourceType, title: String) -> UIAlertAction? { guard UIImagePickerController.isSourceTypeAvailable(type) else { return nil } return UIAlertAction(title: title, style: .default) { (_) in self.imagePicker.sourceType = type self.presentationController?.present(self.imagePicker, animated: true) } } private func dismissPickerController(_ controller: UIImagePickerController, didSelect image: UIImage?) { controller.dismiss(animated: true, completion: nil) delegate?.didSelect(image: image) } } // MARK: - UIImagePickerControllerDelegate extension ImagePicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate { public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismissPickerController(picker, didSelect: nil) } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let image = info[.originalImage] as? UIImage else { return dismissPickerController(picker, didSelect: nil) } dismissPickerController(picker, didSelect: image) } }
38.602564
151
0.703753
5da259a4c983b4d1a84ddb85f2502c196b65cc47
426
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct c{extension{class case,- >
38.727273
78
0.751174
1a55518b8ed7442cbfc652bf1bc54c8686c6e943
5,186
// // ViewControllerDetail.swift // swift-minutiae-project // // Created by Vanessa Primetzhofer on 09.04.21. // import UIKit // TODO: Nur Türen die der User hat anzeigen? oder nicht? ka? class ViewControllerDetail: UITableViewController { let queue = DispatchQueue(label: "queue1") var model = Model() override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. if segue.identifier == "scanQR" { if let viewController = segue.destination as? ViewControllerQR { //viewController.tab_adress = self.address print("perform segue") } } } @IBAction func addDoor(_ sender: Any) { performSegue(withIdentifier: "scanQR", sender: self) } override func viewDidLoad() { super.viewDidLoad() queue.async { self.download() } } func download(){ let model = Model() if let url = URL(string: "http://0.0.0.0:3000/doorTable/"){ if let data = try? Data(contentsOf: url){ if let json = try? JSONSerialization.jsonObject(with:data, options:[]){ if let array = json as? [Any]{ for obj in array { if let dict = obj as? [String: Any]{ let doorTable = DoorTable() doorTable.doorID = dict["doorID"] as! Int doorTable.name = dict["Name"] as! String doorTable.iP = dict["IP"] as! String model.door.append(doorTable) } } DispatchQueue.main.async { self.model = model self.tableView.reloadData() } } } }else{ print("failed to download") } }else{ print("sinnlose URL") } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return model.door.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "login", for: indexPath) let element = model.door[indexPath.row] cell.detailTextLabel?.text = "\(element.name)" cell.textLabel?.text = "\(element.doorID)" // Configure the cell... return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("selected cell \(indexPath.row)") performSegue(withIdentifier: "detailOpen", sender: self) } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
33.24359
138
0.549942
4af870d22fa4a756d61be3174aaa594d8364e4b8
2,181
// // AppDelegate.swift // ListKit // // Created by Leonir Deolindo on 04/07/2019. // Copyright (c) 2019 Leonir Deolindo. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.404255
285
0.7547
218a5683e9e4783a74c759205a10ef259f7e667e
1,504
import Foundation import TSCBasic import TuistCore import TuistGraph import TuistSupport /// Updates path of workspace to point to where automation workspace should be generated public final class AutomationPathWorkspaceMapper: WorkspaceMapping { private let workspaceDirectory: AbsolutePath public init( workspaceDirectory: AbsolutePath ) { self.workspaceDirectory = workspaceDirectory } public func map(workspace: WorkspaceWithProjects) throws -> (WorkspaceWithProjects, [SideEffectDescriptor]) { var workspace = workspace workspace.workspace.xcWorkspacePath = workspaceDirectory.appending(component: "\(workspace.workspace.name).xcworkspace") let mappedProjects = try workspace.projects.map(map(project:)) workspace.projects = mappedProjects.map(\.0) return ( workspace, [ .directory( DirectoryDescriptor( path: workspaceDirectory, state: .present ) ), ] + mappedProjects.flatMap(\.1) ) } // MARK: - Helpers private func map(project: Project) throws -> (Project, [SideEffectDescriptor]) { var project = project let xcodeProjBasename = project.xcodeProjPath.basename project.xcodeProjPath = workspaceDirectory.appending(component: xcodeProjBasename) return ( project, [] ) } }
32
128
0.632979
ed96529838d10458972af371dcbc2641e7e80d93
839
// // PaymentRequestResolver.swift // BillionWallet // // Created by Evolution Group Ltd on 21.12.2017. // Copyright © 2017 Evolution Group Ltd. All rights reserved. // import Foundation class PaymentRequestResolver: SchemeResolverProtocol { private let handler: BitcoinUrlHandlerProtocol private let parser: BitcoinSchemeParserProtocol init(parser: BitcoinSchemeParserProtocol, handler: BitcoinUrlHandlerProtocol) { self.parser = parser self.handler = handler } func resolve(_ url: URL) { do { let data = try parser.parseUrl(url) handler.handle(urlData: data) } catch let err { let popup = PopupView(type: .cancel, labelString: err.localizedDescription) UIApplication.shared.keyWindow?.addSubview(popup) } } }
27.966667
87
0.669845
1eb250595a156b94d28abc3b9d2fd293d01b4049
895
import JSON /// Conformes the `Team` model to `JSONConvertible`. extension Team: JSONConvertible { /// Creates a JSON representation of the model instance. func makeJSON() throws -> JSON { // Create the JSON instance and get all the team's members var json = JSON() let members: [TeamMember] = try self.members().all() // Set the `id`, `name`, and `members` JSON keys try json.set("id", self.id?.wrapped) try json.set("name", self.name) try json.set("members", members.makeJSON()) // Return the JSON return json } /// Creates an instance of `Team` from a JSON object. convenience init(json: JSON) throws { // Get the team's name from the JSON let name: String = try json.get("name") // Create the team. self.init(name: name) } }
29.833333
66
0.576536
8aa726da56db2d59c37dc232535aad674f00a624
2,292
import UIKit /// A position on the screen. Use this to define specific locations on the screen where the animation should start internal enum Position { /// the top left point of the view case topLeft /// the top center point of the view case topMiddle /// the top right point of the view case topRight /// the left point of the view, centered vertically case left /// the absolute center of the view (both horizontally and vertically) case middle /// the right point of the view, centered vertically case right /// the bottom left point of the view case bottomLeft /// the bottom center point of the view case bottomMiddle /// the bottom right point of the view case bottomRight } /// A `DistanceSortFunction` that uses a position attribute to define an animation's starting point. internal protocol PositionSortFunction: DistanceSortFunction { /// the starting position of the animation var position: Position { get set } } internal extension PositionSortFunction { func distancePoint(view: UIView, subviews: [View]) -> CGPoint { guard subviews.count > 0 else { return .zero } let distancePoint: CGPoint let bounds = view.bounds switch position { case .topLeft: distancePoint = CGPoint.zero case .topMiddle: distancePoint = CGPoint(x: (bounds.size.width / 2.0), y: 0.0) case .topRight: distancePoint = CGPoint(x: bounds.size.width, y: 0.0) case .left: distancePoint = CGPoint(x: 0.0, y: (bounds.size.height / 2.0)) case .middle: distancePoint = CGPoint(x: (bounds.size.width / 2.0), y: (bounds.size.height / 2.0)) case .right: distancePoint = CGPoint(x: bounds.size.width, y: (bounds.size.height / 2.0)) case .bottomLeft: distancePoint = CGPoint(x: 0.0, y: bounds.size.height) case .bottomMiddle: distancePoint = CGPoint(x: (bounds.size.width / 2.0), y: bounds.size.height) case .bottomRight: distancePoint = CGPoint(x: bounds.size.width, y: bounds.size.height) } return translate(distancePoint: distancePoint, intoSubviews: subviews) } }
31.39726
114
0.638743
8a1881b33b89d9a1fc3ec2be94587862e51652b7
2,407
// // UrlSessionService.swift // NiceDemo // // Created by Serhii Kharauzov on 3/14/18. // Copyright © 2018 Serhii Kharauzov. All rights reserved. // import Foundation /// Responsible for performing network requests, using `URLSession`. /// /// You shouldn't call its methods explicitly! Please use it as an abstract layer in /// server services via protocols. class UrlSessionService: ServerService { // MARK: Private properties private let session: URLSession // MARK: Public methods init(session: URLSession = URLSession(configuration: .default)) { self.session = session } func performRequest<T>(_ request: URLRequestable, completion: ServerRequestResponseCompletion<T>?) { session.dataTask(with: request.asURLRequest()) { (data, response, error) in let result: Result<T> defer { DispatchQueue.main.async { completion?(result) } } if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode { guard let data = data as? T else { return result = .failure(HTTPRequestError.invalidResponseDataType) } result = .success(data) } else { result = .failure(self.getFormattedError(responseData: data, defaultError: error)) } }.resume() } // MARK: Private methods private func getFormattedError(responseData: Data?, defaultError: Error?) -> Error { if let data = responseData { if let baseResponse = try? JSONDecoder().decode(BaseResponse.self, from: data), let errorString = baseResponse.error { return HTTPRequestError.custom(errorString) } } return defaultError ?? HTTPRequestError.invalidResponse } } extension UrlSessionService { enum HTTPRequestError: Error { case invalidResponseDataType case invalidResponse case custom(String) var localizedDescription: String { switch self { case .invalidResponseDataType: return "Response's data format is different from expected." case .invalidResponse: return "Invalid response." case .custom(let value): return value } } } }
31.671053
119
0.603656
234e53b878c39722bb4fe1b0f18a2ac78b160fb5
2,234
// Copyright (c) 2021 [email protected] < [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 UIKit import RxSwift import RxCocoa import MJRefresh public extension Reactive where Base: Viewable { /// 当触发下拉刷新时发出信号 var headerRefreshing: ControlEvent<()> { let source: Observable<()> = Observable.create { [weak control = self.base] observer in if let control = control { control.contentScrollView.mj_header?.refreshingBlock = { observer.on(.next(())) } } return Disposables.create() } return ControlEvent(events: source) } /// 当触发上拉加载时发出信号 var footerRefreshing: ControlEvent<()> { let source: Observable<()> = Observable.create { [weak control = self.base] observer in if let control = control { control.contentScrollView.mj_footer?.refreshingBlock = { observer.on(.next(())) } } return Disposables.create() } return ControlEvent(events: source) } }
39.892857
83
0.647269
71ac6fdfbdd6181ebde07fb688708d2d9ad73396
1,103
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation import Amplify public class CoreMLTranslateTextOperation: AmplifyOperation<PredictionsTranslateTextRequest, Void, TranslateTextResult, PredictionsError>, PredictionsTranslateTextOperation { init(_ request: PredictionsTranslateTextRequest, listener: EventListener?) { super.init(categoryType: .predictions, eventName: HubPayload.EventName.Predictions.interpret, request: request, listener: listener) } override public func main() { if isCancelled { finish() return } let errorDescription = CoreMLPluginErrorString.operationNotSupported.errorDescription let recovery = CoreMLPluginErrorString.operationNotSupported.recoverySuggestion let predictionsError = PredictionsError.service(errorDescription, recovery, nil) dispatch(event: .failed(predictionsError)) finish() } }
28.282051
93
0.68903
389740d734f71e74a6b4b5718f6c5aad1b051fe2
1,916
import CommonCrypto import CryptoKit // Reference: https://stackoverflow.com/questions/42935148/swift-calculate-md5-checksum-for-large-files func getMd5FileChecksum(url: URL) throws -> String? { let file = try FileHandle(forReadingFrom: url) defer { file.closeFile() } if #available(iOS 13, *) { return getMd5FileChecksumNew(file: file)?.base64EncodedString() } else { return getMd5FileChecksumOld(file: file)?.base64EncodedString() } } fileprivate let bufferSize = 16 * 1024 @available(iOS 13.0, *) fileprivate func getMd5FileChecksumNew(file: FileHandle) -> Data? { // Create and initialize MD5 context: var md5 = CryptoKit.Insecure.MD5() // Read up to `bufferSize` bytes, until EOF is reached, and update MD5 context: while autoreleasepool(invoking: { let data = file.readData(ofLength: bufferSize) if data.count > 0 { md5.update(data: data) return true // Continue } else { return false // End of file } }) {} // Compute the MD5 digest: return Data(md5.finalize()) } fileprivate func getMd5FileChecksumOld(file: FileHandle) -> Data? { // Create and initialize MD5 context: var context = CC_MD5_CTX() CC_MD5_Init(&context) // Read up to `bufferSize` bytes, until EOF is reached, and update MD5 context: while autoreleasepool(invoking: { let data = file.readData(ofLength: bufferSize) if data.count > 0 { data.withUnsafeBytes { _ = CC_MD5_Update(&context, $0.baseAddress, numericCast(data.count)) } return true // Continue } else { return false // End of file } }) {} // Compute the MD5 digest: var digest: [UInt8] = Array(repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) _ = CC_MD5_Final(&digest, &context) return Data(digest) }
32.474576
103
0.636221
bf6733cd97879fa53e064e933d97a7d3f710ec7d
2,787
// // Copyright © 2021 An Tran. All rights reserved. // import Foundation @propertyWrapper struct UserDefault<Value> { private let get: () -> Value private let set: (Value) -> Void var wrappedValue: Value { get { get() } set { set(newValue) } } var projectedValue: UserDefault<Value> { self } } extension UserDefault { init(_ key: String, defaultValue: Value, userDefaults: UserDefaults = .standard) { get = { userDefaults[key: key] ?? defaultValue } set = { userDefaults[key: key] = $0 } } } extension UserDefault { init<T>(_ key: String, userDefaults: UserDefaults = .standard) where Value == T? { get = { userDefaults[key: key] } set = { userDefaults[key: key] = $0 } } } extension UserDefault where Value: RawRepresentable { init(_ key: String, defaultValue: Value, userDefaults: UserDefaults = .standard) { get = { userDefaults[rawValueKey: key] ?? defaultValue } set = { userDefaults[rawValueKey: key] = $0 } } } extension UserDefault { init<T: RawRepresentable>(_ key: String, userDefaults: UserDefaults = .standard) where Value == T? { get = { userDefaults[rawValueKey: key] } set = { userDefaults[rawValueKey: key] = $0 } } } extension UserDefault where Value: Codable { init(_ key: String, defaultValue: Value, userDefaults: UserDefaults = .standard) { get = { userDefaults[rawValueKey: key] ?? defaultValue } set = { userDefaults[rawValueKey: key] = $0 } } } private extension UserDefaults { subscript<Value>(key key: String) -> Value? { get { value(forKey: key) as? Value } set { setValue(newValue, forKey: key) } } subscript<Value: RawRepresentable>(rawValueKey key: String) -> Value? { get { guard let rawValue = value(forKey: key) as? Value.RawValue else { return nil } return Value(rawValue: rawValue) } set { setValue(newValue?.rawValue, forKey: key) } } subscript<Value: Codable>(rawValueKey key: String) -> Value? { get { if let encodedValue = object(forKey: key) as? Data, let value = try? JSONDecoder().decode(Value.self, from: encodedValue) { return value } return nil } set { let encodedValue = try? JSONEncoder().encode(newValue) setValue(encodedValue, forKey: key) } } } extension UserDefaults { func object<Value: Codable>(for key: String, defaultValue: Value) -> Value { self[rawValueKey: key] ?? defaultValue } }
24.025862
104
0.574453
8707e836d2a21747484930e814cc30f30bfdf337
807
// // ViewController.swift // Classroom QR // // Created by Josh Zhanson on 2/10/17. // Copyright © 2017 Josh Zhanson. All rights reserved. // import UIKit struct persistData { static var input: Set<String> = [] static var parsed = [String: String]() static var classes : [classroom] = [] static var currentClass : classroom? = nil static var results = [String: String]() static var currentQuestion : Question? = nil } class StartViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
23.057143
80
0.66171
ff7fa5e14736fba53f7ac4f9511f27bfcbe1b2a5
1,044
// // Drop.swift // idrop.link // // Created by Christian Schulze on 31/05/15. // Copyright (c) 2015 andinfinity. All rights reserved. // import Cocoa class Drop: NSObject { var dropDate: String? var name: String? var _id: String? var url: String? var shortId: String? var type: String? var path: String? var views: Int? override init() { self.dropDate = nil self.name = nil self._id = nil self.url = nil self.shortId = nil self.type = nil self.path = nil self.views = nil } init(dropDate: String?, name: String?, _id: String?, url: String?, shortId: String?, type: String?, path: String?, views: String?) { self.dropDate = dropDate self.name = name self._id = _id self.url = url self.shortId = shortId self.type = type self.path = path if let _views = views { self.views = Int(_views) } } }
22.695652
73
0.528736
767a8d7784d35a05f5cdcf22de4edd647ac528a2
2,594
// // ViewController.swift // Tipster // // Created by Sidney Pho on 7/30/20. // Copyright © 2020 Sidney Pho. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billAmountField: UITextField! @IBOutlet weak var tipPercentages: UISegmentedControl! @IBOutlet weak var funnyText: UILabel! @IBOutlet weak var tipAmountField: UILabel! @IBOutlet weak var slider: UISlider! @IBOutlet weak var totalAmountField: UILabel! @IBOutlet weak var sliderNumber: UILabel! @IBOutlet weak var pricePerPerson: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func calculateTip(_ sender: Any) { let bill = Double(billAmountField.text!) ?? 0 let tipPercentageValues = [0.15, 0.22, 0.27, 0.35] let tipAmount = bill * tipPercentageValues[tipPercentages.selectedSegmentIndex] tipAmountField.text = String(format: "%.2f", tipAmount) totalAmountField.text = String(format: "%.2f", tipAmount+bill) } @IBAction func tipChange(_ sender: Any) { if (tipPercentages.selectedSegmentIndex == 0) { funnyText.text = "I guess I have some change to spare..." } else if (tipPercentages.selectedSegmentIndex == 1) { funnyText.text = "The service was pretty decent, and they gave us some fortune cookies..." } else if (tipPercentages.selectedSegmentIndex == 2) { funnyText.text = "Am I eating at a 5 star restaurant? Amazing service!" } else if (tipPercentages.selectedSegmentIndex == 3) { funnyText.text = "PLEASE TAKE MY MONEY! Out-of-this-world, mind-blowing service." } } @IBAction func editingSliderValue(_ sender: Any) { sliderNumber.text = String(format: "%.0f", slider.value) } @IBAction func changeSlider(_ sender: UISlider) { let bill = Double(billAmountField.text!) ?? 0; slider.value = roundf(slider.value); let tipPercentageValues = [0.15, 0.22, 0.27, 0.35] let tipAmount = bill * tipPercentageValues[tipPercentages.selectedSegmentIndex] let total = bill + tipAmount; let finalPriceDivided = (total)/(Double)(slider.value); if (total == 0.00) { pricePerPerson.text = "0.00"; } else { pricePerPerson.text = String(format: "%.2f", finalPriceDivided); } } }
36.027778
102
0.638782
23100d125fa2c4e932961324e8b38caa25e81c57
615
// // ImageElementBox.swift // CreamsAgent // // Created by Rawlings on 14/11/2017. // Copyright © 2017 Hangzhou Craftsman Network Technology Co.,Ltd. All rights reserved. // import Foundation extension ImageElement { static func rightArrow(_ tintColor: UIColor? = nil) -> ImageElement { let img = ImageElement(ImageElement.Source.local(img: "ic_arrow_mini_right", size: CGSize(width: 6, height: 11), highlightedImg: nil)) img.tintColor = tintColor return img } }
29.285714
89
0.569106
09a7f65463a627be6e6f287ec19d9ab94c33295f
721
// // ViewController.swift // CarthageExample // // Created by Tony Xiao on 6/30/16. // Copyright © 2016 Segment. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. Analytics.track("Carthage Main View Did Load") Analytics.flush() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func fireEvent(_ sender: AnyObject) { Analytics.track("Carthage Button Pressed") Analytics.flush() } }
22.53125
80
0.658807
bb207c23045e0b91517ebd0f720d6dabdcedef8c
2,501
import Foundation import UIKit final class WordsUseCaseImpl { typealias NetworkRepositories = WordMeaningRepository & ImageRepository & WordSearchRepository private let networkRepositories: NetworkRepositories private let player: AudioPlayer init( networkRepositories: NetworkRepositories, player: AudioPlayer ) { self.networkRepositories = networkRepositories self.player = player } } // MARK: - Implement WordsUseCase extension WordsUseCaseImpl: WordsUseCase { func getWordMeanig( id: Int, completion: @escaping (Result<WordMeaning, Error>) -> Void ) -> Cancelable? { networkRepositories.meaning( wordId: id, completion: { [self] result in DispatchQueue.main.async { completion(result.flatMap(getRequiredWordMeaning)) } } ) } func getImage( for type: ImageUrlContainsType, completion: @escaping (Result<UIImage?, Error>) -> Void ) -> Cancelable? { do { let url = try type.getImageUrl() return networkRepositories.loadImage( with: url, completion: { result in DispatchQueue.main.async { completion(result) } } ) } catch { DispatchQueue.main.async { completion(.failure(error)) } return nil } } func findWords( with text: String, completion: @escaping (Result<[Word], Error>) -> Void ) -> Cancelable? { networkRepositories.search( text: text, size: 100, page: 1, completion: { result in DispatchQueue.main.async { completion(result) } } ) } @discardableResult func play(for type: SoundUrlContainsType) throws -> Cancelable { let url = try type.getSoundUrl() return player.play(url: url) } private func getRequiredWordMeaning(_ meanings: [WordMeaning]) -> Result<WordMeaning, Error> { guard let meaning = meanings[safe: 0] else { return .failure(WordsUseCaseImplError.emptyWordMeaning) } return .success(meaning) } private enum WordsUseCaseImplError: Error { case emptyWordMeaning } }
27.788889
98
0.552979
0930ea23b42c031f4785f8b5478145b4c2526bb6
2,046
// // Mastering RxSwift // Copyright (c) KxCoding <[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 UIKit import RxSwift import RxCocoa class ControlPropertyControlEventRxCocoaViewController: UIViewController { let bag = DisposeBag() @IBOutlet weak var colorView: UIView! @IBOutlet weak var redSlider: UISlider! @IBOutlet weak var greenSlider: UISlider! @IBOutlet weak var blueSlider: UISlider! @IBOutlet weak var redComponentLabel: UILabel! @IBOutlet weak var greenComponentLabel: UILabel! @IBOutlet weak var blueComponentLabel: UILabel! @IBOutlet weak var resetButton: UIButton! private func updateComponentLabel() { redComponentLabel.text = "\(Int(redSlider.value))" greenComponentLabel.text = "\(Int(greenSlider.value))" blueComponentLabel.text = "\(Int(blueSlider.value))" } override func viewDidLoad() { super.viewDidLoad() } }
35.894737
81
0.718475
7124e6bd945a53d06b6aa6a57e3b94646c07bc04
497
import Foundation /// print script in console public struct PlantUMLConsolePresenter: PlantUMLPresenting { /// default initializer public init() {} /// present script / diagram to user /// - Parameters: /// - script: in PlantUML notation /// - completionHandler: will to be called when presentation was triggered public func present(script: PlantUMLScript, completionHandler: @escaping () -> Void) { print(script.text) completionHandler() } }
29.235294
90
0.674044
e96f8283f50403d13e7d87fbd3ede4136665e3ea
930
// // CABasicAnimation+Create.swift // Example // // Created by tskim on 17/09/2019. // Copyright © 2019 Assin. All rights reserved. // import UIKit extension CABasicAnimation { static func createAnimationLayer( withDuration duration: TimeInterval, delay: TimeInterval, animationKeyPath: String, timingFunction: CAMediaTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut), fromValue from: Any?, toValue to: Any? ) -> CAAnimation { let animation = CABasicAnimation(keyPath: animationKeyPath) animation.beginTime = CACurrentMediaTime() + delay animation.fromValue = from animation.toValue = to animation.timingFunction = timingFunction animation.isRemovedOnCompletion = false animation.duration = duration animation.fillMode = .forwards return animation } }
31
117
0.683871
3943ba5ce2707b9818c4c473cb94e7b96b195eb3
1,676
// // AppDelegate.swift // CallbackURLKitDemo // // Created by phimage on 03/01/16. // Copyright © 2016 phimage. All rights reserved. // import CallbackURLKit #if os(iOS) import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let manager = Manager.shared manager.callbackURLScheme = Manager.urlSchemes?.first manager[CallbackURLKitDemo.PrintActionString] = CallbackURLKitDemo.PrintAction manager.noMatchActionCallback = { parameters in DispatchQueue.main.async { print("no action match") } } return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return Manager.shared.handleOpen(url: url) } } #elseif os(OSX) import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { let manager = Manager.shared manager.registerToURLEvent() manager.callbackURLScheme = Manager.urlSchemes?.first manager[CallbackURLKitDemo.PrintActionString] = CallbackURLKitDemo.PrintAction manager["success"] = { (parameters, success, failure, cancel) in DispatchQueue.main.async { success(nil) } } manager.noMatchActionCallback = { parameters in DispatchQueue.main.async { print("no action match") } } } } #endif
26.1875
145
0.691527
16d749a4f5a09956d5b9b75d40d56803021e22c8
1,529
// // BoardManager.swift // LifeGameApp // // Created by Yusuke Hosonuma on 2020/08/24. // import SwiftUI import LifeGame import Combine // Important ✅ // このクラスのプロパティ`board`はアニメーション中に頻繁に更新されるため、本当に必要な箇所以外では`GameManager`を経由して処理すること。 final class BoardManager: ObservableObject { static let shared = BoardManager() @Published var board: LifeGameBoard = LifeGameBoard(size: 40) private let setting = SettingEnvironment.shared private var cancellables: [AnyCancellable] = [] init() { setting.$boardSize .dropFirst() .sink { [weak self] size in guard let self = self else { return } self.board.changeBoardSize(to: size) } .store(in: &cancellables) } func setBoard(board: Board<Cell>) { let newSize = (board.size <= self.board.size) ? self.board.size : PresetSizes.first(where: { board.size < $0 }) ?? board.size // fail-safe setting.boardSize = newSize let newBoard = Board(size: newSize, cell: Cell.die).setBoard(toCenter: board) self.board = LifeGameBoard(board: newBoard) } func setLifeGameBoard(board: LifeGameBoard) { self.board = board } func next() { board.next() } func clear() { board.clear() } func generateRandom() { board = LifeGameBoard.random(size: board.size) } func tapCell(x: Int, y: Int) { board.toggle(x: x, y: y) } }
23.523077
86
0.592544
1c328a776ebc4348d32ce5e81629ae25aa210dfa
3,660
// // InformationScreen.swift // TangemSdk // // Created by Andrew Son on 10/30/20. // Copyright © 2020 Tangem AG. All rights reserved. // import UIKit @available (iOS 13.0, *) class InformationScreenViewController: UIViewController { static func instantiateController() -> InformationScreenViewController { let storyboard = UIStoryboard(name: "InformationScreen", bundle: .sdkBundle) let controller: InformationScreenViewController = storyboard.instantiateViewController(identifier: String(describing: self)) controller.modalPresentationStyle = .overFullScreen controller.modalTransitionStyle = .crossDissolve return controller } enum State { case howToScan, spinner, securityDelay, percentProgress, idle } @IBOutlet weak var howToScanView: ScanCardAnimatedView! @IBOutlet weak var indicatorView: CircularIndicatorView! @IBOutlet weak var spinnerView: SpinnerView! @IBOutlet weak var hintLabel: UILabel! @IBOutlet weak var indicatorLabel: UILabel! @IBOutlet weak var indicatorTopConstraint: NSLayoutConstraint! @IBOutlet weak var hintLabelTopConstraint: NSLayoutConstraint! private(set) var state: State = .howToScan override func viewDidLoad() { super.viewDidLoad() setState(.howToScan, animated: false) indicatorLabel.textColor = .tngBlue view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissController))) } override func viewWillAppear(_ animated: Bool) { indicatorView.didAppear() let height = UIScreen.main.bounds.height let coeff: CGFloat = height > 667 ? 6.0 : 14.0 let topOffset = height / coeff indicatorTopConstraint.constant = topOffset hintLabelTopConstraint.constant = topOffset / 3 } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) setState(.idle, animated: false) } func setState(_ state: State, animated: Bool) { guard let howToScan = howToScanView, let indicator = indicatorView, let spinner = spinnerView else { self.state = .idle return } if self.state == state { return } var spinnerTargetAlpha: CGFloat = 0 var howToScanTargetAlpha: CGFloat = 0 var indicatorTargetAlpha: CGFloat = 0 var hintText: String = "" self.state = state switch state { case .howToScan: howToScanTargetAlpha = 1 howToScan.stopAnimation() case .percentProgress, .securityDelay: indicatorTargetAlpha = 1 case .spinner: hintText = Localization.nfcAlertDefault spinnerTargetAlpha = 1 case .idle: spinner.stopAnimation() howToScan.stopAnimation() } state == .spinner ? spinner.startAnimation() : spinner.stopAnimation() hintLabel.text = hintText UIView.animate(withDuration: animated ? 0.3 : 0.0, animations: { howToScan.alpha = howToScanTargetAlpha indicator.alpha = indicatorTargetAlpha spinner.alpha = spinnerTargetAlpha }, completion: { _ in state == .howToScan ? howToScan.startAnimation() : howToScan.stopAnimation() }) } func setupIndicatorTotal(_ value: Float) { indicatorView.totalValue = value } @objc private func dismissController() { dismiss(animated: true, completion: nil) } public func tickSD(remainingValue: Float, message: String, hint: String? = nil) { indicatorView.tickSD(remainingValue: remainingValue) hintLabel.text = hint indicatorLabel.text = message } public func tickPercent(percentValue: Int, message: String, hint: String? = nil) { indicatorView.tickPercent(percentValue: percentValue) indicatorLabel.text = message hintLabel.text = hint indicatorView.currentPercentValue = percentValue } }
29.047619
126
0.736612
1e69c9d79adbcfea71dbe4b21cfb58b6560870c7
2,282
// // ReusableFormattersTests.swift // SwiftyUtils // // Created by Tom Baranes on 25/04/2020. // Copyright © 2020 Tom Baranes. All rights reserved. // import XCTest import SwiftyUtils final class ReusableFormattersTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } } // MARK: - Tests extension UserDefaultsExtensionTests { func testReuseDateFormatter() { let formatter = SUDateFormatter.shared formatter.dateFormat = "YYYY" XCTAssertEqual(formatter.dateFormat, SUDateFormatter.shared.dateFormat) } func testReuseNumberFormatter() { let formatter = SUNumberFormatter.shared formatter.formatWidth = 3 XCTAssertEqual(formatter.formatWidth, SUNumberFormatter.shared.formatWidth) } func testReuseByteFormatter() { let formatter = SUByteCountFormatter.shared formatter.formattingContext = .middleOfSentence XCTAssertEqual(formatter.formattingContext, SUByteCountFormatter.shared.formattingContext) } func testReuseDateComponentsFormatter() { let formatter = SUDateComponentsFormatter.shared formatter.allowedUnits = .day XCTAssertEqual(formatter.allowedUnits, SUDateComponentsFormatter.shared.allowedUnits) } func testReuseDateIntervalFormatter() { let formatter = SUDateIntervalFormatter.shared formatter.dateStyle = .medium XCTAssertEqual(formatter.dateStyle, SUDateIntervalFormatter.shared.dateStyle) } func testReuseEnergyIntervalFormatter() { let formatter = SUEnergyFormatter.shared formatter.isForFoodEnergyUse = true XCTAssertEqual(formatter.isForFoodEnergyUse, SUEnergyFormatter.shared.isForFoodEnergyUse) } func testReuseMassFormatter() { let formatter = SUMassFormatter.shared formatter.isForPersonMassUse = true XCTAssertEqual(formatter.isForPersonMassUse, SUMassFormatter.shared.isForPersonMassUse) } func testReuseLengthFormatter() { let formatter = SULengthFormatter.shared formatter.isForPersonHeightUse = true XCTAssertEqual(formatter.isForPersonHeightUse, SULengthFormatter.shared.isForPersonHeightUse) } }
30.026316
101
0.726117
d9dadbf5107ca8103388a9c29d4c4dbfa5fa1ec8
6,287
// // MYPTextInput.swift // MYPTextInputVC // // Created by wakary redou on 2018/4/20. // Copyright © 2018年 wakary redou. All rights reserved. // import UIKit /** Classes that adopt the MYPTextInput protocol interact with the text input system and thus acquire features such as text processing. All these methods are already implemented in MYPTextInput+IMP.swift */ protocol MYPTextInput: UITextInput { /** - Searches for any matching string prefix at the text input's caret position. - When nothing found, the completion block returns nil values. - This implementation is internally performed on a background thread and forwarded to the main thread once completed. - Parameters: - prefixes: A set of prefixes to search for. - completion: A completion block called whenever the text processing finishes, successfuly or not. Required. - Returns: void */ func look(for prefixes: Set<String>?, completion: @escaping (_ prefix: String?, _ word: String?, _ wordRange: NSRange) -> Void) /** Finds the word close to the caret's position, if any. - Parameters: - range: Returns the range of the found word. - Returns: The found word. */ func word(atCaret range: inout NSRange) -> String? /** Finds the word close to specific range. - Parameters: - range: The range to be used for searching the word. - rangePointer: returns the range of the found word. - Returns: The found word. */ func word(at range: NSRange, rangeInText rangePointer: inout NSRange) -> String? } extension MYPTextInput { func look(for prefixes: Set<String>?, completion: @escaping (_ prefix: String?, _ word: String?, _ wordRange: NSRange) -> Void) { if (prefixes?.count ?? 0) == 0 { return } var wordRange = NSRange() let word = self.word(atCaret: &wordRange) if (word?.count ?? 0) > 0 { for prefix in prefixes! { if word!.hasPrefix(prefix) { completion(prefix, word, wordRange) return } } } completion(nil, nil, NSRange(location: 0, length: 0)) } func word(atCaret range: inout NSRange) -> String? { return word(at: myp_caretRange(), rangeInText: &range) } func word(at range: NSRange, rangeInText rangePointer: inout NSRange) -> String? { let location = Int(range.location) if location == NSNotFound { return nil } let text = myp_text() // Aborts in case minimum requieres are not fufilled if (text?.count ?? 0) == 0 || location < 0 || Int((range.location + range.length)) > (text?.count ?? 0) { rangePointer = NSRange(location: 0, length: 0) return nil } //let leftPortion = (text! as NSString).substring(to: location) let index: String.Index = text!.index(text!.startIndex, offsetBy: location) let leftPortion = String(text![...index]) let leftComponents = leftPortion.components(separatedBy: CharacterSet.whitespacesAndNewlines) let leftWordPart = leftComponents.last //let rightPortion = (text! as NSString).substring(from: location) let rightPortion = String(text![index...]) let rightComponents = rightPortion.components(separatedBy: CharacterSet.whitespacesAndNewlines) let rightPart = rightComponents.first if location > 0 { //let characterBeforeCursor = (text as NSString?)?.substring(with: NSRange(location: location - 1, length: 1)) let beforeIndex = text!.index(text!.startIndex, offsetBy: location - 1) let characterBeforeCursor = String(text![beforeIndex...index]) let whitespaceRange: NSRange? = (characterBeforeCursor as NSString?)?.rangeOfCharacter(from: CharacterSet.whitespaces) if Int(whitespaceRange?.length ?? 0) == 1 { // At the start of a word, just use the word behind the cursor for the current word rangePointer = NSRange(location: location, length: rightPart?.count ?? 0) return rightPart } } // In the middle of a word, so combine the part of the word before the cursor, and after the cursor to get the current word rangePointer = NSRange(location: location - (leftWordPart?.count ?? 0), length: (leftWordPart?.count ?? 0) + (rightPart?.count ?? 0)) var word = leftWordPart ?? "" + (rightPart ?? "") let linebreak = "\n" // If a break is detected, return the last component of the string if Int((word as NSString).range(of: linebreak).location) != NSNotFound { if let aWord = (text as NSString?)?.range(of: word) { rangePointer = aWord } word = word.components(separatedBy: linebreak).last ?? "" } return word } private func myp_text() -> String? { var textRange: UITextRange? = nil let aDocument = self.beginningOfDocument let aDocument1 = self.endOfDocument textRange = self.textRange(from: aDocument, to: aDocument1) if let aRange = textRange { return self.text(in: aRange) } return nil } private func myp_caretRange() -> NSRange { let beginning: UITextPosition? = self.beginningOfDocument let selectedRange: UITextRange? = self.selectedTextRange let selectionStart: UITextPosition? = selectedRange?.start let selectionEnd: UITextPosition? = selectedRange?.end var location: Int? = nil if let aBeginning = beginning, let aStart = selectionStart { location = self.offset(from: aBeginning, to: aStart) } var length: Int? = nil if let aStart = selectionStart, let anEnd = selectionEnd { length = self.offset(from: aStart, to: anEnd) } return NSRange(location: location ?? 0, length: length ?? 0) } }
38.808642
141
0.603149
182eb16aac3146f2f820edaae94b5b559c02d75d
3,507
// // AnimalDetailView.swift // Africa fauna // // Created by Erasmo J.F Da Silva on 14/07/21. // import SwiftUI struct AnimalDetailView: View { // MARK: - PROPERTIES let animal: Animal // MARK: - BODY var body: some View { ScrollView(.vertical, showsIndicators: false) { VStack(alignment: .center, spacing: 20) { // HERO IMAGE Image(animal.image) .resizable() .scaledToFit() // TITLE Text(animal.name.uppercased()) .font(.largeTitle) .fontWeight(.heavy) .multilineTextAlignment(.center) .padding(.vertical, 8) .foregroundColor(.primary) .background( Color.accentColor .frame(height: 6) .offset(y: 24) ) // HEADLINE Text(animal.headline) .font(.headline) .multilineTextAlignment(.leading) .foregroundColor(.accentColor) .padding(.horizontal) // GALLERY Group { HeadingView(headingImage: "photo.on.rectangle.angled", headingText: "Wilderness in pictures") InsetGalleryView(animal: animal) }// Group .padding(.horizontal) // FACTS Group { HeadingView(headingImage: "questionmark.circle", headingText: "Did you know?") InsetFactView(animal: animal) }//: Group .padding(.horizontal) // DESCRIPTION Group { HeadingView(headingImage: "info.circle", headingText: "All about \(animal.name)") Text(animal.description) .multilineTextAlignment(.leading) .layoutPriority(1) }// Group .padding(.horizontal) // MAP Group { HeadingView(headingImage: "map", headingText: "National Parks") InsetMapView() }//: Group .padding(.horizontal) // LINK Group { HeadingView(headingImage: "books.vertical", headingText: "Learn More") ExternalWebLinkView(animal: animal) }// Group .padding(.horizontal) }// VStack .navigationBarTitle("Learn about \(animal.name)", displayMode: .inline) }// Scroll } } // MARK: - PREVIEW struct AnimalDetailView_Previews: PreviewProvider { static let animals: [Animal] = Bundle.main.decode("animals.json") static var previews: some View { NavigationView { AnimalDetailView(animal: animals[0]) }// Navigation .previewDevice("iPhone 11 Pro") } }
30.763158
113
0.415455
1a0facc4a29b12fb13f22accd8ac27cbfc89bb1d
1,233
// // WebView.swift // Thingybase // // Created by Brad Gessler on 12/23/20. // import SwiftUI import UIKit import WebKit struct SimpleWebView: UIViewRepresentable { class Coordinator : NSObject, WKNavigationDelegate { var parent : SimpleWebView init (_ parent: SimpleWebView, _ webView: WKWebView) { self.parent = parent super.init() webView.navigationDelegate = self } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.parent.navigation = navigation } } func makeCoordinator() -> Coordinator { Coordinator(self, webView) } @State var url: String @State var navigation: WKNavigation? let webView = WKWebView() func makeUIView(context: Context) -> WKWebView { return webView } func updateUIView(_ webView: WKWebView, context: Context) { if let reqeustURL = URL(string: url) { let request = URLRequest(url: reqeustURL) webView.load(request) } } } struct WebView_Previews: PreviewProvider { static var previews: some View { SimpleWebView(url: "https://www.thingybase.com/") } }
23.711538
81
0.621249
f463177c3b1051a027123c70a04a02b44b5a8c13
529
// // BaseViewModel.swift // AppStorePlayground // // Created by Key Hui on 6/17/18. // Copyright © 2018 keyfun. All rights reserved. // import RxSwift class BaseViewModel { internal let disposeBag = DisposeBag() var sIsLoading = PublishSubject<Bool>() var sError = PublishSubject<Error>() internal func onIsLoading(value: Bool) { print("isLoading = \(value)") sIsLoading.onNext(value) } internal func onError(error: Error) { sError.onNext(error) } }
19.592593
49
0.62949
20f2b15511468d810527517f71d4a909f3ede59c
777
// // BLPickerView.swift // Pods // // Created by 永田大祐 on 2017/02/08. // // import UIKit class BLPickerView: UIPickerView { let myDatePicker: UIDatePicker = UIDatePicker() override init(frame: CGRect){ super.init(frame: frame) // DatePickerを生成する. let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height myDatePicker.frame = CGRect(x:0, y:screenHeight-200, width:screenWidth, height:200) myDatePicker.backgroundColor = UIColor.white myDatePicker.layer.cornerRadius = 5.0 myDatePicker.layer.shadowOpacity = 0.5 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
23.545455
91
0.638353
119151d07e7f6f795fe2749946703056cc135580
965
import Foundation public class RateAppConfig { public var numberOfDays = 10 public var numberOfLaunches = 15 public var numberOfSecondsFromLaunch = 15.0 public var numberOfLaunchesToShowAfterUserClickLikeApp = 10 public var daysAfterClickLike = 0 public var numberOfLaunchesDefaultsKey = "launchCount" public var dateOfFirstLaunchDefaultsKey = "firstLaunchDate" public var lastVersionPromptedForReviewKey = "lastVersionPromptedForReviewKey" public var rateAppTileDisplayed = "rateAppTileDisplayedKey" public var isUserLikeAppKey = "isUserLikeAppKey" public var clickedNoOnRateAppKey = "clickedNoOnRateAppKey" public var showedRateAppOnCountKey = "showedRateAppOnCountKey" public var shouldCountLaunches: Bool = true public var supportMessageBody = "" public var feedbackSubject = "Feedback about App" public var copyToClipboardText = "%1$@ copied to clipboard"; public init() {} }
38.6
82
0.763731
29e00c3b6e04bd065b844e9c87b53642d5922ffc
11,980
import UIKit import Accounts import Social import EventBox import TwitterAPI class TabSettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: Types struct TableViewConstants { static let tableViewCellIdentifier = "Cell" } struct Constants { static let duration: Double = 0.2 static let delay: TimeInterval = 0 } struct Static { static let instance = TabSettingsViewController() } // MARK: Properties @IBOutlet weak var tableView: UITableView! @IBOutlet weak var leftButton: UIButton! @IBOutlet weak var rightButton: UIButton! let refreshControl = UIRefreshControl() var account: Account? override var nibName: String { return "TabSettingsViewController" } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureEvent() account = AccountSettingsStore.get()?.account() tableView.reloadData() initEditing() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) EventBox.off(self) } // MARK: - Configuration func configureView() { tableView.separatorInset = UIEdgeInsets.zero tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine tableView.delegate = self tableView.dataSource = self tableView.register(UINib(nibName: "TabSettingsCell", bundle: nil), forCellReuseIdentifier: TableViewConstants.tableViewCellIdentifier) tableView.addSubview(refreshControl) refreshControl.addTarget(self, action: #selector(TabSettingsViewController.refresh), for: UIControlEvents.valueChanged) let swipe = UISwipeGestureRecognizer(target: self, action: #selector(TabSettingsViewController.hide)) swipe.numberOfTouchesRequired = 1 swipe.direction = UISwipeGestureRecognizerDirection.right tableView.addGestureRecognizer(swipe) } func configureEvent() { EventBox.onMainThread(self, name: Notification.Name(rawValue: "addTab")) { [weak self] (notification: Notification!) in guard let `self` = self else { return } guard let tab = notification.object as? Tab else { return } guard let userID = self.account?.userID else { return } guard let account = AccountSettingsStore.get()?.find(userID) else { return } let newAccount = Account(account: account, tabs: account.tabs + [tab]) self.account = newAccount self.tableView.insertRows(at: [IndexPath(row: newAccount.tabs.count - 1, section: 0)], with: .automatic) if let settings = AccountSettingsStore.get() { let accounts = settings.accounts.map({ $0.userID == newAccount.userID ? newAccount : $0 }) AccountSettingsStore.save(AccountSettings(current: settings.current, accounts: accounts)) EventBox.post(eventTabChanged) } } EventBox.onMainThread(self, name: Notification.Name(rawValue: "setSavedSearchTab")) { [weak self] (notification: Notification!) in guard let `self` = self else { return } guard var addTabs = notification.object as? [Tab] else { return } guard let account = self.account else { return } var keepTabs = [Tab]() for tab in account.tabs { if tab.type != .Searches { keepTabs.append(tab) } else if let index = addTabs.index(where: { $0.keyword == tab.keyword }) { keepTabs.append(tab) addTabs.remove(at: index) } } let newAccount = Account(account: account, tabs: keepTabs + addTabs) self.account = newAccount self.tableView.reloadData() if let settings = AccountSettingsStore.get() { let accounts = settings.accounts.map({ $0.userID == newAccount.userID ? newAccount : $0 }) AccountSettingsStore.save(AccountSettings(current: settings.current, accounts: accounts)) EventBox.post(eventTabChanged) } } EventBox.onMainThread(self, name: Notification.Name(rawValue: "setListsTab")) { [weak self] (notification: Notification!) in guard let `self` = self else { return } guard var addTabs = notification.object as? [Tab] else { return } guard let account = self.account else { return } var keepTabs = [Tab]() for tab in account.tabs { if tab.type != .Lists { keepTabs.append(tab) } else if let index = addTabs.index(where: { $0.list.id == tab.list.id }) { keepTabs.append(tab) addTabs.remove(at: index) } } let newAccount = Account(account: account, tabs: keepTabs + addTabs) self.account = newAccount self.tableView.reloadData() if let settings = AccountSettingsStore.get() { let accounts = settings.accounts.map({ $0.userID == newAccount.userID ? newAccount : $0 }) AccountSettingsStore.save(AccountSettings(current: settings.current, accounts: accounts)) EventBox.post(eventTabChanged) } } } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return account?.tabs.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // swiftlint:disable:next force_cast let cell = tableView.dequeueReusableCell(withIdentifier: TableViewConstants.tableViewCellIdentifier, for: indexPath) as! TabSettingsCell if let tab = self.account?.tabs[indexPath.row] { switch tab.type { case .HomeTimline: cell.nameLabel.text = "Home" cell.iconLabel.text = "家" case .UserTimline: cell.nameLabel.text = tab.user.name + " / @" + tab.user.screenName cell.iconLabel.text = "人" case .Notifications: cell.nameLabel.text = "Notifications" cell.iconLabel.text = "鐘" case .Mentions: cell.nameLabel.text = "Mentions" cell.iconLabel.text = "@" case .Favorites: cell.nameLabel.text = "Likes" cell.iconLabel.text = "好" case .Searches: cell.nameLabel.text = tab.keyword cell.iconLabel.text = "探" case .Lists: cell.nameLabel.text = tab.list.name cell.iconLabel.text = "欄" case .Messages: cell.nameLabel.text = "Messages" cell.iconLabel.text = "文" } } return cell } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { guard let account = account else { return } if destinationIndexPath.row >= account.tabs.count { return } var tabs = account.tabs tabs.insert(tabs.remove(at: sourceIndexPath.row), at: destinationIndexPath.row) self.account = Account(account: account, tabs: tabs) } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // if let settings = self.settings { // self.settings = AccountSettings(current: indexPath.row, accounts: settings.accounts) // self.tableView.reloadData() // AccountSettingsStore.save(self.settings!) // EventBox.post(eventAccountChanged) // hide() // } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle != .delete { return } guard let account = account else { return } var tabs = account.tabs tabs.remove(at: indexPath.row) self.account = Account(account: account, tabs: tabs) if tabs.count > 0 { tableView.deleteRows(at: [indexPath], with: .automatic) } else { tableView.reloadData() } } // MARK: - Actions @IBAction func close(_ sender: AnyObject) { hide() } @IBAction func left(_ sender: UIButton) { if tableView.isEditing { cancel() } else { if let account = account { AddTabAlert.show(sender, account: account) } } } @IBAction func right(_ sender: UIButton) { if tableView.isEditing { done() } else { edit() } } func hide() { UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { self.view.frame = self.view.frame.offsetBy(dx: self.view.frame.size.width, dy: 0) }, completion: { finished in self.view.removeFromSuperview() }) } func initEditing() { tableView.setEditing(false, animated: false) leftButton.setTitle("Add", for: UIControlState()) rightButton.setTitle("Edit", for: UIControlState()) rightButton.isHidden = account == nil } func cancel() { account = AccountSettingsStore.get()?.account() tableView.reloadData() initEditing() } func edit() { tableView.setEditing(true, animated: true) leftButton.setTitle("Cancel", for: UIControlState()) rightButton.setTitle("Done", for: UIControlState()) } func done() { if let account = account { if let settings = AccountSettingsStore.get() { let accounts = settings.accounts.map({ $0.userID == account.userID ? account : $0 }) _ = AccountSettingsStore.save(AccountSettings(current: settings.current, accounts: accounts)) EventBox.post(eventTabChanged) } } tableView.reloadData() initEditing() } func refresh() { // Twitter.refreshAccounts([]) } class func show() { if let vc = ViewTools.frontViewController() { Static.instance.view.isHidden = true vc.view.addSubview(Static.instance.view) Static.instance.view.frame = CGRect.init(x: vc.view.frame.width, y: 20, width: vc.view.frame.width, height: vc.view.frame.height - 20) Static.instance.view.isHidden = false UIView.animate(withDuration: Constants.duration, delay: Constants.delay, options: .curveEaseOut, animations: { () -> Void in Static.instance.view.frame = CGRect.init(x: 0, y: 20, width: vc.view.frame.size.width, height: vc.view.frame.size.height - 20) }) { (finished) -> Void in } } } }
35.548961
146
0.579883
ef219c5f1fbfb32a3cd7d1b9e618d05da7e58732
1,062
// // ContentView.swift // HotProspects // // Created by Fabio Tiberio on 18/03/22. // import SwiftUI struct ContentView: View { @StateObject var prospects = Prospects() var body: some View { TabView { ProspectsView(filter: .none) .tabItem { Label("Everyone", systemImage: "person.3") } ProspectsView(filter: .contacted) .tabItem { Label("Contacted", systemImage: "questionmark.circle") } ProspectsView(filter: .uncontacted) .tabItem { Label("Uncontacted", systemImage: "questionmark.diamond") } MeView() .tabItem { Label("Me", systemImage: "person.crop.square") } } .environmentObject(prospects) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .environmentObject(Prospects()) } }
25.285714
77
0.511299
e256dff91d50ac91aee1f9bdc71af34e20efdcda
3,310
// // PicCollectionView.swift // LWGWB // // Created by weiguang on 2017/4/13. // Copyright © 2017年 weiguang. All rights reserved. // import UIKit import SDWebImage class PicCollectionView: UICollectionView { // 定义属性 var picURLs : [URL] = [URL]() { didSet { self.reloadData() } } // 系统回调函数 override func awakeFromNib() { super.awakeFromNib() dataSource = self delegate = self } } extension PicCollectionView : UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return picURLs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.获取cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PicCell", for: indexPath) as! PicCollectionViewCell // 2. 给cell设置数据 cell.picURL = picURLs[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 1.获取通知需要传递的参数 let userInfo = [ShowPhotoBrowserIndexKey : indexPath, ShowPhotoBrowserUrlsKey : picURLs] as [String : Any] // 2.发送通知,把object发送出去,成为代理 NotificationCenter.default.post(name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: self, userInfo: userInfo) } } extension PicCollectionView : AnimatorPresentedDelegate { func startRect(indexPath: IndexPath) -> CGRect { // 1.获取cell let cell = self.cellForItem(at: indexPath)! // 2.获取cell的frame let startFrame = self.convert(cell.frame, to: UIApplication.shared.keyWindow) return startFrame } func endRect(indexPath: IndexPath) -> CGRect { // 1.获取该位置的image let picURL = picURLs[indexPath.item] let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picURL.absoluteString)! // 计算结束后的frame let w = SCREEN_WIDTH let h = w / image.size.width * image.size.height var y : CGFloat = 0 if h > SCREEN_HEIGHT { y = 0 } else { y = (SCREEN_HEIGHT - h) * 0.5 } return CGRect(x: 0, y: y, width: w, height: h) } func imageView(indexPath: IndexPath) -> UIImageView { let imageView = UIImageView() // 2.获取该位置的image let picURL = picURLs[indexPath.item] let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picURL.absoluteString)! imageView.image = image imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView } } class PicCollectionViewCell: UICollectionViewCell { // mark: - 定义模型属性 var picURL : URL? { didSet { guard let picURL = picURL else { return } iconView.sd_setImage(with: picURL, placeholderImage: UIImage(named: "empty_picture")) } } // 控件属性 @IBOutlet weak var iconView: UIImageView! }
25.267176
132
0.613293
5051bd8b6ea8502590fe845db04947fdefd3943c
1,179
// // Tip_CalculatorUITests.swift // Tip CalculatorUITests // // Created by James Chen on 2019/2/9. // Copyright © 2019年 James Chen. All rights reserved. // import XCTest class Tip_CalculatorUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.685714
182
0.693808
2f162accd86cfb7b896d90e5fae88bc3335f0821
2,080
// // MapViewController.swift // On the Map // // Created by Daniel Riehs on 3/22/15. // Copyright (c) 2015 Daniel Riehs. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate, ReloadableTab { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() //Sets the map zoom. mapView?.camera.altitude = 50000000; //Sets the center of the map. mapView?.centerCoordinate = CLLocationCoordinate2D(latitude: -3.831239, longitude: -78.183406) //Adding a link to the annotation requires making the mapView a delegate of MKMapView. mapView.delegate = self //Draws the annotations on the map. reloadViewController() } //Opens the mediaURL in Safari when the annotation info box is tapped. func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { UIApplication.shared.openURL(URL(string: view.annotation!.subtitle!!)!) } //Adds a "callout" to the annotation info box so that it can be tapped to access the mediaURL. func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "MapAnnotation") view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView return view } //Required to conform to the ReloadableTab protocol. func reloadViewController() { for result in MapPoints.sharedInstance().mapPoints { //Creates an annotation and coordinate. let annotation = MKPointAnnotation() let location = CLLocationCoordinate2D(latitude: result.latitude, longitude: result.longitude) //Sets the coordinates of the annotation. annotation.coordinate = location //Adds a student name and URL to the annotation. annotation.title = result.fullName annotation.subtitle = result.mediaURL //Adds the annotation to the map. mapView.addAnnotation(annotation) } } }
29.295775
126
0.752885
3ae3de15ba525783430bc0514331622781c3d09e
2,691
// // XcodeRPC.swift // Accord // // Created by evelyn on 2021-12-30. // import Cocoa import Combine import Foundation import OSAKit final class XcodeRPC { static var started = Int(Date().timeIntervalSince1970) * 1000 class func runXcodeScript(_ script: String) -> [String] { let scr = """ tell application "Xcode" \(script) end tell """ // execute the script let script = NSAppleScript(source: scr) let result = script?.executeAndReturnError(nil) guard let desc = result?.literalArray, !desc.isEmpty else { return [] } return desc.map { value -> String in if value.hasSuffix(" — Edited") { return value.dropLast(9).stringLiteral } else { return value } } } class func getActiveFilename() -> String? { let fileNames = runXcodeScript("return name of documents") let windows = runXcodeScript("return name of windows") for name in windows { if fileNames.map({ $0.contains(name.components(separatedBy: " — ").last ?? name) }).contains(true) { return name.components(separatedBy: " — ").last ?? name } } return nil } class func getActiveWorkspace() -> String? { let awd = runXcodeScript("return active workspace document") if awd.count >= 2 { return awd[1] } return nil } class func updatePresence(status: String? = nil, workspace: String, filename: String?) { do { try wss.updatePresence(status: status ?? MediaRemoteWrapper.status ?? "dnd", since: started) { Activity.current! Activity( applicationID: xcodeRPCAppID, flags: 1, name: "Xcode", type: 0, timestamp: started, state: filename != nil ? "Editing \(filename!)" : "Idling.", details: "In \(workspace)" ) } DispatchQueue.main.asyncAfter(deadline: .now() + 5) { let active = Self.getActiveFilename() guard active != filename else { return } Self.updatePresence(status: status, workspace: Self.getActiveWorkspace() ?? workspace, filename: active) } } catch {} } } extension NSAppleEventDescriptor { var literalArray: [String] { var arr: [String?] = [] for i in 1 ... numberOfItems { arr.append(atIndex(i)?.stringValue) } return arr.compactMap(\.self) } }
30.235955
120
0.536603
d9ebab274ca45b219fb98e1657ef0db3eca2e78d
901
// // AppDelegate.swift // Words // // Created by Carlos Cáceres González on 17/03/2021. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } }
29.064516
179
0.741398
e449de3c0af4f9a8fc0830662ebe0d2d320686b5
1,507
// // CustomTabBarItemView.swift // Pods // // Created by Brian Strobach on 4/6/17. // // import Layman import Swiftest import UIKitTheme open class CustomTabBarItemView: BaseButton, ObjectDisplayable { public typealias DisplayableObjectType = UITabBarItem open var tabBarItem: UITabBarItem public required init(tabBarItem: UITabBarItem) { self.tabBarItem = tabBarItem super.init(frame: .zero) self.display(object: tabBarItem) } override open func initProperties() { super.initProperties() buttonLayout = ButtonLayout(layoutType: .centerTitleUnderImage(padding: 4), imageLayoutType: .stretchWidth) } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func display(object: UITabBarItem) { self.tabBarItem = object var images: [ButtonState: UIImage] = [:] images[.normal] =? self.tabBarItem.image images[.selected] =? self.tabBarItem.selectedImage imageMap = images titleMap[.any] = self.tabBarItem.title print(titleMap) } override open func style() { super.style() let tabBarItemStyle: TabBarItemStyle = .defaultStyle styleMap = [.normal: .solid(backgroundColor: .clear, textColor: tabBarItemStyle.normalTextColor), .selected: .solid(backgroundColor: .clear, textColor: tabBarItemStyle.selectedTextColor)] } }
28.980769
115
0.674851
7534049e66957b624b138f980384b87d68c315dd
7,208
// Copyright © 2015 Abhishek Banthia import XCTest extension String { func localizedString() -> String { let bundle = Bundle(for: FloatingWindowTests.self) return NSLocalizedString(self, bundle: bundle, comment: "") } } class FloatingWindowTests: XCTestCase { var app: XCUIApplication! override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.launchArguments.append(CLUITestingLaunchArgument) app.launch() if !app.tables["FloatingTableView"].exists { app.tapMenubarIcon() app.buttons["Pin"].click() } addUIInterruptionMonitor(withDescription: "Reminders Access") { alert -> Bool in let alertButton = alert.buttons["OK"] if alertButton.exists { alertButton.tap() return true } return false } } override func tearDown() { super.tearDown() } func testFloatingWindow() { let cell = app.tables["FloatingTableView"].cells.firstMatch let extraOptionButton = cell.buttons.firstMatch extraOptionButton.click() let remindersCheckbox = app.checkBoxes["ReminderCheckbox"] remindersCheckbox.click() sleep(1) XCTAssertTrue(app.popovers.datePickers.firstMatch.isEnabled) remindersCheckbox.click() sleep(1) XCTAssertFalse(app.popovers.datePickers.firstMatch.isEnabled) } func testAddingANote() { let expectedText = "This is a really important note to me and my friends" if app.buttons["Pin"].exists { app.buttons["Pin"].click() } let cell = app.tables["FloatingTableView"].cells.firstMatch let extraOptionButton = cell.buttons.firstMatch extraOptionButton.click() let notesTextView = app.textViews["NotesTextView"] notesTextView.click() app.textViews["NotesTextView"].click(forDuration: 2, thenDragTo: notesTextView) notesTextView.reset(text: "This is a really important note to me and my friends") let saveButton = app.buttons["SaveButton"] saveButton.click() if let noteLabelInCell = cell.staticTexts["This is a really important note to me and my friends"].value as? String { XCTAssert(noteLabelInCell == expectedText) } } func testSettingAReminder() { if app.buttons["Pin"].exists { app.buttons["Pin"].click() } let cell = app.tables["FloatingTableView"].cells.firstMatch let extraOptionButton = cell.buttons.firstMatch extraOptionButton.click() let remindersCheckbox = app.checkBoxes["ReminderCheckbox"] remindersCheckbox.click() app.buttons["SaveButton"].click() app.tapMenubarIcon() } func testMarkingSlider() { if app.buttons["Pin"].exists { app.buttons["Pin"].click() } let floatingSlider = app.sliders["FloatingSlider"].exists app.buttons["FloatingPreferences"].click() let appearanceTab = app.toolbars.buttons.element(boundBy: 1) appearanceTab.click() let miscTab = app.tabs.element(boundBy: 1) miscTab.click() if floatingSlider { app.radioGroups["FutureSlider"].radioButtons["Hide"].click() } else { app.radioGroups["FutureSlider"].radioButtons["Legacy"].click() } let newFloatingSliderExists = app.sliders["FloatingSlider"].exists XCTAssertNotEqual(floatingSlider, newFloatingSliderExists) } func testHidingMenubarOptions() { if app.buttons["Pin"].exists { app.buttons["Pin"].click() } app.buttons["FloatingPreferences"].click() app.windows["Clocker"].toolbars.buttons["Preferences Tab".localizedString()].click() let menubarDisplayQuery = app.tables.checkBoxes.matching(NSPredicate(format: "value == 1", "")) let menubarDisplayQueryCount = menubarDisplayQuery.count for index in 0 ..< menubarDisplayQueryCount where index < menubarDisplayQueryCount { menubarDisplayQuery.element(boundBy: 0).click() sleep(1) } let appearanceTab = app.toolbars.buttons.element(boundBy: 1) appearanceTab.click() // Select Misc tab let miscTab = app.tabs.element(boundBy: 1) miscTab.click() XCTAssertTrue(app.staticTexts["InformationLabel"].exists) let generalTab = app.toolbars.buttons.element(boundBy: 0) generalTab.click() app.tables["TimezoneTableView"].checkBoxes.firstMatch.click() appearanceTab.click() XCTAssertFalse(app.staticTexts["InformationLabel"].exists) } /// Make sure to ensure supplementary/relative date label is turned on! func testMovingSlider() { if app.buttons["Pin"].exists { app.buttons["Pin"].click() } let floatingSlider = app.sliders["FloatingSlider"].exists if floatingSlider { let tomorrowPredicate = NSPredicate(format: "identifier like %@", "RelativeDate") let tomorrow = app.tables.tableRows.staticTexts.matching(tomorrowPredicate) var previousValues: [String] = [] for index in 0 ..< tomorrow.count { let element = tomorrow.element(boundBy: index) guard let supplementaryText = element.value as? String else { continue } previousValues.append(supplementaryText) } app.sliders["FloatingSlider"].adjust(toNormalizedSliderPosition: 0.7) sleep(1) app.sliders["FloatingSlider"].adjust(toNormalizedSliderPosition: 1) let newTomorrow = app.tables.tableRows.staticTexts.matching(tomorrowPredicate) var newValues: [String] = [] for index in 0 ..< newTomorrow.count { let element = newTomorrow.element(boundBy: index) guard let supplementaryText = element.value as? String else { continue } newValues.append(supplementaryText) } XCTAssertNotEqual(newValues, previousValues) } } } extension XCUIElement { func reset(text: String) { guard let stringValue = value as? String else { XCTFail("Tried to clear and enter text into a non string value") return } if let hasKeyboardFocus = value(forKey: "hasKeyboardFocus") as? Bool, hasKeyboardFocus == false { click() } for _ in 0 ..< stringValue.count { typeKey(XCUIKeyboardKey.delete, modifierFlags: XCUIElement.KeyModifierFlags()) } guard let newStringValue = value as? String else { XCTFail("Tried to clear and enter text into a non string value") return } for _ in 0 ..< newStringValue.count { typeKey(XCUIKeyboardKey.forwardDelete, modifierFlags: XCUIElement.KeyModifierFlags()) } typeText(text) } }
31.33913
124
0.617786
09ed848adfd7635cc58ee42da57629411a1c90fd
120
//: Playground - noun: a place where people can play import Cocoa class A<T> { } class Ab { } A<Ab>()
8.571429
52
0.55
f4a5335b1182df7f4d3aa4ca9173ca52f60c7770
2,097
// // This source file is part of the Apodini open source project // // SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]> // // SPDX-License-Identifier: MIT // import Foundation @testable import ProtobufferCoding // swiftlint:disable discouraged_optional_boolean struct ProtoTestMessage<T: Codable>: Codable { var content: T enum CodingKeys: Int, CodingKey { case content = 1 } } struct ProtoComplexTestMessage: Codable { var numberInt32: Int32 var numberUint32: UInt32 var numberBool: Bool var enumValue: Int32 var numberDouble: Double var content: String var byteData: Data var nestedMessage: ProtoTestMessage<String> var numberFloat: Float enum CodingKeys: String, ProtobufferCodingKey { case numberInt32 case numberUint32 case numberBool case enumValue case numberDouble case content case byteData case nestedMessage case numberFloat var protoRawValue: Int { switch self { case CodingKeys.numberInt32: return 1 case CodingKeys.numberUint32: return 2 case CodingKeys.numberBool: return 4 case CodingKeys.enumValue: return 5 case CodingKeys.numberDouble: return 8 case CodingKeys.content: return 9 case CodingKeys.byteData: return 10 case CodingKeys.nestedMessage: return 11 case CodingKeys.numberFloat: return 14 } } } } struct ProtoComplexTestMessageWithOptionals: Codable { var numberInt32: Int32? var numberUint32: UInt32? var numberBool: Bool? var enumValue: Int32? var numberDouble: Double? var content: String? var byteData: Data? var nestedMessage: ProtoTestMessage<String>? var numberFloat: Float? }
26.884615
135
0.617072
d746b3d71f0919148b857a25c5c2a513fb18d975
505
// // ViewController.swift // CampUtils // // Created by CampUtils on 01/20/2022. // Copyright (c) 2022 CampUtils. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.2
80
0.671287
165ea382b7869a5871a0f0b5b59f9bd2795a97ea
771
// // Easy965.swift // SwiftLeetcode // // Created by roosky on 12/29/18. // Copyright © 2018 K W. All rights reserved. // /** 965. Univalued Binary Tree https://leetcode.com/problems/univalued-binary-tree time: O(N) space: O(H) heigth of the tree **/ import UIKit class Easy965: NSObject { func isUnivalTree(_ root: TreeNode?) -> Bool { if root == nil { return true } return isUnivalTree(root!, root!.val) } func isUnivalTree(_ root: TreeNode?, _ value: Int) -> Bool { if root == nil { return true } if (root?.val != value) { return false } return isUnivalTree(root?.left, value) && isUnivalTree(root?.right, value) } }
20.837838
82
0.555123
3343be521fe8ae419964d03aa424599f0d2e535c
6,462
// // ProductsInfoControllerTests.swift // SwiftyStoreKit // // Copyright (c) 2017 Andrea Bizzotto ([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 XCTest import Foundation @testable import SwiftyStoreKit class TestInAppProductRequest: InAppProductRequest { var hasCompleted: Bool var cachedResults: RetrieveResults? private let productIds: Set<String> private let callback: InAppProductRequestCallback init(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) { self.productIds = productIds self.callback = callback self.hasCompleted = false } func start() { } func cancel() { } func fireCallback() { callback(RetrieveResults(retrievedProducts: [], invalidProductIDs: [], error: nil)) } } class TestInAppProductRequestBuilder: InAppProductRequestBuilder { var requests: [ TestInAppProductRequest ] = [] func request(productIds: Set<String>, callback: @escaping InAppProductRequestCallback) -> InAppProductRequest { let request = TestInAppProductRequest(productIds: productIds, callback: callback) requests.append(request) return request } func fireCallbacks() { requests.forEach { $0.fireCallback() } requests = [] } } class ProductsInfoControllerTests: XCTestCase { let sampleProductIdentifiers: Set<String> = ["com.iap.purchase1"] // Set of in app purchases to ask in different threads let testProducts: Set<String> = ["com.iap.purchase01", "com.iap.purchase02", "com.iap.purchase03", "com.iap.purchase04", "com.iap.purchase05", "com.iap.purchase06", "com.iap.purchase07", "com.iap.purchase08", "com.iap.purchase09", "com.iap.purchase10"] func testRetrieveProductsInfo_when_calledOnce_then_completionCalledOnce() { let requestBuilder = TestInAppProductRequestBuilder() let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder) var completionCount = 0 productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in completionCount += 1 } requestBuilder.fireCallbacks() XCTAssertEqual(completionCount, 1) } func testRetrieveProductsInfo_when_calledTwiceConcurrently_then_eachCompletionCalledOnce() { let requestBuilder = TestInAppProductRequestBuilder() let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder) var completionCount = 0 productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in completionCount += 1 } productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in completionCount += 1 } requestBuilder.fireCallbacks() XCTAssertEqual(completionCount, 2) } func testRetrieveProductsInfo_when_calledTwiceNotConcurrently_then_eachCompletionCalledOnce() { let requestBuilder = TestInAppProductRequestBuilder() let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder) var completionCount = 0 productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in completionCount += 1 } requestBuilder.fireCallbacks() XCTAssertEqual(completionCount, 1) productInfoController.retrieveProductsInfo(sampleProductIdentifiers) { _ in completionCount += 1 } requestBuilder.fireCallbacks() XCTAssertEqual(completionCount, 2) } func testRetrieveProductsInfo_when_calledConcurrentlyInDifferentThreads_then_eachcompletionCalledOnce_noCrashes() { let requestBuilder = TestInAppProductRequestBuilder() let productInfoController = ProductsInfoController(inAppProductRequestBuilder: requestBuilder) var completionCallbackCount = 0 // Create the expectation not to let the test finishes before the other threads complete let expectation = XCTestExpectation(description: "Expect downloads of product informations") // Create the dispatch group to let the test verifies the assert only when // everything else finishes. let group = DispatchGroup() // Dispatch a request for every product in a different thread for product in testProducts { DispatchQueue.global().async { group.enter() productInfoController.retrieveProductsInfo([product]) { _ in completionCallbackCount += 1 group.leave() } } } DispatchQueue.global().asyncAfter(deadline: .now()+0.1) { requestBuilder.fireCallbacks() } // Fullfil the expectation when every thread finishes group.notify(queue: DispatchQueue.global()) { XCTAssertEqual(completionCallbackCount, self.testProducts.count) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } }
37.352601
117
0.673321
26dd501cbb330aee30b1f73a0eee69b632fa27a0
833
// // User.swift // JSONPlaceholderapp // // Created by Iván Díaz Molina on 05/06/2020. // Copyright © 2020 Iván Díaz Molina. All rights reserved. // import Foundation struct User: Codable { var id: Int? var name: String? var username: String? var email: String? var website: String? var avatar: String? init() { id = -1 name = "" username = "" email = "" website = "" avatar = "" } init(_ data: Data) throws { self = try JSONDecoder().decode(User.self, from: data) } init(_ json: String, encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data) } }
21.358974
73
0.553421
5d33d8943c4db313d3f17d8602a5f725cf04c2f1
204
// // UInt16+.swift // DeviceKit // // Created by EyreFree on 2020/5/28. // import Foundation public extension UInt16 { var nsNumber: NSNumber { return NSNumber(value: self) } }
12.75
37
0.612745
649d54f4dc3352a79b4694069af534b673d9a8c2
11,337
// // TicTacChecView.swift // Neural Networks // // Created by Guillermo Cique on 23/03/2019. // import UIKit public protocol TicTacChecViewDelegate: class { func currentPlayerForTicTacChecView(_ ticTacChecView: TicTacChecView) -> Player func lastMoveForTicTacChecView(_ ticTacChecView: TicTacChecView) -> (from: Coordinate?, to: Coordinate?) func ticTacChecView(_ ticTacChecView: TicTacChecView, stateForSquareAt coordinate: Int) -> SquareState func ticTacChecView(_ ticTacChecView: TicTacChecView, pawnDirectionForPlayer player: Player) -> Direction? func ticTacChecView(_ ticTacChecView: TicTacChecView, pocketPiecesForPlayer player: Player) -> Set<Piece> func ticTacChecView(_ ticTacChecView: TicTacChecView, legalMovesForPiece piece: Piece) -> [Coordinate] func ticTacChecView(_ ticTacChecView: TicTacChecView, didMovePiece piece: Piece, toCoordinate coordinate: Int) } public class TicTacChecView: GameView { public weak var delegate: TicTacChecViewDelegate! public var viewPlayer: Player = .white { didSet { reloadData() } } var selectedPiece: Piece? { didSet { reloadData() } } var originalView: SquareView? { didSet { if let oldValue = oldValue { oldValue.isOn = true draggingView?.removeFromSuperview() draggingView = nil } if let view = originalView { view.isOn = false let draggingView = SquareView(frame: view.frame) draggingView.path = selectedPiece?.path draggingView.tintColor = view.tintColor self.draggingView = draggingView addSubview(draggingView) } } } var draggingView: SquareView? let pocketView: UIStackView = { let pocketView = UIStackView() pocketView.translatesAutoresizingMaskIntoConstraints = false pocketView.axis = .horizontal pocketView.distribution = .fillEqually pocketView.tintColor = Constants.playerColor return pocketView }() let opponentPocketView: UIStackView = { let pocketView = UIStackView() pocketView.translatesAutoresizingMaskIntoConstraints = false pocketView.axis = .horizontal pocketView.distribution = .fillEqually pocketView.tintColor = Constants.opponentColor return pocketView }() let hintsView: HintsBoardView public init(frame: CGRect = .zero) { self.hintsView = HintsBoardView(rows: 4, columns: 4) super.init(rows: 4, columns: 4, frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func didLoad() { addSubview(hintsView) super.didLoad() for piece in Piece.allCases { let squareView = SquareView() squareView.path = piece.path pocketView.addArrangedSubview(squareView) let opponentSquareView = SquareView() if piece == .pawn { let path = piece.path path.apply(CGAffineTransform(rotationAngle: .pi)) path.apply(CGAffineTransform(translationX: 100, y: 100)) opponentSquareView.path = path } else { opponentSquareView.path = piece.path } opponentPocketView.addArrangedSubview(opponentSquareView) } addSubview(pocketView) addSubview(opponentPocketView) boardView.translatesAutoresizingMaskIntoConstraints = false hintsView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ hintsView.topAnchor.constraint(equalTo: boardView.topAnchor), hintsView.leftAnchor.constraint(equalTo: boardView.leftAnchor), hintsView.rightAnchor.constraint(equalTo: boardView.rightAnchor), hintsView.bottomAnchor.constraint(equalTo: boardView.bottomAnchor), boardView.widthAnchor.constraint(equalTo: boardView.heightAnchor), opponentPocketView.topAnchor.constraint(equalTo: topAnchor), opponentPocketView.leftAnchor.constraint(equalTo: leftAnchor), opponentPocketView.rightAnchor.constraint(equalTo: rightAnchor), boardView.topAnchor.constraint(equalTo: opponentPocketView.bottomAnchor, constant: 16), boardView.leftAnchor.constraint(equalTo: leftAnchor), boardView.rightAnchor.constraint(equalTo: rightAnchor), pocketView.topAnchor.constraint(equalTo: boardView.bottomAnchor, constant: 16), pocketView.leftAnchor.constraint(equalTo: leftAnchor), pocketView.rightAnchor.constraint(equalTo: rightAnchor), pocketView.bottomAnchor.constraint(equalTo: bottomAnchor), pocketView.heightAnchor.constraint(equalTo: boardView.heightAnchor, multiplier: 0.25), opponentPocketView.heightAnchor.constraint(equalTo: pocketView.heightAnchor) ]) } override public func layoutSubviews() { super.layoutSubviews() reloadData() } public func reloadData() { var hints: [Coordinate: HintsBoardView.HintType] = [:] let lastMove = delegate.lastMoveForTicTacChecView(self) if let fromCoordinate = lastMove.from { let fixedcoordinate = viewPlayer == .white ? fromCoordinate : fromCoordinate.inverse() hints[fixedcoordinate] = .lastMove } if let toCoordinate = lastMove.to { let fixedcoordinate = viewPlayer == .white ? toCoordinate : toCoordinate.inverse() hints[fixedcoordinate] = .lastMove } for (index, squareView) in squareViews.enumerated() { let fixedIndex = viewPlayer == .white ? index : index.inverse() switch delegate.ticTacChecView(self, stateForSquareAt: fixedIndex) { case .empty: squareView.path = nil squareView.tintColor = nil continue case .occupied(let player, let piece): let color = player == viewPlayer ? Constants.playerColor : Constants.opponentColor let path = piece.path if piece == .pawn { let direction = delegate.ticTacChecView(self, pawnDirectionForPlayer: player) if direction == .down && viewPlayer == .white || direction == .up && viewPlayer == .black { path.apply(CGAffineTransform(rotationAngle: .pi)) path.apply(CGAffineTransform(translationX: 100, y: 100)) } } squareView.path = path squareView.tintColor = color if player == viewPlayer && piece == selectedPiece { hints[index] = .selected } } } if let piece = selectedPiece { let legalMoves = delegate.ticTacChecView(self, legalMovesForPiece: piece) for index in legalMoves { let fixedIndex = viewPlayer == .white ? index : index.inverse() if delegate.ticTacChecView(self, stateForSquareAt: index) == .empty { hints[fixedIndex] = .legalMove } else { hints[fixedIndex] = .legalTakingMove } } } hintsView.hints = hints let opponent: Player = viewPlayer == .white ? .black : .white let pocketPieces = delegate.ticTacChecView(self, pocketPiecesForPlayer: viewPlayer) let opponentPocketPieces = delegate.ticTacChecView(self, pocketPiecesForPlayer: opponent) for piece in Piece.allCases { if let squareView = pocketView.subviews[piece.rawValue] as? SquareView, squareView != originalView { let onPocket = pocketPieces.contains(piece) squareView.isOn = onPocket squareView.isSelected = onPocket && piece == selectedPiece } if let squareView = opponentPocketView.subviews[piece.rawValue] as? SquareView { squareView.isOn = opponentPocketPieces.contains(piece) } } } override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let position = touch.location(in: self) guard let index = squareViews.enumerated().first(where: { $1.frame.contains(position) })?.offset else { let pocketPosition = touch.location(in: pocketView) if let index = pocketView.subviews.enumerated().first(where: { $1.frame.contains(pocketPosition) })?.offset, let squareView = pocketView.subviews[index] as? SquareView, squareView.isOn { selectedPiece = Piece(rawValue: index)! originalView = squareView draggingView?.center = position } else { selectedPiece = nil } return } let fixedIndex = viewPlayer == .white ? index : index.inverse() switch delegate.ticTacChecView(self, stateForSquareAt: fixedIndex) { case .occupied(let player, let piece) where player == delegate.currentPlayerForTicTacChecView(self): selectedPiece = piece default: return } originalView = squareViews[index] if let draggingView = draggingView { draggingView.center = position updateShadowOffset(squareView: draggingView) } } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first, let draggingView = draggingView else { return } let position = touch.location(in: self) draggingView.center = position updateShadowOffset(squareView: draggingView) } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { originalView = nil guard let touch = touches.first else { return } let position = touch.location(in: self) guard let index = squareViews.enumerated().first(where: { $1.frame.contains(position) })?.offset else { return } guard let piece = selectedPiece else { return } let fixedIndex = viewPlayer == .white ? index : index.inverse() switch delegate.ticTacChecView(self, stateForSquareAt: fixedIndex) { case .occupied(let player, let piece) where player == delegate.currentPlayerForTicTacChecView(self): if piece != selectedPiece { selectedPiece = nil } default: selectedPiece = nil delegate.ticTacChecView(self, didMovePiece: piece, toCoordinate: fixedIndex) } } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { originalView = nil selectedPiece = nil } }
42.781132
120
0.615595
dd2cee7185601f4c96e5d1986f23cc0f0dd606e3
1,473
// // Mastering iOS // Copyright (c) KxCoding <[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 UIKit class FirstTabViewController: UIViewController { @IBAction func selectSecondTab(_ sender: Any) { } @IBAction func selectThirdTab(_ sender: Any) { } override func viewDidLoad() { super.viewDidLoad() } }
32.021739
81
0.704005
f839b629840b46583a189d9242c231c7fe16f014
788
// // MyCollectionHeaderReusableView.swift // BeautifulPhotos // // Created by ldjhust on 15/9/9. // Copyright (c) 2015年 example. All rights reserved. // import UIKit class MyCollectionHeaderReusableView: UICollectionReusableView { var backgroundImageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) if backgroundImageView == nil { self.backgroundImageView = UIImageView() self.backgroundImageView.center = CGPoint(x: bounds.width/2, y: bounds.height/2) self.backgroundImageView.bounds.size = bounds.size self.addSubview(self.backgroundImageView) } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
26.266667
92
0.648477
08523d9077f8abe18ea44512f44632820e27e5bc
957
// // LandmarkRow.swift // LandmarksApp // // Created by Anatoly Gurbanov on 03.09.2021. // import SwiftUI struct LandmarkRow: View { var landmark: Landmark var body: some View { HStack { landmark.image .resizable() .frame(width: 50, height: 50) Text(landmark.name) Spacer() if landmark.isFavorite { Image(systemName: "star.fill") .foregroundColor(.yellow) } else { Image(systemName: "star") .foregroundColor(.yellow) } } } } struct LandmarkRow_Previews: PreviewProvider { static var landmarks = ModelData().landmarks static var previews: some View { Group { LandmarkRow(landmark: landmarks[0]) LandmarkRow(landmark: landmarks[1]) } .previewLayout(.fixed(width: 300, height: 70)) } }
22.255814
54
0.529781
edcf3ace9d0eacd5eda4ff061608123361502512
1,440
// // PhotosViewModel.swift // Photos // // Created by techthings on 10/5/16. // Copyright © 2016 Ezequiel França. All rights reserved. // import Foundation import RxSwift import RxCocoa import ObjectMapper import Alamofire struct PhotosViewModel { var title: String? var url: String? var internalIdentifier: Int? var thumbnailUrl: String? var albumId: Int? var model: Photos! { didSet{ self.title = model.title self.url = model.url self.internalIdentifier = model.internalIdentifier self.thumbnailUrl = model.thumbnailUrl self.albumId = model.albumId } } init(photo: Photos) { setPhoto(photo) } mutating func setPhoto(photo:Photos) { self.model = photo } } struct ViewModelManager { var manager:PhotoApi = PhotoApi() let load = Variable<Bool>(false) let disposeBag = DisposeBag() lazy var data: Driver<[Photos]> = { return self.load.asObservable() .throttle(0.3, scheduler: MainScheduler.instance) .distinctUntilChanged() .flatMapLatest {_ in self.getPhotos() } .asDriver(onErrorJustReturn: []) }() mutating func getPhotos() -> Observable<[Photos]> { return (manager.download()) } //load: Verdadeiro ou Falso para novo download }
22.153846
62
0.595139
db17fbc1c57bf4feb3c75c31a7e22a623b2f1199
59,632
// // FileProvider.swift // FileProvider // // Created by Amir Abbas Mousavian. // Copyright © 2016 Mousavian. Distributed under MIT license. // import Foundation #if os(iOS) || os(tvOS) import UIKit import ImageIO public typealias ImageClass = UIImage #elseif os(macOS) import Cocoa import ImageIO public typealias ImageClass = NSImage #endif /// Completion handler type with an error argument public typealias SimpleCompletionHandler = ((_ error: Error?) -> Void)? /// This protocol defines FileProvider neccesary functions and properties to connect and get contents list public protocol FileProviderBasic: class, NSSecureCoding, CustomDebugStringConvertible { /// An string to identify type of provider. static var type: String { get } /// An string to identify type of provider. var type: String { get } /// The url of which paths should resolve against. var baseURL: URL? { get } /** Dispatch queue usually used in query methods. Set it to a new object to switch between cuncurrent and serial queues. - **Default:** Cuncurrent `DispatchQueue` object. */ var dispatch_queue: DispatchQueue { get set } /// Operation queue ususlly used in file operation methods. /// use `maximumOperationTasks` property of provider to manage operation queue. var operation_queue: OperationQueue { get set } /// Delegate to update UI after finishing file operations. var delegate: FileProviderDelegate? { get set } /** login credential for provider. Should be set in `init` method. **Example initialization:** ```` provider.credential = URLCredential(user: "user", password: "password", persistence: .forSeession) ```` - Note: In OAuth based providers like `DropboxFileProvider` and `OneDriveFileProvider`, password is Token. use [OAuthSwift](https://github.com/OAuthSwift/OAuthSwift) library to fetch clientId and Token of user. */ var credential: URLCredential? { get set } /** Returns an Array of `FileObject`s identifying the the directory entries via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty array. - Parameters: - path: path to target directory. If empty, root will be iterated. - completionHandler: a closure with result of directory entries or error. - contents: An array of `FileObject` identifying the the directory entries. - error: Error returned by system. */ func contentsOfDirectory(path: String, completionHandler: @escaping (_ contents: [FileObject], _ error: Error?) -> Void) /** Returns a `FileObject` containing the attributes of the item (file, directory, symlink, etc.) at the path in question via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty `FileObject`. - Parameters: - path: path to target directory. If empty, attributes of root will be returned. - completionHandler: a closure with result of directory entries or error. - attributes: A `FileObject` containing the attributes of the item. - error: Error returned by system. */ func attributesOfItem(path: String, completionHandler: @escaping (_ attributes: FileObject?, _ error: Error?) -> Void) /// Returns volume/provider information asynchronously. /// - Parameter volumeInfo: Information of filesystem/Provider returned by system/server. func storageProperties(completionHandler: @escaping (_ volumeInfo: VolumeObject?) -> Void) /** Search files inside directory using query asynchronously. - Note: Query string is limited to file name, to search based on other file attributes, use NSPredicate version. - Parameters: - path: location of directory to start search - recursive: Searching subdirectories of path - query: Simple string that file name begins with to be search, case-insensitive. - foundItemHandler: Closure which is called when a file is found - completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured. - files: all files meat the `query` criteria. - error: `Error` returned by server if occured. */ @discardableResult func searchFiles(path: String, recursive: Bool, query: String, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? /** Search files inside directory using query asynchronously. Sample predicates: ``` NSPredicate(format: "(name CONTAINS[c] 'hello') && (fileSize >= 10000)") NSPredicate(format: "(modifiedDate >= %@)", Date()) NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder") ``` - Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate. - Important: A file name criteria should be provided for Dropbox. - Parameters: - path: location of directory to start search - recursive: Searching subdirectories of path - query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`. - foundItemHandler: Closure which is called when a file is found - completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured. - files: all files meat the `query` criteria. - error: `Error` returned by server if occured. - Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items. */ @discardableResult func searchFiles(path: String, recursive: Bool, query: NSPredicate, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? /** Returns an independent url to access the file. Some providers like `Dropbox` due to their nature. don't return an absolute url to be used to access file directly. - Parameter path: Relative path of file or directory. - Returns: An url, can be used to access to file directly. */ func url(of path: String) -> URL /// Returns the relative path of url, without percent encoding. Even if url is absolute or /// retrieved from another provider, it will try to resolve the url against `baseURL` of /// current provider. It's highly recomended to use this method for displaying purposes. /// /// - Parameter url: Absolute url to file or directory. /// - Returns: A `String` contains relative path of url against base url. func relativePathOf(url: URL) -> String /// Checks the connection to server or permission on local /// /// - Note: To prevent race condition, use this method wisely and avoid it as far possible. /// /// - Parameter success: indicated server is reachable or not. /// - Parameter error: `Error` returned by server if occured. func isReachable(completionHandler: @escaping(_ success: Bool, _ error: Error?) -> Void) } extension FileProviderBasic { public func searchFiles(path: String, recursive: Bool, query: String, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? { let predicate = NSPredicate(format: "name BEGINSWITH[c] %@", query) return self.searchFiles(path: path, recursive: recursive, query: predicate, foundItemHandler: foundItemHandler, completionHandler: completionHandler) } /** Search files inside directory using query asynchronously. Sample predicates: ``` NSPredicate(format: "(name CONTAINS[c] 'hello') && (filesize >= 10000)") NSPredicate(format: "(modifiedDate >= %@)", Date()) NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder") ``` - Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate. - Important: A file name criteria should be provided for Dropbox. - Parameters: - path: location of directory to start search - recursive: Searching subdirectories of path - query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`. - completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured. - files: all files meat the `query` criteria. - error: `Error` returned by server if occured. - Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items. */ func searchFiles(path: String, recursive: Bool, query: NSPredicate, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? { return searchFiles(path: path, recursive: recursive, query: query, foundItemHandler: nil, completionHandler: completionHandler) } /// The maximum number of queued operations that can execute at the same time. /// /// The default value of this property is `OperationQueue.defaultMaxConcurrentOperationCount`. public var maximumOperationTasks: Int { get { return operation_queue.maxConcurrentOperationCount } set { operation_queue.maxConcurrentOperationCount = newValue } } public var debugDescription: String { let typeDesc = "\(Self.type) provider" let urlDesc = self.baseURL.map({ " - " + $0.absoluteString }) ?? "" let credentialDesc = self.credential?.user.map({ " - " + $0.debugDescription }) ?? "" return typeDesc + urlDesc + credentialDesc } } /// Checking equality of two file provider, regardless of current path queues and delegates. public func ==(lhs: FileProviderBasic, rhs: FileProviderBasic) -> Bool { if lhs === rhs { return true } if type(of: lhs) != type(of: rhs) { return false } return lhs.type == rhs.type && lhs.baseURL == rhs.baseURL && lhs.credential == rhs.credential } /// Cancels all active underlying tasks when deallocating remote providers public var fileProviderCancelTasksOnInvalidating = true /// Extending `FileProviderBasic` for web-based file providers public protocol FileProviderBasicRemote: FileProviderBasic { /// Underlying URLSession instance used for HTTP/S requests var session: URLSession { get } /** A `URLCache` to cache downloaded files and contents. - Note: It has no effect unless setting `useCache` property to `true`. - Warning: FileProvider doesn't manage/free `URLCache` object in a memory pressure scenario. It's upon you to clear cache memory when receiving `didReceiveMemoryWarning` or via observing `.UIApplicationDidReceiveMemoryWarning` notification. To clear memory usage use this code: ``` provider.cache?.removeAllCachedResponses() ``` */ var cache: URLCache? { get } /// Determine to use `cache` property to cache downloaded file objects. Doesn't have effect on query type methods. var useCache: Bool { get set } /// Validating cached data using E-Tag or Revision identifier if possible. var validatingCache: Bool { get set } } internal extension FileProviderBasicRemote { func returnCachedDate(with request: URLRequest, validatingCache: Bool, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> Bool { guard let cache = self.cache else { return false } if let response = cache.cachedResponse(for: request) { var validatedCache = !validatingCache let lastModifiedDate = (response.response as? HTTPURLResponse)?.allHeaderFields["Last-Modified"] as? String let eTag = (response.response as? HTTPURLResponse)?.allHeaderFields["ETag"] as? String if lastModifiedDate == nil && eTag == nil, validatingCache { var validateRequest = request validateRequest.httpMethod = "HEAD" let group = DispatchGroup() group.enter() self.session.dataTask(with: validateRequest, completionHandler: { (_, response, e) in if let httpResponse = response as? HTTPURLResponse { let currentETag = httpResponse.allHeaderFields["ETag"] as? String let currentLastModifiedDate = httpResponse.allHeaderFields["ETag"] as? String ?? "nonvalidetag" validatedCache = (eTag != nil && currentETag == eTag) || (lastModifiedDate != nil && currentLastModifiedDate == lastModifiedDate) } group.leave() }).resume() _ = group.wait(timeout: .now() + self.session.configuration.timeoutIntervalForRequest) } if validatedCache { completionHandler(response.data, response.response, nil) return true } } return false } func runDataTask(with request: URLRequest, operation: FileOperationType? = nil, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) { let useCache = self.useCache let validatingCache = self.validatingCache dispatch_queue.async { if useCache { if self.returnCachedDate(with: request, validatingCache: validatingCache, completionHandler: completionHandler) { return } } let task = self.session.dataTask(with: request, completionHandler: completionHandler) task.taskDescription = operation?.json task.resume() } } } /// Defines methods for common file operaions including create, copy/move and delete public protocol FileProviderOperations: FileProviderBasic { /// Delgate for managing operations involving the copying, moving, linking, or removal of files and directories. When you use an FileManager object to initiate a copy, move, link, or remove operation, the file provider asks its delegate whether the operation should begin at all and whether it should proceed when an error occurs. var fileOperationDelegate : FileOperationDelegate? { get set } /** Creates a new directory at the specified path asynchronously. This will create any necessary intermediate directories. - Parameters: - folder: Directory name. - at: Parent path of new directory. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func create(folder: String, at: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Moves a file or directory from `path` to designated path asynchronously. When you want move a file, destination path should also consists of file name. Either a new name or the old one. If file is already exist, an error will be returned via completionHandler. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func moveItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Moves a file or directory from `path` to designated path asynchronously. When you want move a file, destination path should also consists of file name. Either a new name or the old one. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - overwrite: Destination file should be overwritten if file is already exists. **Default** is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func moveItem(path: String, to: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Copies a file or directory from `path` to designated path asynchronously. When want copy a file, destination path should also consists of file name. Either a new name or the old one. If file is already exist, an error will be returned via completionHandler. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func copyItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Copies a file or directory from `path` to designated path asynchronously. When want copy a file, destination path should also consists of file name. Either a new name or the old one. - Parameters: - path: original file or directory path. - to: destination path of file or directory, including file/directory name. - overwrite: Destination file should be overwritten if file is already exists. **Default** is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func copyItem(path: String, to: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Removes the file or directory at the specified path. - Parameters: - path: file or directory path. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func removeItem(path: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Uploads a file from local file url to designated path asynchronously. Method will fail if source is not a local url with `file://` scheme. - Note: It's safe to assume that this method only works on individual files and **won't** copy folders recursively. - Parameters: - localFile: a file url to file. - to: destination path of file, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. */ @discardableResult func copyItem(localFile: URL, to: String, completionHandler: SimpleCompletionHandler) -> Progress? /** Uploads a file from local file url to designated path asynchronously. Method will fail if source is not a local url with `file://` scheme. - Note: It's safe to assume that this method only works on individual files and **won't** copy folders recursively. - Parameters: - localFile: a file url to file. - to: destination path of file, including file/directory name. - overwrite: Destination file should be overwritten if file is already exists. **Default** is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. */ @discardableResult func copyItem(localFile: URL, to: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Download a file from `path` to designated local file url asynchronously. Method will fail if destination is not a local url with `file://` scheme. - Note: It's safe to assume that this method only works on individual files and **won't** copy folders recursively. - Parameters: - path: original file or directory path. - toLocalURL: destination local url of file, including file/directory name. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func copyItem(path: String, toLocalURL: URL, completionHandler: SimpleCompletionHandler) -> Progress? } extension FileProviderOperations { @discardableResult public func moveItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? { return self.moveItem(path: path, to: to, overwrite: false, completionHandler: completionHandler) } @discardableResult public func copyItem(localFile: URL, to: String, completionHandler: SimpleCompletionHandler) -> Progress? { return self.copyItem(localFile: localFile, to: to, overwrite: false, completionHandler: completionHandler) } @discardableResult public func copyItem(path: String, to: String, completionHandler: SimpleCompletionHandler) -> Progress? { return self.copyItem(path: path, to: to, overwrite: false, completionHandler: completionHandler) } } extension FileProviderOperations { internal func delegateNotify(_ operation: FileOperationType, error: Error? = nil) { DispatchQueue.main.async(execute: { if let error = error { self.delegate?.fileproviderFailed(self, operation: operation, error: error) } else { self.delegate?.fileproviderSucceed(self, operation: operation) } }) } internal func delegateNotify(_ operation: FileOperationType, progress: Double) { DispatchQueue.main.async(execute: { self.delegate?.fileproviderProgress(self, operation: operation, progress: Float(progress)) }) } } /// Defines method for fetching and modifying file contents public protocol FileProviderReadWrite: FileProviderBasic { /** Retreives a `Data` object with the contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - completionHandler: a closure with result of file contents or error. - contents: contents of file in a `Data` object. - error: `Error` returned by system if occured. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, completionHandler: @escaping (_ contents: Data?, _ error: Error?) -> Void) -> Progress? /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - offset: First byte index which should be read. **Starts from 0.** - length: Bytes count of data. Pass `-1` to read until the end of file. - completionHandler: a closure with result of file contents or error. - contents: contents of file in a `Data` object. - error: Error returned by system if occured. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, offset: Int64, length: Int, completionHandler: @escaping (_ contents: Data?, _ error: Error?) -> Void) -> Progress? /** Write the contents of the `Data` to a location asynchronously. It will return error if file is already exists. Not attomically by default, unless the provider enforces it. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, completionHandler: SimpleCompletionHandler) -> Progress? /** Write the contents of the `Data` to a location asynchronously. It will return error if file is already exists. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - atomically: data will be written to a temporary file before writing to final location. Default is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, atomically: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Write the contents of the `Data` to a location asynchronously. Not attomically by default, unless the provider enforces it. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - overwrite: Destination file should be overwritten if file is already exists. Default is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? /** Write the contents of the `Data` to a location asynchronously. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - overwrite: Destination file should be overwritten if file is already exists. Default is `false`. - atomically: data will be written to a temporary file before writing to final location. Default is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func writeContents(path: String, contents: Data?, atomically: Bool, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? } extension FileProviderReadWrite { @discardableResult public func contents(path: String, completionHandler: @escaping ((_ contents: Data?, _ error: Error?) -> Void)) -> Progress? { return self.contents(path: path, offset: 0, length: -1, completionHandler: completionHandler) } @discardableResult public func writeContents(path: String, contents: Data?, completionHandler: SimpleCompletionHandler) -> Progress? { return self.writeContents(path: path, contents: contents, atomically: false, overwrite: false, completionHandler: completionHandler) } @discardableResult public func writeContents(path: String, contents: Data?, atomically: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { return self.writeContents(path: path, contents: contents, atomically: atomically, overwrite: false, completionHandler: completionHandler) } @discardableResult public func writeContents(path: String, contents: Data?, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { return self.writeContents(path: path, contents: contents, atomically: false, overwrite: overwrite, completionHandler: completionHandler) } } /// Defines method for fetching file contents progressivly public protocol FileProviderReadWriteProgressive { /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - progressHandler: a closure which will be called every time a new data received from server. - position: Start position of returned data, indexed from zero. - data: returned `Data` from server. - completionHandler: a closure which will be called after receiving is completed or an error occureed. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - responseHandler: a closure which will be called after fetching server response. - response: `URLResponse` returned from server. - progressHandler: a closure which will be called every time a new data received from server. - position: Start position of returned data, indexed from zero. - data: returned `Data` from server. - completionHandler: a closure which will be called after receiving is completed or an error occureed. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, responseHandler: ((_ response: URLResponse) -> Void)?, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? /** Retreives a `Data` object with a portion contents of the file asynchronously vis contents argument of completion handler. If path specifies a directory, or if some other error occurs, data will be nil. - Parameters: - path: Path of file. - offset: First byte index which should be read. **Starts from 0.** - length: Bytes count of data. Pass `-1` to read until the end of file. - responseHandler: a closure which will be called after fetching server response. - response: `URLResponse` returned from server. - progressHandler: a closure which will be called every time a new data received from server. - position: Start position of returned data, indexed from offset. - data: returned `Data` from server. - completionHandler: a closure which will be called after receiving is completed or an error occureed. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult func contents(path: String, offset: Int64, length: Int, responseHandler: ((_ response: URLResponse) -> Void)?, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? } extension FileProviderReadWriteProgressive { @discardableResult public func contents(path: String, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? { return contents(path: path, offset: 0, length: -1, responseHandler: nil, progressHandler: progressHandler, completionHandler: completionHandler) } @discardableResult public func contents(path: String, responseHandler: ((_ response: URLResponse) -> Void)?, progressHandler: @escaping (_ position: Int64, _ data: Data) -> Void, completionHandler: SimpleCompletionHandler) -> Progress? { return contents(path: path, offset: 0, length: -1, responseHandler: responseHandler, progressHandler: progressHandler, completionHandler: completionHandler) } } /// Allows a file provider to notify changes occured public protocol FileProviderMonitor: FileProviderBasic { /** Starts monitoring a path and its subpaths, including files and folders, for any change, including copy, move/rename, content changes, etc. To avoid thread congestion, `evetHandler` will be triggered with 0.2 seconds interval, and has a 0.25 second delay, to ensure it's called after updates. - Note: this functionality is available only in `LocalFileProvider` and `CloudFileProvider`. - Note: `eventHandler` is not called on main thread, for updating UI. dispatch routine to main thread. - Important: `eventHandler` may be called if file is changed in recursive subpaths of registered path. This may cause negative impact on performance if a root path is being monitored. - Parameters: - path: path of directory. - eventHandler: Closure executed after change, on a secondary thread. */ func registerNotifcation(path: String, eventHandler: @escaping () -> Void) /// Stops monitoring the path. /// /// - Parameter path: path of directory. func unregisterNotifcation(path: String) /// Investigate either the path is registered for change notification or not. /// /// - Parameter path: path of directory. /// - Returns: Directory is being monitored or not. func isRegisteredForNotification(path: String) -> Bool } #if os(macOS) || os(iOS) || os(tvOS) /// Allows undo file operations done by provider public protocol FileProvideUndoable: FileProviderOperations { /// To initialize undo manager either call `setupUndoManager()` or set it manually. /// /// - Note: Only some operations (moving/renaming, copying and creating) are supported for undoing. /// - Note: recording operations will occur after setting this object. var undoManager: UndoManager? { get set } /// UndoManager supports undoing this file operation /// - Parameter handle: determines wheither this progress can be rolled back or not. func canUndo(handle: Progress) -> Bool /// UndoManager supports undoing this operation /// - Parameter operation: determines wheither this operation can be rolled back or not. func canUndo(operation: FileOperationType) -> Bool } extension FileProvideUndoable { public func canUndo(operation: FileOperationType) -> Bool { return undoOperation(for: operation) != nil } public func canUndo(handle: Progress) -> Bool { if let operationType = handle.userInfo[.fileProvderOperationTypeKey] as? FileOperationType { return canUndo(operation: operationType) } return false } /// Reuturns roll back operation for provided `operation`. internal func undoOperation(for operation: FileOperationType) -> FileOperationType? { switch operation { case .create(path: let path): return .remove(path: path) case .modify(path: _): return nil case .copy(source: _, destination: let dest): return .remove(path: dest) case .move(source: let source, destination: let dest): return .move(source: dest, destination: source) case .link(link: let link, target: _): return .remove(path: link) case .remove(path: _): return nil default: return nil } } /// Initiates `self.undoManager` if equals with `nil`, and set `levelsOfUndo` to 10. public func setupUndoManager() { guard self.undoManager == nil else { return } self.undoManager = UndoManager() self.undoManager?.levelsOfUndo = 10 } public func _registerUndo(_ operation: FileOperationType) { #if os(macOS) || os(iOS) || os(tvOS) guard let undoManager = self.undoManager, let undoOp = self.undoOperation(for: operation) else { return } let undoBox = UndoBox(provider: self, operation: operation, undoOperation: undoOp) undoManager.beginUndoGrouping() undoManager.registerUndo(withTarget: undoBox, selector: #selector(UndoBox.doSimpleOperation(_:)), object: undoBox) undoManager.setActionName(operation.actionDescription) undoManager.endUndoGrouping() #endif } } class UndoBox: NSObject { weak var provider: FileProvideUndoable? let operation: FileOperationType let undoOperation: FileOperationType init(provider: FileProvideUndoable, operation: FileOperationType, undoOperation: FileOperationType) { self.provider = provider self.operation = operation self.undoOperation = undoOperation } @objc internal func doSimpleOperation(_ box: UndoBox) { switch self.undoOperation { case .move(source: let source, destination: let dest): _=provider?.moveItem(path: source, to: dest, completionHandler: nil) case .remove(let path): _=provider?.removeItem(path: path, completionHandler: nil) default: break } } } #endif /// This protocol defines method to share a public link with other users public protocol FileProviderSharing { /** Genrates a public url to a file to be shared with other users and can be downloaded without authentication. - Important: In some providers url will be available for a limitied time, determined in `expiration` argument. e.g. Dropbox links will be expired after 4 hours. - Parameters: - to: path of file, including file/directory name. - completionHandler: a closure with result of directory entries or error. - link: a url returned by Dropbox to share. - attribute: a `FileObject` containing the attributes of the item. - expiration: a `Date` object, determines when the public url will expires. - error: Error returned by server. */ func publicLink(to path: String, completionHandler: @escaping (_ link: URL?, _ attribute: FileObject?, _ expiration: Date?, _ error: Error?) -> Void) } //efines protocol for provider allows symbolic link operations. public protocol FileProviderSymbolicLink { /** Creates a symbolic link at the specified path that points to an item at the given path. This method does not traverse symbolic links contained in destination path, making it possible to create symbolic links to locations that do not yet exist. Also, if the final path component is a symbolic link, that link is not followed. - Parameters: - symbolicLink: The file path at which to create the new symbolic link. The last component of the path issued as the name of the link. - withDestinationPath: The path that contains the item to be pointed to by the link. In other words, this is the destination of the link. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. */ func create(symbolicLink path: String, withDestinationPath destPath: String, completionHandler: SimpleCompletionHandler) /// Returns the path of the item pointed to by a symbolic link. /// /// - Parameters: /// - path: The path of a file or directory. /// - completionHandler: Returns destination url of given symbolic link, or an `Error` object if it fails. func destination(ofSymbolicLink path: String, completionHandler: @escaping (_ file: FileObject?, _ error: Error?) -> Void) } /// Defines protocol for provider allows all common operations. public protocol FileProvider: FileProviderOperations, FileProviderReadWrite, NSCopying { } internal let pathTrimSet = CharacterSet(charactersIn: " /") extension FileProviderBasic { public var type: String { return Swift.type(of: self).type } public func url(of path: String) -> URL { var rpath: String = path rpath = rpath.addingPercentEncoding(withAllowedCharacters: .filePathAllowed) ?? rpath if let baseURL = baseURL?.absoluteURL { if rpath.hasPrefix("/") { rpath.remove(at: rpath.startIndex) } return URL(string: rpath, relativeTo: baseURL) ?? baseURL } else { return URL(string: rpath) ?? URL(string: "/")! } } public func relativePathOf(url: URL) -> String { // check if url derieved from current base url let relativePath = url.relativePath if !relativePath.isEmpty, url.baseURL == self.baseURL { return (relativePath.removingPercentEncoding ?? relativePath).replacingOccurrences(of: "/", with: "", options: .anchored) } // resolve url string against baseurl guard let baseURL = self.baseURL else { return url.absoluteString } let standardRelativePath = url.absoluteString.replacingOccurrences(of: baseURL.absoluteString, with: "/").replacingOccurrences(of: "/", with: "", options: .anchored) if URLComponents(string: standardRelativePath)?.host?.isEmpty ?? true { return standardRelativePath.removingPercentEncoding ?? standardRelativePath } else { return relativePath.replacingOccurrences(of: "/", with: "", options: .anchored) } } /// Returns a file name supposed to be unique with adding numbers to end of file. /// - Important: It's a synchronous method. Don't use it on main thread. /// - Parameter filePath: supposed path of file which should be examined. public func fileByUniqueName(_ filePath: String) -> String { //assert(!Thread.isMainThread, "\(#function) is not recommended to be executed on Main Thread.") let fileUrl = URL(fileURLWithPath: filePath) let dirPath = fileUrl.deletingLastPathComponent().path let fileName = fileUrl.deletingPathExtension().lastPathComponent let fileExt = fileUrl.pathExtension var result = fileName let group = DispatchGroup() group.enter() self.contentsOfDirectory(path: dirPath) { (contents, error) in var bareFileName = fileName let number = Int(fileName.components(separatedBy: " ").filter { !$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty }.last ?? "noname") if let _ = number { result = fileName.components(separatedBy: " ").filter { !$0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty }.dropLast().joined(separator: " ") bareFileName = result } var i = number ?? 2 let similiar = contents.map { $0.url.lastPathComponent.isEmpty ? $0.name : $0.url.lastPathComponent }.filter { $0.hasPrefix(result) } while similiar.contains(result + (!fileExt.isEmpty ? "." + fileExt : "")) { result = "\(bareFileName) \(i)" i += 1 } group.leave() } _ = group.wait(timeout: .now() + 5) let finalFile = result + (!fileExt.isEmpty ? "." + fileExt : "") return dirPath.appendingPathComponent(finalFile) } internal func NotImplemented(_ fn: String = #function, file: StaticString = #file) { assert(false, "\(fn) method is not yet implemented. \(file)") } } /// Define methods to get preview and thumbnail for files or folders public protocol ExtendedFileProvider: FileProviderBasic { /// Returns true if provider supports fetching properties of file like dimensions, duration, etc. /// Usually media or document files support these meta-infotmations. /// /// - Parameter path: path of file. /// - Returns: A `Bool` idicates path can have properties. func propertiesOfFileSupported(path: String) -> Bool /** Fetching properties of file like dimensions, duration, etc. It's variant depending on file type. Images, videos and audio files meta-information will be returned. - Note: `LocalFileInformationGenerator` variables can be set to change default behavior of thumbnail and properties generator of `LocalFileProvider`. - Parameters: - path: path of file. - completionHandler: a closure with result of preview image or error. - propertiesDictionary: A `Dictionary` of proprty keys and values. - keys: An `Array` contains ordering of keys. - error: Error returned by system. */ @discardableResult func propertiesOfFile(path: String, completionHandler: @escaping (_ propertiesDictionary: [String: Any], _ keys: [String], _ error: Error?) -> Void) -> Progress? #if os(macOS) || os(iOS) || os(tvOS) /// Returuns true if thumbnail preview is supported by provider and file type accordingly. /// /// - Parameter path: path of file. /// - Returns: A `Bool` idicates path can have thumbnail. func thumbnailOfFileSupported(path: String) -> Bool /** Generates and returns a thumbnail preview of document asynchronously. The defualt dimension of returned image is different regarding provider type, usually 64x64 pixels. - Parameters: - path: path of file. - completionHandler: a closure with result of preview image or error. - image: `NSImage`/`UIImage` object contains preview. - error: `Error` returned by system. */ @discardableResult func thumbnailOfFile(path: String, completionHandler: @escaping (_ image: ImageClass?, _ error: Error?) -> Void) -> Progress? /** Generates and returns a thumbnail preview of document asynchronously. The defualt dimension of returned image is different regarding provider type, usually 64x64 pixels. Default value used when `dimenstion` is `nil`. - Note: `LocalFileInformationGenerator` variables can be set to change default behavior of thumbnail and properties generator of `LocalFileProvider`. - Parameters: - path: path of file. - dimension: width and height of result preview image. - completionHandler: a closure with result of preview image or error. - image: `NSImage`/`UIImage` object contains preview. - error: `Error` returned by system. */ @discardableResult func thumbnailOfFile(path: String, dimension: CGSize?, completionHandler: @escaping (_ image: ImageClass?, _ error: Error?) -> Void) -> Progress? #endif } #if os(macOS) || os(iOS) || os(tvOS) extension ExtendedFileProvider { @discardableResult public func thumbnailOfFile(path: String, completionHandler: @escaping ((_ image: ImageClass?, _ error: Error?) -> Void)) -> Progress? { return self.thumbnailOfFile(path: path, dimension: nil, completionHandler: completionHandler) } internal static func convertToImage(pdfData: Data?, page: Int = 1, maxSize: CGSize?) -> ImageClass? { guard let pdfData = pdfData else { return nil } let cfPDFData: CFData = pdfData as CFData if let provider = CGDataProvider(data: cfPDFData), let reference = CGPDFDocument(provider), let pageRef = reference.page(at: page) { return self.convertToImage(pdfPage: pageRef, maxSize: maxSize) } return nil } internal static func convertToImage(pdfURL: URL, page: Int = 1, maxSize: CGSize?) -> ImageClass? { // To accelerate, supporting only local file URL guard pdfURL.isFileURL else { return nil } if let reference = CGPDFDocument(pdfURL as CFURL), let pageRef = reference.page(at: page) { return self.convertToImage(pdfPage: pageRef, maxSize: maxSize) } return nil } private static func convertToImage(pdfPage: CGPDFPage, maxSize: CGSize?) -> ImageClass? { let scale: CGFloat let frame = pdfPage.getBoxRect(CGPDFBox.mediaBox) if let maxSize = maxSize { scale = min(maxSize.width / frame.width, maxSize.height / frame.height) } else { #if os(macOS) scale = NSScreen.main?.backingScaleFactor ?? 1.0 // fetch device is retina or not #else scale = UIScreen.main.scale // fetch device is retina or not #endif } let rect = CGRect(origin: .zero, size: frame.size) let size = CGSize(width: frame.size.width * scale, height: frame.size.height * scale) let transform = pdfPage.getDrawingTransform(CGPDFBox.mediaBox, rect: rect, rotate: 0, preserveAspectRatio: true) #if os(macOS) let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) guard let context = NSGraphicsContext(bitmapImageRep: rep!) else { return nil } NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = context context.cgContext.concatenate(transform) context.cgContext.translateBy(x: 0, y: size.height) context.cgContext.scaleBy(x: scale, y: -scale) context.cgContext.drawPDFPage(pdfPage) let resultingImage = NSImage(size: size) resultingImage.addRepresentation(rep!) return resultingImage #else let handler : (CGContext) -> Void = { context in context.concatenate(transform) context.translateBy(x: 0, y: size.height) context.scaleBy(x: CGFloat(scale), y: CGFloat(-scale)) context.setFillColor(UIColor.white.cgColor) context.fill(rect) context.drawPDFPage(pdfPage) } if #available(iOS 10.0, tvOS 10.0, *) { return UIGraphicsImageRenderer(size: size).image { (rendererContext) in handler(rendererContext.cgContext) } } else { UIGraphicsBeginImageContext(size) guard let context = UIGraphicsGetCurrentContext() else { return nil } context.saveGState() handler(context) context.restoreGState() let resultingImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resultingImage } #endif } internal static func scaleDown(fileURL: URL, toSize maxSize: CGSize?) -> ImageClass? { guard let source = CGImageSourceCreateWithURL(fileURL as CFURL, nil) else { return nil } return scaleDown(source: source, toSize: maxSize) } internal static func scaleDown(data: Data, toSize maxSize: CGSize?) -> ImageClass? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } return scaleDown(source: source, toSize: maxSize) } internal static func scaleDown(source: CGImageSource, toSize maxSize: CGSize?) -> ImageClass? { let options: [NSString: Any] if let maxSize = maxSize { let pixelSize: CGFloat let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) if let width: CGFloat = ((properties as NSDictionary?)?.object(forKey: kCGImagePropertyPixelWidth) as? CGFloat), let height: CGFloat = ((properties as NSDictionary?)?.object(forKey: kCGImagePropertyPixelHeight) as? CGFloat) { pixelSize = (width / maxSize.width < height / maxSize.height) ? maxSize.width : maxSize.height } else { pixelSize = max(maxSize.width, maxSize.height) } options = [ kCGImageSourceThumbnailMaxPixelSize: pixelSize, kCGImageSourceCreateThumbnailFromImageAlways: true] } else { options = [ kCGImageSourceCreateThumbnailFromImageAlways: true] } guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } #if os(macOS) return ImageClass(cgImage: image, size: .zero) #else return ImageClass(cgImage: image) #endif } } #endif /// Operation type description of file operation, included files path in associated values. public enum FileOperationType: CustomStringConvertible { /// Creating a file or directory in path. case create (path: String) /// Copying a file or directory from source to destination. case copy (source: String, destination: String) /// Moving a file or directory from source to destination. case move (source: String, destination: String) /// Modifying data of a file o in path by writing new data. case modify (path: String) /// Deleting file or directory in path. case remove (path: String) /// Creating a symbolic link or alias to target. case link (link: String, target: String) /// Fetching data in file located in path. case fetch (path: String) public var description: String { switch self { case .create: return "Create" case .copy: return "Copy" case .move: return "Move" case .modify: return "Modify" case .remove: return "Remove" case .link: return "Link" case .fetch: return "Fetch" } } /// present participle of action, like `Copying`. public var actionDescription: String { return description.trimmingCharacters(in: CharacterSet(charactersIn: "e")) + "ing" } /// Path of subjecting file. public var source: String { let reflect = Mirror(reflecting: self).children.first!.value let mirror = Mirror(reflecting: reflect) return reflect as? String ?? mirror.children.first?.value as! String } /// Path of subjecting file. public var path: String? { return source } /// Path of destination file. public var destination: String? { guard let reflect = Mirror(reflecting: self).children.first?.value else { return nil } let mirror = Mirror(reflecting: reflect) return mirror.children.dropFirst().first?.value as? String } init? (json: [String: Any]) { guard let type = json["type"] as? String, let source = json["source"] as? String else { return nil } let dest = json["dest"] as? String switch type { case "Fetch": self = .fetch(path: source) case "Create": self = .create(path: source) case "Modify": self = .modify(path: source) case "Remove": self = .remove(path: source) case "Copy": guard let dest = dest else { return nil } self = .copy(source: source, destination: dest) case "Move": guard let dest = dest else { return nil } self = .move(source: source, destination: dest) case "Link": guard let dest = dest else { return nil } self = .link(link: source, target: dest) default: return nil } } internal var json: String? { var dictionary: [String: Any] = ["type": self.description] dictionary["source"] = source dictionary["dest"] = destination return String(jsonDictionary: dictionary) } } /// Delegate methods for reporting provider's operation result and progress, when it's ready to update /// user interface. /// All methods are called in main thread to avoids UI bugs. public protocol FileProviderDelegate: AnyObject { /// fileproviderSucceed(_:operation:) gives delegate a notification when an operation finished with success. /// This method is called in main thread to avoids UI bugs. func fileproviderSucceed(_ fileProvider: FileProviderOperations, operation: FileOperationType) /// fileproviderSucceed(_:operation:) gives delegate a notification when an operation finished with failure. /// This method is called in main thread to avoids UI bugs. func fileproviderFailed(_ fileProvider: FileProviderOperations, operation: FileOperationType, error: Error) /// fileproviderSucceed(_:operation:) gives delegate a notification when an operation progess. /// Supported by some providers, especially remote ones. /// This method is called in main thread to avoids UI bugs. func fileproviderProgress(_ fileProvider: FileProviderOperations, operation: FileOperationType, progress: Float) } /// The `FileOperationDelegate` protocol defines methods for managing operations involving the copying, moving, linking, or removal of files and directories. When you use an `FileProvider` object to initiate a copy, move, link, or remove operation, the file provider asks its delegate whether the operation should begin at all and whether it should proceed when an error occurs. public protocol FileOperationDelegate: AnyObject { /// fileProvider(_:shouldOperate:) gives the delegate an opportunity to filter the file operation. Returning true from this method will allow the copy to happen. Returning false from this method causes the item in question to be skipped. If the item skipped was a directory, no children of that directory will be subject of the operation, nor will the delegate be notified of those children. func fileProvider(_ fileProvider: FileProviderOperations, shouldDoOperation operation: FileOperationType) -> Bool /// fileProvider(_:shouldProceedAfterError:copyingItemAtPath:toPath:) gives the delegate an opportunity to recover from or continue copying after an error. If an error occurs, the error object will contain an ErrorType indicating the problem. The source path and destination paths are also provided. If this method returns true, the FileProvider instance will continue as if the error had not occurred. If this method returns false, the NSFileManager instance will stop copying, return false from copyItemAtPath:toPath:error: and the error will be provied there. func fileProvider(_ fileProvider: FileProviderOperations, shouldProceedAfterError error: Error, operation: FileOperationType) -> Bool }
48.878689
566
0.676331
896af1fbfb60f3536c7f217b43a044ae3bd9d658
501
// // ViewController.swift // Flicker // // Created by Kevin Chow on 1/14/16. // Copyright © 2016 Kevin Chow. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.269231
80
0.664671
03f3316d1e1bd034c62f6e52f4d596b5949a5dce
2,098
// // AKTableView.swift // AudioKit // // Created by Aurelius Prochazka, revision7. // Copyright © 2017 AudioKit. All rights reserved. // import UIKit /// Displays the values in the table into a nice graph public class AKTableView: UIView { var table: AKTable var absmax: Double = 1.0 /// Initialize the table view public init(_ table: AKTable, frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 150)) { self.table = table super.init(frame: frame) let max = Double(table.max() ?? 1.0) let min = Double(table.min() ?? -1.0) absmax = [max, abs(min)].max() ?? 1.0 } /// Required initializer required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Draw the table view override public func draw(_ rect: CGRect) { let width = Double(frame.width) let height = Double(frame.height) / 2.0 let padding = 0.9 let border = UIBezierPath(rect: CGRect(x: 0, y: 0, width: frame.width, height: frame.height)) let bgcolor = AKStylist.sharedInstance.nextColor bgcolor.setFill() border.fill() UIColor.black.setStroke() border.lineWidth = 8 border.stroke() let midline = UIBezierPath() midline.move(to: CGPoint(x: 0, y: frame.height / 2)) midline.addLine(to: CGPoint(x: frame.width, y: frame.height / 2)) UIColor.black.setStroke() midline.lineWidth = 1 midline.stroke() let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 0.0, y: (1.0 - table[0] / absmax) * height)) for i in 1..<table.count { let x = Double(i) / table.count * width let y = (1.0 - table[i] / absmax * padding) * height bezierPath.addLine(to: CGPoint(x: x, y: y)) } bezierPath.addLine(to: CGPoint(x: Double(frame.width), y: (1.0 - table[0] / absmax * padding) * height)) UIColor.black.setStroke() bezierPath.lineWidth = 2 bezierPath.stroke() } }
29.138889
112
0.591039
91a74ea5c32e5869566c21ef1c5c5099e4236801
206
import NinetyNineSwiftProblems import SolutionTester extension SolutionTester { // P27B (**) Group the elements of a set into disjoint subsets - Part 2. func testP27B() { // TODO } }
17.166667
76
0.669903
eb633f6a1e8725fd3677024bb2687b77fb8ffa6e
2,040
// // HomeRouter.swift // AndesUI_Example // // Created by Santiago Lazzari on 19/12/2019. // Copyright © 2019 MercadoLibre. All rights reserved. // import UIKit protocol HomeRouter: NSObject { func route(from: UIViewController) func routeToButton() func routeToMessages() func routeToBadges() func routeToWhatsNew() func routeTextField() func routerCheckbox() func routerRadioButton() func routeTags() func routeSnackbar() } class HomeAppRouter: NSObject { let view = HomeViewController() var presenter: HomePresenter? let buttonsRouter = ButtonsAppRouter() let messagesRouter = MessagesAppRouter() let badgesRouter = BadgesAppRouter() let whatsNewRouter = WhatsNewAppRouter() let textFieldRouter = TextFieldsAppRouter() let checkBoxRouter = CheckboxAppRouter() let radioButtonRouter = RadioButtonAppRouter() let tagRouter = TagsAppRouter() let snackbarRouter = SnackbarAppRouter() } extension HomeAppRouter: HomeRouter { func route(from: UIViewController) { presenter = HomeViewPresenter(view: view, router: self) view.presenter = presenter let navigation = UINavigationController(rootViewController: view) navigation.modalPresentationStyle = .fullScreen from.present(navigation, animated: false, completion: nil) } func routeToButton() { buttonsRouter.route(from: view) } func routeToMessages() { messagesRouter.route(from: view) } func routeToBadges() { badgesRouter.route(from: view) } func routeToWhatsNew() { whatsNewRouter.route(from: view) } func routeTextField() { textFieldRouter.route(from: view) } func routerCheckbox() { checkBoxRouter.route(from: view) } func routerRadioButton() { radioButtonRouter.route(from: view) } func routeTags() { tagRouter.route(from: view) } func routeSnackbar() { snackbarRouter.route(from: view) } }
23.72093
73
0.67549
1aaf99780adfdd1c7f9d18876c8b327b69106198
1,892
import UIKit import RemoteConfiguration public class Client: NSObject { private let manager = Manager(url: URL(string: "http://thisisatestdomain.de")!, currentVersion: AppDelegate.appVersion) public func loadDefaultConfiguration(completion: @escaping (_ error: NSError?, _ data: String?) -> Void) { manager.request(using: HTTPProvider(), with: JSONDeserializer(), completion: { (result) in switch result { case .success(let model): guard var resultString = String.fromJSONObject(object: model.urlConfiguration as AnyObject) else { return completion(NSError(), nil) } resultString.append("\n\(self.source(origin: model.origin))") return completion(nil, resultString) default: return completion(NSError(), nil) } }) } public func loadCustomConfiguration(completion: @escaping (_ error: NSError?, _ data: String?) -> Void) { manager.request(using: CustomHTTPProvider(), with: CustomJSONDeserializer(), completion: { (result) in switch result { case .success(let model): guard var resultString = String.fromJSONObject(object: model.configFile.urlConfig as AnyObject) else { return completion(NSError(), nil) } resultString.append("\n\(self.source(origin: model.origin))") return completion(nil, resultString) default: return completion(NSError(), nil) } }) } public func clearCache() { manager.clearCache() } private func source(origin: Origin) -> String { switch origin { case .provider: return "Provider" case .cache: return "Cache" case .bundle: return "Bundle" } } }
35.698113
124
0.590381
d777e937fa015b6a1ade1bbe64380705c8621446
11,295
// // BaseJSInjectViewController.swift // JSInject // // Created by iOS-dev on 2019/10/12. // Copyright © 2019 iOS-dev. All rights reserved. // import UIKit import WebKit import JavaScriptCore class BaseJSInjectViewController: UIViewController { var context: JSContext = JSContext() private var commonInject: SKCommonJSInject = SKCommonJSInject() private var injectSelectors: [String:Selector] = [:] var jsContext: JSContext! var URLString: String? var editUrlString: String? var HTMLString: String? var showTitle: Bool = true var showEdit: Bool = false static var globalTitle: String! var token: String? var finishBlock:(() -> ())? lazy private var progressView: UIProgressView = { self.progressView = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(1), width: UIScreen.main.bounds.width, height: 1)) self.progressView.tintColor = UIColor.lightGray // 进度条颜色 self.progressView.trackTintColor = UIColor.lightText // 进度条背景色 return self.progressView }() lazy var config: WKWebViewConfiguration = { let config = WKWebViewConfiguration() config.preferences = WKPreferences() config.preferences.minimumFontSize = 10 config.preferences.javaScriptEnabled = true config.preferences.javaScriptCanOpenWindowsAutomatically = false config.processPool = WKProcessPool() config.userContentController = WKUserContentController() // config.userContentController.add(self, name: "jsInject") // setupMsgHandler(config: config) return config }() lazy var webView:WKWebView = { let webView = WKWebView(frame: self.view.bounds, configuration: config) webView.backgroundColor = UIColor.white return webView }() override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) removeMsgHandler(config: webView.configuration) // IQKeyboardManager.shared().isEnabled = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // IQKeyboardManager.shared().isEnabled = false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupMsgHandler(config: webView.configuration) } override func viewDidLoad() { super.viewDidLoad() configUI() } func configUI() { view.addSubview(webView) if #available(iOS 11.0, *) { webView.scrollView.contentInsetAdjustmentBehavior = .never } else { // Fallback on earlier versions } if showEdit { let rightBarButton = UIBarButtonItem(title: "编辑", style: UIBarButtonItem.Style.plain, target: self, action: #selector(loadEditPage)) navigationItem.rightBarButtonItem = rightBarButton } //设置导航栏标题颜色 navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black] navigationController?.navigationBar.shadowImage = nil view.addSubview(webView) webView.uiDelegate = self webView.navigationDelegate = self webView.addSubview(progressView) webView.backgroundColor = UIColor.white // webView.snp.makeConstraints { (make) in // make.edges.equalToSuperview() // } self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) self.webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) guard let token = self.token else { return } if let urlString = URLString, let sk_URL = URL.init(string: urlString), let host = sk_URL.host { // 过期时间1年 let expires: TimeInterval = 60 * 60 * 24 // 定义一个可变字典存放cookie键值对 var properties: [HTTPCookiePropertyKey : Any] = [:] properties[.name] = "token" properties[.path] = "/" properties[.value] = token properties[.secure] = false properties[.domain] = host properties[.version] = 0 properties[.expires] = Date.init(timeIntervalSinceNow: expires) var request = URLRequest(url: sk_URL) // 初始化cookie对象,返回值可选类型 let cookie = HTTPCookie.init(properties: properties) if let cookie = cookie { // 保存cookie,地址是沙盒的 /Library/Cookies HTTPCookieStorage.shared.setCookie(cookie) } request.addValue("token=\(token)", forHTTPHeaderField: "Cookie") webView.load(request) return } if let htmlString = HTMLString { webView.loadHTMLString(BaseJSInjectViewController.adaptWebViewForHTML(html: htmlString), baseURL: nil) return } } //HTML适配图片文字 public static func adaptWebViewForHTML(html: String) -> String { let headHTML = NSMutableString.init(capacity: 0) headHTML.append("<html>") headHTML.append("<head>") headHTML.append("<meta charset=\"utf-8\">") headHTML.append("<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />") headHTML.append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />") headHTML.append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />") headHTML.append("<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />") //适配图片宽度,让图片宽度等于屏幕宽度 headHTML.append("<style>img{width:100%;}</style>") headHTML.append("<style>img{height:auto;}</style>") //适配图片宽度,让图片宽度最大等于屏幕宽度 headHTML.append("<style>img{max-width:100%;width:auto;height:auto;}</style>") //适配图片宽度,如果图片宽度超过手机屏幕宽度,就让图片宽度等于手机屏幕宽度,高度自适应,如果图片宽度小于屏幕宽度,就显示图片大小 headHTML.append("<script type='text/javascript'>\nwindow.onload = function(){\nvar maxwidth=document.body.clientWidth\nfor(i=0;i <document.images.length;i++){\nvar myimg = document.images[i]\nif(myimg.width > maxwidth){\nmyimg.style.width = '100%'\nmyimg.style.height = 'auto'\n}\n}\n}\n</script>\n") headHTML.append("<style>table{width:100%;}</style>") headHTML.append("<title>webview</title>") var HTMLSting = html HTMLSting.append(headHTML as String) return HTMLSting } // override func backAction() { // if let block = self.finishBlock { // block() // } // super.backAction() // } deinit { webView.stopLoading() webView.removeObserver(self, forKeyPath: "estimatedProgress") webView.removeObserver(self, forKeyPath: "title") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setupMsgHandler(config:WKWebViewConfiguration){ let methods = commonInject.getAllSelector() for method in methods { let methodName = NSStringFromSelector(method) // let name = methodName.trimmingCharacters(in: CharacterSet.init(charactersIn: ":")) if let name = methodName.components(separatedBy: ":").first { print(name) injectSelectors[name] = method config.userContentController.add(self, name: name) } } } func removeMsgHandler(config:WKWebViewConfiguration){ let methods = commonInject.getAllSelector() for method in methods { let methodName = NSStringFromSelector(method) if let name = methodName.components(separatedBy: ":").first { config.userContentController.removeScriptMessageHandler(forName: name) } } } } extension BaseJSInjectViewController: WKUIDelegate, WKNavigationDelegate { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // 加载进度条 if keyPath == "estimatedProgress"{ progressView.alpha = 1.0 progressView.setProgress(Float(webView.estimatedProgress), animated: true) if webView.estimatedProgress >= 1.0 { UIView.animate(withDuration: 0.5, delay: 0.1, options: .curveEaseOut, animations: { self.progressView.alpha = 0 }, completion: { (finish) in self.progressView.setProgress(0.0, animated: false) }) } } else if keyPath == "title" { if showTitle { self.title = self.webView.title } } } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){ } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { } } extension BaseJSInjectViewController { @objc func reload() { guard let token = self.token, let urlString = URLString, let sk_URL = URL.init(string: urlString) else { return } var request = URLRequest(url: sk_URL) request.addValue("token=\(token)", forHTTPHeaderField: "Cookie") webView.load(request) } @objc func loadEditPage() { guard let token = self.token, let urlString = editUrlString, let sk_URL = URL.init(string: urlString), urlString.count > 0 else { // SKHUDTools.showTextAutomaticDismiss(title: "暂无权限") return } var request = URLRequest(url: sk_URL) request.addValue("token=\(token)", forHTTPHeaderField: "Cookie") webView.load(request) navigationItem.rightBarButtonItem?.title = nil if showTitle { navigationItem.rightBarButtonItem?.title = nil } } } extension BaseJSInjectViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("\(message.body),\(message.name)") print("thread:\(Thread.current)") DispatchQueue.main.async { self.commonInject.webView = self.webView self.commonInject.controller = self if let para = message.body as? String { if let sel = self.injectSelectors[message.name] { if para.count > 0 { self.commonInject.perform(sel, with: message.body) } else { self.commonInject.perform(sel) } return } } guard let para = message.body as? [Any] else { return } if let sel = self.injectSelectors[message.name] { self.commonInject.perform(sel, with: para) } } } }
36.553398
308
0.603541
918c1b1bba061e150ef56136579747530770555b
368
// // Created by Giang Long Tran on 03.01.22. // import UIKit class LockView: BECompositionView { override func build() -> UIView { BEZStack { BEZStackPosition(mode: .fill) { UIImageView(image: .lockBackground).withTag(1) } BEZStackPosition(mode: .center) { UIImageView(width: 217, height: 164, image: .pLogo) } } } }
24.533333
99
0.619565
4aa6b1935b193aea5e7382283c24056ae2906d4b
18,658
// RUN: %target-typecheck-verify-swift @noescape var fn : () -> Int = { 4 } // expected-error {{@noescape may only be used on 'parameter' declarations}} {{1-11=}} func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{29-39=}} func doesEscape(_ fn : @escaping () -> Int) {} func takesGenericClosure<T>(_ a : Int, _ fn : @noescape () -> T) {} // expected-warning{{@noescape is the default and is deprecated}} {{47-57=}} func takesNoEscapeClosure(_ fn : () -> Int) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-3{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-4{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} takesNoEscapeClosure { 4 } // ok _ = fn() // ok var x = fn // expected-error {{non-escaping parameter 'fn' may only be called}} // This is ok, because the closure itself is noescape. takesNoEscapeClosure { fn() } // This is not ok, because it escapes the 'fn' closure. doesEscape { fn() } // expected-error {{closure use of non-escaping parameter 'fn' may allow it to escape}} // This is not ok, because it escapes the 'fn' closure. func nested_function() { _ = fn() // expected-error {{declaration closing over non-escaping parameter 'fn' may allow it to escape}} } takesNoEscapeClosure(fn) // ok doesEscape(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} takesGenericClosure(4, fn) // ok takesGenericClosure(4) { fn() } // ok. } class SomeClass { final var x = 42 func test() { // This should require "self." doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} // Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't // require "self." qualification of member references. takesNoEscapeClosure { x } } @discardableResult func foo() -> Int { foo() func plain() { foo() } let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} func multi() -> Int { foo(); return 0 } let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}} takesNoEscapeClosure { foo(); return 0 } // okay func outer() { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } } let outer2: () -> Void = { func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}} let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} } doesEscape { func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}} let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} return 0 } takesNoEscapeClosure { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} func multi() -> Int { foo(); return 0 } let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // okay return 0 } struct Outer { @discardableResult func bar() -> Int { bar() func plain() { bar() } let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}} doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} takesNoEscapeClosure { bar() } // okay doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}} takesNoEscapeClosure { bar(); return 0 } // okay return 0 } } func structOuter() { struct Inner { @discardableResult func bar() -> Int { bar() // no-warning func plain() { bar() } let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}} func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}} doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} takesNoEscapeClosure { bar() } // okay doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}} takesNoEscapeClosure { bar(); return 0 } // okay return 0 } } } return 0 } } // Implicit conversions (in this case to @convention(block)) are ok. @_silgen_name("whatever") func takeNoEscapeAsObjCBlock(_: @noescape @convention(block) () -> Void) // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} func takeNoEscapeTest2(_ fn : @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{31-41=}} takeNoEscapeAsObjCBlock(fn) } // Autoclosure implies noescape, but produce nice diagnostics so people know // why noescape problems happen. func testAutoclosure(_ a : @autoclosure () -> Int) { // expected-note{{parameter 'a' is implicitly non-escaping because it was declared @autoclosure}} doesEscape { a() } // expected-error {{closure use of non-escaping parameter 'a' may allow it to escape}} } // <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both func redundant(_ fn : @noescape // expected-error @+1 {{@noescape is implied by @autoclosure and should not be redundantly specified}} @autoclosure () -> Int) { // expected-warning@-2{{@noescape is the default and is deprecated}} {{23-33=}} } protocol P1 { associatedtype Element } protocol P2 : P1 { associatedtype Element } func overloadedEach<O: P1, T>(_ source: O, _ transform: @escaping (O.Element) -> (), _: T) {} func overloadedEach<P: P2, T>(_ source: P, _ transform: @escaping (P.Element) -> (), _: T) {} struct S : P2 { typealias Element = Int func each(_ transform: @noescape (Int) -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{26-36=}} overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, (Int) -> (), Int)'}} transform, 1) // expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, @escaping (O.Element) -> (), T), (P, @escaping (P.Element) -> (), T)}} } } // rdar://19763676 - False positive in @noescape analysis triggered by parameter label func r19763676Callee(_ f: @noescape (_ param: Int) -> Int) {} // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}} func r19763676Caller(_ g: @noescape (Int) -> Int) { // expected-warning{{@noescape is the default and is deprecated}} {{27-37=}} r19763676Callee({ _ in g(1) }) } // <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments func calleeWithDefaultParameters(_ f: @noescape () -> (), x : Int = 1) {} // expected-warning {{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}} func callerOfDefaultParams(_ g: @noescape () -> ()) { // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} calleeWithDefaultParameters(g) } // <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape class NoEscapeImmediatelyApplied { func f() { // Shouldn't require "self.", the closure is obviously @noescape. _ = { return ivar }() } final var ivar = 42 } // Reduced example from XCTest overlay, involves a TupleShuffleExpr public func XCTAssertTrue(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { } public func XCTAssert(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { XCTAssertTrue(expression, message, file: file, line: line); } /// SR-770 - Currying and `noescape`/`rethrows` don't work together anymore func curriedFlatMap<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{41-50=}} return { f in x.flatMap(f) } } func curriedFlatMap2<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-warning{{@noescape is the default and is deprecated}} {{42-51=}} return { (f : @noescape (A) -> [B]) in // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}} x.flatMap(f) } } func bad(_ a : @escaping (Int)-> Int) -> Int { return 42 } func escapeNoEscapeResult(_ x: [Int]) -> (@noescape (Int) -> Int) -> Int { // expected-warning{{@noescape is the default and is deprecated}} {{43-52=}} return { f in // expected-note{{parameter 'f' is implicitly non-escaping}} bad(f) // expected-error {{passing non-escaping parameter 'f' to function expecting an @escaping closure}} } } // SR-824 - @noescape for Type Aliased Closures // // Old syntax -- @noescape is the default, and is redundant typealias CompletionHandlerNE = @noescape (_ success: Bool) -> () // expected-warning{{@noescape is the default and is deprecated}} {{33-43=}} // Explicit @escaping is not allowed here typealias CompletionHandlerE = @escaping (_ success: Bool) -> () // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}} // No @escaping -- it's implicit from context typealias CompletionHandler = (_ success: Bool) -> () var escape : CompletionHandlerNE var escapeOther : CompletionHandler func doThing1(_ completion: (_ success: Bool) -> ()) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing2(_ completion: CompletionHandlerNE) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing3(_ completion: CompletionHandler) { // expected-note@-1{{parameter 'completion' is implicitly non-escaping}} // expected-error @+2 {{non-escaping value 'escape' may only be called}} // expected-error @+1 {{non-escaping parameter 'completion' may only be called}} escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}} } func doThing4(_ completion: @escaping CompletionHandler) { escapeOther = completion } // <rdar://problem/19997680> @noescape doesn't work on parameters of function type func apply<T, U>(_ f: @noescape (T) -> U, g: @noescape (@noescape (T) -> U) -> U) -> U { // expected-warning@-1{{@noescape is the default and is deprecated}} {{23-33=}} // expected-warning@-2{{@noescape is the default and is deprecated}} {{46-56=}} // expected-warning@-3{{@noescape is the default and is deprecated}} {{57-66=}} return g(f) } // <rdar://problem/19997577> @noescape cannot be applied to locals, leading to duplication of code enum r19997577Type { case Unit case Function(() -> r19997577Type, () -> r19997577Type) case Sum(() -> r19997577Type, () -> r19997577Type) func reduce<Result>(_ initial: Result, _ combine: @noescape (Result, r19997577Type) -> Result) -> Result { // expected-warning{{@noescape is the default and is deprecated}} {{53-63=}} let binary: @noescape (r19997577Type, r19997577Type) -> Result = { combine(combine(combine(initial, self), $0), $1) } // expected-warning{{@noescape is the default and is deprecated}} {{17-27=}} switch self { case .Unit: return combine(initial, self) case let .Function(t1, t2): return binary(t1(), t2()) case let .Sum(t1, t2): return binary(t1(), t2()) } } } // type attribute and decl attribute func noescapeD(@noescape f: @escaping () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}} {{16-25=}} {{29-29=@noescape }} func noescapeT(f: @noescape () -> Bool) {} // expected-warning{{@noescape is the default and is deprecated}} {{19-29=}} func autoclosureD(@autoclosure f: () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{19-31=}} {{35-35=@autoclosure }} func autoclosureT(f: @autoclosure () -> Bool) {} // ok func noescapeD_noescapeT(@noescape f: @noescape () -> Bool) {} // expected-error {{@noescape is now an attribute on a parameter type, instead of on the parameter itself}} // expected-warning@-1{{@noescape is the default and is deprecated}} {{39-49=}} func autoclosureD_noescapeT(@autoclosure f: @noescape () -> Bool) {} // expected-error {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{29-41=}} {{45-45=@autoclosure }} // expected-warning@-1{{@noescape is the default and is deprecated}} {{45-55=}}
54.555556
214
0.662236
e4bb8abf6e6640a3286f497b38d2597e7d4dc178
2,388
// Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you under the Apache // License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation final class SettingsViewModel { // MARK: Properties var tracing: CellModel = .tracing var notifications: CellModel = .notifications var backgroundAppRefresh: CellModel = .backgroundAppRefresh var reset: String = AppStrings.Settings.resetLabel } extension SettingsViewModel { struct CellModel { let icon: String let description: String var state: String? let stateActive: String let stateInactive: String let accessibilityIdentifier: String? } } extension SettingsViewModel.CellModel { static let tracing = SettingsViewModel.CellModel( icon: "Icons_Settings_Risikoermittlung", description: AppStrings.Settings.tracingLabel, stateActive: AppStrings.Settings.trackingStatusActive, stateInactive: AppStrings.Settings.trackingStatusInactive, accessibilityIdentifier: AccessibilityIdentifiers.Settings.tracingLabel ) static let notifications = SettingsViewModel.CellModel( icon: "Icons_Settings_Mitteilungen", description: AppStrings.Settings.notificationLabel, stateActive: AppStrings.Settings.notificationStatusActive, stateInactive: AppStrings.Settings.notificationStatusInactive, accessibilityIdentifier: AccessibilityIdentifiers.Settings.notificationLabel ) static let backgroundAppRefresh = SettingsViewModel.CellModel( icon: "Icons_Settings_Hintergrundaktualisierung", description: AppStrings.Settings.backgroundAppRefreshLabel, stateActive: AppStrings.Settings.backgroundAppRefreshStatusActive, stateInactive: AppStrings.Settings.backgroundAppRefreshStatusInactive, accessibilityIdentifier: AccessibilityIdentifiers.Settings.backgroundAppRefreshLabel ) mutating func setState(state newState: Bool) { state = newState ? stateActive : stateInactive } }
35.117647
86
0.805276
03f96cebf2edf667868044e7da768a2f2c229e26
2,232
// // PanelConfiguration.swift // Panels-iOS // // Created by Antonio Casero on 10.08.18. // Copyright © 2018 Panels. All rights reserved. // import Foundation import UIKit public struct PanelConfiguration { /// Panel height public var panelSize: PanelDimensions /// Panel margins between the header and the next views. public var panelMargin: CGFloat /// Visible area when the panel is collapsed public var panelVisibleArea: CGFloat /// Safe area is avoided if this flag is true. public var useSafeArea = true /// Collapse and expand when tapping the header view. public var respondToTap = true /// Collapse and expand when dragging the header view. public var respondToDrag = true /// Collapse when tapping outside the panel public var closeOutsideTap = true /// Animate the panel when the superview is shown. public var animateEntry = false /// If parent view is a navigationcontroller child, this flag allow a better /// calculation when the panelSize is .fullScreen public var enclosedNavigationBar = true /// This value sets defines the height constraint public var heightConstant: CGFloat? // Animation duration when the panel is presented public var entryAnimationDuration: Double = 1.0 // Animation duration when the panel is dimissed public var dismissAnimationDuration: Double = 0.3 /// Observe keyboard events public var keyboardObserver = true public init(size: PanelDimensions = .thirdQuarter, margin: CGFloat = 8.0, visibleArea: CGFloat = 64.0) { panelSize = size panelMargin = margin panelVisibleArea = visibleArea } internal func size(for view: UIView) -> CGFloat { let delta: CGFloat = (panelSize == .fullScreen) ? 0 : 2 let screenSize = panelSize.translate(for: view, navController: enclosedNavigationBar) let size = useSafeArea ? screenSize + (UIApplication.safeAreaBottom() * delta) : screenSize return size } internal func visibleArea() -> CGFloat { let visible = panelVisibleArea + UIApplication.safeAreaBottom() + (panelMargin * 2) return visible } }
30.575342
99
0.685036
de66e69d8a224fe1c278dd042b02202006813115
1,956
// The MIT License (MIT) // // Copyright (c) 2015 Qvik (www.qvik.fi) // // 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 /** Contains utilities related to UIImageViews that require subclassing. */ open class QvikImageView: UIImageView { /// Callback to be called when bounds changes open var boundsChangedCallback: ((Void) -> Void)? /// Callback to be called when frame changes open var frameChangedCallback: ((Void) -> Void)? /// Captures changes to bounds and notifies a listener (if set) override open var bounds: CGRect { didSet { if oldValue != bounds { boundsChangedCallback?() } } } /// Captures changes to frame and notifies a listener (if set) override open var frame: CGRect { didSet { if oldValue != frame { frameChangedCallback?() } } } }
36.90566
81
0.687628
e08eeefd9612a7fca4faf44ead3c58e8735f9fa9
2,847
// // DescriptionSendCell.swift // breadwallet // // Created by Adrian Corscadden on 2016-12-16. // Copyright © 2016 breadwallet LLC. All rights reserved. // import UIKit class DescriptionSendCell : SendCell { init(placeholder: String) { super.init() textView.delegate = self textView.textColor = C.Colors.text textView.font = .customBody(size: 20.0) textView.returnKeyType = .done textView.keyboardAppearance = .dark self.placeholder.textColor = C.Colors.blueGrey self.placeholder.text = placeholder backgroundColor = .clear setupViews() } var didBeginEditing: (() -> Void)? var didReturn: ((UITextView) -> Void)? var didChange: ((String) -> Void)? var content: String? { didSet { textView.text = content textViewDidChange(textView) } } let textView = UITextView() fileprivate let placeholder = UILabel(font: .customBody(size: 16.0), color: C.Colors.lightText) private func setupViews() { textView.isScrollEnabled = false textView.backgroundColor = .clear addSubview(textView) textView.constrain([ textView.constraint(.leading, toView: self, constant: 11.0), textView.topAnchor.constraint(equalTo: topAnchor, constant: C.padding[2]), textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 30.0), textView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -C.padding[2]) ]) textView.addSubview(placeholder) placeholder.constrain([ placeholder.centerYAnchor.constraint(equalTo: textView.centerYAnchor), placeholder.leadingAnchor.constraint(equalTo: textView.leadingAnchor, constant: 5.0) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension DescriptionSendCell : UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { didBeginEditing?() } func textViewDidChange(_ textView: UITextView) { placeholder.isHidden = textView.text.utf8.count > 0 if let text = textView.text { didChange?(text) } } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else { textView.resignFirstResponder() return false } let count = (textView.text ?? "").utf8.count + text.utf8.count return count <= C.maxMemoLength } func textViewDidEndEditing(_ textView: UITextView) { didReturn?(textView) } }
31.988764
116
0.649456
7af497346a5db5cc0e2046174c9b4cc6979d64c8
885
// // FQLiveViewController.swift // FQDouYuSwift // // Created by apple-gaofangqiu on 2018/1/23. // Copyright © 2018年 apple-fangqiu. All rights reserved. // import UIKit class FQLiveViewController: FQBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.583333
106
0.677966
5df5abcee789d6b760bc8361b16c32b741c0a302
1,475
// // Element.swift // StripeiOS // // Created by Yuki Tokuhiro on 6/8/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import Foundation import UIKit // MARK: - Element /** Conform to this protocol to participate in the collection of details for a Payment/SetupIntent. Think of this as a light-weight, specialized view controller. */ protocol Element: AnyObject { /** Modify the params according to your input, or return nil if you are invalid. */ func updateParams(params: IntentConfirmParams) -> IntentConfirmParams? /** - Note: This is set by your parent. */ var delegate: ElementDelegate? { get set } /** Return your UIView instance. */ var view: UIView { get } /** - Returns: Whether or not this object is now the first-responder. */ func becomeResponder() -> Bool } extension Element { func becomeResponder() -> Bool { return view.becomeFirstResponder() } } // MARK: - ElementDelegate /** An Element uses this delegate to communicate events to its owner, which is typically also an Element. */ protocol ElementDelegate: AnyObject { /** This method is called whenever your public/internally visable state changes. */ func didUpdate(element: Element) /** This method is called when the user finishes editing the caller e.g., by pressing the 'return' key. */ func didFinishEditing(element: Element) }
23.412698
104
0.662373
d6441ad0212537fec720692becda1fd038bbeafc
1,540
import Foundation extension Selector { /// `self` as a pointer. It is uniqued across instances, similar to /// `StaticString`. var utf8Start: UnsafePointer<Int8> { return unsafeBitCast(self, to: UnsafePointer<Int8>.self) } /// An alias of `self`, used in method interception. var alias: Selector { return prefixed(with: "_cx_0_") } /// An alias of `self`, used in method interception specifically for /// preserving (if found) an immediate implementation of `self` in the /// runtime subclass. var interopAlias: Selector { return prefixed(with: "_cx_1_") } /// An alias of `self`, used for delegate proxies. var delegateProxyAlias: Selector { return prefixed(with: "_cx_2_") } private func prefixed(with prefix: StaticString) -> Selector { let length = Int(strlen(utf8Start)) let prefixedLength = length + prefix.utf8CodeUnitCount let prefixedStart = UnsafeRawPointer(prefix.utf8Start).assumingMemoryBound(to: Int8.self) let name = UnsafeMutablePointer<Int8>.allocate(capacity: prefixedLength + 1) defer { name.deinitialize(count: prefixedLength + 1) name.deallocate() } name.initialize(from: prefixedStart, count: prefix.utf8CodeUnitCount) (name + prefix.utf8CodeUnitCount).initialize(from: self.utf8Start, count: length) (name + prefixedLength).initialize(to: Int8(UInt8(ascii: "\0"))) return sel_registerName(name) } }
32.765957
97
0.656494
0e76ee926e5825d752a7b59a9ee2967852694672
1,083
// // AppDelegate.swift // picker-control // // Created by Gavin Wiggins on 11/24/19. // Copyright © 2019 Gavin Wiggins. All rights reserved. // import Cocoa import SwiftUI @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Create the window and set the content view. window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], backing: .buffered, defer: false) window.center() window.setFrameAutosaveName("Main Window") window.contentView = NSHostingView(rootView: contentView) window.makeKeyAndOrderFront(nil) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
27.075
95
0.6759
bb72168d6d23b3ee515f001dc2bb898dc6fef23f
2,492
import Cocoa public struct Blog { public let id: Int public let name: String public let url: URL public let followerCount: Int public let trackCount: Int public let imageURL: URL public let imageURLSmall: URL public let featured: Bool public let following: Bool public init( id: Int, name: String, url: URL, followerCount: Int, trackCount: Int, imageURL: URL, imageURLSmall: URL, featured: Bool, following: Bool ) { self.id = id self.name = name self.url = url self.followerCount = followerCount self.trackCount = trackCount self.imageURL = imageURL self.imageURLSmall = imageURLSmall self.featured = featured self.following = following } public var followerCountNum: NSNumber { NSNumber(value: followerCount) } public var trackCountNum: NSNumber { NSNumber(value: trackCount) } public func imageURL(size: ImageSize) -> URL { switch size { case .normal: return imageURL case .small: return imageURLSmall } } public enum ImageSize { case normal case small } } extension Blog: CustomStringConvertible { public var description: String { "Blog: { name: \(name) }" } } extension Blog: ResponseObjectSerializable, ResponseCollectionSerializable { public init?(response: HTTPURLResponse, representation: Any) { guard let representation = representation as? [String: Any], let id = representation["siteid"] as? Int, let name = representation["sitename"] as? String, let urlString = representation["siteurl"] as? String, let url = URL(string: urlString.replacingOccurrences(of: " ", with: "")), let followerCount = representation["followers"] as? Int, let trackCount = representation["total_tracks"] as? Int, let imageURLString = representation["blog_image"] as? String, let imageURL = URL(string: imageURLString), let imageURLSmallString = representation["blog_image_small"] as? String, let imageURLSmall = URL(string: imageURLSmallString) else { return nil } self.id = id self.name = name self.url = url self.followerCount = followerCount self.trackCount = trackCount self.imageURL = imageURL self.imageURLSmall = imageURLSmall self.featured = representation["ts_featured"] is Int self.following = representation["ts_loved_me"] is Int } } extension Blog: Equatable { public static func == (lhs: Blog, rhs: Blog) -> Bool { lhs.id == rhs.id } } extension Blog: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(name) } }
23.961538
76
0.717496
72124b430c9ccfbcc281942c9a148fd01da47078
522
// // ViewController.swift // AgoraIOS // // Created by [email protected] on 12/27/2016. // Copyright (c) 2016 [email protected]. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.88
80
0.67433
76bd54c60c34e851b694c36f8b9f6422dcad4d2f
16,935
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOConcurrencyHelpers /// `NonBlockingFileIO` is a helper that allows you to read files without blocking the calling thread. /// /// It is worth noting that `kqueue`, `epoll` or `poll` returning claiming a file is readable does not mean that the /// data is already available in the kernel's memory. In other words, a `read` from a file can still block even if /// reported as readable. This behaviour is also documented behaviour: /// /// - [`poll`](http://pubs.opengroup.org/onlinepubs/009695399/functions/poll.html): "Regular files shall always poll TRUE for reading and writing." /// - [`epoll`](http://man7.org/linux/man-pages/man7/epoll.7.html): "epoll is simply a faster poll(2), and can be used wherever the latter is used since it shares the same semantics." /// - [`kqueue`](https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2): "Returns when the file pointer is not at the end of file." /// /// `NonBlockingFileIO` helps to work around this issue by maintaining its own thread pool that is used to read the data /// from the files into memory. It will then hand the (in-memory) data back which makes it available without the possibility /// of blocking. public struct NonBlockingFileIO { /// The default and recommended size for `NonBlockingFileIO`'s thread pool. public static let defaultThreadPoolSize = 2 /// The default and recommended chunk size. public static let defaultChunkSize = 128*1024 /// `NonBlockingFileIO` errors. public enum Error: Swift.Error { /// `NonBlockingFileIO` is meant to be used with file descriptors that are set to the default (blocking) mode. /// It doesn't make sense to use it with a file descriptor where `O_NONBLOCK` is set therefore this error is /// raised when that was requested. case descriptorSetToNonBlocking } private let threadPool: NIOThreadPool /// Initialize a `NonBlockingFileIO` which uses the `BlockingIOThreadPool`. /// /// - parameters: /// - threadPool: The `BlockingIOThreadPool` that will be used for all the IO. public init(threadPool: NIOThreadPool) { self.threadPool = threadPool } /// Read a `FileRegion` in chunks of `chunkSize` bytes on `NonBlockingFileIO`'s private thread /// pool which is separate from any `EventLoop` thread. /// /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `fileRegion.readableBytes` is greater than /// zero and there are enough bytes available `chunkHandler` will be called `1 + |_ fileRegion.readableBytes / chunkSize _|` /// times, delivering `chunkSize` bytes each time. If less than `fileRegion.readableBytes` bytes can be read from the file, /// `chunkHandler` will be called less often with the last invocation possibly being of less than `chunkSize` bytes. /// /// The allocation and reading of a subsequent chunk will only be attempted when `chunkHandler` succeeds. /// /// - parameters: /// - fileRegion: The file region to read. /// - chunkSize: The size of the individual chunks to deliver. /// - allocator: A `ByteBufferAllocator` used to allocate space for the chunks. /// - eventLoop: The `EventLoop` to call `chunkHandler` on. /// - chunkHandler: Called for every chunk read. The next chunk will be read upon successful completion of the returned `EventLoopFuture`. If the returned `EventLoopFuture` fails, the overall operation is aborted. /// - returns: An `EventLoopFuture` which is the result of the overall operation. If either the reading of `fileHandle` or `chunkHandler` fails, the `EventLoopFuture` will fail too. If the reading of `fileHandle` as well as `chunkHandler` always succeeded, the `EventLoopFuture` will succeed too. public func readChunked(fileRegion: FileRegion, chunkSize: Int = NonBlockingFileIO.defaultChunkSize, allocator: ByteBufferAllocator, eventLoop: EventLoop, chunkHandler: @escaping (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> { do { let readableBytes = fileRegion.readableBytes try fileRegion.fileHandle.withUnsafeFileDescriptor { descriptor in _ = try Posix.lseek(descriptor: descriptor, offset: off_t(fileRegion.readerIndex), whence: SEEK_SET) } return self.readChunked(fileHandle: fileRegion.fileHandle, byteCount: readableBytes, chunkSize: chunkSize, allocator: allocator, eventLoop: eventLoop, chunkHandler: chunkHandler) } catch { return eventLoop.makeFailedFuture(error) } } /// Read `byteCount` bytes in chunks of `chunkSize` bytes from `fileHandle` in `NonBlockingFileIO`'s private thread /// pool which is separate from any `EventLoop` thread. /// /// `chunkHandler` will be called on `eventLoop` for every chunk that was read. Assuming `byteCount` is greater than /// zero and there are enough bytes available `chunkHandler` will be called `1 + |_ byteCount / chunkSize _|` /// times, delivering `chunkSize` bytes each time. If less than `byteCount` bytes can be read from `descriptor`, /// `chunkHandler` will be called less often with the last invocation possibly being of less than `chunkSize` bytes. /// /// The allocation and reading of a subsequent chunk will only be attempted when `chunkHandler` succeeds. /// /// - note: `readChunked(fileRegion:chunkSize:allocator:eventLoop:chunkHandler:)` should be preferred as it uses `FileRegion` object instead of raw `NIOFileHandle`s. /// /// - parameters: /// - fileHandle: The `NIOFileHandle` to read from. /// - byteCount: The number of bytes to read from `fileHandle`. /// - chunkSize: The size of the individual chunks to deliver. /// - allocator: A `ByteBufferAllocator` used to allocate space for the chunks. /// - eventLoop: The `EventLoop` to call `chunkHandler` on. /// - chunkHandler: Called for every chunk read. The next chunk will be read upon successful completion of the returned `EventLoopFuture`. If the returned `EventLoopFuture` fails, the overall operation is aborted. /// - returns: An `EventLoopFuture` which is the result of the overall operation. If either the reading of `fileHandle` or `chunkHandler` fails, the `EventLoopFuture` will fail too. If the reading of `fileHandle` as well as `chunkHandler` always succeeded, the `EventLoopFuture` will succeed too. public func readChunked(fileHandle: NIOFileHandle, byteCount: Int, chunkSize: Int = NonBlockingFileIO.defaultChunkSize, allocator: ByteBufferAllocator, eventLoop: EventLoop, chunkHandler: @escaping (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> { precondition(chunkSize > 0, "chunkSize must be > 0 (is \(chunkSize))") let remainingReads = 1 + (byteCount / chunkSize) let lastReadSize = byteCount % chunkSize func _read(remainingReads: Int) -> EventLoopFuture<Void> { if remainingReads > 1 || (remainingReads == 1 && lastReadSize > 0) { let readSize = remainingReads > 1 ? chunkSize : lastReadSize assert(readSize > 0) return self.read(fileHandle: fileHandle, byteCount: readSize, allocator: allocator, eventLoop: eventLoop).flatMap { buffer in chunkHandler(buffer).flatMap { () -> EventLoopFuture<Void> in eventLoop.assertInEventLoop() return _read(remainingReads: remainingReads - 1) } } } else { return eventLoop.makeSucceededFuture(()) } } return _read(remainingReads: remainingReads) } /// Read a `FileRegion` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread. /// /// The returned `ByteBuffer` will not have less than `fileRegion.readableBytes` unless we hit end-of-file in which /// case the `ByteBuffer` will contain the bytes available to read. /// /// - note: Only use this function for small enough `FileRegion`s as it will need to allocate enough memory to hold `fileRegion.readableBytes` bytes. /// - note: In most cases you should prefer one of the `readChunked` functions. /// /// - parameters: /// - fileRegion: The file region to read. /// - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`. /// - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from. /// - returns: An `EventLoopFuture` which delivers a `ByteBuffer` if the read was successful or a failure on error. public func read(fileRegion: FileRegion, allocator: ByteBufferAllocator, eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> { do { let readableBytes = fileRegion.readableBytes try fileRegion.fileHandle.withUnsafeFileDescriptor { descriptor in _ = try Posix.lseek(descriptor: descriptor, offset: off_t(fileRegion.readerIndex), whence: SEEK_SET) } return self.read(fileHandle: fileRegion.fileHandle, byteCount: readableBytes, allocator: allocator, eventLoop: eventLoop) } catch { return eventLoop.makeFailedFuture(error) } } /// Read `byteCount` bytes from `fileHandle` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread. /// /// The returned `ByteBuffer` will not have less than `byteCount` bytes unless we hit end-of-file in which /// case the `ByteBuffer` will contain the bytes available to read. /// /// - note: Only use this function for small enough `byteCount`s as it will need to allocate enough memory to hold `byteCount` bytes. /// - note: `read(fileRegion:allocator:eventLoop:)` should be preferred as it uses `FileRegion` object instead of raw `NIOFileHandle`s. /// /// - parameters: /// - fileHandle: The `NIOFileHandle` to read. /// - byteCount: The number of bytes to read from `fileHandle`. /// - allocator: A `ByteBufferAllocator` used to allocate space for the returned `ByteBuffer`. /// - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from. /// - returns: An `EventLoopFuture` which delivers a `ByteBuffer` if the read was successful or a failure on error. public func read(fileHandle: NIOFileHandle, byteCount: Int, allocator: ByteBufferAllocator, eventLoop: EventLoop) -> EventLoopFuture<ByteBuffer> { guard byteCount > 0 else { return eventLoop.makeSucceededFuture(allocator.buffer(capacity: 0)) } var buf = allocator.buffer(capacity: byteCount) return self.threadPool.runIfActive(eventLoop: eventLoop) { () -> ByteBuffer in var bytesRead = 0 while bytesRead < byteCount { let n = try buf.writeWithUnsafeMutableBytes(minimumWritableBytes: byteCount - bytesRead) { ptr in let res = try fileHandle.withUnsafeFileDescriptor { descriptor in try Posix.read(descriptor: descriptor, pointer: ptr.baseAddress!, size: byteCount - bytesRead) } switch res { case .processed(let n): assert(n >= 0, "read claims to have read a negative number of bytes \(n)") return n case .wouldBlock: throw Error.descriptorSetToNonBlocking } } if n == 0 { // EOF break } else { bytesRead += n } } return buf } } /// Write `buffer` to `fileHandle` in `NonBlockingFileIO`'s private thread pool which is separate from any `EventLoop` thread. /// /// - parameters: /// - fileHandle: The `NIOFileHandle` to write to. /// - buffer: The `ByteBuffer` to write. /// - eventLoop: The `EventLoop` to create the returned `EventLoopFuture` from. /// - returns: An `EventLoopFuture` which is fulfilled if the write was successful or fails on error. public func write(fileHandle: NIOFileHandle, buffer: ByteBuffer, eventLoop: EventLoop) -> EventLoopFuture<()> { var byteCount = buffer.readableBytes guard byteCount > 0 else { return eventLoop.makeSucceededFuture(()) } return self.threadPool.runIfActive(eventLoop: eventLoop) { var buf = buffer while byteCount > 0 { let n = try buf.readWithUnsafeReadableBytes { ptr in precondition(ptr.count == byteCount) let res = try fileHandle.withUnsafeFileDescriptor { descriptor in try Posix.write(descriptor: descriptor, pointer: ptr.baseAddress!, size: byteCount) } switch res { case .processed(let n): assert(n >= 0, "write claims to have written a negative number of bytes \(n)") return n case .wouldBlock: throw Error.descriptorSetToNonBlocking } } byteCount -= n } } } /// Open the file at `path` for reading on a private thread pool which is separate from any `EventLoop` thread. /// /// This function will return (a future) of the `NIOFileHandle` associated with the file opened and a `FileRegion` /// comprising of the whole file. The caller must close the returned `NIOFileHandle` when it's no longer needed. /// /// - note: The reason this returns the `NIOFileHandle` and the `FileRegion` is that both the opening of a file as well as the querying of its size are blocking. /// /// - parameters: /// - path: The path of the file to be opened for reading. /// - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire. /// - returns: An `EventLoopFuture` containing the `NIOFileHandle` and the `FileRegion` comprising the whole file. public func openFile(path: String, eventLoop: EventLoop) -> EventLoopFuture<(NIOFileHandle, FileRegion)> { return self.threadPool.runIfActive(eventLoop: eventLoop) { let fh = try NIOFileHandle(path: path) do { let fr = try FileRegion(fileHandle: fh) return (fh, fr) } catch { _ = try? fh.close() throw error } } } /// Open the file at `path` with specified access mode and POSIX flags on a private thread pool which is separate from any `EventLoop` thread. /// /// This function will return (a future) of the `NIOFileHandle` associated with the file opened. /// The caller must close the returned `NIOFileHandle` when it's no longer needed. /// /// - parameters: /// - path: The path of the file to be opened for writing. /// - mode: File access mode. /// - flags: Additional POSIX flags. /// - eventLoop: The `EventLoop` on which the returned `EventLoopFuture` will fire. /// - returns: An `EventLoopFuture` containing the `NIOFileHandle` and the `FileRegion` comprising the whole file. public func openFile(path: String, mode: NIOFileHandle.Mode, flags: NIOFileHandle.Flags = .default, eventLoop: EventLoop) -> EventLoopFuture<NIOFileHandle> { return self.threadPool.runIfActive(eventLoop: eventLoop) { return try NIOFileHandle(path: path, mode: mode, flags: flags) } } }
56.828859
300
0.62669
b96751a01119c496af70d97d22c36fc89764318e
339
// // TestHelper.swift // CacheTests // // Created by Nan Wang on 2017-12-01. // Copyright © 2017 NanTech. All rights reserved. // import Foundation public struct TestStruct: Codable { let name: String } public final class TestClass: Codable { let name: String init(name: String) { self.name = name } }
15.409091
50
0.640118
6189d10cbbbbb0e94ea6e85c7be2316d78d07445
116,956
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import CoreFoundation /// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary` /// containing `Encodable` values (in which case it should be exempt from key conversion strategies). /// fileprivate protocol _JSONStringDictionaryEncodableMarker { } extension Dictionary : _JSONStringDictionaryEncodableMarker where Key == String, Value: Encodable { } /// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary` /// containing `Decodable` values (in which case it should be exempt from key conversion strategies). /// /// The marker protocol also provides access to the type of the `Decodable` values, /// which is needed for the implementation of the key conversion strategy exemption. /// fileprivate protocol _JSONStringDictionaryDecodableMarker { static var elementType: Decodable.Type { get } } extension Dictionary : _JSONStringDictionaryDecodableMarker where Key == String, Value: Decodable { static var elementType: Decodable.Type { return Value.self } } //===----------------------------------------------------------------------===// // JSON Encoder //===----------------------------------------------------------------------===// /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON. open class JSONEncoder { // MARK: Options /// The formatting of the output JSON data. public struct OutputFormatting : OptionSet { /// The format's default value. public let rawValue: UInt /// Creates an OutputFormatting value with the given raw value. public init(rawValue: UInt) { self.rawValue = rawValue } /// Produce human-readable JSON with indented output. public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0) /// Produce JSON with dictionary keys sorted in lexicographic order. @available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static let sortedKeys = OutputFormatting(rawValue: 1 << 1) } /// The strategy to use for encoding `Date` values. public enum DateEncodingStrategy { /// Defer to `Date` for choosing an encoding. This is the default strategy. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a JSON number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncodingStrategy { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Encoder) throws -> Void) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatEncodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Encode the values using the given representation strings. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before encoding. public enum KeyEncodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload. /// /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt). /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from camel case to snake case: /// 1. Splits words at the boundary of lower-case to upper-case /// 2. Inserts `_` between words /// 3. Lowercases the entire string /// 4. Preserves starting and ending `_`. /// /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. /// /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. case convertToSnakeCase /// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types. /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the result. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } var words : [Range<String.Index>] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property // // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex // Find next uppercase character while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) { let untilUpperCase = wordStart..<upperCaseRange.lowerBound words.append(untilUpperCase) // Find next lowercase character searchRange = upperCaseRange.lowerBound..<searchRange.upperBound guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else { // There are no more lower case letters. Just end here. wordStart = searchRange.lowerBound break } // Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound) if lowerCaseRange.lowerBound == nextCharacterAfterCapital { // The next character after capital is a lower case character and therefore not a word boundary. // Continue searching for the next upper case for the boundary. wordStart = upperCaseRange.lowerBound } else { // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound..<beforeLowerIndex) // Next word starts at the capital before the lowercase we just found wordStart = beforeLowerIndex } searchRange = lowerCaseRange.upperBound..<searchRange.upperBound } words.append(wordStart..<searchRange.upperBound) let result = words.map({ (range) in return stringKey[range].lowercased() }).joined(separator: "_") return result } } /// The output format to produce. Defaults to `[]`. open var outputFormatting: OutputFormatting = [] /// The strategy to use in encoding dates. Defaults to `.deferredToDate`. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate /// The strategy to use in encoding binary data. Defaults to `.base64`. open var dataEncodingStrategy: DataEncodingStrategy = .base64 /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`. open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let dateEncodingStrategy: DateEncodingStrategy let dataEncodingStrategy: DataEncodingStrategy let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy let keyEncodingStrategy: KeyEncodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(dateEncodingStrategy: dateEncodingStrategy, dataEncodingStrategy: dataEncodingStrategy, nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy, keyEncodingStrategy: keyEncodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its JSON representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded JSON data. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<T : Encodable>(_ value: T) throws -> Data { let encoder = _JSONEncoder(options: self.options) guard let topLevel = try encoder.box_(value) else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } if topLevel is NSNull { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as null JSON fragment.")) } else if topLevel is NSNumber { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as number JSON fragment.")) } else if topLevel is NSString { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) encoded as string JSON fragment.")) } let writingOptions = JSONSerialization.WritingOptions(rawValue: self.outputFormatting.rawValue) do { return try JSONSerialization.data(withJSONObject: topLevel, options: writingOptions) } catch { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value to JSON.", underlyingError: error)) } } } // MARK: - _JSONEncoder fileprivate class _JSONEncoder : Encoder { // MARK: Properties /// The encoder's storage. fileprivate var storage: _JSONEncodingStorage /// Options set on the top-level encoder. fileprivate let options: JSONEncoder._Options /// The path to the current point in encoding. public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level encoder options. fileprivate init(options: JSONEncoder._Options, codingPath: [CodingKey] = []) { self.options = options self.storage = _JSONEncodingStorage() self.codingPath = codingPath } /// Returns whether a new element can be encoded at this coding path. /// /// `true` if an element has not yet been encoded at this coding path; `false` otherwise. fileprivate var canEncodeNewValue: Bool { // Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container). // At the same time, every time a container is requested, a new value gets pushed onto the storage stack. // If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition. // // This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path. // Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here). return self.storage.count == self.codingPath.count } // MARK: - Encoder Methods public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> { // If an existing keyed container was already requested, return that one. let topContainer: NSMutableDictionary if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushKeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableDictionary else { preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.") } topContainer = container } let container = _JSONKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer) return KeyedEncodingContainer(container) } public func unkeyedContainer() -> UnkeyedEncodingContainer { // If an existing unkeyed container was already requested, return that one. let topContainer: NSMutableArray if self.canEncodeNewValue { // We haven't yet pushed a container at this level; do so here. topContainer = self.storage.pushUnkeyedContainer() } else { guard let container = self.storage.containers.last as? NSMutableArray else { preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.") } topContainer = container } return _JSONUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer) } public func singleValueContainer() -> SingleValueEncodingContainer { return self } } // MARK: - Encoding Storage and Containers fileprivate struct _JSONEncodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, NSString, NSArray, NSDictionary). private(set) fileprivate var containers: [NSObject] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary { let dictionary = NSMutableDictionary() self.containers.append(dictionary) return dictionary } fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray { let array = NSMutableArray() self.containers.append(array) return array } fileprivate mutating func push(container: NSObject) { self.containers.append(container) } fileprivate mutating func popContainer() -> NSObject { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.popLast()! } } // MARK: - Encoding Containers fileprivate struct _JSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableDictionary /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - Coding Path Operations private func _converted(_ key: CodingKey) -> CodingKey { switch encoder.options.keyEncodingStrategy { case .useDefaultKeys: return key case .convertToSnakeCase: let newKeyString = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue) return _JSONKey(stringValue: newKeyString, intValue: key.intValue) case .custom(let converter): return converter(codingPath + [key]) } } // MARK: - KeyedEncodingContainerProtocol Methods public mutating func encodeNil(forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = NSNull() } public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: String, forKey key: Key) throws { self.container[_converted(key).stringValue._bridgeToObjectiveC()] = self.encoder.box(value) } public mutating func encode(_ value: Float, forKey key: Key) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) #else self.container[_converted(key).stringValue] = try self.encoder.box(value) #endif } public mutating func encode(_ value: Double, forKey key: Key) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) #else self.container[_converted(key).stringValue] = try self.encoder.box(value) #endif } public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = try self.encoder.box(value) #else self.container[_converted(key).stringValue] = try self.encoder.box(value) #endif } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let dictionary = NSMutableDictionary() #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = dictionary #else self.container[_converted(key).stringValue] = dictionary #endif self.codingPath.append(key) defer { self.codingPath.removeLast() } let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let array = NSMutableArray() #if DEPLOYMENT_RUNTIME_SWIFT self.container[_converted(key).stringValue._bridgeToObjectiveC()] = array #else self.container[_converted(key).stringValue] = array #endif self.codingPath.append(key) defer { self.codingPath.removeLast() } return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: _JSONKey.super, wrapping: self.container) } public mutating func superEncoder(forKey key: Key) -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container) } } fileprivate struct _JSONUnkeyedEncodingContainer : UnkeyedEncodingContainer { // MARK: Properties /// A reference to the encoder we're writing to. private let encoder: _JSONEncoder /// A reference to the container we're writing to. private let container: NSMutableArray /// The path of coding keys taken to get to this point in encoding. private(set) public var codingPath: [CodingKey] /// The number of elements encoded into the container. public var count: Int { return self.container.count } // MARK: - Initialization /// Initializes `self` with the given references. fileprivate init(referencing encoder: _JSONEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) { self.encoder = encoder self.codingPath = codingPath self.container = container } // MARK: - UnkeyedEncodingContainer Methods public mutating func encodeNil() throws { self.container.add(NSNull()) } public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) } public mutating func encode(_ value: Float) throws { // Since the float may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode(_ value: Double) throws { // Since the double may be invalid and throw, the coding path needs to contain this key. self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func encode<T : Encodable>(_ value: T) throws { self.encoder.codingPath.append(_JSONKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.container.add(try self.encoder.box(value)) } public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let dictionary = NSMutableDictionary() self.container.add(dictionary) let container = _JSONKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary) return KeyedEncodingContainer(container) } public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self.codingPath.append(_JSONKey(index: self.count)) defer { self.codingPath.removeLast() } let array = NSMutableArray() self.container.add(array) return _JSONUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array) } public mutating func superEncoder() -> Encoder { return _JSONReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container) } } extension _JSONEncoder : SingleValueEncodingContainer { // MARK: - SingleValueEncodingContainer Methods fileprivate func assertCanEncodeNewValue() { precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.") } public func encodeNil() throws { assertCanEncodeNewValue() self.storage.push(container: NSNull()) } public func encode(_ value: Bool) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Int64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt8) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt16) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt32) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: UInt64) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: String) throws { assertCanEncodeNewValue() self.storage.push(container: self.box(value)) } public func encode(_ value: Float) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode(_ value: Double) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } public func encode<T : Encodable>(_ value: T) throws { assertCanEncodeNewValue() try self.storage.push(container: self.box(value)) } } // MARK: - Concrete Value Representations extension _JSONEncoder { /// Returns the given value boxed in a container appropriate for pushing onto the container stack. fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) } fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) } fileprivate func box(_ float: Float) throws -> NSObject { guard !float.isInfinite && !float.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(float, at: codingPath) } if float == Float.infinity { return NSString(string: posInfString) } else if float == -Float.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: float) } fileprivate func box(_ double: Double) throws -> NSObject { guard !double.isInfinite && !double.isNaN else { guard case let .convertToString(positiveInfinity: posInfString, negativeInfinity: negInfString, nan: nanString) = self.options.nonConformingFloatEncodingStrategy else { throw EncodingError._invalidFloatingPointValue(double, at: codingPath) } if double == Double.infinity { return NSString(string: posInfString) } else if double == -Double.infinity { return NSString(string: negInfString) } else { return NSString(string: nanString) } } return NSNumber(value: double) } fileprivate func box(_ date: Date) throws -> NSObject { switch self.options.dateEncodingStrategy { case .deferredToDate: // Must be called with a surrounding with(pushedKey:) call. // Dates encode as single-value objects; this can't both throw and push a container, so no need to catch the error. try date.encode(to: self) return self.storage.popContainer() case .secondsSince1970: return NSNumber(value: date.timeIntervalSince1970) case .millisecondsSince1970: return NSNumber(value: 1000.0 * date.timeIntervalSince1970) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return NSString(string: _iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return NSString(string: formatter.string(from: date)) case .custom(let closure): let depth = self.storage.count do { try closure(date, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ data: Data) throws -> NSObject { switch self.options.dataEncodingStrategy { case .deferredToData: // Must be called with a surrounding with(pushedKey:) call. let depth = self.storage.count do { try data.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. // This shouldn't be possible for Data (which encodes as an array of bytes), but it can't hurt to catch a failure. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } return self.storage.popContainer() case .base64: return NSString(string: data.base64EncodedString()) case .custom(let closure): let depth = self.storage.count do { try closure(data, self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } guard self.storage.count > depth else { // The closure didn't encode anything. Return the default keyed container. return NSDictionary() } // We can pop because the closure encoded something. return self.storage.popContainer() } } fileprivate func box(_ dict: [String : Encodable]) throws -> NSObject? { let depth = self.storage.count let result = self.storage.pushKeyedContainer() do { for (key, value) in dict { self.codingPath.append(_JSONKey(stringValue: key, intValue: nil)) defer { self.codingPath.removeLast() } result[key] = try box(value) } } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } fileprivate func box(_ value: Encodable) throws -> NSObject { return try self.box_(value) ?? NSDictionary() } // This method is called "box_" instead of "box" to disambiguate it from the overloads. Because the return type here is different from all of the "box" overloads (and is more general), any "box" calls in here would call back into "box" recursively instead of calling the appropriate overload, which is not what we want. fileprivate func box_(_ value: Encodable) throws -> NSObject? { let type = Swift.type(of: value) #if DEPLOYMENT_RUNTIME_SWIFT if type == Date.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if type == Data.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if type == URL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if type == Decimal.self { // JSONSerialization can consume NSDecimalNumber values. return NSDecimalNumber(decimal: value as! Decimal) } else if value is _JSONStringDictionaryEncodableMarker { return try box(value as! [String : Encodable]) } #else if type == Date.self || type == NSDate.self { // Respect Date encoding strategy return try self.box((value as! Date)) } else if type == Data.self || type == NSData.self { // Respect Data encoding strategy return try self.box((value as! Data)) } else if type == URL.self || type == NSURL.self { // Encode URLs as single strings. return self.box((value as! URL).absoluteString) } else if type == Decimal.self { // JSONSerialization can consume NSDecimalNumber values. return NSDecimalNumber(decimal: value as! Decimal) } else if value is _JSONStringDictionaryEncodableMarker { return try box(value as! [String : Encodable]) } #endif // The value should request a container from the _JSONEncoder. let depth = self.storage.count do { try value.encode(to: self) } catch { // If the value pushed a container before throwing, pop it back off to restore state. if self.storage.count > depth { let _ = self.storage.popContainer() } throw error } // The top container should be a new container. guard self.storage.count > depth else { return nil } return self.storage.popContainer() } } // MARK: - _JSONReferencingEncoder /// _JSONReferencingEncoder is a special subclass of _JSONEncoder which has its own storage, but references the contents of a different encoder. /// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container). fileprivate class _JSONReferencingEncoder : _JSONEncoder { // MARK: Reference types. /// The type of container we're referencing. private enum Reference { /// Referencing a specific index in an array container. case array(NSMutableArray, Int) /// Referencing a specific key in a dictionary container. case dictionary(NSMutableDictionary, String) } // MARK: - Properties /// The encoder we're referencing. fileprivate let encoder: _JSONEncoder /// The container reference itself. private let reference: Reference // MARK: - Initialization /// Initializes `self` by referencing the given array container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, at index: Int, wrapping array: NSMutableArray) { self.encoder = encoder self.reference = .array(array, index) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(_JSONKey(index: index)) } /// Initializes `self` by referencing the given dictionary container in the given encoder. fileprivate init(referencing encoder: _JSONEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) { self.encoder = encoder self.reference = .dictionary(dictionary, key.stringValue) super.init(options: encoder.options, codingPath: encoder.codingPath) self.codingPath.append(key) } // MARK: - Coding Path Operations fileprivate override var canEncodeNewValue: Bool { // With a regular encoder, the storage and coding path grow together. // A referencing encoder, however, inherits its parents coding path, as well as the key it was created for. // We have to take this into account. return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1 } // MARK: - Deinitialization // Finalizes `self` by writing the contents of our storage to the referenced encoder's storage. deinit { let value: Any switch self.storage.count { case 0: value = NSDictionary() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } switch self.reference { case .array(let array, let index): array.insert(value, at: index) case .dictionary(let dictionary, let key): dictionary[NSString(string: key)] = value } } } //===----------------------------------------------------------------------===// // JSON Decoder //===----------------------------------------------------------------------===// /// `JSONDecoder` facilitates the decoding of JSON into semantic `Decodable` types. open class JSONDecoder { // MARK: Options /// The strategy to use for decoding `Date` values. public enum DateDecodingStrategy { /// Defer to `Date` for decoding. This is the default strategy. case deferredToDate /// Decode the `Date` as a UNIX timestamp from a JSON number. case secondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a JSON number. case millisecondsSince1970 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decode the `Date` as a string parsed by the given formatter. case formatted(DateFormatter) /// Decode the `Date` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Date) } /// The strategy to use for decoding `Data` values. public enum DataDecodingStrategy { /// Defer to `Data` for decoding. case deferredToData /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case base64 /// Decode the `Data` as a custom value decoded by the given closure. case custom((_ decoder: Decoder) throws -> Data) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatDecodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Decode the values from the given representation strings. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before decoding. public enum KeyDecodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "snake_case_keys" to "camelCaseKeys" before attempting to match a key with the one specified by each type. /// /// The conversion to upper case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from snake case to camel case: /// 1. Capitalizes the word starting after each `_` /// 2. Removes all `_` /// 3. Preserves starting and ending `_` (as these are often used to indicate private variables or other metadata). /// For example, `one_two_three` becomes `oneTwoThree`. `_one_two_three_` becomes `_oneTwoThree_`. /// /// - Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the `_` character. case convertFromSnakeCase /// Provide a custom conversion from the key in the encoded JSON to the keys specified by the decoded types. /// The full path to the current decoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before decoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the container for the type to decode from. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertFromSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } // Find the first non-underscore character guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else { // Reached the end without finding an _ return stringKey } // Find the last non-underscore character var lastNonUnderscore = stringKey.index(before: stringKey.endIndex) while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" { stringKey.formIndex(before: &lastNonUnderscore) } let keyRange = firstNonUnderscore...lastNonUnderscore let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex var components = stringKey[keyRange].split(separator: "_") let joinedString : String if components.count == 1 { // No underscores in key, leave the word as is - maybe already camel cased joinedString = String(stringKey[keyRange]) } else { joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined() } // Do a cheap isEmpty check before creating and appending potentially empty strings let result : String if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) { result = joinedString } else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) { // Both leading and trailing underscores result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange]) } else if (!leadingUnderscoreRange.isEmpty) { // Just leading result = String(stringKey[leadingUnderscoreRange]) + joinedString } else { // Just trailing result = joinedString + String(stringKey[trailingUnderscoreRange]) } return result } } /// The strategy to use in decoding dates. Defaults to `.deferredToDate`. open var dateDecodingStrategy: DateDecodingStrategy = .deferredToDate /// The strategy to use in decoding binary data. Defaults to `.base64`. open var dataDecodingStrategy: DataDecodingStrategy = .base64 /// The strategy to use in decoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy = .throw /// The strategy to use for decoding keys. Defaults to `.useDefaultKeys`. open var keyDecodingStrategy: KeyDecodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during decoding. open var userInfo: [CodingUserInfoKey : Any] = [:] /// Options set on the top-level encoder to pass down the decoding hierarchy. fileprivate struct _Options { let dateDecodingStrategy: DateDecodingStrategy let dataDecodingStrategy: DataDecodingStrategy let nonConformingFloatDecodingStrategy: NonConformingFloatDecodingStrategy let keyDecodingStrategy: KeyDecodingStrategy let userInfo: [CodingUserInfoKey : Any] } /// The options set on the top-level decoder. fileprivate var options: _Options { return _Options(dateDecodingStrategy: dateDecodingStrategy, dataDecodingStrategy: dataDecodingStrategy, nonConformingFloatDecodingStrategy: nonConformingFloatDecodingStrategy, keyDecodingStrategy: keyDecodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Decoder /// Initializes `self` with default strategies. public init() {} // MARK: - Decoding Values /// Decodes a top-level value of the given type from the given JSON representation. /// /// - parameter type: The type of the value to decode. /// - parameter data: The data to decode from. /// - returns: A value of the requested type. /// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON. /// - throws: An error if any value throws an error during decoding. open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T { let topLevel: Any do { topLevel = try JSONSerialization.jsonObject(with: data) } catch { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error)) } let decoder = _JSONDecoder(referencing: topLevel, options: self.options) guard let value = try decoder.unbox(topLevel, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value.")) } return value } } // MARK: - _JSONDecoder fileprivate class _JSONDecoder : Decoder { // MARK: Properties /// The decoder's storage. fileprivate var storage: _JSONDecodingStorage /// Options set on the top-level decoder. fileprivate let options: JSONDecoder._Options /// The path to the current point in encoding. fileprivate(set) public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: JSONDecoder._Options) { self.storage = _JSONDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer) } let container = _JSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.")) } guard let topContainer = self.storage.topContainer as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer) } return _JSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } } // MARK: - Decoding Storage fileprivate struct _JSONDecodingStorage { // MARK: Properties /// The container stack. /// Elements may be any one of the JSON types (NSNull, NSNumber, String, Array, [String : Any]). private(set) fileprivate var containers: [Any] = [] // MARK: - Initialization /// Initializes `self` with no containers. fileprivate init() {} // MARK: - Modifying the Stack fileprivate var count: Int { return self.containers.count } fileprivate var topContainer: Any { precondition(!self.containers.isEmpty, "Empty container stack.") return self.containers.last! } fileprivate mutating func push(container: Any) { self.containers.append(container) } fileprivate mutating func popContainer() { precondition(!self.containers.isEmpty, "Empty container stack.") self.containers.removeLast() } } // MARK: Decoding Containers fileprivate struct _JSONKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol { typealias Key = K // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [String : Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [String : Any]) { self.decoder = decoder switch decoder.options.keyDecodingStrategy { case .useDefaultKeys: self.container = container case .convertFromSnakeCase: // Convert the snake case keys in the container to camel case. // If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries. self.container = Dictionary(container.map { key, value in (JSONDecoder.KeyDecodingStrategy._convertFromSnakeCase(key), value) }, uniquingKeysWith: { (first, _) in first }) case .custom(let converter): self.container = Dictionary(container.map { key, value in (converter(decoder.codingPath + [_JSONKey(stringValue: key, intValue: nil)]).stringValue, value) }, uniquingKeysWith: { (first, _) in first }) } self.codingPath = decoder.codingPath } // MARK: - KeyedDecodingContainerProtocol Methods public var allKeys: [Key] { return self.container.keys.compactMap { Key(stringValue: $0) } } public func contains(_ key: Key) -> Bool { return self.container[key.stringValue] != nil } private func _errorDescription(of key: CodingKey) -> String { switch decoder.options.keyDecodingStrategy { case .convertFromSnakeCase: // In this case we can attempt to recover the original value by reversing the transform let original = key.stringValue let converted = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(original) if converted == original { return "\(key) (\"\(original)\")" } else { return "\(key) (\"\(original)\"), converted to \(converted)" } default: // Otherwise, just report the converted string return "\(key) (\"\(key.stringValue)\")" } } public func decodeNil(forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } return entry is NSNull } public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int.Type, forKey key: Key) throws -> Int { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Float.Type, forKey key: Key) throws -> Float { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: Double.Type, forKey key: Key) throws -> Double { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode(_ type: String.Type, forKey key: Key) throws -> String { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T { guard let entry = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(_errorDescription(of: key)).")) } self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = try self.decoder.unbox(entry, as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead.")) } return value } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get \(KeyedDecodingContainer<NestedKey>.self) -- no value found for key \(_errorDescription(of: key))")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = self.container[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get UnkeyedDecodingContainer -- no value found for key \(_errorDescription(of: key))")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } private func _superDecoder(forKey key: CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } let value: Any = self.container[key.stringValue] ?? NSNull() return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: _JSONKey.super) } public func superDecoder(forKey key: Key) throws -> Decoder { return try _superDecoder(forKey: key) } } fileprivate struct _JSONUnkeyedDecodingContainer : UnkeyedDecodingContainer { // MARK: Properties /// A reference to the decoder we're reading from. private let decoder: _JSONDecoder /// A reference to the container we're reading from. private let container: [Any] /// The path of coding keys taken to get to this point in decoding. private(set) public var codingPath: [CodingKey] /// The index of the element we're about to decode. private(set) public var currentIndex: Int // MARK: - Initialization /// Initializes `self` by referencing the given decoder and container. fileprivate init(referencing decoder: _JSONDecoder, wrapping container: [Any]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } // MARK: - UnkeyedDecodingContainer Methods public var count: Int? { return self.container.count } public var isAtEnd: Bool { return self.currentIndex >= self.count! } public mutating func decodeNil() throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } if self.container[self.currentIndex] is NSNull { self.currentIndex += 1 return true } else { return false } } public mutating func decode(_ type: Bool.Type) throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int.Type) throws -> Int { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int8.Type) throws -> Int8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int16.Type) throws -> Int16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int32.Type) throws -> Int32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Int64.Type) throws -> Int64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt.Type) throws -> UInt { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt8.Type) throws -> UInt8 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt16.Type) throws -> UInt16 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt32.Type) throws -> UInt32 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: UInt64.Type) throws -> UInt64 { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Float.Type) throws -> Float { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: Double.Type) throws -> Double { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode(_ type: String.Type) throws -> String { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end.")) } self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_JSONKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead.")) } self.currentIndex += 1 return decoded } public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let dictionary = value as? [String : Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value) } self.currentIndex += 1 let container = _JSONKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary) return KeyedDecodingContainer(container) } public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested keyed container -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] guard !(value is NSNull) else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.")) } guard let array = value as? [Any] else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value) } self.currentIndex += 1 return _JSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array) } public mutating func superDecoder() throws -> Decoder { self.decoder.codingPath.append(_JSONKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get superDecoder() -- unkeyed container is at end.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return _JSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options) } } extension _JSONDecoder : SingleValueDecodingContainer { // MARK: SingleValueDecodingContainer Methods private func expectNonNull<T>(_ type: T.Type) throws { guard !self.decodeNil() else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead.")) } } public func decodeNil() -> Bool { return self.storage.topContainer is NSNull } public func decode(_ type: Bool.Type) throws -> Bool { try expectNonNull(Bool.self) return try self.unbox(self.storage.topContainer, as: Bool.self)! } public func decode(_ type: Int.Type) throws -> Int { try expectNonNull(Int.self) return try self.unbox(self.storage.topContainer, as: Int.self)! } public func decode(_ type: Int8.Type) throws -> Int8 { try expectNonNull(Int8.self) return try self.unbox(self.storage.topContainer, as: Int8.self)! } public func decode(_ type: Int16.Type) throws -> Int16 { try expectNonNull(Int16.self) return try self.unbox(self.storage.topContainer, as: Int16.self)! } public func decode(_ type: Int32.Type) throws -> Int32 { try expectNonNull(Int32.self) return try self.unbox(self.storage.topContainer, as: Int32.self)! } public func decode(_ type: Int64.Type) throws -> Int64 { try expectNonNull(Int64.self) return try self.unbox(self.storage.topContainer, as: Int64.self)! } public func decode(_ type: UInt.Type) throws -> UInt { try expectNonNull(UInt.self) return try self.unbox(self.storage.topContainer, as: UInt.self)! } public func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNonNull(UInt8.self) return try self.unbox(self.storage.topContainer, as: UInt8.self)! } public func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNonNull(UInt16.self) return try self.unbox(self.storage.topContainer, as: UInt16.self)! } public func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNonNull(UInt32.self) return try self.unbox(self.storage.topContainer, as: UInt32.self)! } public func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNonNull(UInt64.self) return try self.unbox(self.storage.topContainer, as: UInt64.self)! } public func decode(_ type: Float.Type) throws -> Float { try expectNonNull(Float.self) return try self.unbox(self.storage.topContainer, as: Float.self)! } public func decode(_ type: Double.Type) throws -> Double { try expectNonNull(Double.self) return try self.unbox(self.storage.topContainer, as: Double.self)! } public func decode(_ type: String.Type) throws -> String { try expectNonNull(String.self) return try self.unbox(self.storage.topContainer, as: String.self)! } public func decode<T : Decodable>(_ type: T.Type) throws -> T { try expectNonNull(type) return try self.unbox(self.storage.topContainer, as: type)! } } // MARK: - Concrete Value Representations extension _JSONDecoder { /// Returns the given value unboxed from a container. fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? { guard !(value is NSNull) else { return nil } #if DEPLOYMENT_RUNTIME_SWIFT // Bridging differences require us to split implementations here guard let number = __SwiftValue.store(value) as? NSNumber else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } // TODO: Add a flag to coerce non-boolean numbers into Bools? guard number._cfTypeID == CFBooleanGetTypeID() else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return number.boolValue #else if let number = value as? NSNumber { // TODO: Add a flag to coerce non-boolean numbers into Bools? if number === kCFBooleanTrue as NSNumber { return true } else if number === kCFBooleanFalse as NSNumber { return false } /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let bool = value as? Bool { return bool */ } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) #endif } fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int = number.intValue guard NSNumber(value: int) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int } fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int8 = number.int8Value guard NSNumber(value: int8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int8 } fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int16 = number.int16Value guard NSNumber(value: int16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int16 } fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int32 = number.int32Value guard NSNumber(value: int32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int32 } fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let int64 = number.int64Value guard NSNumber(value: int64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return int64 } fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint = number.uintValue guard NSNumber(value: uint) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint } fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint8 = number.uint8Value guard NSNumber(value: uint8) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint8 } fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint16 = number.uint16Value guard NSNumber(value: uint16) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint16 } fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint32 = number.uint32Value guard NSNumber(value: uint32) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint32 } fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? { guard !(value is NSNull) else { return nil } guard let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let uint64 = number.uint64Value guard NSNumber(value: uint64) == number else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number <\(number)> does not fit in \(type).")) } return uint64 } fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? { guard !(value is NSNull) else { return nil } if let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are willing to return a Float by losing precision: // * If the original value was integral, // * and the integral value was > Float.greatestFiniteMagnitude, we will fail // * and the integral value was <= Float.greatestFiniteMagnitude, we are willing to lose precision past 2^24 // * If it was a Float, you will get back the precise value // * If it was a Double or Decimal, you will get back the nearest approximation if it will fit let double = number.doubleValue guard abs(double) <= Double(Float.greatestFiniteMagnitude) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed JSON number \(number) does not fit in \(type).")) } return Float(double) /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { if abs(double) <= Double(Float.max) { return Float(double) } overflow = true } else if let int = value as? Int { if let float = Float(exactly: int) { return float } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Float.infinity } else if string == negInfString { return -Float.infinity } else if string == nanString { return Float.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? { guard !(value is NSNull) else { return nil } if let number = __SwiftValue.store(value) as? NSNumber, number !== kCFBooleanTrue, number !== kCFBooleanFalse { // We are always willing to return the number as a Double: // * If the original value was integral, it is guaranteed to fit in a Double; we are willing to lose precision past 2^53 if you encoded a UInt64 but requested a Double // * If it was a Float or Double, you will get back the precise value // * If it was Decimal, you will get back the nearest approximation return number.doubleValue /* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested: } else if let double = value as? Double { return double } else if let int = value as? Int { if let double = Double(exactly: int) { return double } overflow = true */ } else if let string = value as? String, case .convertFromString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatDecodingStrategy { if string == posInfString { return Double.infinity } else if string == negInfString { return -Double.infinity } else if string == nanString { return Double.nan } } throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? { guard !(value is NSNull) else { return nil } guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } return string } fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? { guard !(value is NSNull) else { return nil } switch self.options.dateDecodingStrategy { case .deferredToDate: self.storage.push(container: value) defer { self.storage.popContainer() } return try Date(from: self) case .secondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double) case .millisecondsSince1970: let double = try self.unbox(value, as: Double.self)! return Date(timeIntervalSince1970: double / 1000.0) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let string = try self.unbox(value, as: String.self)! guard let date = _iso8601Formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected date string to be ISO8601-formatted.")) } return date } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): let string = try self.unbox(value, as: String.self)! guard let date = formatter.date(from: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Date string does not match format expected by formatter.")) } return date case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? { guard !(value is NSNull) else { return nil } switch self.options.dataDecodingStrategy { case .deferredToData: self.storage.push(container: value) defer { self.storage.popContainer() } return try Data(from: self) case .base64: guard let string = value as? String else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } guard let data = Data(base64Encoded: string) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Encountered Data is not valid Base64.")) } return data case .custom(let closure): self.storage.push(container: value) defer { self.storage.popContainer() } return try closure(self) } } fileprivate func unbox(_ value: Any, as type: Decimal.Type) throws -> Decimal? { guard !(value is NSNull) else { return nil } // Attempt to bridge from NSDecimalNumber. if let decimal = value as? Decimal { return decimal } else { let doubleValue = try self.unbox(value, as: Double.self)! return Decimal(doubleValue) } } fileprivate func unbox<T>(_ value: Any, as type: _JSONStringDictionaryDecodableMarker.Type) throws -> T? { guard !(value is NSNull) else { return nil } var result = [String : Any]() guard let dict = value as? NSDictionary else { throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value) } let elementType = type.elementType for (key, value) in dict { let key = key as! String self.codingPath.append(_JSONKey(stringValue: key, intValue: nil)) defer { self.codingPath.removeLast() } result[key] = try unbox_(value, as: elementType) } return result as? T } fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? { return try unbox_(value, as: type) as? T } fileprivate func unbox_(_ value: Any, as type: Decodable.Type) throws -> Any? { #if DEPLOYMENT_RUNTIME_SWIFT // Bridging differences require us to split implementations here if type == Date.self { guard let date = try self.unbox(value, as: Date.self) else { return nil } return date } else if type == Data.self { guard let data = try self.unbox(value, as: Data.self) else { return nil } return data } else if type == URL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } return url } else if type == Decimal.self { guard let decimal = try self.unbox(value, as: Decimal.self) else { return nil } return decimal } else if let stringKeyedDictType = type as? _JSONStringDictionaryDecodableMarker.Type { return try self.unbox(value, as: stringKeyedDictType) } else { self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) } #else if type == Date.self || type == NSDate.self { return try self.unbox(value, as: Date.self) } else if type == Data.self || type == NSData.self { return try self.unbox(value, as: Data.self) } else if type == URL.self || type == NSURL.self { guard let urlString = try self.unbox(value, as: String.self) else { return nil } guard let url = URL(string: urlString) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid URL string.")) } return url } else if type == Decimal.self || type == NSDecimalNumber.self { return try self.unbox(value, as: Decimal.self) } else if let stringKeyedDictType = type as? _JSONStringDictionaryDecodableMarker.Type { return try self.unbox(value, as: stringKeyedDictType) } else { self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) } #endif } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// fileprivate struct _JSONKey : CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } fileprivate init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } fileprivate static let `super` = _JSONKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Shared ISO8601 Date Formatter //===----------------------------------------------------------------------===// // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) fileprivate var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T : FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } }
45.402174
323
0.650561
c156ce4112a8127712e19079613e8946b7a02621
3,836
// // Router.swift // // Copyright (c) 2021 @mtzaquia // // 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 OSLog import UIKit /// A property wrapper for fetching ``Routing`` instances attached to a given controller or controller hierarchy. Similar to ``@EnvironemntObject`` on `SwiftUI`. /// /// Usage: /// ``` /// final class MyController: UIViewController { /// @Router var appRouter: AppRouter /// @Router(searchParents: false) var featureRouter: MyFeatureRouter /// /// func done() { /// featureRouter.go(to: .nextStep) /// } /// } /// ``` @propertyWrapper public struct Router<Routable> where Routable: Routing { public static subscript<T>(_enclosingInstance instance: T, wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, Routable>, storage storageKeyPath: ReferenceWritableKeyPath<T, Self>) -> Routable where T: UIViewController { get { var controller: UIViewController = instance let nameForLookup = instance[keyPath: storageKeyPath].nameForLookup let searchParents = instance[keyPath: storageKeyPath].searchParents while true { if let targetRouter = controller.routers[nameForLookup] as? Routable { Logger.highway.info("\(String(describing: targetRouter)) found on \(String(describing: instance)) hierarchy with name \(nameForLookup).") return targetRouter } else { guard let parent = controller.parent, searchParents else { break } controller = parent } } let type = String(describing: Routable.self) fatalError("No router of type \(type) found. A UIViewController.routing(_:) for \(type) may be missing for this controller or its parents.") } set {} } @available(*, unavailable) public var wrappedValue: Routable { get { fatalError() } set { fatalError() } } private var named: String? private var searchParents: Bool /// Declares a new ``Routing`` accessor in a given ``UIViewController``. /// - Parameters: /// - named: The name to be used for lookup. If not provided, the type of the router will be used as the name for lookup. /// - searchParents: A flag indicating if the routers should be searched for in parent controllers if not attached to the declaring controller. Defaults to `true`. public init(named: String? = nil, searchParents: Bool = true) { self.named = named self.searchParents = searchParents } private var nameForLookup: String { named ?? String(describing: Routable.self) } }
41.247312
169
0.657456
ff31402d928e8ac9d8c5170088e680967c3efd5b
1,743
// // TaskObject.swift // ThinkSNS + // // Created by GorCat on 2017/7/24. // Copyright © 2017年 ZhiYiCX. All rights reserved. // import UIKit import RealmSwift class TaskObject: Object { /// 唯一标识,请使用 TaskIdPrefix 作为 id 的前缀 dynamic var id = "" /// 任务的完成状态,0 进行中,1 已完成,2 未完成 dynamic var taskStatus = 2 // MARK: 附加参数 /// 任务将要执行的操作,一般用于任务具有两种状态时。例如 1/0 :收藏/取消收藏,点赞/取消点赞 let operation = RealmOptional<Int>() /// 设置主键 override static func primaryKey() -> String? { return "id" } /// 通过 task id 获取相关 id 信息 func getIdInfo1() -> Int { let ids = id.components(separatedBy: ".") let idInfo = Int(ids[3])! return idInfo } func getIdInfo2() -> (Int, Int) { let ids = id.components(separatedBy: ".") let idInfo1 = Int(ids[3])! let idInfo2 = Int(ids[4])! return(idInfo1, idInfo2) } func getIdInfo3() -> (Int, Int, Int) { let ids = id.components(separatedBy: ".") let idInfo1 = Int(ids[3])! let idInfo2 = Int(ids[4])! let idInfo3 = Int(ids[5])! return(idInfo1, idInfo2, idInfo3) } } enum TaskIdPrefix { // 圈子 enum Group: String { /// 帖子点赞 case postDigg = "task.group.post_digg" /// 收藏帖子 case postCollect = "task.group.post_collect" /// 加入/退出圈子 case joinGroup = "task.group.group_join" /// 删除帖子 case deletePost = "task.group.delete_post" /// 删除帖子评论 case deleteComment = "task.group.delete_comment" } // 广告 enum Advert: String { case update = "task.advert.update" } // 用户 enum User: String { case certificate = "task.user.certificate" } }
22.063291
56
0.560528
5d7aeaf49e615b37784fce84749fb3e9a4b70e30
896
// // ReusableComponent.swift // Soliu // // Created by JungpyoHong on 8/28/21. // import Foundation import UIKit enum ReusableComponent { static func alertMessage(title: String, message: String) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let alertAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(alertAction) return alert } static func addRadiusForView(_ view: UIView) { view.layer.cornerRadius = 5 view.layer.masksToBounds = true } static func addMoreRadiusForView(_ view: UIView) { view.layer.cornerRadius = 10 view.layer.masksToBounds = true } static func addRadiusForImage(_ view: UIView) { view.layer.cornerRadius = 10 view.layer.masksToBounds = true } }
26.352941
93
0.658482
fbaaba5379b7eb66ac2adfc83e6d3ed4a66e79b0
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d = [ { } var { var d { protocol a { class a { class case ,
17.923077
87
0.712446