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
d7e84aa1d02ab371d1d5293a356f560cd8af4600
1,519
//: Playground - noun: a place where people can play import Foundation /**二叉树的层次遍历 II 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其自底向上的层次遍历为: [ [15,7], [9,20], [3] ] */ public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { var levelArr = [[TreeNode]]() var level = [TreeNode]() level.append(root!) var result = [[Int]]() var levelNum = [Int]() levelNum.append(root!.val) while level.count != 0 { levelArr.insert(level, at: 0) result.insert(levelNum, at: 0) var nextLevel = [TreeNode]() var nextLevelNum = [Int]() for node in level { if node.left != nil { nextLevel.append(node.left!) nextLevelNum.append(node.left!.val) } if node.right != nil { nextLevel.append(node.right!) nextLevelNum.append(node.right!.val) } } level = nextLevel levelNum = nextLevelNum } return result } let tn = TreeNode(3) let tn1 = TreeNode(9) let tn2 = TreeNode(20) let tn3 = TreeNode(15) let tn4 = TreeNode(7) tn.left = tn1 tn.right = tn2 tn2.left = tn3 tn2.right = tn4 print(levelOrderBottom(tn))
19.986842
55
0.560895
ebd15a8c505e9ba33a4c55da515d28019e0b92a9
360
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing private let t: e = c> String { } private class B? = c>(n: Int = { x } typealias e = B<T -> ((v: A" protocol P { typealias e : AnyObject, e)(self
27.692308
87
0.686111
620c20ccac3449b1ec7d2e7b112477d133c4ae6d
1,502
// // UICollectionViewDemoUITests.swift // UICollectionViewDemoUITests // // Created by 王嘉宁 on 2020/8/12. // Copyright © 2020 Johnny. All rights reserved. // import XCTest class UICollectionViewDemoUITests: XCTestCase { override func setUpWithError() throws { // 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 tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // 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() throws { 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() } } } }
34.136364
182
0.667776
cc871b8339df1e4e0db25146c37cc92265ce6bc5
2,341
import UIKit internal final class UIImageViewEx : ExProtocol { public unowned let view: UIImageView public let url: URLImageProperty public var urlImageHandler: ((UIImage?) -> Void)? public var isURLLoadingHandler: ((Bool) -> Void)? public var showsURLSpinner: Bool = false public var spinner: UIActivityIndicatorView? public init(view: UIView) { self.view = view as! UIImageView self.url = URLImageProperty() url.isLoadingHandler = { [weak self] (isLoading) in guard let self = self else { return } if isLoading, self.showsURLSpinner { self.view.showSpinnerIfNeed(spinner: &self.spinner) } else { self.view.hideSpinner(spinner: &self.spinner) } self.isURLLoadingHandler?(isLoading) } url.imageHandler = { [weak self] (image) in guard let self = self else { return } self.view.image = image self.urlImageHandler?(image) } } } extension UIImageView { internal var ex: UIImageViewEx { return exImpl() } public var url: URL? { get { return ex.url.url } set { ex.url.url = newValue } } public var urlImage: UIImage? { get { return ex.url.image } set { ex.url.image = newValue } } public var urlImageHandler: ((UIImage?) -> Void)? { get { return ex.urlImageHandler } set { ex.urlImageHandler = newValue } } public var urlImageFilter: ((UIImage?) -> UIImage?)? { get { return ex.url.imageFilter } set { ex.url.imageFilter = newValue } } public var isURLLoading: Bool { get { return ex.url.isLoading } } public var isURLLoadingHandler: ((Bool) -> Void)? { get { return ex.isURLLoadingHandler } set { ex.isURLLoadingHandler = newValue } } @IBInspectable public var showsURLSpinner: Bool { get { return ex.showsURLSpinner } set { ex.showsURLSpinner = newValue } } public func renderURLImage() { ex.url.render() } public var mustStoreURLImageCache: Bool { get { return ex.url.mustStoreCache } set { ex.url.mustStoreCache = newValue } } }
28.204819
67
0.576677
69e606dffb10810f783a61a671b66fd0591e0182
1,436
// // MonthlyStatementReport.swift // AptoSDK // // Created by Takeichi Kanzaki on 20/09/2019. // import Foundation import SwiftyJSON public class MonthlyStatementReport: NSObject { @objc public let id: String @objc public let month: Int @objc public let year: Int @objc public let downloadUrl: String? @objc public let urlExpirationDate: Date? @objc public init(id: String, month: Int, year: Int, downloadUrl: String?, urlExpirationDate: Date?) { self.id = id self.month = month self.year = year self.downloadUrl = downloadUrl self.urlExpirationDate = urlExpirationDate super.init() } } extension JSON { var monthlyStatementReport: MonthlyStatementReport? { guard let id = self["id"].string, let month = self["month"].int, let year = self["year"].int else { ErrorLogger.defaultInstance().log(error: ServiceError(code: ServiceError.ErrorCodes.jsonError, reason: "Can't parse MonthlyStatementReport \(self)")) return nil } let downloadUrl = self["download_url"].string var urlExpirationDate: Date? if let urlExpiration = self["url_expiration"].string { urlExpirationDate = Date.dateFromISO8601(string: urlExpiration) } return MonthlyStatementReport(id: id, month: month, year: year, downloadUrl: downloadUrl, urlExpirationDate: urlExpirationDate) } }
32.636364
114
0.673398
f56554fda1c22cae8f78bd93df7085fd221956cd
9,831
// // LeftSideViewController.swift // Artfull // // Created by Joseph Kiley on 12/2/15. // Copyright © 2015 Joseph Kiley. All rights reserved. // import UIKit import Parse class LeftSideViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var menuItems:[String] = ["Explore Galleries", "Change Password"] @IBOutlet weak var userProfilePicture: UIImageView! @IBOutlet weak var userFullNameLabel: UILabel! @IBOutlet weak var SignOutButtonOutlet: UIButton! // SIGN OUT @IBAction func ButtonTapped(sender: AnyObject) { NSUserDefaults.standardUserDefaults().removeObjectForKey("user_name") NSUserDefaults.standardUserDefaults().synchronize() let spiningActivity = MBProgressHUD.showHUDAddedTo(self.view, animated: true) spiningActivity.labelText = "Signing Out" spiningActivity.detailsLabelText = "Please wait" PFUser.logOutInBackgroundWithBlock { (error:NSError?) -> Void in spiningActivity.hide(true) // Navigate to Protected page let mainStoryBoard:UIStoryboard = UIStoryboard(name:"Main", bundle:nil) let signInPage:ViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController let signInPageNav = UINavigationController(rootViewController:signInPage) let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.window?.rootViewController = signInPageNav } } // VIEW DID LOAD override func viewDidLoad() { super.viewDidLoad() // Hide Navigation Controller self.navigationController?.navigationBarHidden = true; userProfilePicture.layer.cornerRadius = userProfilePicture.frame.size.width / 2 userProfilePicture.layer.borderWidth = 2.0 userProfilePicture.clipsToBounds = true // Format with rounded corners SignOutButtonOutlet.layer.cornerRadius = 5 loadUserDetails() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let myCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) myCell.textLabel?.text = menuItems[indexPath.row] return myCell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch(indexPath.row) { case 0: // Open Gallery List let mainPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as! MainPageViewController let mainPageNav = UINavigationController(rootViewController: mainPageViewController) let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.drawerContainer!.centerViewController = mainPageNav appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) break // case 1: // // Open Event page // let eventPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("EventListViewController") as! ARTEventListViewController // let eventPageNav = UINavigationController(rootViewController: eventPageViewController) // let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // // appDelegate.drawerContainer!.centerViewController = eventPageNav // appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) // break // // case 2: // // Open Artist page // let artistPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ArtistListViewController") as! ARTArtistListsCollectionViewController // let artistPageNav = UINavigationController(rootViewController: artistPageViewController) // let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // // appDelegate.drawerContainer!.centerViewController = artistPageNav // appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) // break // // case 3: // // Open Art page // let artPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ArtListViewController") as! ARTArtListCollectionViewController // let artPageNav = UINavigationController(rootViewController: artPageViewController) // let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // // appDelegate.drawerContainer!.centerViewController = artPageNav // appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) // break // // case 4: // // Open Friends // let friendsPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("FriendsViewController") as! ARTFriendsTableViewController // let friendsPageNav = UINavigationController(rootViewController: friendsPageViewController) // let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // // appDelegate.drawerContainer!.centerViewController = friendsPageNav // appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) // break // // case 5: // // Open Settings // let settingsPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SettingsTableViewController") as! ARTSettingsTableViewController // let settingsPageNav = UINavigationController(rootViewController: settingsPageViewController) // let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // // appDelegate.drawerContainer!.centerViewController = settingsPageNav // appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) // break // case 5: // // Open About page // let aboutPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AboutViewController") as! ARTAboutViewController // let aboutPageNav = UINavigationController(rootViewController: aboutPageViewController) // let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // // appDelegate.drawerContainer!.centerViewController = aboutPageNav // appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) // break // case 6: // // Open Terms $ Conditions // let termsPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("TermsAndConditionsViewController") as! TermsAndConditionsViewController // let termsPageNav = UINavigationController(rootViewController: termsPageViewController) // let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // // appDelegate.drawerContainer!.centerViewController = termsPageNav // appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) // break default: print("Menu option not handled") } } // View Profile Button @IBAction func editButtonTapped(sender: AnyObject) { let editProfile = self.storyboard?.instantiateViewControllerWithIdentifier("EditProfileTableViewController") as! ARTEditProfileTableViewController //editProfile.opener = self let editProfileNav = UINavigationController(rootViewController: editProfile) self.presentViewController(editProfileNav, animated: true, completion: nil) } func loadUserDetails() { if(PFUser.currentUser() == nil) { return } let userFirstName = PFUser.currentUser()?.objectForKey("first_name") as? String if userFirstName == nil { return } let userLastName = PFUser.currentUser()?.objectForKey("last_name") as! String userFullNameLabel.text = userFirstName! + " " + userLastName let profilePictureObject = PFUser.currentUser()?.objectForKey("profile_picture") as? PFFile if(profilePictureObject != nil) { profilePictureObject!.getDataInBackgroundWithBlock { (imageData:NSData?, error:NSError?) -> Void in if(imageData != nil) { self.userProfilePicture.image = UIImage(data: imageData!) } } } } }
45.09633
185
0.646221
6901cb9a2829fa36e0f5164aa40abad9e4b99859
1,318
// // Stack_Overflow_TableView_1UITests.swift // Stack Overflow TableView 1UITests // // Created by Framework Access Point on 07/09/2018. // Copyright © 2018 Framework Central. All rights reserved. // import XCTest class Stack_Overflow_TableView_1UITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
35.621622
182
0.6783
fc69781152d92b30e01f8d9eb76bd7d505c89287
1,269
// MIT License // // Copyright (c) 2019 John Lima // // 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 BaseTrackingTests var tests = [XCTestCaseEntry]() tests += BaseTrackingTests.allTests() XCTMain(tests)
42.3
82
0.754925
0e9491449c526b97cc6d3147bb9a04eec6f5cfb3
1,794
import UIKit import AuthenticationServices @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { guard let userId = Keychain.shared.string(for: Constants.Keys.userId) else { performSignOut() return true } let appleIDProvider = ASAuthorizationAppleIDProvider() // Fast API to be called on app launch to handle log-in state appropriately. appleIDProvider.getCredentialState(forUserID: userId) { [weak self] (credentialState, error) in switch credentialState { case .authorized: break // The Apple ID credential is valid. case .revoked, .notFound: // Apple ID credential revoked // - or - // The Apple ID credential was not found. // // Show the sign-in UI. self?.performSignOut() default: break } } // Setup Revocation Listener let center = NotificationCenter.default let name = ASAuthorizationAppleIDProvider.credentialRevokedNotification center.addObserver(forName: name, object: nil, queue: nil) { [weak self] _ in DispatchQueue.main.async { [weak self] in guard self?.window?.rootViewController?.presentingViewController == nil else {return} self?.performSignOut() } } return true } private func performSignOut() { DispatchQueue.main.async { GlobalState.performSignOut() } } }
28.47619
145
0.600334
03dce86537cf07ed7506a52746269544040c4fdc
299
// // ConfigurableCell.swift // GenericDataSource // // Created by Andrea Prearo on 4/20/17. // Copyright © 2017 Andrea Prearo. All rights reserved. // import UIKit public protocol ConfigurableCell: ReusableCell { associatedtype T func configure(_ item: T, at indexPath: IndexPath) }
18.6875
56
0.719064
cc502efd568669a6c08afdaceacadb2a8eb843d4
2,186
// // AppDelegate.swift // YouTube // // Created by Haik Aslanyan on 6/16/16. // Copyright © 2016 Haik Aslanyan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func applicationDidReceiveMemoryWarning(_ application: UIApplication) { } }
45.541667
285
0.753888
621936994ac01c550ebf4dc24ee9845f748d6983
371
import Foundation extension Array { func at(index: Int?) -> Element? { if let index = index where index >= 0 && index < endIndex { return self[index] } else { return nil } } func random() -> Element? { var object: Element? if count > 0 { object = self[Int(arc4random_uniform(UInt32(count)))] } return object } }
16.130435
63
0.574124
0eaf96df8d0c04cd2f453cb9f7618752d57d85f0
2,465
// This file is generated. import XCTest #if canImport(MapboxMaps) @testable import MapboxMaps #else @testable import MapboxMapsStyle import Turf #endif class RasterDemSourceTests: XCTestCase { func testEncodingAndDecoding() { var source = RasterDemSource() source.url = String.testSourceValue() source.tiles = [String].testSourceValue() source.bounds = [Double].testSourceValue() source.minzoom = Double.testSourceValue() source.maxzoom = Double.testSourceValue() source.tileSize = Double.testSourceValue() source.attribution = String.testSourceValue() source.encoding = Encoding.testSourceValue() source.volatile = Bool.testSourceValue() source.prefetchZoomDelta = Double.testSourceValue() source.minimumTileUpdateInterval = Double.testSourceValue() source.maxOverscaleFactorForParentTiles = Double.testSourceValue() var data: Data? do { data = try JSONEncoder().encode(source) } catch { XCTFail("Failed to encode RasterDemSource.") } guard let validData = data else { XCTFail("Failed to encode RasterDemSource.") return } do { let decodedSource = try JSONDecoder().decode(RasterDemSource.self, from: validData) XCTAssert(decodedSource.type == SourceType.rasterDem) XCTAssert(decodedSource.url == String.testSourceValue()) XCTAssert(decodedSource.tiles == [String].testSourceValue()) XCTAssert(decodedSource.bounds == [Double].testSourceValue()) XCTAssert(decodedSource.minzoom == Double.testSourceValue()) XCTAssert(decodedSource.maxzoom == Double.testSourceValue()) XCTAssert(decodedSource.tileSize == Double.testSourceValue()) XCTAssert(decodedSource.attribution == String.testSourceValue()) XCTAssert(decodedSource.encoding == Encoding.testSourceValue()) XCTAssert(decodedSource.volatile == Bool.testSourceValue()) XCTAssert(decodedSource.prefetchZoomDelta == Double.testSourceValue()) XCTAssert(decodedSource.minimumTileUpdateInterval == Double.testSourceValue()) XCTAssert(decodedSource.maxOverscaleFactorForParentTiles == Double.testSourceValue()) } catch { XCTFail("Failed to decode RasterDemSource.") } } } // End of generated file
40.409836
97
0.668966
1aa5b25ab183e3251a913a3649a839c080bf2ac9
22,457
//===--- StringUTF16.swift ------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // FIXME(ABI): The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of UTF-16 code units. /// /// You can access a string's view of UTF-16 code units by using its `utf16` /// property. A string's UTF-16 view encodes the string's Unicode scalar /// values as 16-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf16 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 55357 /// // 56464 /// /// Unicode scalar values that make up a string's contents can be up to 21 /// bits long. The longer scalar values may need two `UInt16` values for /// storage. Those "pairs" of code units are called *surrogate pairs*. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf16 { /// print(v) /// } /// // 55357 /// // 56464 /// /// To convert a `String.UTF16View` instance back into a string, use the /// `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.utf16.index(where: { $0 >= 128 }) { /// let asciiPrefix = String(favemoji.utf16.prefix(upTo: i)) /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " /// /// UTF16View Elements Match NSString Characters /// ============================================ /// /// The UTF-16 code units of a string's `utf16` view match the elements /// accessed through indexed `NSString` APIs. /// /// print(flowers.utf16.count) /// // Prints "10" /// /// let nsflowers = flowers as NSString /// print(nsflowers.length) /// // Prints "10" /// /// Unlike `NSString`, however, `String.UTF16View` does not use integer /// indices. If you need to access a specific position in a UTF-16 view, use /// Swift's index manipulation methods. The following example accesses the /// fourth code unit in both the `flowers` and `nsflowers` strings: /// /// print(nsflowers.character(at: 3)) /// // Prints "119" /// /// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3) /// print(flowers.utf16[i]) /// // Prints "119" /// /// Although the Swift overlay updates many Objective-C methods to return /// native Swift indices and index ranges, some still return instances of /// `NSRange`. To convert an `NSRange` instance to a range of /// `String.UTF16View.Index`, follow these steps: /// /// 1. Use the `NSRange` type's `toRange` method to convert the instance to /// an optional range of `Int` values. /// 2. Use your string's `utf16` view's index manipulation methods to convert /// the integer bounds to `String.UTF16View.Index` values. /// 3. Create a new `Range` instance from the new index values. /// /// Here's an implementation of those steps, showing how to retrieve a /// substring described by an `NSRange` instance from the middle of a /// string. /// /// let snowy = "❄️ Let it snow! ☃️" /// let nsrange = NSRange(location: 3, length: 12) /// if let r = nsrange.toRange() { /// let start = snowy.utf16.index(snowy.utf16.startIndex, offsetBy: r.lowerBound) /// let end = snowy.utf16.index(snowy.utf16.startIndex, offsetBy: r.upperBound) /// let substringRange = start..<end /// print(snowy.utf16[substringRange]) /// } /// // Prints "Let it snow!" public struct UTF16View : BidirectionalCollection, CustomStringConvertible, CustomDebugStringConvertible { /// A position in a string's collection of UTF-16 code units. /// /// You can convert between indices of the different string views by using /// conversion initializers and the `samePosition(in:)` method overloads. /// For example, the following code sample finds the index of the first /// space in the string's character view and then converts that to the same /// position in the UTF-16 view. /// /// let hearts = "Hearts <3 ♥︎ 💘" /// if let i = hearts.characters.index(of: " ") { /// let j = i.samePosition(in: hearts.utf16) /// print(Array(hearts.utf16.suffix(from: j))) /// print(hearts.utf16.suffix(from: j)) /// } /// // Prints "[32, 60, 51, 32, 9829, 65038, 32, 55357, 56472]" /// // Prints " <3 ♥︎ 💘" public struct Index : Comparable { // Foundation needs access to these fields so it can expose // random access public // SPI(Foundation) init(_offset: Int) { self._offset = _offset } public let _offset: Int } public typealias IndexDistance = Int /// The position of the first code unit if the `String` is /// nonempty; identical to `endIndex` otherwise. public var startIndex: Index { return Index(_offset: 0) } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty UTF-16 view, `endIndex` is equal to `startIndex`. public var endIndex: Index { return Index(_offset: _length) } public struct Indices { internal var _elements: String.UTF16View internal var _startIndex: Index internal var _endIndex: Index } public var indices: Indices { return Indices( _elements: self, startIndex: startIndex, endIndex: endIndex) } // TODO: swift-3-indexing-model - add docs public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: range check i? return Index(_offset: _unsafePlus(i._offset, 1)) } // TODO: swift-3-indexing-model - add docs public func index(before i: Index) -> Index { // FIXME: swift-3-indexing-model: range check i? return Index(_offset: _unsafeMinus(i._offset, 1)) } // TODO: swift-3-indexing-model - add docs public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: range check i? return Index(_offset: i._offset.advanced(by: n)) } // TODO: swift-3-indexing-model - add docs public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: range check i? let d = i._offset.distance(to: limit._offset) if (d > 0) ? (d < n) : (d > n) { return nil } return Index(_offset: i._offset.advanced(by: n)) } // TODO: swift-3-indexing-model - add docs public func distance(from start: Index, to end: Index) -> IndexDistance { // FIXME: swift-3-indexing-model: range check start and end? return start._offset.distance(to: end._offset) } func _internalIndex(at i: Int) -> Int { return _core.startIndex + _offset + i } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-16 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf16.startIndex /// print("First character's UTF-16 code unit: \(greeting.utf16[i])") /// // Prints "First character's UTF-16 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` must be /// less than the view's end index. public subscript(i: Index) -> UTF16.CodeUnit { let position = i._offset _precondition(position >= 0 && position < _length, "out-of-range access on a UTF16View") let index = _internalIndex(at: position) let u = _core[index] if _fastPath((u >> 11) != 0b1101_1) { // Neither high-surrogate, nor low-surrogate -- well-formed sequence // of 1 code unit. return u } if (u >> 10) == 0b1101_10 { // `u` is a high-surrogate. Sequence is well-formed if it // is followed by a low-surrogate. if _fastPath( index + 1 < _core.count && (_core[index + 1] >> 10) == 0b1101_11) { return u } return 0xfffd } // `u` is a low-surrogate. Sequence is well-formed if // previous code unit is a high-surrogate. if _fastPath(index != 0 && (_core[index - 1] >> 10) == 0b1101_10) { return u } return 0xfffd } #if _runtime(_ObjC) // These may become less important once <rdar://problem/19255291> is addressed. @available( *, unavailable, message: "Indexing a String's UTF16View requires a String.UTF16View.Index, which can be constructed from Int when Foundation is imported") public subscript(i: Int) -> UTF16.CodeUnit { Builtin.unreachable() } @available( *, unavailable, message: "Slicing a String's UTF16View requires a Range<String.UTF16View.Index>, String.UTF16View.Index can be constructed from Int when Foundation is imported") public subscript(bounds: Range<Int>) -> UTF16View { Builtin.unreachable() } #endif /// Accesses the contiguous subrange of elements enclosed by the specified /// range. /// /// - Complexity: O(*n*) if the underlying string is bridged from /// Objective-C, where *n* is the length of the string; otherwise, O(1). public subscript(bounds: Range<Index>) -> UTF16View { return UTF16View( _core, offset: _internalIndex(at: bounds.lowerBound._offset), length: bounds.upperBound._offset - bounds.lowerBound._offset) } internal init(_ _core: _StringCore) { self._offset = 0 self._length = _core.count self._core = _core } internal init(_ _core: _StringCore, offset: Int, length: Int) { self._offset = offset self._length = length self._core = _core } public var description: String { let start = _internalIndex(at: 0) let end = _internalIndex(at: _length) return String(_core[start..<end]) } public var debugDescription: String { return "StringUTF16(\(self.description.debugDescription))" } internal var _offset: Int internal var _length: Int internal let _core: _StringCore } /// A UTF-16 encoding of `self`. public var utf16: UTF16View { get { return UTF16View(_core) } set { self = String(newValue) } } /// Creates a string corresponding to the given sequence of UTF-8 code units. /// /// If `utf16` contains unpaired UTF-16 surrogates, the result is `nil`. /// /// You can use this initializer to create a new string from a slice of /// another string's `utf16` view. /// /// let picnicGuest = "Deserving porcupine" /// if let i = picnicGuest.utf16.index(of: 32) { /// let adjective = String(picnicGuest.utf16.prefix(upTo: i)) /// print(adjective) /// } /// // Prints "Optional(Deserving)" /// /// The `adjective` constant is created by calling this initializer with a /// slice of the `picnicGuest.utf16` view. /// /// - Parameter utf16: A UTF-16 code sequence. public init?(_ utf16: UTF16View) { let wholeString = String(utf16._core) if let start = UTF16Index( _offset: utf16._offset ).samePosition(in: wholeString) { if let end = UTF16Index( _offset: utf16._offset + utf16._length ).samePosition(in: wholeString) { self = wholeString[start..<end] return } } return nil } /// The index type for subscripting a string's `utf16` view. public typealias UTF16Index = UTF16View.Index } // FIXME: swift-3-indexing-model: add complete set of forwards for Comparable // assuming String.UTF8View.Index continues to exist public func == ( lhs: String.UTF16View.Index, rhs: String.UTF16View.Index ) -> Bool { return lhs._offset == rhs._offset } public func < ( lhs: String.UTF16View.Index, rhs: String.UTF16View.Index ) -> Bool { return lhs._offset < rhs._offset } // Index conversions extension String.UTF16View.Index { /// Creates an index in the given UTF-16 view that corresponds exactly to the /// specified `UTF8View` position. /// /// The following example finds the position of a space in a string's `utf8` /// view and then converts that position to an index in the the string's /// `utf16` view. /// /// let cafe = "Café 🍵" /// /// let utf8Index = cafe.utf8.index(of: 32)! /// let utf16Index = String.UTF16View.Index(utf8Index, within: cafe.utf16)! /// /// print(cafe.utf16.prefix(upTo: utf16Index)) /// // Prints "Café" /// /// If the position passed as `utf8Index` doesn't have an exact corresponding /// position in `utf16`, the result of the initializer is `nil`. For /// example, because UTF-8 and UTF-16 represent high Unicode code points /// differently, an attempt to convert the position of a UTF-8 continuation /// byte fails. /// /// - Parameters: /// - utf8Index: A position in a `UTF8View` instance. `utf8Index` must be /// an element in `String(utf16).utf8.indices`. /// - utf16: The `UTF16View` in which to find the new position. public init?( _ utf8Index: String.UTF8Index, within utf16: String.UTF16View ) { let core = utf16._core _precondition( utf8Index._coreIndex >= 0 && utf8Index._coreIndex <= core.endIndex, "Invalid String.UTF8Index for this UTF-16 view") // Detect positions that have no corresponding index. if !utf8Index._isOnUnicodeScalarBoundary { return nil } _offset = utf8Index._coreIndex } /// Creates an index in the given UTF-16 view that corresponds exactly to the /// specified `UnicodeScalarView` position. /// /// The following example finds the position of a space in a string's `utf8` /// view and then converts that position to an index in the the string's /// `utf16` view. /// /// let cafe = "Café 🍵" /// /// let scalarIndex = cafe.unicodeScalars.index(of: "é")! /// let utf16Index = String.UTF16View.Index(scalarIndex, within: cafe.utf16) /// /// print(cafe.utf16.prefix(through: utf16Index)) /// // Prints "Café" /// /// - Parameters: /// - unicodeScalarIndex: A position in a `UnicodeScalarView` instance. /// `unicodeScalarIndex` must be an element in /// `String(utf16).unicodeScalarIndex.indices`. /// - utf16: The `UTF16View` in which to find the new position. public init( _ unicodeScalarIndex: String.UnicodeScalarIndex, within utf16: String.UTF16View) { _offset = unicodeScalarIndex._position } /// Creates an index in the given UTF-16 view that corresponds exactly to the /// specified `CharacterView` position. /// /// The following example finds the position of a space in a string's `characters` /// view and then converts that position to an index in the the string's /// `utf16` view. /// /// let cafe = "Café 🍵" /// /// let characterIndex = cafe.characters.index(of: "é")! /// let utf16Index = String.UTF16View.Index(characterIndex, within: cafe.utf16) /// /// print(cafe.utf16.prefix(through: utf16Index)) /// // Prints "Café" /// /// - Parameters: /// - characterIndex: A position in a `CharacterView` instance. /// `characterIndex` must be an element in /// `String(utf16).characters.indices`. /// - utf16: The `UTF16View` in which to find the new position. public init(_ characterIndex: String.Index, within utf16: String.UTF16View) { _offset = characterIndex._utf16Index } /// Returns the position in the given UTF-8 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf8).utf16`. /// /// This example first finds the position of a space (UTF-16 code point `32`) /// in a string's `utf16` view and then uses this method to find the same /// position in the string's `utf8` view. /// /// let cafe = "Café 🍵" /// let i = cafe.utf16.index(of: 32)! /// let j = i.samePosition(in: cafe.utf8)! /// print(Array(cafe.utf8.prefix(upTo: j))) /// // Prints "[67, 97, 102, 195, 169]" /// /// - Parameter utf8: The view to use for the index conversion. /// - Returns: The position in `utf8` that corresponds exactly to this index. /// If this index does not have an exact corresponding position in `utf8`, /// this method returns `nil`. For example, an attempt to convert the /// position of a UTF-16 trailing surrogate returns `nil`. public func samePosition( in utf8: String.UTF8View ) -> String.UTF8View.Index? { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in the given view of Unicode scalars that /// corresponds exactly to this index. /// /// This index must be a valid index of `String(unicodeScalars).utf16`. /// /// This example first finds the position of a space (UTF-16 code point `32`) /// in a string's `utf16` view and then uses this method to find the same /// position in the string's `unicodeScalars` view. /// /// let cafe = "Café 🍵" /// let i = cafe.utf16.index(of: 32)! /// let j = i.samePosition(in: cafe.unicodeScalars)! /// print(cafe.unicodeScalars.prefix(upTo: j)) /// // Prints "Café" /// /// - Parameter unicodeScalars: The view to use for the index conversion. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `unicodeScalars`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-16 trailing surrogate /// returns `nil`. public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarIndex? { return String.UnicodeScalarIndex(self, within: unicodeScalars) } /// Returns the position in the given string that corresponds exactly to this /// index. /// /// This index must be a valid index of `characters.utf16`. /// /// This example first finds the position of a space (UTF-16 code point `32`) /// in a string's `utf16` view and then uses this method find the same position /// in the string. /// /// let cafe = "Café 🍵" /// let i = cafe.utf16.index(of: 32)! /// let j = i.samePosition(in: cafe)! /// print(cafe[cafe.startIndex ..< j]) /// // Prints "Café" /// /// - Parameter characters: The string to use for the index conversion. /// - Returns: The position in `characters` that corresponds exactly to this /// index. If this index does not have an exact corresponding position in /// `characters`, this method returns `nil`. For example, an attempt to /// convert the position of a UTF-16 trailing surrogate returns `nil`. public func samePosition( in characters: String ) -> String.Index? { return String.Index(self, within: characters) } } // Reflection extension String.UTF16View : CustomReflectable { /// Returns a mirror that reflects the UTF-16 view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } extension String.UTF16View : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(description) } } extension String.UTF16View.Indices : BidirectionalCollection { public typealias Index = String.UTF16View.Index public typealias IndexDistance = String.UTF16View.IndexDistance public typealias Indices = String.UTF16View.Indices public typealias SubSequence = String.UTF16View.Indices internal init( _elements: String.UTF16View, startIndex: Index, endIndex: Index ) { self._elements = _elements self._startIndex = startIndex self._endIndex = endIndex } public var startIndex: Index { return _startIndex } public var endIndex: Index { return _endIndex } public var indices: Indices { return self } public subscript(i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return i } public subscript(bounds: Range<Index>) -> String.UTF16View.Indices { // FIXME: swift-3-indexing-model: range check. return String.UTF16View.Indices( _elements: _elements, startIndex: bounds.lowerBound, endIndex: bounds.upperBound) } public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _elements.index(after: i) } public func formIndex(after i: inout Index) { // FIXME: swift-3-indexing-model: range check. _elements.formIndex(after: &i) } public func index(before i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _elements.index(before: i) } public func formIndex(before i: inout Index) { // FIXME: swift-3-indexing-model: range check. _elements.formIndex(before: &i) } public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: range check i? return _elements.index(i, offsetBy: n) } public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: range check i? return _elements.index(i, offsetBy: n, limitedBy: limit) } // TODO: swift-3-indexing-model - add docs public func distance(from start: Index, to end: Index) -> IndexDistance { // FIXME: swift-3-indexing-model: range check start and end? return _elements.distance(from: start, to: end) } }
35.089063
167
0.631295
0ac499b1e90c9adb933de68d4871aa7fc63523c0
1,349
// // UIImage+Ex.swift // Pods // // Created by 杨建祥 on 2020/4/8. // import UIKit import QMUIKit public extension UIImage { fileprivate class func image(name: String) -> UIImage { var image = UIImage(named: name, in: Bundle.main, compatibleWith: nil) if image == nil { let bundle = Bundle(path: Bundle(module: "SWFrame")!.path(forResource: "SWFrame", ofType: "bundle")!) image = UIImage(named: name, in: bundle, compatibleWith: nil) } return image! } static var back: UIImage { return self.image(name: "back") } static var close: UIImage { return self.image(name: "close") } static var indicator: UIImage { return self.image(name: "indicator") } static var loading: UIImage { return self.image(name: "loading") } static var waiting: UIImage { return self.image(name: "waiting") } static var networkError: UIImage { return self.image(name: "errorNetwork") } static var serverError: UIImage { return self.image(name: "errorServer") } static var emptyError: UIImage { return self.image(name: "errorEmpty") } static var expireError: UIImage { return self.image(name: "errorExpire") } }
22.864407
113
0.581913
e4c1a361804e10561e288bba0411c449fc60c7a6
3,616
// // PasscodeLock.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import Foundation import LocalAuthentication open class PasscodeLock: PasscodeLockType { open weak var delegate: PasscodeLockTypeDelegate? public let configuration: PasscodeLockConfigurationType open var repository: PasscodeRepositoryType { return configuration.repository } open var state: PasscodeLockStateType { return lockState } open var isTouchIDAllowed: Bool { return isTouchIDEnabled() && configuration.isTouchIDAllowed && lockState.isTouchIDAllowed } fileprivate var lockState: PasscodeLockStateType open lazy var passcode = [String]() public init(state: PasscodeLockStateType, configuration: PasscodeLockConfigurationType) { precondition(configuration.passcodeLength > 0, "Passcode length sould be greather than zero.") self.lockState = state self.configuration = configuration } open func addSign(_ sign: String) { passcode.append(sign) delegate?.passcodeLock(self, addedSignAtIndex: passcode.count - 1) if passcode.count >= configuration.passcodeLength { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {[weak self] in if let weakSelf = self { weakSelf.lockState.acceptPasscode(weakSelf.passcode, fromLock: weakSelf) weakSelf.passcode.removeAll(keepingCapacity: true) } }) DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {[weak self] in if let weakSelf = self { weakSelf.delegate?.passcodeEntered(weakSelf, passcode:weakSelf.passcode.joined()) } }) } } open func clean() { guard passcode.count > 0 else { return } passcode = [] delegate?.passcodeLock(self, removedSignAtIndex: passcode.count) } open func removeSign() { guard passcode.count > 0 else { return } passcode.removeLast() delegate?.passcodeLock(self, removedSignAtIndex: passcode.count) } open func changeStateTo(_ state: PasscodeLockStateType) { DispatchQueue.main.async { self.lockState = state self.delegate?.passcodeLockDidChangeState(self) } } open func authenticateWithBiometrics() { guard isTouchIDAllowed else { return } let context = LAContext() let reason = localizedStringFor("PasscodeLockTouchIDReason", comment: "TouchID authentication reason") context.localizedFallbackTitle = localizedStringFor("PasscodeLockTouchIDButton", comment: "TouchID authentication fallback button") context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, error in self.handleTouchIDResult(success) } } fileprivate func handleTouchIDResult(_ success: Bool) { DispatchQueue.main.async { if success { self.delegate?.passcodeLockDidSucceed(self) } } } fileprivate func isTouchIDEnabled() -> Bool { let context = LAContext() return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } }
30.905983
139
0.618916
0e5ebf7d51daf9833269929ea6720f6b09999075
934
// // tipTests.swift // tipTests // // Created by Maria Cordero on 8/1/20. // Copyright © 2020 Maria Cordero. All rights reserved. // import XCTest @testable import tip class tipTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.685714
111
0.6606
f8fccc92195ff416f217c42ebceb004edffd2eaf
890
// // Copyright (c) Vatsal Manot // import Swift import SwiftUI /// A control which dismisses an active presentation when triggered. public struct DismissPresentationButton<Label: View>: View { private let label: Label private let action: (() -> ())? @Environment(\.presentationManager) private var presentationManager public init(action: (() -> ())? = nil, label: () -> Label) { self.action = action self.label = label() } public var body: some View { Button(action: dismiss, label: { label }) } public func dismiss() { action?() presentationManager.dismiss() } } #if !os(macOS) extension DismissPresentationButton where Label == Image { public init(action: (() -> ())? = nil) { self.init(action: action) { Image(systemName: .xCircleFill) } } } #endif
21.707317
71
0.596629
399a34b103c1daee4dd81a4ec8e16fab0dbed35c
2,630
// // MapViewController.swift // GetHomeSafe // // Created by Geonhyeong LIm on 2021/04/28. // import RIBs import RxSwift import RxCocoa import UIKit import NMapsMap import Combine final class MapViewController: UIViewController, MapViewControllable, NMFMapViewCameraDelegate { func popover(viewController: ViewControllable) { present(viewController.uiviewController, animated: true) } func dismiss(viewController: ViewControllable) { viewController.uiviewController.dismiss(animated: true) } init(viewModel: ViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) self.viewModel.view = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func show(floatingActionsView: ViewControllable) { addChild(floatingActionsView.uiviewController) view.addSubview(floatingActionsView.uiviewController.view) floatingActionsView.uiviewController.view.snp.makeConstraints { $0.bottom.equalTo(view.snp_bottom).inset(15) $0.width.equalTo(view.snp_width).inset(30) $0.centerX.equalTo(view.snp_centerX) } } override func viewDidLoad() { super.viewDidLoad() setupMap() } // MARK: - Private lazy var naverMapView = NMFNaverMapView(frame: view.frame) private lazy var locationControlView = NMFLocationButton() private(set) var viewModel: ViewModel private func setupMap() { viewModel.setupMap() view.addSubview(naverMapView) view.addSubview(locationControlView) locationControlView.mapView = naverMapView.mapView locationControlView.snp.makeConstraints { $0.bottom.equalTo(naverMapView.snp.bottom).inset(120) $0.left.equalTo(naverMapView.snp.left).inset(10) } naverMapView.mapView.positionMode = .compass naverMapView.mapView.logoAlign = .rightTop } func mapViewCameraIdle(_ mapView: NMFMapView) { viewModel.cameraLocationChanged() } } #if DEBUG import SwiftUI struct MapVCRepresentable: UIViewControllerRepresentable { func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { } @available(iOS 13.0.0, *) func makeUIViewController(context: Context) -> some UIViewController { MapViewController(viewModel: .init()) } } @available(iOS 13.0.0, *) struct Map_Previews: PreviewProvider { static var previews: some View { MapVCRepresentable() } } #endif
28.586957
96
0.68251
2fc404968d555bc05a94f7b1a5ac36cf6fc64474
2,716
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: View controller for the configuration screen. */ import UIKit import HealthKit class ConfigurationViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { // MARK: Properties var selectedActivityType: HKWorkoutActivityType var selectedLocationType: HKWorkoutSessionLocationType let activityTypes: [HKWorkoutActivityType] = [.walking, .running, .hiking] let locationTypes: [HKWorkoutSessionLocationType] = [.unknown, .indoor, .outdoor] // MARK: IBOutlets @IBOutlet var activityTypePicker: UIPickerView! @IBOutlet var locationTypePicker: UIPickerView! // MARK: Initialization required init?(coder: NSCoder) { selectedActivityType = activityTypes[0] selectedLocationType = locationTypes[0] super.init(coder: coder) } // MARK: UIPickerViewDataSource func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView == activityTypePicker { return activityTypes.count } else if pickerView == locationTypePicker { return locationTypes.count } return 0 } // MARK: UIPickerViewDelegate func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView == activityTypePicker { return format(activityType: activityTypes[row]) } else if pickerView == locationTypePicker { return format(locationType: locationTypes[row]) } return nil } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView == activityTypePicker { selectedActivityType = activityTypes[row] } else if pickerView == locationTypePicker { selectedLocationType = locationTypes[row] } } @IBAction func didTapStartButton() { let workoutConfiguration = HKWorkoutConfiguration() workoutConfiguration.activityType = selectedActivityType workoutConfiguration.locationType = selectedLocationType if let workoutViewController = storyboard?.instantiateViewController(withIdentifier: "WorkoutViewController") as? WorkoutViewController { workoutViewController.configuration = workoutConfiguration present(workoutViewController, animated: true, completion:nil) } } }
31.952941
145
0.684094
08298b107ce81cf4693e2e63deeb4b98a9aac9a2
8,269
// // PlaceDetailsPresenter.swift // Travelling // // Created by Dimitri Strauneanu on 08/10/2020. // Copyright (c) 2020 Travelling. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol PlaceDetailsPresentationLogic { func presentWillFetchPlace() func presentDidFetchPlace() func presentPlace(response: PlaceDetailsModels.PlacePresentation.Response) func presentResetPlace() func presentWillFetchImage(response: PlaceDetailsModels.ImageFetching.Response) func presentDidFetchImage(response: PlaceDetailsModels.ImageFetching.Response) func presentImage(response: PlaceDetailsModels.ImagePresentation.Response) func presentPlaceholderImage(response: PlaceDetailsModels.ImagePresentation.Response) func presentErrorState() func presentRemoveErrorState() func presentErrorAlert(response: PlaceDetailsModels.ErrorAlertPresentation.Response) func presentNavigateToFullscreenImage(response: PlaceDetailsModels.FullscreenImageNavigation.Response) func presentNavigateToPlaceComments(response: PlaceDetailsModels.PlaceCommentsNavigation.Response) func presentPlaceTitle(response: PlaceDetailsModels.TitlePresentation.Response) func presentSharePlace(response: PlaceDetailsModels.PlaceSharing.Response) } class PlaceDetailsPresenter: PlaceDetailsPresentationLogic { weak var displayer: PlaceDetailsDisplayLogic? var iso8601DateFormatter: ISO8601DateFormatter = ISO8601DateFormatter() var dateFormatter: DateFormatter = DateFormatter() init() { self.dateFormatter.dateStyle = .medium self.dateFormatter.timeStyle = .none } func presentWillFetchPlace() { self.displayer?.displayWillFetchPlace() } func presentDidFetchPlace() { self.displayer?.displayDidFetchPlace() } func presentPlace(response: PlaceDetailsModels.PlacePresentation.Response) { self.displayer?.displayPlace(viewModel: PlaceDetailsModels.PlacePresentation.ViewModel(items: self.displayedItems(place: response.place))) } func presentResetPlace() { self.displayer?.displayResetPlace() } func presentWillFetchImage(response: PlaceDetailsModels.ImageFetching.Response) { self.displayer?.displayWillFetchImage(viewModel: PlaceDetailsModels.ImageFetching.ViewModel(model: response.model)) } func presentDidFetchImage(response: PlaceDetailsModels.ImageFetching.Response) { self.displayer?.displayDidFetchImage(viewModel: PlaceDetailsModels.ImageFetching.ViewModel(model: response.model)) } func presentImage(response: PlaceDetailsModels.ImagePresentation.Response) { self.displayer?.displayImage(viewModel: PlaceDetailsModels.ImagePresentation.ViewModel(model: response.model, image: response.image, contentMode: .scaleAspectFill)) } func presentPlaceholderImage(response: PlaceDetailsModels.ImagePresentation.Response) { let image = PlaceDetailsStyle.shared.photoCellModel.imagePlaceholderImage self.displayer?.displayImage(viewModel: PlaceDetailsModels.ImagePresentation.ViewModel(model: response.model, image: image, contentMode: .center)) } func presentErrorState() { let image = PlaceDetailsStyle.shared.errorStateViewModel.image let text = PlaceDetailsLocalization.shared.errorStateText.attributed(attributes: PlaceDetailsStyle.shared.errorStateViewModel.textAttributes()) self.displayer?.displayErrorState(viewModel: PlaceDetailsModels.ErrorStatePresentation.ViewModel(image: image, text: text)) } func presentRemoveErrorState() { self.displayer?.displayRemoveErrorState() } func presentErrorAlert(response: PlaceDetailsModels.ErrorAlertPresentation.Response) { let message = PlaceDetailsLocalization.shared.errorAlertMessage let cancelTitle = PlaceDetailsLocalization.shared.errorAlertCancelTitle self.displayer?.displayErrorAlert(viewModel: PlaceDetailsModels.ErrorAlertPresentation.ViewModel(title: nil, message: message, cancelTitle: cancelTitle)) } func presentNavigateToFullscreenImage(response: PlaceDetailsModels.FullscreenImageNavigation.Response) { self.displayer?.displayNavigateToFullscreenImage(viewModel: PlaceDetailsModels.FullscreenImageNavigation.ViewModel(imageName: response.imageName)) } func presentNavigateToPlaceComments(response: PlaceDetailsModels.PlaceCommentsNavigation.Response) { self.displayer?.displayNavigateToPlaceComments(viewModel: PlaceDetailsModels.PlaceCommentsNavigation.ViewModel(placeId: response.placeId)) } func presentPlaceTitle(response: PlaceDetailsModels.TitlePresentation.Response) { let title = response.place?.name self.displayer?.displayPlaceTitle(viewModel: PlaceDetailsModels.TitlePresentation.ViewModel(title: title)) } func presentSharePlace(response: PlaceDetailsModels.PlaceSharing.Response) { let name = response.place?.name ?? "" let applicationName = Bundle.main.applicationName let url = BundleConfiguration.string(for: BundleConfiguration.Keys.appStoreUrl) let text = PlaceDetailsLocalization.shared.sharePlaceText(name: name, applicationName: applicationName, url: url) let excludedActivityTypes: [UIActivity.ActivityType] = [.print, .assignToContact, .saveToCameraRoll, .addToReadingList, .airDrop, .openInIBooks, .markupAsPDF] self.displayer?.displaySharePlace(viewModel: PlaceDetailsModels.PlaceSharing.ViewModel(text: text, excludedActivityTypes: excludedActivityTypes)) } } // MARK: - Displayed items extension PlaceDetailsPresenter { private func displayedItems(place: Place) -> [PlaceDetailsModels.DisplayedItem] { return [ self.displayedPhotoItem(place: place), self.displayedDescriptionItem(place: place), self.displayedCommentsItem(place: place) ] } private func displayedPhotoItem(place: Place) -> PlaceDetailsModels.DisplayedItem { let model = PlaceDetailsModels.PhotoModel() model.imageName = place.photo?.imageName model.imageDominantColor = place.photo?.imageDominantColor?.hexColor() ?? PlaceDetailsStyle.shared.photoCellModel.imageBackgroundColor return PlaceDetailsModels.DisplayedItem(type: .photo, model: model) } private func displayedDescriptionItem(place: Place) -> PlaceDetailsModels.DisplayedItem { let title = self.displayedTitle(place: place)?.attributed(attributes: PlaceDetailsStyle.shared.descriptionCellModel.titleAttributes()) let text = place.description?.attributed(attributes: PlaceDetailsStyle.shared.descriptionCellModel.textAttributes()) let model = PlaceDetailsModels.DescriptionModel(title: title, text: text) return PlaceDetailsModels.DisplayedItem(type: .description, model: model) } private func displayedTitle(place: Place) -> String? { guard let city = place.location.city, let country = place.location.country else { return nil } return String(format: "%@, %@", city, country) } private func displayedCommentsItem(place: Place) -> PlaceDetailsModels.DisplayedItem { let comments = PlaceDetailsLocalization.shared.commentCount(place.commentCount).attributed(attributes: PlaceDetailsStyle.shared.commentsCellModel.textAttributes()) let time = self.displayedTime(createdAt: place.createdAt)?.attributed(attributes: PlaceDetailsStyle.shared.commentsCellModel.textAttributes()) let model = PlaceDetailsModels.CommentsModel(comments: comments, time: time) return PlaceDetailsModels.DisplayedItem(type: .comments, model: model) } private func displayedTime(createdAt: String?) -> String? { guard let createdAt = createdAt else { return nil } guard let date = self.iso8601DateFormatter.date(from: createdAt) else { return nil } return self.dateFormatter.string(from: date) } }
48.356725
172
0.752207
e417c64a1fb2c0db4ec67d63589cb5b344dbc8ba
190
// // QuizCell.swift // Quizzes // // Created by Nathalie on 2/1/19. // Copyright © 2019 Alex Paul. All rights reserved. // import UIKit class QuizCell: UICollectionViewCell { }
13.571429
52
0.657895
2214cb6755f648117fee33dec90c129cf67044f5
1,557
//: Playground - noun: a place where people can play import UIKit /* Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. */ func createRandArray(size:Int, maxValue:UInt32) -> Array<Int> { var numberArray:Array<Int> = [] for _ in 1...size { numberArray.append(arc4random_uniform(maxValue).hashValue) } return numberArray.sorted() } func createSumArrayIndex(array:Array<Int>, target:Int) -> Array<Int> { var sumArray:Array<Int> = [] for n in 0...array.count - 1 { for i in n ... array.count - 1 { if (array[n] + array[i] == target) { sumArray.append(contentsOf: [n,i]) break } } if sumArray.count == 2 { break } } return sumArray } let target = 9 let numberArray = createRandArray(size: 10, maxValue: 10) print("The Original Array of \(numberArray.count) elements\n\(numberArray)") let SumArrayIndex = createSumArrayIndex(array: numberArray, target: target) if let first = SumArrayIndex.first,let last = SumArrayIndex.last { print("\nSolution in array for target: \(target)\n\(SumArrayIndex)\n\n \(numberArray[first])\n \(numberArray[last]) +\n-------\n \(target)") } else { print("\nNo solution in array for target: \(target)") }
28.309091
144
0.6307
16a2ff7c8a1a9cf26ad341d4b5986cf3ea1403ff
428
// // StringProtocol+Components.swift // // // Created by Christopher Weems on 9/30/21. // import Foundation extension StringProtocol { public func headTailSplit(separator: Character) -> (head: SubSequence, tail: SubSequence)? { let components = split(separator: separator, maxSplits: 1) guard components.count == 2 else { return nil } return (components[0], components[1]) } }
22.526316
96
0.651869
6901b833624896cb59bd6d0001c1fc2c6c639c91
1,271
import UIKit let image = UIImage(named: "forest.png")! let myRGBA = RGBAImage(image: image)! let x = 10 let y = 10 let index = y * myRGBA.width + x var pixel = myRGBA.pixels[index] pixel.red pixel.green pixel.blue pixel.red = 255 pixel.green = 0 pixel.blue = 0 myRGBA.pixels[index] = pixel let newImage = myRGBA.toUIImage()! /* var totalRed = 0 var totalGreen = 0 var totalBlue = 0 for y in 0..<myRGBA.height { for x in 0..<myRGBA.width { let index = y * myRGBA.width + x var pixel = myRGBA.pixels[index] totalRed += Int(pixel.red) totalGreen += Int(pixel.green) totalBlue += Int(pixel.blue) } } let count = myRGBA.width * myRGBA.height let avgRed = totalRed / count let avgGreen = totalGreen / count let avgBlue = totalBlue / count */ let avgRed = 133 let avgGreen = 123 let avgBlue = 77 for y in 0..<myRGBA.height { for x in 0..<myRGBA.width { let index = y * myRGBA.width + x var pixel = myRGBA.pixels[index] let redDiff = Int(pixel.red) - avgRed if redDiff > 0 { pixel.red = UInt8( max(0,min(255,avgRed+redDiff/5) ) ) myRGBA.pixels[index] = pixel } } } let newImage2 = myRGBA.toUIImage() image
18.157143
69
0.605822
1a9ecb77fdb7a8f61654e078e621999be1864870
1,675
// // Copyright (C) 2017-2021 HERE Europe B.V. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MSDKUI import UIKit final class ManeuverItemViewController: UIViewController { @IBOutlet private(set) var maneuverView: ManeuverItemView! override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let settingsViewController = segue.destination as? ManeuverItemSettingsViewController settingsViewController?.didSelect = { [weak self] item in self?.title = item.title self?.maneuverView.icon = item.configuration.icon self?.maneuverView.iconTintColor = item.configuration.iconTintColor self?.maneuverView.instructions = item.configuration.instructions self?.maneuverView.instructionsTextColor = item.configuration.instructionsTextColor self?.maneuverView.address = item.configuration.address self?.maneuverView.addressTextColor = item.configuration.addressTextColor self?.maneuverView.distance = item.configuration.distance self?.maneuverView.distanceTextColor = item.configuration.distanceTextColor } } }
41.875
95
0.730149
03c25f5b47cc98aacb6ec9ad249931f7587215e9
2,564
// // SceneDelegate.swift // SwiftVG // // Created by ben on 6/29/20. // Copyright © 2020 Stand Alone, Inc. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
39.446154
141
0.75663
fe9a2637dd3227f410a1cf9e7df6bd714b72156c
1,445
// // AppDelegate.swift // Prometheus // // Created by PAN Weiheng on 2020/7/7. // Copyright © 2020 PAN Weiheng. Please refer to LICENSE for license information. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
38.026316
179
0.749481
c11cc7733389aea2b4dae2246d20301771160b52
16,418
// // MakeTableViewController.swift // myFitz // // Created by Andre Villanueva on 1/21/15. // Copyright (c) 2015 BangBangStudios. All rights reserved. // import UIKit import CoreData //import Crashlytics // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } //MARK: -MakeTableViewController Class class MakeTableViewController: UITableViewController{ //MARK: -Outlets @IBOutlet weak var TypeBarButtonLabel: UIBarButtonItem! //MARK: - Variables ///items in a dictionary of arrays holds the categories of the items @objc var keyOfSelectedArray = [String]() @objc var indexReference: [String: Int] = [:] ///Dictionary path to item @objc var path: [String: String]! = [String: String]() //Core Data @objc let context = DataBaseController.getContext() // var items: [Item]? = nil @objc var wardrobe: Wardrobe? = nil @objc var items: [Item]? = nil @objc var fetchRequestController: NSFetchedResultsController = NSFetchedResultsController<NSFetchRequestResult>() @objc func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>{ log.verbose(#function) let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Item") let categorySorter = NSSortDescriptor(key: "category", ascending: true) let nameSorter = NSSortDescriptor(key: "model", ascending: true) let favoritesSorter = NSSortDescriptor(key: "isFavorite", ascending: true) fetchRequest.sortDescriptors = [nameSorter, favoritesSorter, categorySorter] // let wardrobePredicate = NSPredicate(format: "self.wardrobe = %@", wardrobe!) // let categoryPredicates = return fetchRequest } @objc func getFRC() -> NSFetchedResultsController<NSFetchRequestResult>{ log.verbose(#function) fetchRequestController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) return fetchRequestController } //MARK: -View Methods override func viewDidLoad(){ log.verbose(#function) super.viewDidLoad() self.view.backgroundColor = SiliverSilkSheet self.initializeFetchedResultsController() self.setUpTypes() // self.setUPSearchBar() // defaults.addAndSend("MAKE_PAGE_COUNT") //self.logPageView() tableView.delegate = self tableView.dataSource = self // self.setUpSearchBar() } override func viewDidAppear(_ animated: Bool){ log.verbose(#function) tableView.reloadData() } override func didReceiveMemoryWarning(){ log.verbose(#function) super.didReceiveMemoryWarning() log.warning("Recieved Memory Warning") } override func prepare(for segue: UIStoryboardSegue, sender: Any?){ log.verbose(#function) defer{ log.debug("Segue transfer: \(String(describing: segue.identifier))") } if segue.identifier == Segue.SEGUE_MAKE_TO_MODEL{ // let index = self.tableView.indexPathForSelectedRow let modelController = segue.destination as! ModelTableViewController modelController.path = self.path }else if segue.identifier == Segue.SEGUE_MAKE_TO_CREATION{ let createItemViewController: CreateItemViewController! = segue.destination as! CreateItemViewController createItemViewController.lastVCSegue = Segue.SEGUE_CREATION_TO_MAKE }else if segue.identifier == Segue.SEGUE_MAKE_TO_SELECTION{ let selectionViewController = segue.destination as! SelectionViewController selectionViewController.wardrobe = self.wardrobe } } deinit{ log.verbose(#function) } } //MARK: - Core Data extension MakeTableViewController: NSFetchedResultsControllerDelegate{ @objc func initializeFetchedResultsController() { log.verbose(#function) fetchRequestController = getFRC() fetchRequestController.delegate = self do{ try fetchRequestController.performFetch() }catch{ log.error("Fetch Failed") } //User // let fetchRequestUser:NSFetchRequest<User> = User.fetchRequest() // do{ // let fetchedUsers = try DataBaseController.getContext().fetch(fetchRequestUser) // log.debug("Users Count: \(fetchedUsers.count)") // if fetchedUsers.count < 1{ // user = NSEntityDescription.insertNewObject(forEntityName: myfitzEntities.Item, into: context) as! Item // user?.name = "User1" //// user?.wardrobe = Wardrobe() //// user?.wardrobe?.items = [] //// // DataBaseController.saveContext() // }else{ // user = fetchedUsers.first! // } // // }catch{ // log.error("Fetch Failed") // } // // let fetchRequestWardrobe:NSFetchRequest<Item> = Item.fetchRequest() // do{ // let fetchedWardrobes = try DataBaseController.getContext().fetch(fetchRequestWardrobe) // log.debug("Search Results Count: \(fetchedWardrobes.count)") // // if fetchedWardrobes.count < 1{ // let wardrobe = NSEntityDescription.insertNewObject(forEntityName: myfitzEntities.wardrobe, into: context) as! Wardrobe // user?.wardrobe = wardrobe // user?.wardrobe?.isBoy = true // user?.wardrobe?.items = [] // }else{ // user?.wardrobe = fetchedWardrobes.first // } // // }catch{ // log.error("Fetch Failed") // } // // let item = NSEntityDescription.insertNewObject(forEntityName: myfitzEntities.item, into: context) as! Item // // // item.brand = "Brand" // item.category = "Category" // item.subCategory = "Sub-Category" // item.index = 25 // // user?.wardrobe?.addToItems(item) // // do{ // try context.save() // log.verbose("User: \(user)\nWardrobe: \(user?.wardrobe!)\nItems Count: \(user?.wardrobe?.items?.count)\nItems: \(user?.wardrobe?.items)") // }catch{ // log.error("item saved failed") // } // // let fetchRequestItems:NSFetchRequest<Item> = Item.fetchRequest() // log.debug(user?.wardrobe?.items) tableView.reloadData() // // // do{ // items = try context.fetch(Item.fetchRequest()) // log.debug(items) // log.debug("Items Count: \(items.count)") // }catch{ // log.error("Fetch Failed") // } // // // // // // // // let fetchRequestItem:NSFetchRequest<Item> = Item.fetchRequest() // do{ // let searchResults = try DataBaseController.getContext().fetch(fetchRequestItem) // log.debug("Search Results Count: \(searchResults.count)") // // for result in searchResults { // log.debug("\(result.category!) - \(result.subCategory!) favorited: \(result.isFavorite)") // } // }catch{ // log.error("Fetch Failed") // } } } //MARK: - Action-MakeTableViewController Extension extension MakeTableViewController{ @IBAction func backButtonPressed(_ sender: UIBarButtonItem) { log.verbose(#function) // playSoundEffects(backSFX) performSegue(withIdentifier: Segue.SEGUE_MAKE_TO_SELECTION, sender: self) } } //MARK: - Initializer Created Methods extension MakeTableViewController{ @objc func setUpTypes(){ log.verbose(#function) self.animateAllButtons() // self.itemsInArrayInDictionary = Users_Wardrobe.selectedCloset[path[PathType.PATHTYPE_CATEGORY_STRING]!] self.setTitle() }//Sets up @objc func selection(){ TypeBarButtonLabel.title = path[PathType.PATHTYPE_CATEGORY_STRING]! } @objc func setTitle(){ log.verbose(#function) //self.title = grabTitle(Users_Wardrobe.closetSelectionString, view: PathType.PATHTYPE_CATEGORY_STRING) if self.title == MY_CLOSET{ self.navigationController?.navigationBar.tintColor = MY_CLOSET_BAR_COLOR }else if self.title == MY_WANTS_CLOSET{ self.navigationController?.navigationBar.tintColor = MY_WANTS_CLOSET_BAR_COLOR } self.navigationController?.navigationBar.isTranslucent = false } } //MARK: -TableView Methods-MakeTableViewController Extension extension MakeTableViewController:UIAlertViewDelegate{ override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ log.verbose(#function) let count = fetchRequestController.sections?[section].numberOfObjects return count! }//Returns Int for number of sections in tableView override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ log.verbose(#function) let cell: MakeCustomCell = (tableView.dequeueReusableCell(withIdentifier: CellIdentifier.MAKE_CELL) as? MakeCustomCell)! if indexPath.row % 2 == 0//If even number make this color { cell.backgroundColor = UIColor(patternImage: UIImage(named: CELL_BACKGROUND_IMAGE_MAKE)!) }else{ cell.backgroundColor = UIColor(patternImage: UIImage(named: CELL_BACKGROUND_IMAGE_MAKE)!) } let itemCell = fetchRequestController.object(at: indexPath) as! Item let image = UIImage(named: "blank image") cell.setCell(image!, makeLabelText: itemCell.brand ?? "N/A", numberOfItemsText: 0) return cell }//Returns a tableView cell at a specific row override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath){ log.verbose(#function) if editingStyle == UITableViewCellEditingStyle.delete { let alert = UIAlertController(title: "Alert!", message:"Are you sure you want to delete", preferredStyle: .alert) let act = UIAlertAction(title: "cancel", style: .default){_ in} let action = UIAlertAction(title: "Delete", style: .destructive) { _ in let item = self.fetchRequestController.object(at: (indexPath)) self.context.delete(item as! NSManagedObject) do{ try self.context.save() }catch{ log.error("Deleted item failed") } self.tableView.reloadData() } alert.addAction(action) alert.addAction(act) self.present(alert, animated: true, completion: {}) } }//Editing to delete row override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{ log.verbose(#function) //TODO: - Fix Me return String()//String(path[PathType.PATHTYPE_CATEGORY_STRING]! + ": " + "\(self.itemsInArrayInDictionary.count)") }//Category name is shown in the title header override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { log.verbose(#function) view.tintColor = LeatherTexture let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView headerView.textLabel?.textColor = Gold } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ log.verbose(#function) self.tableView.deselectRow(at: indexPath, animated: true) // let arrayItemCell: [Item] = Array(self.itemsInArrayInDictionary.values)[indexPath.row] // let keyOfSelectedArray = Array(self.itemsInArrayInDictionary.keys)[indexPath.row] // path[PathType.PATHTYPE_SUBCATEGORY_STRING] = keyOfSelectedArray playSoundEffects(itemSelectSFX) performSegue(withIdentifier: Segue.SEGUE_MAKE_TO_MODEL, sender: self) }//Shows when a cell at row was selected // override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { // return 200 // }//Xcode bug hack that lets cell autosize properly } //MARK: - UI-ModelTableViewController Extension extension MakeTableViewController{ @objc func animateAllButtons(){ log.verbose(#function) // self.animateSearchButton() // self.animateStarButton() // self.animateHamperButton() // self.animateSearchButton() // self.animatePictureLabels() // self.animatePictureImages() // self.animateNumberLabels() // self.animateTrashButton() // self.animateLogo() // self.animateViews() } @objc func animateLogo(){ log.verbose(#function) // logoCustomization(self.logoImage) } } //MARK: - Search Bar extension MakeTableViewController: UISearchBarDelegate{ fileprivate func setUPSearchBar(){ log.verbose(#function) let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 65)) searchBar.showsScopeBar = true searchBar.scopeButtonTitles = [myfitzEntities.user, myfitzEntities.wardrobe, myfitzEntities.item] searchBar.selectedScopeButtonIndex = 0 searchBar.delegate = self as UISearchBarDelegate self.tableView.tableFooterView = searchBar } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { log.verbose(#function) guard !searchText.isEmpty else { // item = //Fetch All objects tableView.reloadData() return } //array = CoreDataManager.fetchObj(selectedScopeIdx: searchBar.selectedScopeButtonIndex, targetText:searchText) tableView.reloadData() print(searchText) } func searchBarShouldEndEditting(_ searchBar: UISearchBar)->Bool{ log.verbose(#function) searchBar.resignFirstResponder() return true } } //MARK: -Anylitics-MakeTableViewController Extension //extension MakeTableViewController{ // func logPageView(){ // GlobalBackgroundQueue.async(execute: { // let pageCount:Int? = defaults.returnIntValue("MAKE_PAGE_COUNT") // Answers.logContentView(withName: "Category Content View", // contentType: "Category View", // contentId: "MF3", // customAttributes: ["MAKE_PAGE_COUNT": pageCount! // ]) // }) // } //}
37.829493
161
0.600865
23a28e12e3a62ca21ebf34decdfca37e2c61694c
4,384
// // DayWidget.swift // IkachanWidget // // Created by Sketch on 2021/1/24. // import WidgetKit import SwiftUI import Intents struct DayProvider: IntentTimelineProvider { func placeholder(in context: Context) -> DayEntry { DayEntry(date: Date(), configuration: DayIntent(), schedule: SchedulePlaceholder) } func getSnapshot(for configuration: DayIntent, in context: Context, completion: @escaping (DayEntry) -> Void) { fetchSchedules { (schedules, error) in let current = Date().floorToMin() guard let schedules = schedules else { completion(DayEntry(date: current, configuration: configuration, schedule: nil)) return } let filtered = schedules.filter { schedule in schedule.gameMode == IntentHandler.gameModeConvertTo(gameMode: configuration.gameMode) } if filtered.count > 0 { let entry = DayEntry(date: current, configuration: configuration, schedule: filtered[0]) completion(entry) } else { completion(DayEntry(date: current, configuration: configuration, schedule: nil)) } } } func getTimeline(for configuration: DayIntent, in context: Context, completion: @escaping (Timeline<DayEntry>) -> Void) { fetchSchedules { (schedules, error) in var entries: [DayEntry] = [] var current = Date().floorToMin() guard let schedules = schedules else { let entry = DayEntry(date: current, configuration: configuration, schedule: nil) completion(Timeline(entries: [entry], policy: .after(current.addingTimeInterval(300)))) return } let filtered = schedules.filter { schedule in schedule.gameMode == IntentHandler.gameModeConvertTo(gameMode: configuration.gameMode) } for schedule in filtered { while current < schedule.endTime && entries.count < MaxWidgetEntryCount { let entry = DayEntry(date: current, configuration: configuration, schedule: schedule) entries.append(entry) current = current.addingTimeInterval(60) } if entries.count >= MaxWidgetEntryCount { break } } if entries.count > 0 { if entries.last!.date < Date() { let entry = DayEntry(date: current, configuration: configuration, schedule: nil) completion(Timeline(entries: [entry], policy: .after(current.addingTimeInterval(60)))) } else { completion(Timeline(entries: entries, policy: .atEnd)) } } else { let entry = DayEntry(date: current, configuration: configuration, schedule: nil) completion(Timeline(entries: [entry], policy: .after(current.addingTimeInterval(300)))) } } } } struct DayEntry: TimelineEntry { let date: Date let configuration: DayIntent let schedule: Schedule? } struct DayWidgetEntryView: View { var entry: DayProvider.Entry var body: some View { SmallDayView(current: entry.date, schedule: entry.schedule) .widgetURL(URL(string: IntentHandler.gameModeConvertTo(gameMode: entry.configuration.gameMode).url)!) } } struct DayWidget: Widget { let kind = "DayWidget" var body: some WidgetConfiguration { IntentConfiguration(kind: kind, intent: DayIntent.self, provider: DayProvider()) { entry in DayWidgetEntryView(entry: entry) } .configurationDisplayName("day_widget_name") .description("day_widget_description") .supportedFamilies([.systemSmall]) } } struct DayWidget_Previews: PreviewProvider { static var previews: some View { DayWidgetEntryView(entry: DayEntry(date: Date(), configuration: DayIntent(), schedule: SchedulePlaceholder)) .previewContext(WidgetPreviewContext(family: .systemSmall)) } }
35.354839
125
0.581204
7aeecee4784b2c9515d4dffab91d300aee790395
2,757
/* This source file is part of the Swift.org open source project Copyright (c) 2018 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 Swift project authors */ extension Version: ExpressibleByStringLiteral { public init(stringLiteral value: String) { if let version = Version(value) { self.init(version) } else { // If version can't be initialized using the string literal, report // the error and initialize with a dummy value. This is done to // report error to the invoking tool (like swift build) gracefully // rather than just crashing. errors.append("Invalid semantic version string '\(value)'") self.init(0, 0, 0) } } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } } extension Version { public init(_ version: Version) { major = version.major minor = version.minor patch = version.patch prereleaseIdentifiers = version.prereleaseIdentifiers buildMetadataIdentifiers = version.buildMetadataIdentifiers } public init?(_ versionString: String) { let prereleaseStartIndex = versionString.index(of: "-") let metadataStartIndex = versionString.index(of: "+") let requiredEndIndex = prereleaseStartIndex ?? metadataStartIndex ?? versionString.endIndex let requiredCharacters = versionString.prefix(upTo: requiredEndIndex) let requiredComponents = requiredCharacters .split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false) .map(String.init) .compactMap({ Int($0) }) .filter({ $0 >= 0 }) guard requiredComponents.count == 3 else { return nil } self.major = requiredComponents[0] self.minor = requiredComponents[1] self.patch = requiredComponents[2] func identifiers(start: String.Index?, end: String.Index) -> [String] { guard let start = start else { return [] } let identifiers = versionString[versionString.index(after: start)..<end] return identifiers.split(separator: ".").map(String.init) } self.prereleaseIdentifiers = identifiers( start: prereleaseStartIndex, end: metadataStartIndex ?? versionString.endIndex) self.buildMetadataIdentifiers = identifiers(start: metadataStartIndex, end: versionString.endIndex) } }
36.76
107
0.65905
6180e8299966c3fcc91674d2cc6ee1cb50fb2744
460
import Foundation public enum MatrixMembership: String, Codable { case invite, join, knock, leave, ban, unknown // implement a custom decoder that will decode as unknown if // the string received can't be decoded as one of the cases public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self = MatrixMembership(rawValue: (try? container.decode(String.self)) ?? "") ?? .unknown } }
35.384615
97
0.697826
691ff8a393e57978859dbacde05b346107a83275
805
// // UITextView+Validator.swift // Validator // // Created by Adam Waite on 31/10/2016. // Copyright © 2016 adamjwaite.co.uk. All rights reserved. // import UIKit extension UITextView: ValidatableInterfaceElement { public typealias InputType = String open var inputValue: String? { return text } open func validateOnInputChange(enabled: Bool) { switch enabled { case true: NotificationCenter.default.addObserver(self, selector: #selector(validate), name: Notification.Name.UITextViewTextDidChange, object: self) case false: NotificationCenter.default.removeObserver(self, name: Notification.Name.UITextViewTextDidChange, object: self) } } @objc internal func validate(_ sender: Notification) { validate() } }
27.758621
157
0.69441
50358c4695dd814662965d5e3b1fb560a8cb85bc
204
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c<S:String class A{ func a<e:a
29.142857
87
0.764706
dbcad101e948e02dd8bee36cd13dbacd950e46d9
1,810
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "hsdoc", platforms: [.macOS(.v11)], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "HSDocKit", targets: ["HSDocKit"]), .executable( name: "hsdoc", targets: ["hsdoc"]), ], dependencies: [ .package(url: "https://github.com/pointfreeco/swift-parsing.git", branch: "0.5.0"), .package(url: "https://github.com/pointfreeco/swift-nonempty.git", from: "0.4.0"), .package(url: "https://github.com/Quick/Nimble.git", from: "9.0.0"), .package(url: "https://github.com/Quick/Quick.git", from: "3.0.1"), .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "0.3.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "HSDocKit", dependencies: [ .product(name: "Parsing", package: "swift-parsing"), .product(name: "NonEmpty", package: "swift-nonempty"), ]), .testTarget( name: "HSDocKitTests", dependencies: [ "HSDocKit", "Nimble", "Quick", .product(name: "CustomDump", package: "swift-custom-dump"), ]), .executableTarget(name: "hsdoc", dependencies: [ "HSDocKit" ]), ] )
39.347826
117
0.565193
ac4ad824c413ebace283727681cb2e3784ba4cec
1,480
// // SongCellSliderController.swift // MusicPlayer // // Created by Daniyar Yeralin on 7/19/17. // Copyright © 2017 Daniyar Yeralin. All rights reserved. // import Foundation import MediaPlayer // TODO: Refactor SliderUI controller // MARK: Song cell slider UI controller extension SongCell { internal func resetSliderCAD() { if sliderCAD == nil { log.warning("sliderCAD is already nil, nothing to do") return } sliderCAD.invalidate() sliderCAD = nil songProgressSlider.value = 0 songProgressSlider.isEnabled = false } internal func restoreSliderCAD() { guard let duration = AudioPlayer.instance.duration(), let currentTime = AudioPlayer.instance.currentTime() else { fatalError("Could not retrieve AudioPlayer instance") } songProgressSlider.isEnabled = true songProgressSlider.minimumValue = 0 songProgressSlider.maximumValue = Float(duration) songProgressSlider.value = Float(currentTime) sliderCAD = CADisplayLink(target: self, selector: #selector(self.updateSliderCAD)) sliderCAD.preferredFramesPerSecond = 30 sliderCAD.add(to: .current, forMode: RunLoop.Mode.default) } @objc internal func updateSliderCAD() { if let currentTime = AudioPlayer.instance.currentTime(), sliderCAD != nil { songProgressSlider.value = Float(currentTime) } } }
31.489362
90
0.664189
16b04eef35132cdc33916b0764c3b0fbb3a7002e
99,706
// // SwiftyJsonTests.swift // AmadeusCheckoutTests // // Created by Yann Armelin on 18/07/2019. // Copyright © 2019 Amadeus. All rights reserved. // import XCTest import Foundation @testable import AmadeusCheckout // ArrayTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class ArrayTests: XCTestCase { func testSingleDimensionalArraysGetter() { let array = ["1", "2", "a", "B", "D"] let json = JSON(array) XCTAssertEqual((json.array![0] as JSON).string!, "1") XCTAssertEqual((json.array![1] as JSON).string!, "2") XCTAssertEqual((json.array![2] as JSON).string!, "a") XCTAssertEqual((json.array![3] as JSON).string!, "B") XCTAssertEqual((json.array![4] as JSON).string!, "D") } func testSingleDimensionalArraysSetter() { let array = ["1", "2", "a", "B", "D"] var json = JSON(array) json.arrayObject = ["111", "222"] XCTAssertEqual((json.array![0] as JSON).string!, "111") XCTAssertEqual((json.array![1] as JSON).string!, "222") } } // BaseTests.swift // // Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // 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. class BaseTests: XCTestCase { var testData: Data! override func setUp() { super.setUp() // let file = "./Tests/Tes/Tests.json" // self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) if let file = Bundle(for: BaseTests.self).path(forResource: "Tests", ofType: "json") { self.testData = try? Data(contentsOf: URL(fileURLWithPath: file)) } else { XCTFail("Can't find the test JSON file") } } override func tearDown() { super.tearDown() } func testInit() { guard let json0 = try? JSON(data: self.testData) else { XCTFail("Unable to parse testData") return } XCTAssertEqual(json0.array!.count, 3) XCTAssertEqual(JSON("123").description, "123") XCTAssertEqual(JSON(["1": "2"])["1"].string!, "2") let dictionary = NSMutableDictionary() dictionary.setObject(NSNumber(value: 1.0), forKey: "number" as NSString) dictionary.setObject(NSNull(), forKey: "null" as NSString) _ = JSON(dictionary) do { let object: Any = try JSONSerialization.jsonObject(with: self.testData, options: []) let json2 = JSON(object) XCTAssertEqual(json0, json2) } catch _ { } } func testCompare() { XCTAssertNotEqual(JSON("32.1234567890"), JSON(32.1234567890)) let veryLargeNumber: UInt64 = 9876543210987654321 XCTAssertNotEqual(JSON("9876543210987654321"), JSON(NSNumber(value: veryLargeNumber))) XCTAssertNotEqual(JSON("9876543210987654321.12345678901234567890"), JSON(9876543210987654321.12345678901234567890)) XCTAssertEqual(JSON("😊"), JSON("😊")) XCTAssertNotEqual(JSON("😱"), JSON("😁")) XCTAssertEqual(JSON([123, 321, 456]), JSON([123, 321, 456])) XCTAssertNotEqual(JSON([123, 321, 456]), JSON(123456789)) XCTAssertNotEqual(JSON([123, 321, 456]), JSON("string")) XCTAssertNotEqual(JSON(["1": 123, "2": 321, "3": 456]), JSON("string")) XCTAssertEqual(JSON(["1": 123, "2": 321, "3": 456]), JSON(["2": 321, "1": 123, "3": 456])) XCTAssertEqual(JSON(NSNull()), JSON(NSNull())) XCTAssertNotEqual(JSON(NSNull()), JSON(123)) } func testJSONDoesProduceValidWithCorrectKeyPath() { guard let json = try? JSON(data: self.testData) else { XCTFail("Unable to parse testData") return } let tweets = json let tweets_array = json.array let tweets_1 = json[1] _ = tweets_1[1] let tweets_1_user_name = tweets_1["user"]["name"] let tweets_1_user_name_string = tweets_1["user"]["name"].string XCTAssertNotEqual(tweets.type, Type.null) XCTAssert(tweets_array != nil) XCTAssertNotEqual(tweets_1.type, Type.null) XCTAssertEqual(tweets_1_user_name, JSON("Raffi Krikorian")) XCTAssertEqual(tweets_1_user_name_string!, "Raffi Krikorian") let tweets_1_coordinates = tweets_1["coordinates"] let tweets_1_coordinates_coordinates = tweets_1_coordinates["coordinates"] let tweets_1_coordinates_coordinates_point_0_double = tweets_1_coordinates_coordinates[0].double let tweets_1_coordinates_coordinates_point_1_float = tweets_1_coordinates_coordinates[1].float let new_tweets_1_coordinates_coordinates = JSON([-122.25831, 37.871609] as NSArray) XCTAssertEqual(tweets_1_coordinates_coordinates, new_tweets_1_coordinates_coordinates) XCTAssertEqual(tweets_1_coordinates_coordinates_point_0_double!, -122.25831) XCTAssertTrue(tweets_1_coordinates_coordinates_point_1_float! == 37.871609) let tweets_1_coordinates_coordinates_point_0_string = tweets_1_coordinates_coordinates[0].stringValue let tweets_1_coordinates_coordinates_point_1_string = tweets_1_coordinates_coordinates[1].stringValue XCTAssertEqual(tweets_1_coordinates_coordinates_point_0_string, "-122.25831") XCTAssertEqual(tweets_1_coordinates_coordinates_point_1_string, "37.871609") let tweets_1_coordinates_coordinates_point_0 = tweets_1_coordinates_coordinates[0] let tweets_1_coordinates_coordinates_point_1 = tweets_1_coordinates_coordinates[1] XCTAssertEqual(tweets_1_coordinates_coordinates_point_0, JSON(-122.25831)) XCTAssertEqual(tweets_1_coordinates_coordinates_point_1, JSON(37.871609)) let created_at = json[0]["created_at"].string let id_str = json[0]["id_str"].string let favorited = json[0]["favorited"].bool let id = json[0]["id"].int64 let in_reply_to_user_id_str = json[0]["in_reply_to_user_id_str"] XCTAssertEqual(created_at!, "Tue Aug 28 21:16:23 +0000 2012") XCTAssertEqual(id_str!, "240558470661799936") XCTAssertFalse(favorited!) XCTAssertEqual(id!, 240558470661799936) XCTAssertEqual(in_reply_to_user_id_str.type, Type.null) let user = json[0]["user"] let user_name = user["name"].string let user_profile_image_url = user["profile_image_url"].url XCTAssert(user_name == "OAuth Dancer") XCTAssert(user_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) let user_dictionary = json[0]["user"].dictionary let user_dictionary_name = user_dictionary?["name"]?.string let user_dictionary_name_profile_image_url = user_dictionary?["profile_image_url"]?.url XCTAssert(user_dictionary_name == "OAuth Dancer") XCTAssert(user_dictionary_name_profile_image_url == URL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg")) } func testJSONNumberCompare() { XCTAssertEqual(JSON(12376352.123321), JSON(12376352.123321)) XCTAssertGreaterThan(JSON(20.211), JSON(20.112)) XCTAssertGreaterThanOrEqual(JSON(30.211), JSON(20.112)) XCTAssertGreaterThanOrEqual(JSON(65232), JSON(65232)) XCTAssertLessThan(JSON(-82320.211), JSON(20.112)) XCTAssertLessThanOrEqual(JSON(-320.211), JSON(123.1)) XCTAssertLessThanOrEqual(JSON(-8763), JSON(-8763)) XCTAssertEqual(JSON(12376352.123321), JSON(12376352.123321)) XCTAssertGreaterThan(JSON(20.211), JSON(20.112)) XCTAssertGreaterThanOrEqual(JSON(30.211), JSON(20.112)) XCTAssertGreaterThanOrEqual(JSON(65232), JSON(65232)) XCTAssertLessThan(JSON(-82320.211), JSON(20.112)) XCTAssertLessThanOrEqual(JSON(-320.211), JSON(123.1)) XCTAssertLessThanOrEqual(JSON(-8763), JSON(-8763)) } func testNumberConvertToString() { XCTAssertEqual(JSON(true).stringValue, "true") XCTAssertEqual(JSON(999.9823).stringValue, "999.9823") XCTAssertEqual(JSON(true).number!.stringValue, "1") XCTAssertEqual(JSON(false).number!.stringValue, "0") XCTAssertEqual(JSON("hello").numberValue.stringValue, "0") XCTAssertEqual(JSON(NSNull()).numberValue.stringValue, "0") XCTAssertEqual(JSON(["a", "b", "c", "d"]).numberValue.stringValue, "0") XCTAssertEqual(JSON(["a": "b", "c": "d"]).numberValue.stringValue, "0") } func testNumberPrint() { XCTAssertEqual(JSON(false).description, "false") XCTAssertEqual(JSON(true).description, "true") XCTAssertEqual(JSON(1).description, "1") XCTAssertEqual(JSON(22).description, "22") #if (arch(x86_64) || arch(arm64)) XCTAssertEqual(JSON(9.22337203685478E18).description, "9.22337203685478e+18") #elseif (arch(i386) || arch(arm)) XCTAssertEqual(JSON(2147483647).description, "2147483647") #endif XCTAssertEqual(JSON(-1).description, "-1") XCTAssertEqual(JSON(-934834834).description, "-934834834") XCTAssertEqual(JSON(-2147483648).description, "-2147483648") XCTAssertEqual(JSON(1.5555).description, "1.5555") XCTAssertEqual(JSON(-9.123456789).description, "-9.123456789") XCTAssertEqual(JSON(-0.00000000000000001).description, "-1e-17") XCTAssertEqual(JSON(-999999999999999999999999.000000000000000000000001).description, "-1e+24") XCTAssertEqual(JSON(-9999999991999999999999999.88888883433343439438493483483943948341).stringValue, "-9.999999991999999e+24") XCTAssertEqual(JSON(Int(Int.max)).description, "\(Int.max)") XCTAssertEqual(JSON(NSNumber(value: Int.min)).description, "\(Int.min)") XCTAssertEqual(JSON(NSNumber(value: UInt.max)).description, "\(UInt.max)") XCTAssertEqual(JSON(NSNumber(value: UInt64.max)).description, "\(UInt64.max)") XCTAssertEqual(JSON(NSNumber(value: Int64.max)).description, "\(Int64.max)") XCTAssertEqual(JSON(NSNumber(value: UInt64.max)).description, "\(UInt64.max)") XCTAssertEqual(JSON(Double.infinity).description, "inf") XCTAssertEqual(JSON(-Double.infinity).description, "-inf") XCTAssertEqual(JSON(Double.nan).description, "nan") XCTAssertEqual(JSON(1.0/0.0).description, "inf") XCTAssertEqual(JSON(-1.0/0.0).description, "-inf") XCTAssertEqual(JSON(0.0/0.0).description, "nan") } func testNullJSON() { XCTAssertEqual(JSON(NSNull()).debugDescription, "null") let json: JSON = JSON.null XCTAssertEqual(json.debugDescription, "null") XCTAssertNil(json.error) let json1: JSON = JSON(NSNull()) if json1 != JSON.null { XCTFail("json1 should be nil") } } func testExistance() { let dictionary = ["number": 1111] let json = JSON(dictionary) XCTAssertFalse(json["unspecifiedValue"].exists()) XCTAssertFalse(json[0].exists()) XCTAssertTrue(json["number"].exists()) let array = [["number": 1111]] let jsonForArray = JSON(array) XCTAssertTrue(jsonForArray[0].exists()) XCTAssertFalse(jsonForArray[1].exists()) XCTAssertFalse(jsonForArray["someValue"].exists()) } func testErrorHandle() { guard let json = try? JSON(data: self.testData) else { XCTFail("Unable to parse testData") return } if json["wrong-type"].string != nil { XCTFail("Should not run into here") } else { XCTAssertEqual(json["wrong-type"].error, SwiftyJSONError.wrongType) } if json[0]["not-exist"].string != nil { XCTFail("Should not run into here") } else { XCTAssertEqual(json[0]["not-exist"].error, SwiftyJSONError.notExist) } let wrongJSON = JSON(NSObject()) if let error = wrongJSON.error { XCTAssertEqual(error, SwiftyJSONError.unsupportedType) } } func testReturnObject() { guard let json = try? JSON(data: self.testData) else { XCTFail("Unable to parse testData") return } XCTAssertNotNil(json.object) } func testErrorThrowing() { let invalidJson = "{\"foo\": 300]" // deliberately incorrect JSON let invalidData = invalidJson.data(using: .utf8)! do { _ = try JSON(data: invalidData) XCTFail("Should have thrown error; we should not have gotten here") } catch { // everything is OK } } } // CodableTests.swift // // Created by Lei Wang on 2018/1/9. // // 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. class CodableTests: XCTestCase { func testEncodeNull() { var json = JSON([NSNull()]) _ = try! JSONEncoder().encode(json) json = JSON([nil]) _ = try! JSONEncoder().encode(json) let dictionary: [String: Any?] = ["key": nil] json = JSON(dictionary) _ = try! JSONEncoder().encode(json) } func testArrayCodable() { let jsonString = """ [1,"false", ["A", 4.3231],"3",true] """ var data = jsonString.data(using: .utf8)! let json = try! JSONDecoder().decode(JSON.self, from: data) XCTAssertEqual(json.arrayValue.first?.int, 1) XCTAssertEqual(json[1].bool, nil) XCTAssertEqual(json[1].string, "false") XCTAssertEqual(json[3].string, "3") XCTAssertEqual(json[2][1].double!, 4.3231) XCTAssertEqual(json.arrayValue[0].bool, nil) XCTAssertEqual(json.array!.last!.bool, true) let jsonList = try! JSONDecoder().decode([JSON].self, from: data) XCTAssertEqual(jsonList.first?.int, 1) XCTAssertEqual(jsonList.last!.bool, true) data = try! JSONEncoder().encode(json) let list = try! JSONSerialization.jsonObject(with: data, options: []) as! [Any] XCTAssertEqual(list[0] as! Int, 1) XCTAssertEqual((list[2] as! [Any])[1] as! NSNumber, 4.3231) } func testDictionaryCodable() { let dictionary: [String: Any] = ["number": 9823.212, "name": "NAME", "list": [1234, 4.21223256], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] var data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let json = try! JSONDecoder().decode(JSON.self, from: data) XCTAssertNotNil(json.dictionary) XCTAssertEqual(json["number"].float, 9823.212) XCTAssertEqual(json["list"].arrayObject is [NSNumber], true) XCTAssertEqual(json["object"]["sub_number"].float, 877.2323) XCTAssertEqual(json["bool"].bool, true) let jsonDict = try! JSONDecoder().decode([String: JSON].self, from: data) XCTAssertEqual(jsonDict["number"]?.int, 9823) XCTAssertEqual(jsonDict["object"]?["sub_name"], "sub_name") data = try! JSONEncoder().encode(json) var encoderDict = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] XCTAssertEqual(encoderDict["list"] as! [NSNumber], [1234, 4.21223256]) XCTAssertEqual(encoderDict["bool"] as! Bool, true) data = try! JSONEncoder().encode(jsonDict) encoderDict = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] XCTAssertEqual(encoderDict["name"] as! String, dictionary["name"] as! String) XCTAssertEqual((encoderDict["object"] as! [String: Any])["sub_number"] as! NSNumber, 877.2323) } func testCodableModel() { let dictionary: [String: Any] = [ "number": 9823.212, "name": "NAME", "list": [1234, 4.21223256], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) let model = try! JSONDecoder().decode(CodableModel.self, from: data) XCTAssertEqual(model.subName, "sub_name") } } private struct CodableModel: Codable { let name: String let number: Double let bool: Bool let list: [Double] private let object: JSON var subName: String? { return object["sub_name"].string } } // ComparableTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class ComparableTests: XCTestCase { func testNumberEqual() { let jsonL1: JSON = 1234567890.876623 let jsonR1: JSON = JSON(1234567890.876623) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 == 1234567890.876623) let jsonL2: JSON = 987654321 let jsonR2: JSON = JSON(987654321) XCTAssertEqual(jsonL2, jsonR2) XCTAssertTrue(jsonR2 == 987654321) let jsonL3: JSON = JSON(NSNumber(value: 87654321.12345678)) let jsonR3: JSON = JSON(NSNumber(value: 87654321.12345678)) XCTAssertEqual(jsonL3, jsonR3) XCTAssertTrue(jsonR3 == 87654321.12345678) } func testNumberNotEqual() { let jsonL1: JSON = 1234567890.876623 let jsonR1: JSON = JSON(123.123) XCTAssertNotEqual(jsonL1, jsonR1) XCTAssertFalse(jsonL1 == 34343) let jsonL2: JSON = 8773 let jsonR2: JSON = JSON(123.23) XCTAssertNotEqual(jsonL2, jsonR2) XCTAssertFalse(jsonR1 == 454352) let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) let jsonR3: JSON = JSON(NSNumber(value: 87654321.45678)) XCTAssertNotEqual(jsonL3, jsonR3) XCTAssertFalse(jsonL3 == 4545.232) } func testNumberGreaterThanOrEqual() { let jsonL1: JSON = 1234567890.876623 let jsonR1: JSON = JSON(123.123) XCTAssertGreaterThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 >= -37434) let jsonL2: JSON = 8773 let jsonR2: JSON = JSON(-87343) XCTAssertGreaterThanOrEqual(jsonL2, jsonR2) XCTAssertTrue(jsonR2 >= -988343) let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) let jsonR3: JSON = JSON(NSNumber(value: 87621.12345678)) XCTAssertGreaterThanOrEqual(jsonL3, jsonR3) XCTAssertTrue(jsonR3 >= 0.3232) } func testNumberLessThanOrEqual() { let jsonL1: JSON = 1234567890.876623 let jsonR1: JSON = JSON(123.123) XCTAssertLessThanOrEqual(jsonR1, jsonL1) XCTAssertFalse(83487343.3493 <= jsonR1) let jsonL2: JSON = 8773 let jsonR2: JSON = JSON(-123.23) XCTAssertLessThanOrEqual(jsonR2, jsonL2) XCTAssertFalse(9348343 <= jsonR2) let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) let jsonR3: JSON = JSON(NSNumber(value: 87621.12345678)) XCTAssertLessThanOrEqual(jsonR3, jsonL3) XCTAssertTrue(87621.12345678 <= jsonR3) } func testNumberGreaterThan() { let jsonL1: JSON = 1234567890.876623 let jsonR1: JSON = JSON(123.123) XCTAssertGreaterThan(jsonL1, jsonR1) XCTAssertFalse(jsonR1 > 192388843.0988) let jsonL2: JSON = 8773 let jsonR2: JSON = JSON(123.23) XCTAssertGreaterThan(jsonL2, jsonR2) XCTAssertFalse(jsonR2 > 877434) let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) let jsonR3: JSON = JSON(NSNumber(value: 87621.1234567)) XCTAssertGreaterThan(jsonL3, jsonR3) XCTAssertFalse(-7799 > jsonR3) } func testNumberLessThan() { let jsonL1: JSON = 1234567890.876623 let jsonR1: JSON = JSON(123.123) XCTAssertLessThan(jsonR1, jsonL1) XCTAssertTrue(jsonR1 < 192388843.0988) let jsonL2: JSON = 8773 let jsonR2: JSON = JSON(123.23) XCTAssertLessThan(jsonR2, jsonL2) XCTAssertTrue(jsonR2 < 877434) let jsonL3: JSON = JSON(NSNumber(value: 87621.12345678)) let jsonR3: JSON = JSON(NSNumber(value: 87621.1234567)) XCTAssertLessThan(jsonR3, jsonL3) XCTAssertTrue(-7799 < jsonR3) } func testBoolEqual() { let jsonL1: JSON = true let jsonR1: JSON = JSON(true) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 == true) let jsonL2: JSON = false let jsonR2: JSON = JSON(false) XCTAssertEqual(jsonL2, jsonR2) XCTAssertTrue(jsonL2 == false) } func testBoolNotEqual() { let jsonL1: JSON = true let jsonR1: JSON = JSON(false) XCTAssertNotEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 != false) let jsonL2: JSON = false let jsonR2: JSON = JSON(true) XCTAssertNotEqual(jsonL2, jsonR2) XCTAssertTrue(jsonL2 != true) } func testBoolGreaterThanOrEqual() { let jsonL1: JSON = true let jsonR1: JSON = JSON(true) XCTAssertGreaterThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 >= true) let jsonL2: JSON = false let jsonR2: JSON = JSON(false) XCTAssertGreaterThanOrEqual(jsonL2, jsonR2) XCTAssertFalse(jsonL2 >= true) } func testBoolLessThanOrEqual() { let jsonL1: JSON = true let jsonR1: JSON = JSON(true) XCTAssertLessThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(true <= jsonR1) let jsonL2: JSON = false let jsonR2: JSON = JSON(false) XCTAssertLessThanOrEqual(jsonL2, jsonR2) XCTAssertFalse(jsonL2 <= true) } func testBoolGreaterThan() { let jsonL1: JSON = true let jsonR1: JSON = JSON(true) XCTAssertFalse(jsonL1 > jsonR1) XCTAssertFalse(jsonL1 > true) XCTAssertFalse(jsonR1 > false) let jsonL2: JSON = false let jsonR2: JSON = JSON(false) XCTAssertFalse(jsonL2 > jsonR2) XCTAssertFalse(jsonL2 > false) XCTAssertFalse(jsonR2 > true) let jsonL3: JSON = true let jsonR3: JSON = JSON(false) XCTAssertFalse(jsonL3 > jsonR3) XCTAssertFalse(jsonL3 > false) XCTAssertFalse(jsonR3 > true) let jsonL4: JSON = false let jsonR4: JSON = JSON(true) XCTAssertFalse(jsonL4 > jsonR4) XCTAssertFalse(jsonL4 > false) XCTAssertFalse(jsonR4 > true) } func testBoolLessThan() { let jsonL1: JSON = true let jsonR1: JSON = JSON(true) XCTAssertFalse(jsonL1 < jsonR1) XCTAssertFalse(jsonL1 < true) XCTAssertFalse(jsonR1 < false) let jsonL2: JSON = false let jsonR2: JSON = JSON(false) XCTAssertFalse(jsonL2 < jsonR2) XCTAssertFalse(jsonL2 < false) XCTAssertFalse(jsonR2 < true) let jsonL3: JSON = true let jsonR3: JSON = JSON(false) XCTAssertFalse(jsonL3 < jsonR3) XCTAssertFalse(jsonL3 < false) XCTAssertFalse(jsonR3 < true) let jsonL4: JSON = false let jsonR4: JSON = JSON(true) XCTAssertFalse(jsonL4 < jsonR4) XCTAssertFalse(jsonL4 < false) XCTAssertFalse(true < jsonR4) } func testStringEqual() { let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 == "abcdefg 123456789 !@#$%^&*()") } func testStringNotEqual() { let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" let jsonR1: JSON = JSON("-=[]\\\"987654321") XCTAssertNotEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 != "not equal") } func testStringGreaterThanOrEqual() { let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") XCTAssertGreaterThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 >= "abcdefg 123456789 !@#$%^&*()") let jsonL2: JSON = "z-+{}:" let jsonR2: JSON = JSON("a<>?:") XCTAssertGreaterThanOrEqual(jsonL2, jsonR2) XCTAssertTrue(jsonL2 >= "mnbvcxz") } func testStringLessThanOrEqual() { let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") XCTAssertLessThanOrEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 <= "abcdefg 123456789 !@#$%^&*()") let jsonL2: JSON = "z-+{}:" let jsonR2: JSON = JSON("a<>?:") XCTAssertLessThanOrEqual(jsonR2, jsonL2) XCTAssertTrue("mnbvcxz" <= jsonL2) } func testStringGreaterThan() { let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") XCTAssertFalse(jsonL1 > jsonR1) XCTAssertFalse(jsonL1 > "abcdefg 123456789 !@#$%^&*()") let jsonL2: JSON = "z-+{}:" let jsonR2: JSON = JSON("a<>?:") XCTAssertGreaterThan(jsonL2, jsonR2) XCTAssertFalse("87663434" > jsonL2) } func testStringLessThan() { let jsonL1: JSON = "abcdefg 123456789 !@#$%^&*()" let jsonR1: JSON = JSON("abcdefg 123456789 !@#$%^&*()") XCTAssertFalse(jsonL1 < jsonR1) XCTAssertFalse(jsonL1 < "abcdefg 123456789 !@#$%^&*()") let jsonL2: JSON = "98774" let jsonR2: JSON = JSON("123456") XCTAssertLessThan(jsonR2, jsonL2) XCTAssertFalse(jsonL2 < "09") } func testNil() { let jsonL1: JSON = JSON.null let jsonR1: JSON = JSON(NSNull()) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 != "123") XCTAssertFalse(jsonL1 > "abcd") XCTAssertFalse(jsonR1 < "*&^") XCTAssertFalse(jsonL1 >= "jhfid") XCTAssertFalse(jsonR1 <= "你好") XCTAssertTrue(jsonL1 >= jsonR1) XCTAssertTrue(jsonL1 <= jsonR1) } func testArray() { let jsonL1: JSON = [1, 2, "4", 5, "6"] let jsonR1: JSON = JSON([1, 2, "4", 5, "6"]) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 == [1, 2, "4", 5, "6"]) XCTAssertTrue(jsonL1 != ["abcd", "efg"]) XCTAssertTrue(jsonL1 >= jsonR1) XCTAssertTrue(jsonL1 <= jsonR1) XCTAssertFalse(jsonL1 > ["abcd", ""]) XCTAssertFalse(jsonR1 < []) XCTAssertFalse(jsonL1 >= [:]) } func testDictionary() { let jsonL1: JSON = ["2": 2, "name": "Jack", "List": ["a", 1.09, NSNull()]] let jsonR1: JSON = JSON(["2": 2, "name": "Jack", "List": ["a", 1.09, NSNull()]]) XCTAssertEqual(jsonL1, jsonR1) XCTAssertTrue(jsonL1 != ["1": 2, "Hello": "World", "Koo": "Foo"]) XCTAssertTrue(jsonL1 >= jsonR1) XCTAssertTrue(jsonL1 <= jsonR1) XCTAssertFalse(jsonL1 >= [:]) XCTAssertFalse(jsonR1 <= ["999": "aaaa"]) XCTAssertFalse(jsonL1 > [")(*&^": 1234567]) XCTAssertFalse(jsonR1 < ["MNHH": "JUYTR"]) } } // DictionaryTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class DictionaryTests: XCTestCase { func testGetter() { let dictionary = ["number": 9823.212, "name": "NAME", "list": [1234, 4.212], "object": ["sub_number": 877.2323, "sub_name": "sub_name"], "bool": true] as [String: Any] let json = JSON(dictionary) //dictionary XCTAssertEqual((json.dictionary!["number"]! as JSON).double!, 9823.212) XCTAssertEqual((json.dictionary!["name"]! as JSON).string!, "NAME") XCTAssertEqual(((json.dictionary!["list"]! as JSON).array![0] as JSON).int!, 1234) XCTAssertEqual(((json.dictionary!["list"]! as JSON).array![1] as JSON).double!, 4.212) XCTAssertEqual((((json.dictionary!["object"]! as JSON).dictionaryValue)["sub_number"]! as JSON).double!, 877.2323) XCTAssertTrue(json.dictionary!["null"] == nil) //dictionaryValue XCTAssertEqual(((((json.dictionaryValue)["object"]! as JSON).dictionaryValue)["sub_name"]! as JSON).string!, "sub_name") XCTAssertEqual((json.dictionaryValue["bool"]! as JSON).bool!, true) XCTAssertTrue(json.dictionaryValue["null"] == nil) XCTAssertTrue(JSON.null.dictionaryValue == [:]) //dictionaryObject XCTAssertEqual(json.dictionaryObject!["number"]! as? Double, 9823.212) XCTAssertTrue(json.dictionaryObject!["null"] == nil) XCTAssertTrue(JSON.null.dictionaryObject == nil) } func testSetter() { var json: JSON = ["test": "case"] XCTAssertEqual(json.dictionaryObject! as! [String: String], ["test": "case"]) json.dictionaryObject = ["name": "NAME"] XCTAssertEqual(json.dictionaryObject! as! [String: String], ["name": "NAME"]) } } // LiteralConvertibleTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class LiteralConvertibleTests: XCTestCase { func testNumber() { let json: JSON = 1234567890.876623 XCTAssertEqual(json.int!, 1234567890) XCTAssertEqual(json.intValue, 1234567890) XCTAssertEqual(json.double!, 1234567890.876623) XCTAssertEqual(json.doubleValue, 1234567890.876623) XCTAssertTrue(json.float! == 1234567890.876623) XCTAssertTrue(json.floatValue == 1234567890.876623) } func testBool() { let jsonTrue: JSON = true XCTAssertEqual(jsonTrue.bool!, true) XCTAssertEqual(jsonTrue.boolValue, true) let jsonFalse: JSON = false XCTAssertEqual(jsonFalse.bool!, false) XCTAssertEqual(jsonFalse.boolValue, false) } func testString() { let json: JSON = "abcd efg, HIJK;LMn" XCTAssertEqual(json.string!, "abcd efg, HIJK;LMn") XCTAssertEqual(json.stringValue, "abcd efg, HIJK;LMn") } func testNil() { let jsonNil_1: JSON = JSON.null XCTAssert(jsonNil_1 == JSON.null) let jsonNil_2: JSON = JSON(NSNull.self) XCTAssert(jsonNil_2 != JSON.null) let jsonNil_3: JSON = JSON([1: 2]) XCTAssert(jsonNil_3 != JSON.null) } func testArray() { let json: JSON = [1, 2, "4", 5, "6"] XCTAssertEqual(json.array!, [1, 2, "4", 5, "6"]) XCTAssertEqual(json.arrayValue, [1, 2, "4", 5, "6"]) } func testDictionary() { let json: JSON = ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]] XCTAssertEqual(json.dictionary!, ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]]) XCTAssertEqual(json.dictionaryValue, ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]]) } } // MergeTests.swift // // Created by Daniel Kiedrowski on 17.11.16. // // 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. class MergeTests: XCTestCase { func testDifferingTypes() { let A = JSON("a") let B = JSON(1) do { _ = try A.merged(with: B) } catch let error as SwiftyJSONError { XCTAssertEqual(error.errorCode, SwiftyJSONError.wrongType.rawValue) XCTAssertEqual(type(of: error).errorDomain, SwiftyJSONError.errorDomain) XCTAssertEqual(error.errorUserInfo as! [String: String], [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) } catch _ {} } func testPrimitiveType() { let A = JSON("a") let B = JSON("b") XCTAssertEqual(try! A.merged(with: B), B) } func testMergeEqual() { let json = JSON(["a": "A"]) XCTAssertEqual(try! json.merged(with: json), json) } func testMergeUnequalValues() { let A = JSON(["a": "A"]) let B = JSON(["a": "B"]) XCTAssertEqual(try! A.merged(with: B), B) } func testMergeUnequalKeysAndValues() { let A = JSON(["a": "A"]) let B = JSON(["b": "B"]) XCTAssertEqual(try! A.merged(with: B), JSON(["a": "A", "b": "B"])) } func testMergeFilledAndEmpty() { let A = JSON(["a": "A"]) let B = JSON([:]) XCTAssertEqual(try! A.merged(with: B), A) } func testMergeEmptyAndFilled() { let A = JSON([:]) let B = JSON(["a": "A"]) XCTAssertEqual(try! A.merged(with: B), B) } func testMergeArray() { let A = JSON(["a"]) let B = JSON(["b"]) XCTAssertEqual(try! A.merged(with: B), JSON(["a", "b"])) } func testMergeNestedJSONs() { let A = JSON([ "nested": [ "A": "a" ] ]) let B = JSON([ "nested": [ "A": "b" ] ]) XCTAssertEqual(try! A.merged(with: B), B) } } // MutabilityTests.swift // // Copyright (c) 2014 - 2017 Zigii Wong // // 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. class MutabilityTests: XCTestCase { func testDictionaryMutability() { let dictionary: [String: Any] = [ "string": "STRING", "number": 9823.212, "bool": true, "empty": ["nothing"], "foo": ["bar": ["1"]], "bar": ["foo": ["1": "a"]] ] var json = JSON(dictionary) XCTAssertEqual(json["string"], "STRING") XCTAssertEqual(json["number"], 9823.212) XCTAssertEqual(json["bool"], true) XCTAssertEqual(json["empty"], ["nothing"]) json["string"] = "muted" XCTAssertEqual(json["string"], "muted") json["number"] = 9999.0 XCTAssertEqual(json["number"], 9999.0) json["bool"] = false XCTAssertEqual(json["bool"], false) json["empty"] = [] XCTAssertEqual(json["empty"], []) json["new"] = JSON(["foo": "bar"]) XCTAssertEqual(json["new"], ["foo": "bar"]) json["foo"]["bar"] = JSON([]) XCTAssertEqual(json["foo"]["bar"], []) json["bar"]["foo"] = JSON(["2": "b"]) XCTAssertEqual(json["bar"]["foo"], ["2": "b"]) } func testArrayMutability() { let array: [Any] = ["1", "2", 3, true, []] var json = JSON(array) XCTAssertEqual(json[0], "1") XCTAssertEqual(json[1], "2") XCTAssertEqual(json[2], 3) XCTAssertEqual(json[3], true) XCTAssertEqual(json[4], []) json[0] = false XCTAssertEqual(json[0], false) json[1] = 2 XCTAssertEqual(json[1], 2) json[2] = "3" XCTAssertEqual(json[2], "3") json[3] = [:] XCTAssertEqual(json[3], [:]) json[4] = [1, 2] XCTAssertEqual(json[4], [1, 2]) } func testValueMutability() { var intArray = JSON([0, 1, 2]) intArray[0] = JSON(55) XCTAssertEqual(intArray[0], 55) XCTAssertEqual(intArray[0].intValue, 55) var dictionary = JSON(["foo": "bar"]) dictionary["foo"] = JSON("foo") XCTAssertEqual(dictionary["foo"], "foo") XCTAssertEqual(dictionary["foo"].stringValue, "foo") var number = JSON(1) number = JSON("111") XCTAssertEqual(number, "111") XCTAssertEqual(number.intValue, 111) XCTAssertEqual(number.stringValue, "111") var boolean = JSON(true) boolean = JSON(false) XCTAssertEqual(boolean, false) XCTAssertEqual(boolean.boolValue, false) } func testArrayRemovability() { let array = ["Test", "Test2", "Test3"] var json = JSON(array) json.arrayObject?.removeFirst() XCTAssertEqual(false, json.arrayValue.isEmpty) XCTAssertEqual(json.arrayValue, ["Test2", "Test3"]) json.arrayObject?.removeLast() XCTAssertEqual(false, json.arrayValue.isEmpty) XCTAssertEqual(json.arrayValue, ["Test2"]) json.arrayObject?.removeAll() XCTAssertEqual(true, json.arrayValue.isEmpty) XCTAssertEqual(JSON([]), json) } func testDictionaryRemovability() { let dictionary: [String: Any] = ["key1": "Value1", "key2": 2, "key3": true] var json = JSON(dictionary) json.dictionaryObject?.removeValue(forKey: "key1") XCTAssertEqual(false, json.dictionaryValue.isEmpty) XCTAssertEqual(json.dictionaryValue, ["key2": 2, "key3": true]) json.dictionaryObject?.removeValue(forKey: "key3") XCTAssertEqual(false, json.dictionaryValue.isEmpty) XCTAssertEqual(json.dictionaryValue, ["key2": 2]) json.dictionaryObject?.removeAll() XCTAssertEqual(true, json.dictionaryValue.isEmpty) XCTAssertEqual(json.dictionaryValue, [:]) } } // NestedJSONTests.swift // // Created by Hector Matos on 9/27/16. // // 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. class NestedJSONTests: XCTestCase { let family: JSON = [ "names": [ "Brooke Abigail Matos", "Rowan Danger Matos" ], "motto": "Hey, I don't know about you, but I'm feeling twenty-two! So, release the KrakenDev!" ] func testTopLevelNestedJSON() { let nestedJSON: JSON = [ "family": family ] XCTAssertNotNil(try? nestedJSON.rawData()) } func testDeeplyNestedJSON() { let nestedFamily: JSON = [ "count": 1, "families": [ [ "isACoolFamily": true, "family": [ "hello": family ] ] ] ] XCTAssertNotNil(try? nestedFamily.rawData()) } func testArrayJSON() { let arr: [JSON] = ["a", 1, ["b", 2]] let json = JSON(arr) XCTAssertEqual(json[0].string, "a") XCTAssertEqual(json[2, 1].int, 2) } func testDictionaryJSON() { let json: JSON = ["a": JSON("1"), "b": JSON([1, 2, "3"]), "c": JSON(["aa": "11", "bb": 22])] XCTAssertEqual(json["a"].string, "1") XCTAssertEqual(json["b"].array!, [1, 2, "3"]) XCTAssertEqual(json["c"]["aa"].string, "11") } func testNestedJSON() { let inner = JSON([ "some_field": "1" + "2" ]) let json = JSON([ "outer_field": "1" + "2", "inner_json": inner ]) XCTAssertEqual(json["inner_json"], ["some_field": "12"]) let foo = "foo" let json2 = JSON([ "outer_field": foo, "inner_json": inner ]) XCTAssertEqual(json2["inner_json"].rawValue as! [String: String], ["some_field": "12"]) } } // NumberTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class NumberTests: XCTestCase { func testNumber() { //getter var json = JSON(NSNumber(value: 9876543210.123456789)) XCTAssertEqual(json.number!, 9876543210.123456789) XCTAssertEqual(json.numberValue, 9876543210.123456789) XCTAssertEqual(json.stringValue, "9876543210.123457") json.string = "1000000000000000000000000000.1" XCTAssertNil(json.number) XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000.1") json.string = "1e+27" XCTAssertEqual(json.numberValue.description, "1000000000000000000000000000") //setter json.number = NSNumber(value: 123456789.0987654321) XCTAssertEqual(json.number!, 123456789.0987654321) XCTAssertEqual(json.numberValue, 123456789.0987654321) json.number = nil XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.number == nil) json.numberValue = 2.9876 XCTAssertEqual(json.number!, 2.9876) } func testBool() { var json = JSON(true) XCTAssertEqual(json.bool!, true) XCTAssertEqual(json.boolValue, true) XCTAssertEqual(json.numberValue, true as NSNumber) XCTAssertEqual(json.stringValue, "true") json.bool = false XCTAssertEqual(json.bool!, false) XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.numberValue, false as NSNumber) json.bool = nil XCTAssertTrue(json.bool == nil) XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.numberValue, 0) json.boolValue = true XCTAssertEqual(json.bool!, true) XCTAssertEqual(json.boolValue, true) XCTAssertEqual(json.numberValue, true as NSNumber) } func testDouble() { var json = JSON(9876543210.123456789) XCTAssertEqual(json.double!, 9876543210.123456789) XCTAssertEqual(json.doubleValue, 9876543210.123456789) XCTAssertEqual(json.numberValue, 9876543210.123456789) XCTAssertEqual(json.stringValue, "9876543210.123457") json.double = 2.8765432 XCTAssertEqual(json.double!, 2.8765432) XCTAssertEqual(json.doubleValue, 2.8765432) XCTAssertEqual(json.numberValue, 2.8765432) json.doubleValue = 89.0987654 XCTAssertEqual(json.double!, 89.0987654) XCTAssertEqual(json.doubleValue, 89.0987654) XCTAssertEqual(json.numberValue, 89.0987654) json.double = nil XCTAssertEqual(json.boolValue, false) XCTAssertEqual(json.doubleValue, 0.0) XCTAssertEqual(json.numberValue, 0) } func testFloat() { var json = JSON(54321.12345) XCTAssertTrue(json.float! == 54321.12345) XCTAssertTrue(json.floatValue == 54321.12345) XCTAssertEqual(json.numberValue, 54321.12345) XCTAssertEqual(json.stringValue, "54321.12345") json.double = 23231.65 XCTAssertTrue(json.float! == 23231.65) XCTAssertTrue(json.floatValue == 23231.65) XCTAssertEqual(json.numberValue, NSNumber(value: 23231.65)) json.double = -98766.23 XCTAssertEqual(json.float!, -98766.23) XCTAssertEqual(json.floatValue, -98766.23) XCTAssertEqual(json.numberValue, NSNumber(value: -98766.23)) } func testInt() { var json = JSON(123456789) XCTAssertEqual(json.int!, 123456789) XCTAssertEqual(json.intValue, 123456789) XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") json.int = nil XCTAssertTrue(json.boolValue == false) XCTAssertTrue(json.intValue == 0) XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.int == nil) json.intValue = 76543 XCTAssertEqual(json.int!, 76543) XCTAssertEqual(json.intValue, 76543) XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) json.intValue = 98765421 XCTAssertEqual(json.int!, 98765421) XCTAssertEqual(json.intValue, 98765421) XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } func testUInt() { var json = JSON(123456789) XCTAssertTrue(json.uInt! == 123456789) XCTAssertTrue(json.uIntValue == 123456789) XCTAssertEqual(json.numberValue, NSNumber(value: 123456789)) XCTAssertEqual(json.stringValue, "123456789") json.uInt = nil XCTAssertTrue(json.boolValue == false) XCTAssertTrue(json.uIntValue == 0) XCTAssertEqual(json.numberValue, 0) XCTAssertEqual(json.object as? NSNull, NSNull()) XCTAssertTrue(json.uInt == nil) json.uIntValue = 76543 XCTAssertTrue(json.uInt! == 76543) XCTAssertTrue(json.uIntValue == 76543) XCTAssertEqual(json.numberValue, NSNumber(value: 76543)) json.uIntValue = 98765421 XCTAssertTrue(json.uInt! == 98765421) XCTAssertTrue(json.uIntValue == 98765421) XCTAssertEqual(json.numberValue, NSNumber(value: 98765421)) } func testInt8() { let n127 = NSNumber(value: 127) var json = JSON(n127) XCTAssertTrue(json.int8! == n127.int8Value) XCTAssertTrue(json.int8Value == n127.int8Value) XCTAssertTrue(json.number! == n127) XCTAssertEqual(json.numberValue, n127) XCTAssertEqual(json.stringValue, "127") let nm128 = NSNumber(value: -128) json.int8Value = nm128.int8Value XCTAssertTrue(json.int8! == nm128.int8Value) XCTAssertTrue(json.int8Value == nm128.int8Value) XCTAssertTrue(json.number! == nm128) XCTAssertEqual(json.numberValue, nm128) XCTAssertEqual(json.stringValue, "-128") let n0 = NSNumber(value: 0 as Int8) json.int8Value = n0.int8Value XCTAssertTrue(json.int8! == n0.int8Value) XCTAssertTrue(json.int8Value == n0.int8Value) XCTAssertTrue(json.number!.isEqual(to: n0)) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") let n1 = NSNumber(value: 1 as Int8) json.int8Value = n1.int8Value XCTAssertTrue(json.int8! == n1.int8Value) XCTAssertTrue(json.int8Value == n1.int8Value) XCTAssertTrue(json.number!.isEqual(to:n1)) XCTAssertEqual(json.numberValue, n1) XCTAssertEqual(json.stringValue, "1") } func testUInt8() { let n255 = NSNumber(value: 255) var json = JSON(n255) XCTAssertTrue(json.uInt8! == n255.uint8Value) XCTAssertTrue(json.uInt8Value == n255.uint8Value) XCTAssertTrue(json.number! == n255) XCTAssertEqual(json.numberValue, n255) XCTAssertEqual(json.stringValue, "255") let nm2 = NSNumber(value: 2) json.uInt8Value = nm2.uint8Value XCTAssertTrue(json.uInt8! == nm2.uint8Value) XCTAssertTrue(json.uInt8Value == nm2.uint8Value) XCTAssertTrue(json.number! == nm2) XCTAssertEqual(json.numberValue, nm2) XCTAssertEqual(json.stringValue, "2") let nm0 = NSNumber(value: 0) json.uInt8Value = nm0.uint8Value XCTAssertTrue(json.uInt8! == nm0.uint8Value) XCTAssertTrue(json.uInt8Value == nm0.uint8Value) XCTAssertTrue(json.number! == nm0) XCTAssertEqual(json.numberValue, nm0) XCTAssertEqual(json.stringValue, "0") let nm1 = NSNumber(value: 1) json.uInt8 = nm1.uint8Value XCTAssertTrue(json.uInt8! == nm1.uint8Value) XCTAssertTrue(json.uInt8Value == nm1.uint8Value) XCTAssertTrue(json.number! == nm1) XCTAssertEqual(json.numberValue, nm1) XCTAssertEqual(json.stringValue, "1") } func testInt16() { let n32767 = NSNumber(value: 32767) var json = JSON(n32767) XCTAssertTrue(json.int16! == n32767.int16Value) XCTAssertTrue(json.int16Value == n32767.int16Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let nm32768 = NSNumber(value: -32768) json.int16Value = nm32768.int16Value XCTAssertTrue(json.int16! == nm32768.int16Value) XCTAssertTrue(json.int16Value == nm32768.int16Value) XCTAssertTrue(json.number! == nm32768) XCTAssertEqual(json.numberValue, nm32768) XCTAssertEqual(json.stringValue, "-32768") let n0 = NSNumber(value: 0) json.int16Value = n0.int16Value XCTAssertTrue(json.int16! == n0.int16Value) XCTAssertTrue(json.int16Value == n0.int16Value) XCTAssertEqual(json.number, n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") let n1 = NSNumber(value: 1) json.int16 = n1.int16Value XCTAssertTrue(json.int16! == n1.int16Value) XCTAssertTrue(json.int16Value == n1.int16Value) XCTAssertTrue(json.number! == n1) XCTAssertEqual(json.numberValue, n1) XCTAssertEqual(json.stringValue, "1") } func testUInt16() { let n65535 = NSNumber(value: 65535) var json = JSON(n65535) XCTAssertTrue(json.uInt16! == n65535.uint16Value) XCTAssertTrue(json.uInt16Value == n65535.uint16Value) XCTAssertTrue(json.number! == n65535) XCTAssertEqual(json.numberValue, n65535) XCTAssertEqual(json.stringValue, "65535") let n32767 = NSNumber(value: 32767) json.uInt16 = n32767.uint16Value XCTAssertTrue(json.uInt16! == n32767.uint16Value) XCTAssertTrue(json.uInt16Value == n32767.uint16Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") } func testInt32() { let n2147483647 = NSNumber(value: 2147483647) var json = JSON(n2147483647) XCTAssertTrue(json.int32! == n2147483647.int32Value) XCTAssertTrue(json.int32Value == n2147483647.int32Value) XCTAssertTrue(json.number! == n2147483647) XCTAssertEqual(json.numberValue, n2147483647) XCTAssertEqual(json.stringValue, "2147483647") let n32767 = NSNumber(value: 32767) json.int32 = n32767.int32Value XCTAssertTrue(json.int32! == n32767.int32Value) XCTAssertTrue(json.int32Value == n32767.int32Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let nm2147483648 = NSNumber(value: -2147483648) json.int32Value = nm2147483648.int32Value XCTAssertTrue(json.int32! == nm2147483648.int32Value) XCTAssertTrue(json.int32Value == nm2147483648.int32Value) XCTAssertTrue(json.number! == nm2147483648) XCTAssertEqual(json.numberValue, nm2147483648) XCTAssertEqual(json.stringValue, "-2147483648") } func testUInt32() { let n2147483648 = NSNumber(value: 2147483648 as UInt32) var json = JSON(n2147483648) XCTAssertTrue(json.uInt32! == n2147483648.uint32Value) XCTAssertTrue(json.uInt32Value == n2147483648.uint32Value) XCTAssertTrue(json.number! == n2147483648) XCTAssertEqual(json.numberValue, n2147483648) XCTAssertEqual(json.stringValue, "2147483648") let n32767 = NSNumber(value: 32767 as UInt32) json.uInt32 = n32767.uint32Value XCTAssertTrue(json.uInt32! == n32767.uint32Value) XCTAssertTrue(json.uInt32Value == n32767.uint32Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let n0 = NSNumber(value: 0 as UInt32) json.uInt32Value = n0.uint32Value XCTAssertTrue(json.uInt32! == n0.uint32Value) XCTAssertTrue(json.uInt32Value == n0.uint32Value) XCTAssertTrue(json.number! == n0) XCTAssertEqual(json.numberValue, n0) XCTAssertEqual(json.stringValue, "0") } func testInt64() { let int64Max = NSNumber(value: INT64_MAX) var json = JSON(int64Max) XCTAssertTrue(json.int64! == int64Max.int64Value) XCTAssertTrue(json.int64Value == int64Max.int64Value) XCTAssertTrue(json.number! == int64Max) XCTAssertEqual(json.numberValue, int64Max) XCTAssertEqual(json.stringValue, int64Max.stringValue) let n32767 = NSNumber(value: 32767) json.int64 = n32767.int64Value XCTAssertTrue(json.int64! == n32767.int64Value) XCTAssertTrue(json.int64Value == n32767.int64Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") let int64Min = NSNumber(value: (INT64_MAX-1) * -1) json.int64Value = int64Min.int64Value XCTAssertTrue(json.int64! == int64Min.int64Value) XCTAssertTrue(json.int64Value == int64Min.int64Value) XCTAssertTrue(json.number! == int64Min) XCTAssertEqual(json.numberValue, int64Min) XCTAssertEqual(json.stringValue, int64Min.stringValue) } func testUInt64() { let uInt64Max = NSNumber(value: UINT64_MAX) var json = JSON(uInt64Max) XCTAssertTrue(json.uInt64! == uInt64Max.uint64Value) XCTAssertTrue(json.uInt64Value == uInt64Max.uint64Value) XCTAssertTrue(json.number! == uInt64Max) XCTAssertEqual(json.numberValue, uInt64Max) XCTAssertEqual(json.stringValue, uInt64Max.stringValue) let n32767 = NSNumber(value: 32767) json.int64 = n32767.int64Value XCTAssertTrue(json.int64! == n32767.int64Value) XCTAssertTrue(json.int64Value == n32767.int64Value) XCTAssertTrue(json.number! == n32767) XCTAssertEqual(json.numberValue, n32767) XCTAssertEqual(json.stringValue, "32767") } } // PrintableTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class PrintableTests: XCTestCase { func testNumber() { let json: JSON = 1234567890.876623 XCTAssertEqual(json.description, "1234567890.876623") XCTAssertEqual(json.debugDescription, "1234567890.876623") } func testBool() { let jsonTrue: JSON = true XCTAssertEqual(jsonTrue.description, "true") XCTAssertEqual(jsonTrue.debugDescription, "true") let jsonFalse: JSON = false XCTAssertEqual(jsonFalse.description, "false") XCTAssertEqual(jsonFalse.debugDescription, "false") } func testString() { let json: JSON = "abcd efg, HIJK;LMn" XCTAssertEqual(json.description, "abcd efg, HIJK;LMn") XCTAssertEqual(json.debugDescription, "abcd efg, HIJK;LMn") } func testNil() { let jsonNil_1: JSON = JSON.null XCTAssertEqual(jsonNil_1.description, "null") XCTAssertEqual(jsonNil_1.debugDescription, "null") let jsonNil_2: JSON = JSON(NSNull()) XCTAssertEqual(jsonNil_2.description, "null") XCTAssertEqual(jsonNil_2.debugDescription, "null") } func testArray() { let json: JSON = [1, 2, "4", 5, "6"] var description = json.description.replacingOccurrences(of: "\n", with: "") description = description.replacingOccurrences(of: " ", with: "") XCTAssertEqual(description, "[1,2,\"4\",5,\"6\"]") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) } func testArrayWithStrings() { let array = ["\"123\""] let json = JSON(array) var description = json.description.replacingOccurrences(of: "\n", with: "") description = description.replacingOccurrences(of: " ", with: "") XCTAssertEqual(description, "[\"\\\"123\\\"\"]") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) } func testArrayWithOptionals() { let array = [1, 2, "4", 5, "6", nil] as [Any?] let json = JSON(array) guard var description = json.rawString([.castNilToNSNull: true]) else { XCTFail("could not represent array") return } description = description.replacingOccurrences(of: "\n", with: "") description = description.replacingOccurrences(of: " ", with: "") XCTAssertEqual(description, "[1,2,\"4\",5,\"6\",null]") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) } func testDictionary() { let json: JSON = ["1": 2, "2": "two", "3": 3] var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: String.CompareOptions.caseInsensitive) != nil) XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: String.CompareOptions.caseInsensitive) != nil) XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: String.CompareOptions.caseInsensitive) != nil) } func testDictionaryWithStrings() { let dict = ["foo": "{\"bar\":123}"] as [String: Any] let json = JSON(dict) var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) let exceptedResult = "{\"foo\":\"{\\\"bar\\\":123}\"}" XCTAssertEqual(debugDescription, exceptedResult) } func testDictionaryWithOptionals() { let dict = ["1": 2, "2": "two", "3": nil] as [String: Any?] let json = JSON(dict) guard var description = json.rawString([.castNilToNSNull: true]) else { XCTFail("could not represent dictionary") return } description = description.replacingOccurrences(of: "\n", with: "") description = description.replacingOccurrences(of: " ", with: "") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(description.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitive) != nil) XCTAssertTrue(description.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitive) != nil) XCTAssertTrue(description.range(of: "\"3\":null", options: NSString.CompareOptions.caseInsensitive) != nil) } } // RawRepresentableTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class RawRepresentableTests: XCTestCase { func testNumber() { let json: JSON = JSON(rawValue: 948394394.347384 as NSNumber)! XCTAssertEqual(json.int!, 948394394) XCTAssertEqual(json.intValue, 948394394) XCTAssertEqual(json.double!, 948394394.347384) XCTAssertEqual(json.doubleValue, 948394394.347384) XCTAssertEqual(json.float!, 948394394.347384) XCTAssertEqual(json.floatValue, 948394394.347384) let object: Any = json.rawValue if let int = object as? Int { XCTAssertEqual(int, 948394394) } XCTAssertEqual(object as? Double, 948394394.347384) if let float = object as? Float { XCTAssertEqual(float, 948394394.347384) } XCTAssertEqual(object as? NSNumber, 948394394.347384) } func testBool() { let jsonTrue: JSON = JSON(rawValue: true as NSNumber)! XCTAssertEqual(jsonTrue.bool!, true) XCTAssertEqual(jsonTrue.boolValue, true) let jsonFalse: JSON = JSON(rawValue: false)! XCTAssertEqual(jsonFalse.bool!, false) XCTAssertEqual(jsonFalse.boolValue, false) let objectTrue = jsonTrue.rawValue XCTAssertEqual(objectTrue as? Bool, true) let objectFalse = jsonFalse.rawValue XCTAssertEqual(objectFalse as? Bool, false) } func testString() { let string = "The better way to deal with JSON data in Swift." if let json: JSON = JSON(rawValue: string) { XCTAssertEqual(json.string!, string) XCTAssertEqual(json.stringValue, string) XCTAssertTrue(json.array == nil) XCTAssertTrue(json.dictionary == nil) XCTAssertTrue(json.null == nil) XCTAssertTrue(json.error == nil) XCTAssertTrue(json.type == .string) XCTAssertEqual(json.object as? String, string) } else { XCTFail("Should not run into here") } let object: Any = JSON(rawValue: string)!.rawValue XCTAssertEqual(object as? String, string) } func testNil() { if JSON(rawValue: NSObject()) != nil { XCTFail("Should not run into here") } } func testArray() { let array = [1, 2, "3", 4102, "5632", "abocde", "!@# $%^&*()"] as NSArray if let json: JSON = JSON(rawValue: array) { XCTAssertEqual(json, JSON(array)) } let object: Any = JSON(rawValue: array)!.rawValue XCTAssertTrue(array == object as! NSArray) } func testDictionary() { let dictionary = ["1": 2, "2": 2, "three": 3, "list": ["aa", "bb", "dd"]] as NSDictionary if let json: JSON = JSON(rawValue: dictionary) { XCTAssertEqual(json, JSON(dictionary)) } let object: Any = JSON(rawValue: dictionary)!.rawValue XCTAssertTrue(dictionary == object as! NSDictionary) } } // RawTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class RawTests: XCTestCase { func testRawData() { let json: JSON = ["somekey": "some string value"] let expectedRawData = "{\"somekey\":\"some string value\"}".data(using: String.Encoding.utf8) do { let data: Data = try json.rawData() XCTAssertEqual(expectedRawData, data) } catch _ {} } func testInvalidJSONForRawData() { let json: JSON = "...<nonsense>xyz</nonsense>" do { _ = try json.rawData() } catch let error as SwiftyJSONError { XCTAssertEqual(error, SwiftyJSONError.invalidJSON) } catch _ {} } func testArray() { let json: JSON = [1, "2", 3.12, NSNull(), true, ["name": "Jack"]] let data: Data? do { data = try json.rawData() } catch _ { data = nil } let string = json.rawString() XCTAssertTrue (data != nil) XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) } func testDictionary() { let json: JSON = ["number": 111111.23456789, "name": "Jack", "list": [1, 2, 3, 4], "bool": false, "null": NSNull()] let data: Data? do { data = try json.rawData() } catch _ { data = nil } let string = json.rawString() XCTAssertTrue (data != nil) XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0) } func testString() { let json: JSON = "I'm a json" XCTAssertEqual(json.rawString(), "I'm a json") } func testNumber() { let json: JSON = 123456789.123 XCTAssertEqual(json.rawString(), "123456789.123") } func testBool() { let json: JSON = true XCTAssertEqual(json.rawString(), "true") } func testNull() { let json: JSON = JSON.null XCTAssertEqual(json.rawString(), "null") } func testNestedJSON() { let inner: JSON = ["name": "john doe"] let json: JSON = ["level": 1337, "user": inner] let data: Data? do { data = try json.rawData() } catch _ { data = nil } let string = json.rawString() XCTAssertNotNil(data) XCTAssertNotNil(string) } } // SequenceTypeTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class SequenceTypeTests: XCTestCase { func testJSONFile() { if let file = Bundle(for: BaseTests.self).path(forResource: "Tests", ofType: "json") { let testData = try? Data(contentsOf: URL(fileURLWithPath: file)) guard let json = try? JSON(data: testData!) else { XCTFail("Unable to parse the data") return } for (index, sub) in json { switch (index as NSString).integerValue { case 0: XCTAssertTrue(sub["id_str"] == "240558470661799936") case 1: XCTAssertTrue(sub["id_str"] == "240556426106372096") case 2: XCTAssertTrue(sub["id_str"] == "240539141056638977") default: continue } } } else { XCTFail("Can't find the test JSON file") } } func testArrayAllNumber() { let json: JSON = [1, 2.0, 3.3, 123456789, 987654321.123456789] XCTAssertEqual(json.count, 5) var index = 0 var array = [NSNumber]() for (i, sub) in json { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.number!) index += 1 } XCTAssertEqual(index, 5) XCTAssertEqual(array, [1, 2.0, 3.3, 123456789, 987654321.123456789]) } func testArrayAllBool() { let json: JSON = JSON([true, false, false, true, true]) XCTAssertEqual(json.count, 5) var index = 0 var array = [Bool]() for (i, sub) in json { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.bool!) index += 1 } XCTAssertEqual(index, 5) XCTAssertEqual(array, [true, false, false, true, true]) } func testArrayAllString() { let json: JSON = JSON(rawValue: ["aoo", "bpp", "zoo"] as NSArray)! XCTAssertEqual(json.count, 3) var index = 0 var array = [String]() for (i, sub) in json { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.string!) index += 1 } XCTAssertEqual(index, 3) XCTAssertEqual(array, ["aoo", "bpp", "zoo"]) } func testArrayWithNull() { let json: JSON = JSON(rawValue: ["aoo", "bpp", NSNull(), "zoo"] as NSArray)! XCTAssertEqual(json.count, 4) var index = 0 var array = [AnyObject]() for (i, sub) in json { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.object as AnyObject) index += 1 } XCTAssertEqual(index, 4) XCTAssertEqual(array[0] as? String, "aoo") XCTAssertEqual(array[2] as? NSNull, NSNull()) } func testArrayAllDictionary() { let json: JSON = [["1": 1, "2": 2], ["a": "A", "b": "B"], ["null": NSNull()]] XCTAssertEqual(json.count, 3) var index = 0 var array = [AnyObject]() for (i, sub) in json { XCTAssertEqual(sub, json[index]) XCTAssertEqual(i, "\(index)") array.append(sub.object as AnyObject) index += 1 } XCTAssertEqual(index, 3) XCTAssertEqual((array[0] as! [String: Int])["1"]!, 1) XCTAssertEqual((array[0] as! [String: Int])["2"]!, 2) XCTAssertEqual((array[1] as! [String: String])["a"]!, "A") XCTAssertEqual((array[1] as! [String: String])["b"]!, "B") XCTAssertEqual((array[2] as! [String: NSNull])["null"]!, NSNull()) } func testDictionaryAllNumber() { let json: JSON = ["double": 1.11111, "int": 987654321] XCTAssertEqual(json.count, 2) var index = 0 var dictionary = [String: NSNumber]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.number! index += 1 } XCTAssertEqual(index, 2) XCTAssertEqual(dictionary["double"]! as NSNumber, 1.11111) XCTAssertEqual(dictionary["int"]! as NSNumber, 987654321) } func testDictionaryAllBool() { let json: JSON = ["t": true, "f": false, "false": false, "tr": true, "true": true] XCTAssertEqual(json.count, 5) var index = 0 var dictionary = [String: Bool]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.bool! index += 1 } XCTAssertEqual(index, 5) XCTAssertEqual(dictionary["t"]! as Bool, true) XCTAssertEqual(dictionary["false"]! as Bool, false) } func testDictionaryAllString() { let json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "z": "zoo"] as NSDictionary)! XCTAssertEqual(json.count, 3) var index = 0 var dictionary = [String: String]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.string! index += 1 } XCTAssertEqual(index, 3) XCTAssertEqual(dictionary["a"]! as String, "aoo") XCTAssertEqual(dictionary["bb"]! as String, "bpp") } func testDictionaryWithNull() { let json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "null": NSNull(), "z": "zoo"] as NSDictionary)! XCTAssertEqual(json.count, 4) var index = 0 var dictionary = [String: AnyObject]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.object as AnyObject? index += 1 } XCTAssertEqual(index, 4) XCTAssertEqual(dictionary["a"]! as? String, "aoo") XCTAssertEqual(dictionary["bb"]! as? String, "bpp") XCTAssertEqual(dictionary["null"]! as? NSNull, NSNull()) } func testDictionaryAllArray() { let json: JSON = JSON (["Number": [NSNumber(value: 1), NSNumber(value: 2.123456), NSNumber(value: 123456789)], "String": ["aa", "bbb", "cccc"], "Mix": [true, "766", NSNull(), 655231.9823]]) XCTAssertEqual(json.count, 3) var index = 0 var dictionary = [String: AnyObject]() for (key, sub) in json { XCTAssertEqual(sub, json[key]) dictionary[key] = sub.object as AnyObject? index += 1 } XCTAssertEqual(index, 3) XCTAssertEqual((dictionary["Number"] as! NSArray)[0] as? Int, 1) XCTAssertEqual((dictionary["Number"] as! NSArray)[1] as? Double, 2.123456) XCTAssertEqual((dictionary["String"] as! NSArray)[0] as? String, "aa") XCTAssertEqual((dictionary["Mix"] as! NSArray)[0] as? Bool, true) XCTAssertEqual((dictionary["Mix"] as! NSArray)[1] as? String, "766") XCTAssertEqual((dictionary["Mix"] as! NSArray)[2] as? NSNull, NSNull()) XCTAssertEqual((dictionary["Mix"] as! NSArray)[3] as? Double, 655231.9823) } func testDictionaryIteratingPerformance() { var json: JSON = [:] for i in 1...1000 { json[String(i)] = "hello" } measure { for (key, value) in json { print(key, value) } } } } // StringTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class StringTests: XCTestCase { func testString() { //getter var json = JSON("abcdefg hijklmn;opqrst.?+_()") XCTAssertEqual(json.string!, "abcdefg hijklmn;opqrst.?+_()") XCTAssertEqual(json.stringValue, "abcdefg hijklmn;opqrst.?+_()") json.string = "12345?67890.@#" XCTAssertEqual(json.string!, "12345?67890.@#") XCTAssertEqual(json.stringValue, "12345?67890.@#") } func testUrl() { let json = JSON("http://github.com") XCTAssertEqual(json.url!, URL(string: "http://github.com")!) } func testBool() { let json = JSON("true") XCTAssertTrue(json.boolValue) } func testBoolWithY() { let json = JSON("Y") XCTAssertTrue(json.boolValue) } func testBoolWithT() { let json = JSON("T") XCTAssertTrue(json.boolValue) } func testBoolWithYes() { let json = JSON("Yes") XCTAssertTrue(json.boolValue) } func testBoolWith1() { let json = JSON("1") XCTAssertTrue(json.boolValue) } func testUrlPercentEscapes() { let emDash = "\\u2014" let urlString = "http://examble.com/unencoded" + emDash + "string" guard let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return XCTFail("Couldn't encode URL string \(urlString)") } let json = JSON(urlString) XCTAssertEqual(json.url!, URL(string: encodedURLString)!, "Wrong unpacked ") let preEscaped = JSON(encodedURLString) XCTAssertEqual(preEscaped.url!, URL(string: encodedURLString)!, "Wrong unpacked ") } } // SubscriptTests.swift // // Copyright (c) 2014 - 2017 Pinglin Tang // // 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. class SubscriptTests: XCTestCase { func testArrayAllNumber() { var json: JSON = [1, 2.0, 3.3, 123456789, 987654321.123456789] XCTAssertTrue(json == [1, 2.0, 3.3, 123456789, 987654321.123456789]) XCTAssertTrue(json[0] == 1) XCTAssertEqual(json[1].double!, 2.0) XCTAssertTrue(json[2].floatValue == 3.3) XCTAssertEqual(json[3].int!, 123456789) XCTAssertEqual(json[4].doubleValue, 987654321.123456789) json[0] = 1.9 json[1] = 2.899 json[2] = 3.567 json[3] = 0.999 json[4] = 98732 XCTAssertTrue(json[0] == 1.9) XCTAssertEqual(json[1].doubleValue, 2.899) XCTAssertTrue(json[2] == 3.567) XCTAssertTrue(json[3].float! == 0.999) XCTAssertTrue(json[4].intValue == 98732) } func testArrayAllBool() { var json: JSON = [true, false, false, true, true] XCTAssertTrue(json == [true, false, false, true, true]) XCTAssertTrue(json[0] == true) XCTAssertTrue(json[1] == false) XCTAssertTrue(json[2] == false) XCTAssertTrue(json[3] == true) XCTAssertTrue(json[4] == true) json[0] = false json[4] = true XCTAssertTrue(json[0] == false) XCTAssertTrue(json[4] == true) } func testArrayAllString() { var json: JSON = JSON(rawValue: ["aoo", "bpp", "zoo"] as NSArray)! XCTAssertTrue(json == ["aoo", "bpp", "zoo"]) XCTAssertTrue(json[0] == "aoo") XCTAssertTrue(json[1] == "bpp") XCTAssertTrue(json[2] == "zoo") json[1] = "update" XCTAssertTrue(json[0] == "aoo") XCTAssertTrue(json[1] == "update") XCTAssertTrue(json[2] == "zoo") } func testArrayWithNull() { var json: JSON = JSON(rawValue: ["aoo", "bpp", NSNull(), "zoo"] as NSArray)! XCTAssertTrue(json[0] == "aoo") XCTAssertTrue(json[1] == "bpp") XCTAssertNil(json[2].string) XCTAssertNotNil(json[2].null) XCTAssertTrue(json[3] == "zoo") json[2] = "update" json[3] = JSON(NSNull()) XCTAssertTrue(json[0] == "aoo") XCTAssertTrue(json[1] == "bpp") XCTAssertTrue(json[2] == "update") XCTAssertNil(json[3].string) XCTAssertNotNil(json[3].null) } func testArrayAllDictionary() { let json: JSON = [["1": 1, "2": 2], ["a": "A", "b": "B"], ["null": NSNull()]] XCTAssertTrue(json[0] == ["1": 1, "2": 2]) XCTAssertEqual(json[1].dictionary!, ["a": "A", "b": "B"]) XCTAssertEqual(json[2], JSON(["null": NSNull()])) XCTAssertTrue(json[0]["1"] == 1) XCTAssertTrue(json[0]["2"] == 2) XCTAssertEqual(json[1]["a"], JSON(rawValue: "A")!) XCTAssertEqual(json[1]["b"], JSON("B")) XCTAssertNotNil(json[2]["null"].null) XCTAssertNotNil(json[2, "null"].null) let keys: [JSONSubscriptType] = [1, "a"] XCTAssertEqual(json[keys], JSON(rawValue: "A")!) } func testDictionaryAllNumber() { var json: JSON = ["double": 1.11111, "int": 987654321] XCTAssertEqual(json["double"].double!, 1.11111) XCTAssertTrue(json["int"] == 987654321) json["double"] = 2.2222 json["int"] = 123456789 json["add"] = 7890 XCTAssertTrue(json["double"] == 2.2222) XCTAssertEqual(json["int"].doubleValue, 123456789.0) XCTAssertEqual(json["add"].intValue, 7890) } func testDictionaryAllBool() { var json: JSON = ["t": true, "f": false, "false": false, "tr": true, "true": true, "yes": true, "1": true] XCTAssertTrue(json["1"] == true) XCTAssertTrue(json["yes"] == true) XCTAssertTrue(json["t"] == true) XCTAssertTrue(json["f"] == false) XCTAssertTrue(json["false"] == false) XCTAssertTrue(json["tr"] == true) XCTAssertTrue(json["true"] == true) json["f"] = true json["tr"] = false XCTAssertTrue(json["f"] == true) XCTAssertTrue(json["tr"] == JSON(false)) } func testDictionaryAllString() { var json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "z": "zoo"] as NSDictionary)! XCTAssertTrue(json["a"] == "aoo") XCTAssertEqual(json["bb"], JSON("bpp")) XCTAssertTrue(json["z"] == "zoo") json["bb"] = "update" XCTAssertTrue(json["a"] == "aoo") XCTAssertTrue(json["bb"] == "update") XCTAssertTrue(json["z"] == "zoo") } func testDictionaryWithNull() { var json: JSON = JSON(rawValue: ["a": "aoo", "bb": "bpp", "null": NSNull(), "z": "zoo"] as NSDictionary)! XCTAssertTrue(json["a"] == "aoo") XCTAssertEqual(json["bb"], JSON("bpp")) XCTAssertEqual(json["null"], JSON(NSNull())) XCTAssertTrue(json["z"] == "zoo") json["null"] = "update" XCTAssertTrue(json["a"] == "aoo") XCTAssertTrue(json["null"] == "update") XCTAssertTrue(json["z"] == "zoo") } func testDictionaryAllArray() { //Swift bug: [1, 2.01,3.09] is convert to [1, 2, 3] (Array<Int>) let json: JSON = JSON ([[NSNumber(value: 1), NSNumber(value: 2.123456), NSNumber(value: 123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertTrue(json[0] == [1, 2.123456, 123456789]) XCTAssertEqual(json[0][1].double!, 2.123456) XCTAssertTrue(json[0][2] == 123456789) XCTAssertTrue(json[1][0] == "aa") XCTAssertTrue(json[1] == ["aa", "bbb", "cccc"]) XCTAssertTrue(json[2][0] == true) XCTAssertTrue(json[2][1] == "766") XCTAssertTrue(json[[2, 1]] == "766") XCTAssertEqual(json[2][2], JSON(NSNull())) XCTAssertEqual(json[2, 2], JSON(NSNull())) XCTAssertEqual(json[2][3], JSON(655231.9823)) XCTAssertEqual(json[2, 3], JSON(655231.9823)) XCTAssertEqual(json[[2, 3]], JSON(655231.9823)) } func testOutOfBounds() { let json: JSON = JSON ([[NSNumber(value: 1), NSNumber(value: 2.123456), NSNumber(value: 123456789)], ["aa", "bbb", "cccc"], [true, "766", NSNull(), 655231.9823]] as NSArray) XCTAssertEqual(json[9], JSON.null) XCTAssertEqual(json[-2].error, SwiftyJSONError.indexOutOfBounds) XCTAssertEqual(json[6].error, SwiftyJSONError.indexOutOfBounds) XCTAssertEqual(json[9][8], JSON.null) XCTAssertEqual(json[8][7].error, SwiftyJSONError.indexOutOfBounds) XCTAssertEqual(json[8, 7].error, SwiftyJSONError.indexOutOfBounds) XCTAssertEqual(json[999].error, SwiftyJSONError.indexOutOfBounds) } func testErrorWrongType() { let json = JSON(12345) XCTAssertEqual(json[9], JSON.null) XCTAssertEqual(json[9].error, SwiftyJSONError.wrongType) XCTAssertEqual(json[8][7].error, SwiftyJSONError.wrongType) XCTAssertEqual(json["name"], JSON.null) XCTAssertEqual(json["name"].error, SwiftyJSONError.wrongType) XCTAssertEqual(json[0]["name"].error, SwiftyJSONError.wrongType) XCTAssertEqual(json["type"]["name"].error, SwiftyJSONError.wrongType) XCTAssertEqual(json["name"][99].error, SwiftyJSONError.wrongType) XCTAssertEqual(json[1, "Value"].error, SwiftyJSONError.wrongType) XCTAssertEqual(json[1, 2, "Value"].error, SwiftyJSONError.wrongType) XCTAssertEqual(json[[1, 2, "Value"]].error, SwiftyJSONError.wrongType) } func testErrorNotExist() { let json: JSON = ["name": "NAME", "age": 15] XCTAssertEqual(json["Type"], JSON.null) XCTAssertEqual(json["Type"].error, SwiftyJSONError.notExist) XCTAssertEqual(json["Type"][1].error, SwiftyJSONError.notExist) XCTAssertEqual(json["Type", 1].error, SwiftyJSONError.notExist) XCTAssertEqual(json["Type"]["Value"].error, SwiftyJSONError.notExist) XCTAssertEqual(json["Type", "Value"].error, SwiftyJSONError.notExist) } func testMultilevelGetter() { let json: JSON = [[[[["one": 1]]]]] XCTAssertEqual(json[[0, 0, 0, 0, "one"]].int!, 1) XCTAssertEqual(json[0, 0, 0, 0, "one"].int!, 1) XCTAssertEqual(json[0][0][0][0]["one"].int!, 1) } func testMultilevelSetter1() { var json: JSON = [[[[["num": 1]]]]] json[0, 0, 0, 0, "num"] = 2 XCTAssertEqual(json[[0, 0, 0, 0, "num"]].intValue, 2) json[0, 0, 0, 0, "num"] = JSON.null XCTAssertEqual(json[0, 0, 0, 0, "num"].null!, NSNull()) json[0, 0, 0, 0, "num"] = 100.009 XCTAssertEqual(json[0][0][0][0]["num"].doubleValue, 100.009) json[[0, 0, 0, 0]] = ["name": "Jack"] XCTAssertEqual(json[0, 0, 0, 0, "name"].stringValue, "Jack") XCTAssertEqual(json[0][0][0][0]["name"].stringValue, "Jack") XCTAssertEqual(json[[0, 0, 0, 0, "name"]].stringValue, "Jack") json[[0, 0, 0, 0, "name"]].string = "Mike" XCTAssertEqual(json[0, 0, 0, 0, "name"].stringValue, "Mike") let path: [JSONSubscriptType] = [0, 0, 0, 0, "name"] json[path].string = "Jim" XCTAssertEqual(json[path].stringValue, "Jim") } func testMultilevelSetter2() { var json: JSON = ["user": ["id": 987654, "info": ["name": "jack", "email": "[email protected]"], "feeds": [98833, 23443, 213239, 23232]]] json["user", "info", "name"] = "jim" XCTAssertEqual(json["user", "id"], 987654) XCTAssertEqual(json["user", "info", "name"], "jim") XCTAssertEqual(json["user", "info", "email"], "[email protected]") XCTAssertEqual(json["user", "feeds"], [98833, 23443, 213239, 23232]) json["user", "info", "email"] = "[email protected]" XCTAssertEqual(json["user", "id"], 987654) XCTAssertEqual(json["user", "info", "name"], "jim") XCTAssertEqual(json["user", "info", "email"], "[email protected]") XCTAssertEqual(json["user", "feeds"], [98833, 23443, 213239, 23232]) json["user", "info"] = ["name": "tom", "email": "[email protected]"] XCTAssertEqual(json["user", "id"], 987654) XCTAssertEqual(json["user", "info", "name"], "tom") XCTAssertEqual(json["user", "info", "email"], "[email protected]") XCTAssertEqual(json["user", "feeds"], [98833, 23443, 213239, 23232]) json["user", "feeds"] = [77323, 2313, 4545, 323] XCTAssertEqual(json["user", "id"], 987654) XCTAssertEqual(json["user", "info", "name"], "tom") XCTAssertEqual(json["user", "info", "email"], "[email protected]") XCTAssertEqual(json["user", "feeds"], [77323, 2313, 4545, 323]) } }
39.100392
197
0.631918
1de3275b8cf7a20924cb17f2056b211c632c8c1c
1,112
// // ServiceError.swift // // // Created by Kunal Shrivastava on 11/23/19. // import Foundation /** List of error provided by the Networking module */ public enum ServiceError: Error { case error(_ error: Error) case invalidEndpoint case invalidResponse case dataDecodeError case unknownError case networkError case noData } extension ServiceError: Equatable { public static func ==(lhs: ServiceError, rhs: ServiceError) -> Bool { switch (lhs, rhs) { case (let .error(error1), let .error(error2)): return error1.localizedDescription == error2.localizedDescription case (.invalidEndpoint, .invalidEndpoint): return true case (.invalidResponse, .invalidResponse): return true case (.dataDecodeError, .dataDecodeError): return true case (.unknownError, .unknownError): return true case (.networkError, .networkError): return true case (.noData, .noData): return true default: return false } } }
24.711111
77
0.616906
2202b92546675075024c763b628966186b90aa13
1,335
import Foundation import NIO // MARK: AnnouncementsActor /// Announcements use cases. public protocol AnnouncementsActor: Actor { /// Presents publicly available information. /// - Parameter specification: Specification for this action. /// - Parameter boundaries: Boundaries for this action. /// /// Does mostly nothing, but returns an `UserRepresentation` if a user id is specified. This /// can be used to present different information for users. /// /// Specification: /// - `userID`: ID of the user to create the invitation for. /// /// Boundaries: /// - `worker`: EventLoop /// /// The result returned by this action: /// ``` /// struct Result { /// let user: UserRepresentation /// } /// ``` func presentPublicly( _ specification: PresentPublicly.Specification, _ boundaries: PresentPublicly.Boundaries ) throws -> EventLoopFuture<PresentPublicly.Result> } /// This is the domain’s implementation of the Announcements use cases. Actions will extend this by /// their corresponding use case methods. public final class DomainAnnouncementsActor: AnnouncementsActor { let userRepository: UserRepository public required init(userRepository: UserRepository) { self.userRepository = userRepository } }
29.021739
99
0.681648
fbaee6f2ddf94d9e8d8443c184a469a11b20b487
3,279
// // ViewController.swift // FillableLoaders // // Created by Pol Quintana on 2/8/15. // Copyright (c) 2015 Pol Quintana. All rights reserved. // import UIKit import FillableLoaders class ViewController: UIViewController { var segmentedControl: UISegmentedControl = UISegmentedControl() var button: UIButton = UIButton() var loader: FillableLoader = FillableLoader() var firstLogo: Bool = true override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) loader = PlainLoader.showLoader(with: path()) setupSubviews() } func setupSubviews() { // let imageView = UIImageView(image: UIImage(named: "bg.png")) // imageView.frame = view.frame // view.addSubview(imageView) let margin: CGFloat = 30 let width: CGFloat = view.frame.width let height: CGFloat = view.frame.height let window = UIApplication.shared.delegate?.window! let items = ["Waves", "Plain", "Spike", "Rounded"] segmentedControl = UISegmentedControl(items: items) segmentedControl.selectedSegmentIndex = 0 segmentedControl.layer.cornerRadius = 5.0 segmentedControl.backgroundColor = UIColor.white segmentedControl.tintColor = UIColor(white: 0.2, alpha: 1) segmentedControl.frame = CGRect(x: margin, y: height - margin - 40, width: width - margin*2, height: 40) segmentedControl.addTarget(self, action: #selector(segmentedControlTouch), for: .valueChanged) window!.addSubview(segmentedControl) button.frame = CGRect(x: 0, y: 0, width: 150, height: 35) button.center = CGPoint(x: view.frame.width/2, y: view.frame.height - 2*margin - 35) button.backgroundColor = UIColor.white button.layer.cornerRadius = 5.0 button.setTitle("Change Logo", for: UIControl.State()) button.setTitleColor(UIColor.black, for: UIControl.State()) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.addTarget(self, action: #selector(changeLogo), for: .touchUpInside) window!.addSubview(button) } @objc func segmentedControlTouch(_ sender: UISegmentedControl) { presentFillableLoader(at: sender.selectedSegmentIndex) } @objc func changeLogo() { firstLogo = !firstLogo presentFillableLoader(at: segmentedControl.selectedSegmentIndex) } func presentFillableLoader(at index: Int) { loader.removeLoader(false) switch index { case 1: loader = PlainLoader.showLoader(with: path()) case 2: loader = SpikeLoader.showLoader(with: path()) case 3: loader = RoundedLoader.showLoader(with: path()) default: loader = WavesLoader.showLoader(with: path()) } let window = UIApplication.shared.delegate?.window! window!.bringSubviewToFront(segmentedControl) window!.bringSubviewToFront(button) } func path() -> CGPath{ return firstLogo ? Paths.twitterPath() : Paths.githubPath() } override var prefersStatusBarHidden : Bool { return true } }
35.258065
112
0.648063
0e4f2c0006ad030c52d24496dba7a201600f7b7c
1,301
// // NetworkSessionMockFromFile.swift // MasKitTests // // Created by Ben Chatelain on 2019-01-05. // Copyright © 2019 mas-cli. All rights reserved. // import MasKit /// Mock NetworkSession for testing with saved JSON response payload files. class NetworkSessionMockFromFile: NetworkSessionMock { /// Path to response payload file relative to test bundle. private let responseFile: String /// Initializes a mock URL session with a file for the response. /// /// - Parameter responseFile: Name of file containing JSON response body. init(responseFile: String) { self.responseFile = responseFile } /// Loads data from a file. /// /// - Parameters: /// - url: unused /// - completionHandler: Closure which is delivered either data or an error. @objc override func loadData(from _: URL, completionHandler: @escaping (Data?, Error?) -> Void) { guard let fileURL = Bundle.url(for: responseFile) else { fatalError("Unable to load file \(responseFile)") } do { let data = try Data(contentsOf: fileURL, options: .mappedIfSafe) completionHandler(data, nil) } catch { print("Error opening file: \(error)") completionHandler(nil, error) } } }
31.731707
101
0.644889
e0839fba275f284728bfdd6a6396ffdbbb9c4e36
2,050
import Foundation import GitHubAPI import XCTest @testable import struct GitHubAPI.Release final class GetReleasesTests: XCTestCase { let client = GitHubClient(token: "this-is-stub") override func tearDown() { clearStubs() super.tearDown() } func testGetReleases_success() throws { stubGetRequest(path: "/repos/417-72KI/SSGH/releases", responseData: [ [ "name": "1.0.0", "url": "https://api.github.com/repos/417-72KI/SSGH/releases/22078686", "tag_name":"1.0.0", "prerelease":false, "draft":false ] ]) let expected: [Release] = [Release(url: URL(string: "https://api.github.com/repos/417-72KI/SSGH/releases/22078686")!, name: "1.0.0", tagName: "1.0.0", prerelease: false, draft: false) ] let releases = try client.getReleases(for: "417-72KI", repo: "SSGH").get() XCTAssertEqual(releases, expected) } func testGetReleases_userNotExist() throws { stubGetRequest(path: "/repos/41772KI/SSGH/releases", statusCode: 404) let result = client.getReleases(for: "41772KI", repo: "SSGH") XCTAssertThrowsError(try result.get()) { guard case .repoNotFound("41772KI/SSGH") = ($0 as? GitHubClient.Error) else { XCTFail("Unexpected error: \($0)") return } } } func testGetReleases_repoNotExist() throws { stubGetRequest(path: "/repos/417-72KI/SGH/releases", statusCode: 404) let result = client.getReleases(for: "417-72KI", repo: "SGH") XCTAssertThrowsError(try result.get()) { guard case .repoNotFound("417-72KI/SGH") = ($0 as? GitHubClient.Error) else { XCTFail("Unexpected error: \($0)") return } } } }
34.166667
125
0.532195
0175294037e507f80ecbbb72ba4487b77ed9b354
1,180
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "LedgerToTaskjuggler", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "LedgerToTaskjuggler", targets: ["LedgerToTaskjuggler"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "l2tj", dependencies: ["LedgerToTaskjuggler"]), .target( name: "LedgerToTaskjuggler", dependencies: []), .testTarget( name: "LedgerToTaskjugglerTests", dependencies: ["LedgerToTaskjuggler"]), ] )
36.875
122
0.627966
5d4c96027ccb255cd939bf037188ab6b62d88219
5,149
// // AppDelegate.swift // DailyGit // // Created by Vlad Munteanu on 2/23/19. // Copyright © 2019 Vlad Munteanu. All rights reserved. // import UIKit import UserNotifications import Firebase import FirebaseCore import FirebaseMessaging @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? let gcmMessageIDKey = "gcm.message_id" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // SwiftTrace.traceBundle(containing: type(of: self)) // SwiftTrace.trace(aClass: MainVC.self) FirebaseApp.configure() Messaging.messaging().delegate = self if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) { Constants.isIpad = true } if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self } //resetDefaults() UINavigationBar.appearance().barTintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) UINavigationBar.appearance().isTranslucent = false UITabBar.appearance().tintColor = Constants.gitGreenColor window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() if (userExist() == true) { AutoUpdater.shared.startTimer() let navigationController = UINavigationController(rootViewController: MainVC()) self.window?.rootViewController = navigationController } else { //Not Logged In let navController = OnboardingVC() window?.rootViewController = navController } return true } func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Firebase registration token: \(fcmToken)") let dataDict:[String: String] = ["token": fcmToken] NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict) // TODO: If necessary send token to application server. // Note: This callback is fired at each app startup and whenever a new token is generated. } func applicationWillTerminate(_ application: UIApplication) { AutoUpdater.shared.stopTimer() } func applicationDidFinishLaunching(_ application: UIApplication) { AutoUpdater.shared.stopTimer() } func resetDefaults() { let defaults = UserDefaults.standard let dictionary = defaults.dictionaryRepresentation() dictionary.keys.forEach { key in defaults.removeObject(forKey: key) } } func userExist() -> Bool { return (UserInfoHelper.shared.readInfo(info: .username) as? String != "") } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Unable to register for remote notifications: \(error.localizedDescription)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } // Print full message. print(userInfo) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } // Print full message. print(userInfo) completionHandler(UIBackgroundFetchResult.newData) } } extension UserDefaults { static func exists(key: String) -> Bool { return UserDefaults.standard.object(forKey: key) != nil } }
35.027211
145
0.643426
1a8345c75da492ff29bbc1626f8bae97358a94aa
5,114
// // Game.swift // Halite-III // // Created by Chris Downie on 10/24/18. // Copyright © 2018 Chris Downie. All rights reserved. // import Foundation /// The game object holds all metadata to run the game, and is an organizing layer between your code and the game /// engine. Game initializes the game, which includes generating the map and registering the players. struct Game { var turnNumber = 0 var me: Player { return players.first(where: { $0.id == myId })! } var gameMap: Map private var myId: Int private var players: [Player] private let shouldStripNewlines = false private let networking: Networking init() { let networking = Networking() self.networking = networking // Load shared constants from the first line of input let constantInput = networking.readConstants() do { try Constant.loadShared(with: constantInput.json) } catch { fatalError("Failed to parse constants from input") } // Load player count and ID from next line of input. let identity = networking.readIdentity() myId = identity.myId _ = Log.seedShared(playerId: myId) // Load each player players = (0..<identity.numPlayers).map { index in let playerInput = networking.readPlayer() let shipyard = Shipyard(owner: playerInput.playerId, id: unknownStructureId, position: playerInput.shipyardPosition) return Player(id: playerInput.playerId, shipyard: shipyard) } // Load map size let mapSize = networking.readMapDimensions() let initialHalite = (0..<mapSize.mapHeight).map { row -> [Int] in let mapRow = networking.readMapRow() return mapRow.haliteAmount } gameMap = Map(width: mapSize.mapWidth, height: mapSize.mapHeight, initialHalite: initialHalite) } /// A game of Halite III is initialized when each player sends a string name. Game forwards this to the engine, /// and launches the game. /// /// - Parameter botName: The name of the bot func ready(botName: String) { networking.writeReady(botName: botName) } /// The game loop sends the game state to the players and processes commands returned from the players. This /// repeats for each turn. Games last between 400 and 500 turns per game depending on map size. The game engine /// kills any bot that takes more than 2,000 milliseconds to process. /// /// Updates the game state, and returns nothing. mutating func updateFrame() { turnNumber = networking.readTurnNumber() Log.shared.info("============ TURN \(turnNumber) ============") let playerUpdates = (0..<players.count).map { _ -> Networking.PlayerUpdate in networking.readPlayerUpdate() } let mapUpdates = networking.readMapUpdates() apply(playerUpdates: playerUpdates, mapUpdates: mapUpdates) } /// The command queue is a list of commands. The player’s code fills this list with commands and sends it to the /// game object, where it is sent to the game engine. The game engine kills any bot that attempts to issue /// multiple commands to one ship. /// /// - Parameter commands: The command queue to execute. func endTurn(commands: [Command]) { networking.write(commands: commands) } // MARK: - Private methods mutating func apply(playerUpdates: [Networking.PlayerUpdate], mapUpdates: [Networking.MapUpdate]) { // Update Players var updatedPlayers = [Player]() playerUpdates.forEach { update in guard let playerToUpdate = players.first(where: { $0.id == update.playerID }) else { fatalError("Can't fild player with id \(update.playerID) to update.") } let updatedPlayer = Player(id: update.playerID, shipyard: playerToUpdate.shipyard, haliteAmount: update.halite, ships: update.ships, dropoffs: update.dropoffs) updatedPlayers.append(updatedPlayer) } players = updatedPlayers // Update Map var haliteGrid = gameMap.haliteGrid mapUpdates.forEach { update in haliteGrid[update.position.y][update.position.x] = update.haliteAmount } let newMap = Map(width: gameMap.width, height: gameMap.height, initialHalite: haliteGrid) players.forEach { player in player.getShips().forEach { ship in newMap[ship.position].markUnsafe(ship: ship) } newMap[player.shipyard.position].structure = player.shipyard player.getDropoffs().forEach { dropoff in newMap[dropoff.position].structure = dropoff } } gameMap = newMap } }
38.451128
128
0.608526
22d999e13ea6e59f128a885a7318912aaae29bc1
1,922
// // ContentView.swift // Shared // // Created by Frad LEE on 5/27/21. // import SwiftUI // MARK: - ListItem struct ListItem: Identifiable { let id = UUID() let icon: String let name: String } // MARK: - ContentView struct ContentView: View { let list = [ ListItem(icon: "icon_calc", name: "Calculator Button"), ListItem(icon: "icon_spring", name: "Spring Animations"), ListItem(icon: "icon_flash", name: "Flashlight Button"), ListItem(icon: "icon_rubber", name: "Rubberbanding"), ListItem(icon: "icon_acceleration", name: "Acceleration Pausing"), ListItem(icon: "icon_momentum", name: "Rewarding Momentum"), ListItem(icon: "icon_pip", name: "FaceTime PiP") ] var body: some View { NavigationView { List(list) { listItem in NavigationLink(destination: destinationView(listItem.name)) { HStack(spacing: 16) { Image(listItem.icon) .resizable() .frame(width: 28, height: 28, alignment: .center) Text(listItem.name).bold() } .padding(.vertical) } } .navigationTitle("Fluid Interfaces") } } } extension ContentView { @ViewBuilder private func destinationView(_ destination: String) -> some View { switch destination { case "Calculator Button": CalculatorButtonView() case "Spring Animations": SpringAnimationsView() case "Flashlight Button": FlashlightButtonView() case "Rubberbanding": RubberbandingView() case "Acceleration Pausing": AccelerationPausingView() case "Rewarding Momentum": RewardingMomentumView() case "FaceTime PiP": FaceTimePiPView() default: Text("ERROR") } } } // MARK: - ContentView_Previews struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .preferredColorScheme(.dark) } }
23.728395
70
0.637877
09bbb5481248e07e1d26044072eb62e4351169b4
1,035
// // ModifierKeyActionPicker.swift // LinearMouse // // Created by lujjjh on 2021/7/29. // import Foundation import SwiftUI struct ModifierKeyActionPicker: View { @State var label: String @Binding var action: ModifierKeyAction var body: some View { Picker(label, selection: $action.type) { ForEach(ModifierKeyActionType.allCases, id: \.self) { Text(NSLocalizedString($0.rawValue, comment: "")).tag($0) } } if action.type == .changeSpeed { HStack { Text("to") Slider(value: $action.speedFactor, in: 0.1...5.0, step: 0.1) Text(String(format: "%.1f×", action.speedFactor)) } .padding(.bottom, 20) } } } struct ModifierKeyActionPicker_Previews: PreviewProvider { static var previews: some View { ModifierKeyActionPicker(label: "shift", action: .constant(.init(type: .noAction, speedFactor: 1.0))) } }
25.243902
108
0.564251
fc6118709a3c1aef60aec01b36f3f1b781411702
149
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(MGUtilitiesTests.allTests), ] } #endif
14.9
45
0.731544
feec70c7ea9ecc4c44754e35e032264d054dbac2
1,409
// // Validatable.swift // R.swift.Library // // Created by Mathijs Kadijk on 17-12-15. // From: https://github.com/mac-cain13/R.swift.Library // License: MIT License // import Foundation /// Error thrown during validation public struct ValidationError: Error, CustomStringConvertible { /// Human readable description public let description: String public init(description: String) { self.description = description } } public protocol Validatable { /** Validates this entity and throws if it encounters a invalid situation, a validatable should also validate it sub-validatables if it has any. - throws: If there the configuration error a ValidationError is thrown */ static func validate() throws } extension Validatable { /** Validates this entity and asserts if it encounters a invalid situation, a validatable should also validate it sub-validatables if it has any. In -O builds (the default for Xcode's Release configuration), validation is not evaluated, and there are no effects. */ @available(*, deprecated, message: "Use validate() instead, preferably from a testcase.") public static func assertValid() { assert( theRealAssert() ) } fileprivate static func theRealAssert() -> Bool { do { try validate() } catch { assertionFailure("Validation of \(type(of: self)) failed with error: \(error)") } return true } }
28.18
261
0.713982
0188dd6e2570292cfcc8f3e1147d7e418fc71a6e
5,960
// // PDSortingMapListRepository.swift // PD // // Created by Henry on 2019/07/02. // /// A list that stores key-value pairs in sorted order by comparable key. /// /// You modify this repository like `Map` and read like `List`. public struct PDSortingMapListRepository<Key,Value>: PDListRepositoryProtocol where Key: Comparable { private var impl = Timeline() public init() {} init(timeline tx: Timeline) { impl = tx } // mutating func recordSetStep(_ v: Value?, for k: Key, with t: PDTimestamp) { // func determinateOp(old:V?, new:V?) -> Step.Operation? { // switch (old,new) { // case (nil,nil): return nil // case (nil,_): return // } // } // let p1 = timeline.steps.last?.new ?? Step.Point(time: PDTimestamp(), snapshot: Snapshot()) // let s1 = p1.snapshot // let i1 = s1.index(for: k)! // var s2 = s1 // if let v = v { // // } // else { // // } // let op = v == nil // s2[k] = nil // let p2 = Step.Point(time: t, snapshot: s2) // let x = Step(operation: .remove, range: i1..<i1+1, old: p1, new: p2) // impl.record(x) // } mutating func recordWholeSnapshotReplacementSteps(_ s: Snapshot, with t: PDTimestamp) { if let x1 = timeline.steps.last { let p1 = x1.new let s1 = p1.snapshot let r1 = s1.startIndex..<s1.endIndex let p2 = Step.Point(time: PDTimestamp(), snapshot: Snapshot()) impl.record(Step(operation: .remove, range: r1, old: p1, new: p2)) } // Now existence of last step is guaranteed. let x1 = timeline.steps.last! let p1 = x1.new let s2 = s let r2 = s2.startIndex..<s2.endIndex let p2 = Step.Point(time: t, snapshot: s2) let x2 = Step(operation: .insert, range: r2, old: p1, new: p2) impl.record(x2) } mutating func recordRemoveStep(for k: Key, with t: PDTimestamp) { precondition(self[k] != nil) let p1 = timeline.steps.last?.new ?? Step.Point(time: PDTimestamp(), snapshot: Snapshot()) let s1 = p1.snapshot let i1 = s1.index(for: k)! var s2 = s1 s2[k] = nil let p2 = Step.Point(time: t, snapshot: s2) let x = Step(operation: .remove, range: i1..<i1+1, old: p1, new: p2) impl.record(x) } mutating func recordInsertionStep(_ v: Value, for k: Key, with t: PDTimestamp) { precondition(self[k] == nil) let p1 = timeline.steps.last?.new ?? Step.Point(time: PDTimestamp(), snapshot: Snapshot()) let s1 = p1.snapshot var s2 = s1 s2[k] = v let i2 = s2.index(for: k)! let p2 = Step.Point(time: t, snapshot: s2) let x = Step(operation: .insert, range: i2..<i2+1, old: p1, new: p2) impl.record(x) } mutating func recordReplacementStep(_ v: Value, for k: Key, with t: PDTimestamp) { precondition(self[k] != nil) let p1 = timeline.steps.last?.new ?? Step.Point(time: PDTimestamp(), snapshot: Snapshot()) let s1 = p1.snapshot var s2 = s1 s2[k] = v let i = s2.index(for: k)! let p2 = Step.Point(time: t, snapshot: s2) // As key is same, we can use same index again. let x = Step(operation: .replace, range: i..<i+1, old: p1, new: p2) impl.record(x) } var latestSnapshot: Snapshot { return impl.steps.last?.new.snapshot ?? Snapshot() } } public extension PDSortingMapListRepository { var startIndex: Int { return 0 } var endIndex: Int { return latestSnapshot.count } subscript(_ i: Int) -> Element { return latestSnapshot[i] } } public extension PDSortingMapListRepository { typealias Timeline = PDTimeline<Step> typealias Step = PDListStep<Snapshot> typealias Snapshot = PDSortingMapList<Key,Value> typealias Element = Snapshot.Element var timeline: Timeline { return impl } var latestOnly: PDSortingMapListRepository { guard let x = timeline.steps.last else { return self } var z = self z.impl = Timeline(x) return z } } public extension PDSortingMapListRepository { func latest(since p: PDTimestamp) -> PDSortingMapListRepository? { guard let tx = timeline.suffix(since: p) else { return nil } return PDSortingMapListRepository(timeline: tx) } subscript(_ k: Key) -> Value? { get { return latestSnapshot[k] } set(v) { if let v = v { if latestSnapshot[k] != nil { // Replace. recordReplacementStep(v, for: k, with: PDTimestamp()) } else { // Insert. recordInsertionStep(v, for: k, with: PDTimestamp()) } } else { if latestSnapshot[k] != nil { // Remove. recordRemoveStep(for: k, with: PDTimestamp()) } else { // Ignore. } } } } // subscript(_ k: Key) -> Value? { // return latestSnapshot[k] // } // mutating func setValues<C>(_ es:C) where // C:Collection, // C.Element == Element { // recordReplacementStep(es, with: PDTimestamp()) // } // mutating func insert<C>(contentsOf es:C) where // C:Collection, // C.Element == Element { // recordInsertingStep(es, with: PDTimestamp()) // } // mutating func insert(_ e: Element) { // insert(contentsOf: CollectionOfOne(e)) // } // mutating func removeSubrange<C>(_ ks: C) where // C:Collection, // C.Element == Key { // recordRemovingStep(PDSet(ks), with: PDTimestamp()) // } // mutating func remove(_ k: Key) { // removeSubrange(CollectionOfOne(k)) // } }
35.058824
100
0.554362
61600ed72234da908a2b6f3a1b6c546a322945c6
455
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct B<T where g:a{class A{var f{class B:A?{protocol c
45.5
79
0.751648
f79c5bf143d8753299334e4929e8822ac8e31f1c
880
// // main.swift // mas-cli // // Created by Andrew Naylor on 11/07/2015. // Copyright © 2015 Andrew Naylor. All rights reserved. // import Foundation public struct StderrOutputStream: TextOutputStream { public mutating func write(_ string: String) { fputs(string, stderr) } } let registry = CommandRegistry<MASError>() let helpCommand = HelpCommand(registry: registry) registry.register(AccountCommand()) registry.register(InstallCommand()) registry.register(ListCommand()) registry.register(OutdatedCommand()) registry.register(ResetCommand()) registry.register(SearchCommand()) registry.register(SignInCommand()) registry.register(SignOutCommand()) registry.register(UpgradeCommand()) registry.register(VersionCommand()) registry.register(helpCommand) registry.main(defaultVerb: helpCommand.verb) { error in printError(String(describing: error)) }
25.142857
56
0.767045
678e8ba72dd7d1537baaa8ff3a1ad431aa1dd27a
2,574
// // MovieDetailViewModel.swift // SwiftMovie // // Created by Lucas Farah on 8/27/20. // Copyright © 2020 Lucas Farah. All rights reserved. // import Foundation import RxSwift import RxCocoa struct MovieDetailViewModel { let repository = MovieRepository() let bag = DisposeBag() enum Section { case mainMovie(title: String, imageURL: URL?, likesCount: Int, viewsCount: Double) case similarMovie(title: String, imageURL: URL?, year: String?, genres: [String]) } struct MovieDetailInfo { let detail: MovieDetail let similarMovies: [MovieDetail] let genreList: [MovieGenre] } let dataSource = BehaviorRelay<[Section]>(value: []) let movieInfo = BehaviorRelay<MovieDetailInfo?>(value: nil) init() { requestMovieInfo() .bind(to: movieInfo) .disposed(by: bag) movieInfo .filterNotNil() .map { info -> [Section] in var sections: [Section] = [] let mainMovieSection = Section.mainMovie(title: info.detail.title, imageURL: info.detail.imageURL, likesCount: info.detail.likesCount, viewsCount: info.detail.viewsCount) sections += [mainMovieSection] sections += info.similarMovies.map({ (movie) -> Section in let genres = movie.genreIds?.compactMap({ (genreId) -> String? in info.genreList.first(where: { $0.id == genreId })?.name }) ?? [] return .similarMovie(title: movie.title, imageURL: movie.imageURL, year: movie.releaseYear, genres: genres) }) return sections } .bind(to: dataSource) .disposed(by: bag) } func requestMovieInfo() -> Observable<MovieDetailInfo> { let detailRequest = repository.requestMovieDetail() let similarMoviesRequest = repository.requestSimilarMovies() let movieGenreRequest = repository.requestGenres() return Observable.combineLatest(detailRequest, similarMoviesRequest, movieGenreRequest) .map { (requests) -> MovieDetailInfo in return MovieDetailInfo(detail: requests.0, similarMovies: requests.1.results, genreList: requests.2.genres) } } }
35.75
127
0.554779
b9de851c4cadfca11b6d5310dc320e57ebad1b10
4,543
import Foundation import UIKit import AsyncDisplayKit public class ActionSheetSwitchItem: ActionSheetItem { public let title: String public let isOn: Bool public let action: (Bool) -> Void public init(title: String, isOn: Bool, action: @escaping (Bool) -> Void) { self.title = title self.isOn = isOn self.action = action } public func node(theme: ActionSheetControllerTheme) -> ActionSheetItemNode { let node = ActionSheetSwitchNode(theme: theme) node.setItem(self) return node } public func updateNode(_ node: ActionSheetItemNode) { guard let node = node as? ActionSheetSwitchNode else { assertionFailure() return } node.setItem(self) node.requestLayoutUpdate() } } public class ActionSheetSwitchNode: ActionSheetItemNode { private let theme: ActionSheetControllerTheme private var item: ActionSheetSwitchItem? private let button: HighlightTrackingButton private let label: ImmediateTextNode private let switchNode: SwitchNode private let accessibilityArea: AccessibilityAreaNode override public init(theme: ActionSheetControllerTheme) { self.theme = theme self.button = HighlightTrackingButton() self.button.isAccessibilityElement = false self.label = ImmediateTextNode() self.label.isUserInteractionEnabled = false self.label.maximumNumberOfLines = 1 self.label.displaysAsynchronously = false self.label.truncationType = .end self.label.isAccessibilityElement = false self.switchNode = SwitchNode() self.switchNode.frameColor = theme.switchFrameColor self.switchNode.contentColor = theme.switchContentColor self.switchNode.handleColor = theme.switchHandleColor self.switchNode.isAccessibilityElement = false self.accessibilityArea = AccessibilityAreaNode() super.init(theme: theme) self.view.addSubview(self.button) self.label.isUserInteractionEnabled = false self.addSubnode(self.label) self.addSubnode(self.switchNode) self.addSubnode(self.accessibilityArea) self.button.addTarget(self, action: #selector(self.buttonPressed), for: .touchUpInside) self.switchNode.valueUpdated = { [weak self] value in self?.item?.action(value) } self.accessibilityArea.activate = { [weak self] in self?.buttonPressed() return true } } func setItem(_ item: ActionSheetSwitchItem) { self.item = item let defaultFont = Font.regular(floor(theme.baseFontSize * 20.0 / 17.0)) self.label.attributedText = NSAttributedString(string: item.title, font: defaultFont, textColor: self.theme.primaryTextColor) self.label.isAccessibilityElement = false self.switchNode.isOn = item.isOn self.accessibilityArea.accessibilityLabel = item.title var accessibilityTraits: UIAccessibilityTraits = [.button] if item.isOn { accessibilityTraits.insert(.selected) } self.accessibilityArea.accessibilityTraits = accessibilityTraits } public override func updateLayout(constrainedSize: CGSize, transition: ContainedViewLayoutTransition) -> CGSize { let size = CGSize(width: constrainedSize.width, height: 57.0) self.button.frame = CGRect(origin: CGPoint(), size: size) let labelSize = self.label.updateLayout(CGSize(width: max(1.0, size.width - 51.0 - 16.0 * 2.0), height: size.height)) self.label.frame = CGRect(origin: CGPoint(x: 16.0, y: floorToScreenPixels((size.height - labelSize.height) / 2.0)), size: labelSize) let switchSize = CGSize(width: 51.0, height: 31.0) self.switchNode.frame = CGRect(origin: CGPoint(x: size.width - 16.0 - switchSize.width, y: floor((size.height - switchSize.height) / 2.0)), size: switchSize) self.accessibilityArea.frame = CGRect(origin: CGPoint(), size: size) self.updateInternalLayout(size, constrainedSize: constrainedSize) return size } @objc func buttonPressed() { let value = !self.switchNode.isOn self.switchNode.setOn(value, animated: true) self.item?.action(value) } }
35.492188
165
0.64781
09c56335496fadbd1ed19844d3f5fb6c459c8496
22,986
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// extension String { /// A view of a string's contents as a collection of Unicode scalar values. /// /// You can access a string's view of Unicode scalar values by using its /// `unicodeScalars` property. Unicode scalar values are the 21-bit codes /// that are the basic unit of Unicode. Each scalar value is represented by /// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit. /// /// let flowers = "Flowers 💐" /// for v in flowers.unicodeScalars { /// print(v.value) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 128144 /// /// Some characters that are visible in a string are made up of more than one /// Unicode scalar value. In that case, a string's `unicodeScalars` view /// contains more elements than the string itself. /// /// let flag = "🇵🇷" /// for c in flag { /// print(c) /// } /// // 🇵🇷 /// /// for v in flag.unicodeScalars { /// print(v.value) /// } /// // 127477 /// // 127479 /// /// You can convert a `String.UnicodeScalarView` instance back into a string /// using the `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.unicodeScalars.index(where: { $0.value >= 128 }) { /// let asciiPrefix = String(favemoji.unicodeScalars[..<i]) /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " public struct UnicodeScalarView : BidirectionalCollection, CustomStringConvertible, CustomDebugStringConvertible { internal init(_ _core: _StringCore, coreOffset: Int = 0) { self._core = _core self._coreOffset = coreOffset } internal struct _ScratchIterator : IteratorProtocol { var core: _StringCore var idx: Int @_versioned init(_ core: _StringCore, _ pos: Int) { self.idx = pos self.core = core } @inline(__always) mutating func next() -> UTF16.CodeUnit? { if idx == core.endIndex { return nil } defer { idx += 1 } return self.core[idx] } } /// A position in a string's `UnicodeScalars` view. /// /// You can convert between indices of the different string views by using /// conversion initializers and the `samePosition(in:)` method overloads. /// The following example finds the index of the solid heart pictograph in /// the string's character view and then converts that to the same /// position in the Unicode scalars view: /// /// let hearts = "Hearts <3 ♥︎ 💘" /// let i = hearts.index(of: "♥︎")! /// /// let j = i.samePosition(in: hearts.unicodeScalars) /// print(hearts.unicodeScalars[j...]) /// // Prints "♥︎ 💘" /// print(hearts.unicodeScalars[j].value) /// // Prints "9829" public struct Index { public // SPI(Foundation) init(_position: Int) { self._position = _position } @_versioned internal var _position: Int } /// Translates a `_core` index into a `UnicodeScalarIndex` using this view's /// `_coreOffset`. internal func _fromCoreIndex(_ i: Int) -> Index { return Index(_position: i + _coreOffset) } /// Translates a `UnicodeScalarIndex` into a `_core` index using this view's /// `_coreOffset`. internal func _toCoreIndex(_ i: Index) -> Int { return i._position - _coreOffset } /// The position of the first Unicode scalar value if the string is /// nonempty. /// /// If the string is empty, `startIndex` is equal to `endIndex`. public var startIndex: Index { return _fromCoreIndex(_core.startIndex) } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`. public var endIndex: Index { return _fromCoreIndex(_core.endIndex) } /// Returns the next consecutive location after `i`. /// /// - Precondition: The next location exists. public func index(after i: Index) -> Index { let i = _toCoreIndex(i) var scratch = _ScratchIterator(_core, i) var decoder = UTF16() let (_, length) = decoder._decodeOne(&scratch) return _fromCoreIndex(i + length) } /// Returns the previous consecutive location before `i`. /// /// - Precondition: The previous location exists. public func index(before i: Index) -> Index { var i = _toCoreIndex(i) - 1 let codeUnit = _core[i] if _slowPath((codeUnit >> 10) == 0b1101_11) { if i != 0 && (_core[i - 1] >> 10) == 0b1101_10 { i -= 1 } } return _fromCoreIndex(i) } /// Accesses the Unicode scalar value at the given position. /// /// The following example searches a string's Unicode scalars view for a /// capital letter and then prints the character and Unicode scalar value /// at the found index: /// /// let greeting = "Hello, friend!" /// if let i = greeting.unicodeScalars.index(where: { "A"..."Z" ~= $0 }) { /// print("First capital letter: \(greeting.unicodeScalars[i])") /// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)") /// } /// // Prints "First capital letter: H" /// // Prints "Unicode scalar value: 72" /// /// - Parameter position: A valid index of the character view. `position` /// must be less than the view's end index. public subscript(position: Index) -> Unicode.Scalar { var scratch = _ScratchIterator(_core, _toCoreIndex(position)) var decoder = UTF16() switch decoder.decode(&scratch) { case .scalarValue(let us): return us case .emptyInput: _sanityCheckFailure("cannot subscript using an endIndex") case .error: return Unicode.Scalar(0xfffd)! } } /// Accesses the Unicode scalar values in the given range. /// /// The example below uses this subscript to access the scalar values up /// to, but not including, the first comma (`","`) in the string. /// /// let str = "All this happened, more or less." /// let i = str.unicodeScalars.index(of: ",")! /// let substring = str.unicodeScalars[str.unicodeScalars.startIndex ..< i] /// print(String(substring)) /// // Prints "All this happened" /// /// - Complexity: O(*n*) if the underlying string is bridged from /// Objective-C, where *n* is the length of the string; otherwise, O(1). public subscript(r: Range<Index>) -> UnicodeScalarView { let rawSubRange = _toCoreIndex(r.lowerBound)..<_toCoreIndex(r.upperBound) return UnicodeScalarView(_core[rawSubRange], coreOffset: r.lowerBound._position) } /// An iterator over the Unicode scalars that make up a `UnicodeScalarView` /// collection. public struct Iterator : IteratorProtocol { init(_ _base: _StringCore) { if _base.hasContiguousStorage { self._baseSet = true if _base.isASCII { self._ascii = true self._asciiBase = UnsafeBufferPointer( start: _base._baseAddress?.assumingMemoryBound( to: UTF8.CodeUnit.self), count: _base.count).makeIterator() } else { self._ascii = false self._base = UnsafeBufferPointer<UInt16>( start: _base._baseAddress?.assumingMemoryBound( to: UTF16.CodeUnit.self), count: _base.count).makeIterator() } } else { self._ascii = false self._baseSet = false self._iterator = _base.makeIterator() } } /// Advances to the next element and returns it, or `nil` if no next /// element exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. public mutating func next() -> Unicode.Scalar? { var result: UnicodeDecodingResult if _baseSet { if _ascii { switch self._asciiBase.next() { case let x?: result = .scalarValue(Unicode.Scalar(x)) case nil: result = .emptyInput } } else { result = _decoder.decode(&(self._base!)) } } else { result = _decoder.decode(&(self._iterator!)) } switch result { case .scalarValue(let us): return us case .emptyInput: return nil case .error: return Unicode.Scalar(0xfffd) } } internal var _decoder: UTF16 = UTF16() internal let _baseSet: Bool internal let _ascii: Bool internal var _asciiBase: UnsafeBufferPointerIterator<UInt8>! internal var _base: UnsafeBufferPointerIterator<UInt16>! internal var _iterator: IndexingIterator<_StringCore>! } /// Returns an iterator over the Unicode scalars that make up this view. /// /// - Returns: An iterator over this collection's `Unicode.Scalar` elements. public func makeIterator() -> Iterator { return Iterator(_core) } public var description: String { return String(_core) } public var debugDescription: String { return "StringUnicodeScalarView(\(self.description.debugDescription))" } internal var _core: _StringCore /// The offset of this view's `_core` from an original core. This works /// around the fact that `_StringCore` is always zero-indexed. /// `_coreOffset` should be subtracted from `UnicodeScalarIndex._position` /// before that value is used as a `_core` index. internal var _coreOffset: Int } /// Creates a string corresponding to the given collection of Unicode /// scalars. /// /// You can use this initializer to create a new string from a slice of /// another string's `unicodeScalars` view. /// /// let picnicGuest = "Deserving porcupine" /// if let i = picnicGuest.unicodeScalars.index(of: " ") { /// let adjective = String(picnicGuest.unicodeScalars[..<i]) /// print(adjective) /// } /// // Prints "Deserving" /// /// The `adjective` constant is created by calling this initializer with a /// slice of the `picnicGuest.unicodeScalars` view. /// /// - Parameter unicodeScalars: A collection of Unicode scalar values. public init(_ unicodeScalars: UnicodeScalarView) { self.init(unicodeScalars._core) } /// The index type for a string's `unicodeScalars` view. public typealias UnicodeScalarIndex = UnicodeScalarView.Index } extension String.UnicodeScalarView : _SwiftStringView { var _persistentContent : String { return String(_core) } } extension String { /// The string's value represented as a collection of Unicode scalar values. public var unicodeScalars: UnicodeScalarView { get { return UnicodeScalarView(_core) } set { _core = newValue._core } } } extension String.UnicodeScalarView.Index : Comparable { public static func == ( lhs: String.UnicodeScalarView.Index, rhs: String.UnicodeScalarView.Index ) -> Bool { return lhs._position == rhs._position } public static func < ( lhs: String.UnicodeScalarView.Index, rhs: String.UnicodeScalarView.Index ) -> Bool { return lhs._position < rhs._position } } extension String.UnicodeScalarView : RangeReplaceableCollection { /// Creates an empty view instance. public init() { self = String.UnicodeScalarView(_StringCore()) } /// Reserves enough space in the view's underlying storage to store the /// specified number of ASCII characters. /// /// Because a Unicode scalar value can require more than a single ASCII /// character's worth of storage, additional allocation may be necessary /// when adding to a Unicode scalar view after a call to /// `reserveCapacity(_:)`. /// /// - Parameter n: The minimum number of ASCII character's worth of storage /// to allocate. /// /// - Complexity: O(*n*), where *n* is the capacity being reserved. public mutating func reserveCapacity(_ n: Int) { _core.reserveCapacity(n) } /// Appends the given Unicode scalar to the view. /// /// - Parameter c: The character to append to the string. public mutating func append(_ x: Unicode.Scalar) { _core.append(x) } /// Appends the Unicode scalar values in the given sequence to the view. /// /// - Parameter newElements: A sequence of Unicode scalar values. /// /// - Complexity: O(*n*), where *n* is the length of the resulting view. public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Unicode.Scalar { _core.append(contentsOf: newElements.lazy.flatMap { $0.utf16 }) } /// Replaces the elements within the specified bounds with the given Unicode /// scalar values. /// /// Calling this method invalidates any existing indices for use with this /// string. /// /// - Parameters: /// - bounds: The range of elements to replace. The bounds of the range /// must be valid indices of the view. /// - newElements: The new Unicode scalar values to add to the string. /// /// - Complexity: O(*m*), where *m* is the combined length of the view and /// `newElements`. If the call to `replaceSubrange(_:with:)` simply /// removes elements at the end of the string, the complexity is O(*n*), /// where *n* is equal to `bounds.count`. public mutating func replaceSubrange<C>( _ bounds: Range<Index>, with newElements: C ) where C : Collection, C.Element == Unicode.Scalar { let rawSubRange: Range<Int> = _toCoreIndex(bounds.lowerBound) ..< _toCoreIndex(bounds.upperBound) let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 } _core.replaceSubrange(rawSubRange, with: lazyUTF16) } } // Index conversions extension String.UnicodeScalarIndex { /// Creates an index in the given Unicode scalars view that corresponds /// exactly to the specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `unicodeScalars` view: /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.index(of: 32)! /// let scalarIndex = String.UnicodeScalarView.Index(utf16Index, within: cafe.unicodeScalars)! /// /// print(String(cafe.unicodeScalars[..<scalarIndex])) /// // Prints "Café" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `unicodeScalars`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the trailing surrogate of a UTF-16 surrogate pair fails. /// /// - Parameters: /// - utf16Index: A position in the `utf16` view of a string. `utf16Index` /// must be an element of `String(unicodeScalars).utf16.indices`. /// - unicodeScalars: The `UnicodeScalarView` in which to find the new /// position. public init?( _ utf16Index: String.UTF16Index, within unicodeScalars: String.UnicodeScalarView ) { let utf16 = String.UTF16View(unicodeScalars._core) if utf16Index != utf16.startIndex && utf16Index != utf16.endIndex { _precondition( utf16Index >= utf16.startIndex && utf16Index <= utf16.endIndex, "Invalid String.UTF16Index for this Unicode.Scalar view") // Detect positions that have no corresponding index. Note that // we have to check before and after, because an unpaired // surrogate will be decoded as a single replacement character, // thus making the corresponding position valid. if UTF16.isTrailSurrogate(utf16[utf16Index]) && UTF16.isLeadSurrogate(utf16[utf16.index(before: utf16Index)]) { return nil } } self.init(_position: utf16Index._offset) } /// Creates an index in the given Unicode scalars view that corresponds /// exactly to the specified `UTF8View` position. /// /// If the position passed as `utf8Index` doesn't have an exact corresponding /// position in `unicodeScalars`, the result of the initializer is `nil`. /// For example, an attempt to convert the position of a UTF-8 continuation /// byte returns `nil`. /// /// - Parameters: /// - utf8Index: A position in the `utf8` view of a string. `utf8Index` /// must be an element of `String(unicodeScalars).utf8.indices`. /// - unicodeScalars: The `UnicodeScalarView` in which to find the new /// position. public init?( _ utf8Index: String.UTF8Index, within unicodeScalars: String.UnicodeScalarView ) { let core = unicodeScalars._core _precondition( utf8Index._coreIndex >= 0 && utf8Index._coreIndex <= core.endIndex, "Invalid String.UTF8Index for this Unicode.Scalar view") // Detect positions that have no corresponding index. if !utf8Index._isOnUnicodeScalarBoundary(in: core) { return nil } self.init(_position: utf8Index._coreIndex) } /// Creates an index in the given Unicode scalars view that corresponds /// exactly to the specified string position. /// /// The following example converts the position of the teacup emoji (`"🍵"`) /// into its corresponding position in the string's `unicodeScalars` view. /// /// let cafe = "Café 🍵" /// let stringIndex = cafe.index(of: "🍵")! /// let scalarIndex = String.UnicodeScalarView.Index(stringIndex, within: cafe.unicodeScalars) /// /// print(cafe.unicodeScalars[scalarIndex...]) /// // Prints "🍵" /// /// - Parameters: /// - index: A position in a string. `index` must be an element of /// `String(unicodeScalars).indices`. /// - unicodeScalars: The `UnicodeScalarView` in which to find the new /// position. public init( _ index: String.Index, within unicodeScalars: String.UnicodeScalarView ) { self.init(_position: index._base._position) } /// Returns the position in the given UTF-8 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf8).unicodeScalars`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf8` view. /// /// let cafe = "Café" /// if let i = cafe.unicodeScalars.index(of: "é") { /// let j = i.samePosition(in: cafe.utf8) /// print(Array(cafe.utf8[j...])) /// } /// // Prints "[195, 169]" /// /// - Parameter utf8: The view to use for the index conversion. /// - Returns: The position in `utf8` that corresponds exactly to this index. public func samePosition(in utf8: String.UTF8View) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in the given UTF-16 view that corresponds exactly to /// this index. /// /// The index must be a valid index of `String(utf16).unicodeScalars`. /// /// This example first finds the position of the character `"é"` and then uses /// this method find the same position in the string's `utf16` view. /// /// let cafe = "Café" /// if let i = cafe.unicodeScalars.index(of: "é") { /// let j = i.samePosition(in: cafe.utf16) /// print(cafe.utf16[j]) /// } /// // Prints "233" /// /// - Parameter utf16: The view to use for the index conversion. /// - Returns: The position in `utf16` that corresponds exactly to this index. public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Returns the position in the given string that corresponds exactly to this /// index. /// /// This index must be a valid index of `characters.unicodeScalars`. /// /// This example first finds the position of a space (UTF-8 code point `32`) /// in a string's `utf8` view and then uses this method find the same position /// in the string. /// /// let cafe = "Café 🍵" /// let i = cafe.unicodeScalars.index(of: "🍵") /// let j = i.samePosition(in: cafe)! /// print(cafe[j...]) /// // Prints "🍵" /// /// - Parameter characters: The string to use for the index conversion. /// - Returns: The position in `characters` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `characters`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-8 continuation byte /// returns `nil`. public func samePosition(in characters: String) -> String.Index? { return String.Index(self, within: characters) } } extension String.UnicodeScalarView { // NOTE: Don't make this function inlineable. Grapheme cluster // segmentation uses a completely different algorithm in Unicode 9.0. internal func _isOnGraphemeClusterBoundary(_ i: Index) -> Bool { if i == startIndex || i == endIndex { return true } let precedingScalar = self[index(before: i)] let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() let gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( precedingScalar.value) if segmenter.isBoundaryAfter(gcb0) { return true } let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue(self[i].value) return segmenter.isBoundary(gcb0, gcb1) } } // Reflection extension String.UnicodeScalarView : CustomReflectable { /// Returns a mirror that reflects the Unicode scalars view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } extension String.UnicodeScalarView : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(description) } }
35.803738
100
0.632385
9c4ce15da2c1797361eeadecc3946f23d35fcf41
972
// // VeracitySDKCoreTests.swift // VeracitySDKCoreTests // // Created by Andrew on 06/04/2020. // Copyright © 2020 Veracity Protocol s.r.o. All rights reserved. // import XCTest class VeracitySDKCoreTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } // func testPerformanceExample() throws { // // This is an example of a performance test case. // measure { // // Put the code you want to measure the time of here. // } // } }
27.771429
111
0.65535
f5b64663e8b140017f36f6947d2ec35d87d510b9
348
enum TestError: Int, Error, CustomStringConvertible, Codable { case e0 case e1 case e2 var description: String { switch self { case .e0: return "TestError.e0" case .e1: return "TestError.e1" case .e2: return "TestError.e2" } } } extension TestError: Equatable { }
20.470588
62
0.560345
f57c791f9934577eab2f11199fd3eae6510989aa
912
// // CPScalableButton.swift // KeezyButtonDemo // // Created by Parsifal on 2017/1/23. // Copyright © 2017年 Parsifal. All rights reserved. // import UIKit open class CPScalableButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { self.addTarget(self, action: #selector(zoomIn), for: [.touchDown]) self.addTarget(self, action: #selector(zoomOut), for: [.touchUpInside, .touchUpOutside]) } func zoomIn() { UIView.animate(withDuration: 0.1) { self.transform = CGAffineTransform.init(scaleX: 0.8, y: 0.8) } } func zoomOut() { UIView.animate(withDuration: 0.1) { self.transform = CGAffineTransform.identity } } }
23.384615
96
0.593202
69eb6c8ec734fda2b8b08aab8fca75bb285a1843
587
// // Plan.swift // // // Created by Lika Vorobeva on 10.02.2022. // import Foundation public struct SentinelPlan { public let id: UInt64 public let provider: String public let price: [CoinToken] public let validity: TimeInterval public let bytes: String public let isActive: Bool init(from plan: Sentinel_Plan_V1_Plan) { id = plan.id provider = plan.provider price = plan.price.map(CoinToken.init) validity = plan.validity.timeInterval bytes = plan.bytes isActive = plan.status == .active } }
20.241379
46
0.637138
8a4008cd5feeeb1fe998616c41fc8e6ccdf06cac
868
// // AFReachabilityManagerMock.swift // // // Created by Prabin Kumar Datta on 31/08/21. // import XCTest import Alamofire @testable import SimpleRIBNetworking class AFReachabilityManagerMock: AFReachabilityManagerProtocol { var shouldReturnReachable: Bool = false var isReachable: Bool { shouldReturnReachable } var didCallStartListening: Bool = false var listener: NetworkReachabilityManager.Listener? func startListening(onQueue queue: DispatchQueue, onUpdatePerforming listener: @escaping NetworkReachabilityManager.Listener) -> Bool { self.didCallStartListening = true self.listener = listener return true } func sendStatus(_ status: NetworkReachabilityManager.NetworkReachabilityStatus) { self.listener?(status) } }
24.111111
109
0.686636
26f184921be4c286d529d92f5ec59b1031a1cd61
3,019
// // DispatchTimer.swift // Telegraph // // Created by Yvo van Beek on 2/23/17. // Copyright © 2017 Building42. All rights reserved. // import Foundation public class DispatchTimer { private let interval: TimeInterval private let queue: DispatchQueue private let block: () -> Void private var timer: DispatchSourceTimer? /// Initializes a DispatchTimer. public init(interval: TimeInterval = 0, queue: DispatchQueue, execute block: @escaping () -> Void) { self.interval = interval self.queue = queue self.block = block } /// (Re)starts the timer, next run is immediately, after the interval or at a specific date. public func start(at startAt: Date? = nil) { stop() // Create a new timer timer = DispatchSource.makeTimerSource(queue: queue) timer?.setEventHandler(handler: block) // Schedule the timer to start at a specific time or after the interval let startDate = startAt ?? Date().addingTimeInterval(interval) let deadline = DispatchWallTime(date: startDate) if interval > 0 { timer?.schedule(wallDeadline: deadline, repeating: interval) } else { timer?.schedule(wallDeadline: deadline) } // Activate the timer timer?.resume() } /// (Re)starts the timer, next run will be after the specified interval. public func start(after: TimeInterval) { start(at: Date().addingTimeInterval(after)) } /// Stops the timer. public func stop() { timer?.cancel() timer = nil } } // MARK: DispatchTimer convenience methods extension DispatchTimer { /// Creates and starts a timer that runs multiple times with a specific interval. public static func run(interval: TimeInterval, queue: DispatchQueue, execute block: @escaping () -> Void) -> DispatchTimer { let timer = DispatchTimer(interval: interval, queue: queue, execute: block) timer.start() return timer } /// Creates and starts a timer that runs at a specfic data, optionally repeating with a specific interval. public static func run(at: Date, interval: TimeInterval = 0, queue: DispatchQueue, execute block: @escaping () -> Void) -> DispatchTimer { let timer = DispatchTimer(interval: interval, queue: queue, execute: block) timer.start(at: at) return timer } /// Creates and starts a timer that runs after a while, optionally repeating with a specific interval. public static func run(after: TimeInterval, interval: TimeInterval = 0, queue: DispatchQueue, execute block: @escaping () -> Void) -> DispatchTimer { let timer = DispatchTimer(interval: interval, queue: queue, execute: block) timer.start(after: after) return timer } } // MARK: DispatchWallTime convenience initializers extension DispatchWallTime { /// Initializes a DispatchWallTime with a date. public init(date: Date) { let (seconds, frac) = modf(date.timeIntervalSince1970) let wallTime = timespec(tv_sec: Int(seconds), tv_nsec: Int(frac * Double(NSEC_PER_SEC))) self.init(timespec: wallTime) } }
32.117021
151
0.703875
e4dfc2370e15223f019edea66bc106fd18db83bc
1,493
// // Array+Unique.swift // Seeds // // Created by Илья Харабет on 16.06.2018. // Copyright © 2018 Илья Харабет. All rights reserved. // import Foundation public extension Array { /** Возвращает массив с уникальными объектами, выбранными в соответствии с переданным условием. Пример: ``` ["a", "b", "a"].unique { $0.0 == $0.1 } --> ["a", "b"] ``` - Parameter include: Определяет условие, по которому будут выбраны уникальные элементы - Parameter lhs: Первый элемент - Parameter rhs: Второй элемент - Returns: Массив с уникальными элементами */ public func unique(include: @escaping (_ lhs: Element, _ rhs: Element) -> Bool) -> [Element] { return reduce([]) { (acc, element) in return acc.contains(where: { include(element, $0) }) ? acc : acc + [element] } } } public extension Array where Element: Equatable { /// Возвращает массив с уникальными объектами, полученными в результате обычного сравнения public var unique: [Element] { var acc: [Element] = [] self.forEach { if !acc.contains($0) { acc.append($0) } } return acc } } public extension Array where Element: Hashable { /// Быстрое получение уникальных значений для Hashable-элементов public var uniqueByHash: [Element] { return Array(Set(self)) } }
23.698413
98
0.576021
619c1ee2373303b5835bfd987e54d4cf36952209
679
// // LinkedListIndex.swift // SwiftSpellBook // // Created by Braden Scothern on 7/15/20. // Copyright © 2020-2021 Braden Scothern. All rights reserved. // @usableFromInline protocol LinkedListIndex: Comparable, ExpressibleByIntegerLiteral { associatedtype Base: _LinkedListProtocol typealias Value = Base.Buffer.Index var value: Value { get } init(_ value: Value) } extension LinkedListIndex { @inlinable public static func < (lhs: Self, rhs: Self) -> Bool { lhs.value < rhs.value } } extension LinkedListIndex { @inlinable public init(integerLiteral value: Int) { self.init(.init(node: nil, offset: value)) } }
21.21875
67
0.681885
8f089101aaef7c1f4e64708c61bb20e1818c28fe
1,346
// // Copyright (c) 2021 Hiroshi Kimura(Muukii) <[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 #if !COCOAPODS import BrightroomEngine #endif public protocol CIImageDisplaying: AnyObject { func display(image: CIImage?) var postProcessing: (CIImage) -> CIImage { get set } }
42.0625
80
0.761516
e0a41791dbc21fc04dfc491f19231ea43cd026fc
1,077
// // StoryDetailViewController.swift // GetSuccess // // Created by Arie May Wibowo on 13/03/20. // Copyright © 2020 Arie May Wibowo. All rights reserved. // import UIKit class StoryDetailViewController: UIViewController { @IBOutlet weak var personName: UILabel! @IBOutlet weak var personImage: UIImageView! @IBOutlet weak var headline: UILabel! @IBOutlet weak var personContent: UITextView! var name: String = "" var image: UIImage? var content: String = "" override func viewDidLoad() { super.viewDidLoad() personName.text = name headline.text = "Who is \(name)" personImage.image = image personContent.text = content personImage.layer.borderWidth=1.0 personImage.layer.masksToBounds = false personImage.layer.borderColor = UIColor.white.cgColor personImage.layer.cornerRadius = personImage.frame.size.height/2 personImage.clipsToBounds = true // Do any additional setup after loading the view. } }
25.642857
72
0.654596
91f33a4e0d1059f83abdb4f53d01149db61c547e
36,533
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 public let ErrorInvalidJSON: Int! = 490 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { error.memory = aError } self.init(NSNull()) } } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: AnyObject]() for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } /// Private object private var rawArray: [AnyObject] = [] private var rawDictionary: [String : AnyObject] = [:] private var rawString: String = "" private var rawNumber: NSNumber = 0 private var rawNull: NSNull = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? = nil /// Object in JSON public var object: AnyObject { get { switch self.type { case .Array: return self.rawArray case .Dictionary: return self.rawDictionary case .String: return self.rawString case .Number: return self.rawNumber case .Bool: return self.rawNumber default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } self.rawNumber = number case let string as String: _type = .String self.rawString = string case _ as NSNull: _type = .Null case let array as [AnyObject]: _type = .Array self.rawArray = array case let dictionary as [String : AnyObject]: _type = .Dictionary self.rawDictionary = dictionary default: _type = .Unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json @available(*, unavailable, renamed="null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } // MARK: - CollectionType, SequenceType, Indexable extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable { public typealias Generator = JSONGenerator public typealias Index = JSONIndex public var startIndex: JSON.Index { switch self.type { case .Array: return JSONIndex(arrayIndex: self.rawArray.startIndex) case .Dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex) default: return JSONIndex() } } public var endIndex: JSON.Index { switch self.type { case .Array: return JSONIndex(arrayIndex: self.rawArray.endIndex) case .Dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex) default: return JSONIndex() } } public subscript (position: JSON.Index) -> JSON.Generator.Element { switch self.type { case .Array: return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!])) case .Dictionary: let (key, value) = self.rawDictionary[position.dictionaryIndex!] return (key, JSON(value)) default: return ("", JSON.null) } } /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return self.rawArray.isEmpty case .Dictionary: return self.rawDictionary.isEmpty default: return true } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { switch self.type { case .Array: return self.rawArray.count case .Dictionary: return self.rawDictionary.count default: return 0 } } public func underestimateCount() -> Int { switch self.type { case .Array: return self.rawArray.underestimateCount() case .Dictionary: return self.rawDictionary.underestimateCount() default: return 0 } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of JSON. */ public func generate() -> JSON.Generator { return JSON.Generator(self) } } public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable { let arrayIndex: Int? let dictionaryIndex: DictionaryIndex<String, AnyObject>? let type: Type init(){ self.arrayIndex = nil self.dictionaryIndex = nil self.type = .Unknown } init(arrayIndex: Int) { self.arrayIndex = arrayIndex self.dictionaryIndex = nil self.type = .Array } init(dictionaryIndex: DictionaryIndex<String, AnyObject>) { self.arrayIndex = nil self.dictionaryIndex = dictionaryIndex self.type = .Dictionary } public func successor() -> JSONIndex { switch self.type { case .Array: return JSONIndex(arrayIndex: self.arrayIndex!.successor()) case .Dictionary: return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor()) default: return JSONIndex() } } } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex == rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex == rhs.dictionaryIndex default: return false } } public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex < rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex < rhs.dictionaryIndex default: return false } } public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex <= rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex <= rhs.dictionaryIndex default: return false } } public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex >= rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex >= rhs.dictionaryIndex default: return false } } public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.Array, .Array): return lhs.arrayIndex > rhs.arrayIndex case (.Dictionary, .Dictionary): return lhs.dictionaryIndex > rhs.dictionaryIndex default: return false } } public struct JSONGenerator : GeneratorType { public typealias Element = (String, JSON) private let type: Type private var dictionayGenerate: DictionaryGenerator<String, AnyObject>? private var arrayGenerate: IndexingGenerator<[AnyObject]>? private var arrayIndex: Int = 0 init(_ json: JSON) { self.type = json.type if type == .Array { self.arrayGenerate = json.rawArray.generate() }else { self.dictionayGenerate = json.rawDictionary.generate() } } public mutating func next() -> JSONGenerator.Element? { switch self.type { case .Array: if let o = self.arrayGenerate!.next() { return (String(self.arrayIndex++), JSON(o)) } else { return nil } case .Dictionary: if let (k, v): (String, AnyObject) = self.dictionayGenerate!.next() { return (k, JSON(v)) } else { return nil } default: return nil } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol JSONSubscriptType {} extension Int: JSONSubscriptType {} extension String: JSONSubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .Array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .Dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .Dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: JSONSubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.removeAtIndex(0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in var d = dictionary d[element.0] = element.1 return d }) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { guard NSJSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return self.rawString case .Number: return self.rawNumber.stringValue case .Bool: return self.rawNumber.boolValue.description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .Dictionary { return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in var d = dictionary d[element.0] = JSON(element.1) return d } } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.rawNumber.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.rawNumber default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber() { // indicates parse error return NSDecimalNumber.zero() } return decimal case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func isExists() -> Bool{ if let errorValue = error where errorValue.code == ErrorNotExist{ return false } return true } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber == rhs.rawNumber case (.String, .String): return lhs.rawString == rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber <= rhs.rawNumber case (.String, .String): return lhs.rawString <= rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber >= rhs.rawNumber case (.String, .String): return lhs.rawString >= rhs.rawString case (.Bool, .Bool): return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue case (.Array, .Array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.Dictionary, .Dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber > rhs.rawNumber case (.String, .String): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return lhs.rawNumber < rhs.rawNumber case (.String, .String): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } }
27.02145
265
0.537842
231ea35fb7c0e9fa94f3adf2d65a428c5680626b
242
// // Formattable.swift // Formalist // // Created by Viktor Radchenko on 7/21/17. // Copyright © 2017 Seed Platform, Inc. All rights reserved. // import Foundation public protocol Formattable { func from(input: String) -> String }
17.285714
61
0.690083
23ee37491e4235b52aa6d8acd4cf319aea2f1ee1
2,548
import UIKit import ThemeKit class ManageAccountsRouter { weak var viewController: UIViewController? } extension ManageAccountsRouter: IManageAccountsRouter { func showUnlink(account: Account, predefinedAccountType: PredefinedAccountType) { viewController?.present(UnlinkRouter.module(account: account, predefinedAccountType: predefinedAccountType), animated: true) } func showBackup(account: Account, predefinedAccountType: PredefinedAccountType) { let module = BackupRouter.module(account: account, predefinedAccountType: predefinedAccountType) viewController?.present(module, animated: true) } func showBackupRequired(account: Account, predefinedAccountType: PredefinedAccountType) { let module = BackupRequiredRouter.module( account: account, predefinedAccountType: predefinedAccountType, sourceViewController: viewController, text: "settings_manage_keys.delete.cant_delete".localized ) viewController?.present(module, animated: true) } func showCreateWallet(predefinedAccountType: PredefinedAccountType) { CreateWalletModule.start(mode: .present(viewController: viewController), predefinedAccountType: predefinedAccountType) } func showRestore(predefinedAccountType: PredefinedAccountType) { RestoreModule.start(mode: .present(viewController: viewController), predefinedAccountType: predefinedAccountType) } func showSettings() { let module = AddressFormatModule.viewController() viewController?.navigationController?.pushViewController(module, animated: true) } func close() { viewController?.dismiss(animated: true) } } extension ManageAccountsRouter { static func module() -> UIViewController { let router = ManageAccountsRouter() let interactor = ManageAccountsInteractor(predefinedAccountTypeManager: App.shared.predefinedAccountTypeManager, accountManager: App.shared.accountManager, derivationSettingsManager: App.shared.derivationSettingsManager, bitcoinCashCoinTypeManager: App.shared.bitcoinCashCoinTypeManager, walletManager: App.shared.walletManager) let presenter = ManageAccountsPresenter(interactor: interactor, router: router) let viewController = ManageAccountsViewController(delegate: presenter) interactor.delegate = presenter presenter.view = viewController router.viewController = viewController return viewController } }
39.2
336
0.75
0e4501817fd9b87847bb41bca0d470d586d38054
1,047
import Foundation import FluentKit import WKCodable public struct GeographicMultiPoint2D: Codable, Equatable, CustomStringConvertible { /// The points public var points: [GeographicPoint2D] /// Create a new `GISGeographicLineString2D` public init(points: [GeographicPoint2D]) { self.points = points } } extension GeographicMultiPoint2D: GeometryConvertible, GeometryCollectable { /// Convertible type public typealias GeometryType = MultiPoint public init(geometry lineString: GeometryType) { let points = lineString.points.map { GeographicPoint2D(geometry: $0) } self.init(points: points) } public var geometry: GeometryType { return .init(points: self.points.map { $0.geometry }, srid: FluentPostGISSrid) } public var baseGeometry: Geometry { return self.geometry } } extension GeographicMultiPoint2D: PostGISDataType { public static var dataType: DatabaseSchema.DataType { return PostGISDataTypeList.geographicMultiPoint } }
29.083333
107
0.716332
1c1013fdc0c7aedc581988f905e788abaf17df30
238
// // Array+Add.swift // PROJECT // // Created by USER_NAME on TODAYS_DATE. // Copyright (c) TODAYS_YEAR PROJECT_OWNER. All rights reserved. // import Foundation // https://www.jianshu.com/p/f501e465d1c4 public extension Array { }
17
65
0.710084
4676e232a87bcd094c0ad751fe506e1ebbe974be
2,033
// // ViewController.swift // Pursuit-Core-iOS-Unit2Final // // Created by Alex Paul on 11/15/18. // Copyright © 2018 Alex Paul. All rights reserved. // import UIKit class CrayonsVC: UIViewController { @IBOutlet weak var tableView: UITableView! var crayons = [Crayon]() { didSet{ tableView.reloadData() } } var selectedColor: UIColor = .white { didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self crayons = Crayon.allTheCrayons } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let colorSliderVC = segue.destination as? ColorSlidersVC, let indexPath = tableView.indexPathForSelectedRow else { fatalError("prepare for segue isn't working") } colorSliderVC.currentColor = crayons[indexPath.row] } } extension CrayonsVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return crayons.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "crayonCell", for: indexPath) let crayonColor = crayons[indexPath.row] let redAsCGFloat = CGFloat(crayonColor.red) / 255 let greenAsCGFloat = CGFloat(crayonColor.green) / 255 let blueAsCGFloat = CGFloat(crayonColor.blue) / 255 cell.textLabel?.text = crayonColor.name cell.detailTextLabel?.text = crayonColor.hex cell.backgroundColor = UIColor(red: redAsCGFloat, green: greenAsCGFloat, blue: blueAsCGFloat, alpha: 1) if crayonColor.blue < 10 && crayonColor.green < 10 && crayonColor.red < 10 { cell.textLabel?.textColor = .white cell.detailTextLabel?.textColor = .white } return cell } }
30.343284
128
0.641417
64a5755f15fba63ad54d76fa032c2fee4b549959
471
// // ABFCDataCore.swift // ABFCDataCore // // Created by 1741103 on 10/08/19. // Copyright © 2019 1741103. All rights reserved. // import UIKit public class ABFCDataCore: NSObject { private override init() { super.init() } public static let shared: ABFCDataCore = { let instance = ABFCDataCore() // Setup code return instance }() public func storeData() { print("Storing Data...") } }
16.821429
50
0.581741
4b571606e7729443f32e7687085821c3c7a4bf0b
2,482
// // ModelPickerViewController.swift // CSDTModelViewer // // Created by Jing Wei Li on 2/2/18. // Copyright © 2018 Jing Wei Li. All rights reserved. // import UIKit import Alamofire class ModelPickerViewController: UIViewController { var customURL: String! = "None" let defaultURL = "http://thingiverse-production-new.s3.amazonaws.com/assets/c4/4c/76/de/9b/jordanb.stl" @IBOutlet weak var customURLButton: UIButton! @IBOutlet weak var defaultURLButton: UIButton! @IBOutlet weak var listButton: UIButton! override func viewDidLoad() { super.viewDidLoad() customURLButton.layer.cornerRadius = 15.0 customURLButton.clipsToBounds = true defaultURLButton.layer.cornerRadius = 15.0 defaultURLButton.clipsToBounds = true listButton.layer.cornerRadius = 15.0 listButton.clipsToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation @IBAction func defaultSegue(_ sender: UIButton) { DispatchQueue.main.async { self.performSegue(withIdentifier: "donePickingModel", sender: self) } } @IBAction func customURLSegue(_ sender: UIButton) { let alert = UIAlertController(title: "Enter Model URL", message: nil, preferredStyle: .alert) alert.addTextField{ textField in textField.text = self.defaultURL } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in let textField = alert?.textFields![0] // Force unwrapping because we know it exists. self.customURL = textField?.text ?? "" DispatchQueue.main.async { self.performSegue(withIdentifier: "donePickingModel", sender: self) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.view.tintColor = customGreen() self.present(alert, animated: true, completion: nil) } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let dest = segue.destination as? SceneViewController{ if customURL != "None"{ dest.customURL = customURL } } } }
35.457143
107
0.647462
c1cbb467390c3ef283fbcf0aa87f09d02ef00af7
1,008
// // NavigationStackDemoTests.swift // NavigationStackDemoTests // // Created by Alex K. on 26/02/16. // Copyright © 2016 Alex K. All rights reserved. // import XCTest @testable import NavigationStackDemo class NavigationStackDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.243243
111
0.644841
71f0704aab14b978fbb9e975d341ad8ff86f236d
559
// // ArticleView.swift // Multiplatform macOS // // Created by Maurice Parker on 7/8/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import SwiftUI import Articles struct ArticleView: NSViewControllerRepresentable { @EnvironmentObject private var sceneModel: SceneModel func makeNSViewController(context: Context) -> WebViewController { let controller = WebViewController() controller.sceneModel = sceneModel return controller } func updateNSViewController(_ controller: WebViewController, context: Context) { } }
21.5
81
0.763864
d7725a1fd2023f4f0c64632cc407ce3d4540bcfb
3,000
import XCTest @testable import IntervalReminder class CoreDataCacheTests: XCTestCase { // MARK: - Parameters & Constants private let timerInterval: Double = 23.342 private let timerText = "TestString3123213123" private let timerText2 = "asd22222" // MARK: - Test variables private var sut: CoreDataCache! lazy var container: NSPersistentContainer = { return NSPersistentContainer(name: CoreDataCache.coreDataName) }() // MARK: - Set up and tear down override func setUp() { super.setUp() loadStore() sut = CoreDataCache() sut.persistentContainer = container } private func loadStore() { weak var expectation = self.expectation(description: "callback") let configuration = NSPersistentStoreDescription() configuration.type = NSInMemoryStoreType container.persistentStoreDescriptions = [configuration] container.loadPersistentStores() { _, error in if let error = error as? NSError { XCTFail("Unresolved error \(error), \(error.userInfo)") } expectation?.fulfill() } waitForExpectations(timeout: 5, handler: nil) } override func tearDown() { sut = nil super.tearDown() } // MARK: - Tests func testCanCreateInterval() { XCTAssertNotNil(sut, "SUT must not be nil") } func testPersistentContainerNameIsValid() { XCTAssertEqual(sut.persistentContainer.name, CoreDataCache.coreDataName) } func testGetIntervalsMustReturnSavedIntervals() { createCacheInterval(interval: timerInterval, text: timerText, index: 0) save() XCTAssertEqual(sut.getIntervals()[0].text, timerText) XCTAssertEqual(sut.getIntervals().count, 1) } func testGetIntervalsOrder() { createCacheInterval(interval: timerInterval, text: timerText, index: 1) createCacheInterval(interval: timerInterval, text: timerText2, index: 0) save() XCTAssertEqual(sut.getIntervals()[0].text, timerText2) } private func save() { try! container.viewContext.save() } private func createCacheInterval(interval: Double, text: String, index: Int) { let cacheInterval = CacheInterval(context: container.viewContext) cacheInterval.interval = interval cacheInterval.text = text cacheInterval.index = Int64(index) } func testSaveIntervalsMustCacheProdidedIntervals() { let intervals = [Interval(timerInterval, timerText)] sut.saveIntervals(intervals) XCTAssertEqual(sut.getIntervals()[0].text, timerText) } func testSaveMustRemoveOldIntervals() { createCacheInterval(interval: timerInterval, text: timerText2, index: 0) let intervals = [Interval(timerInterval, timerText)] sut.saveIntervals(intervals) XCTAssertEqual(sut.getIntervals().count, 1) } }
35.714286
82
0.657333
3a9bf77b1c035e89fe8c4aacfd7a171820312fbc
8,615
// // AuthSpec.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/25/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import XCTest import RealmSwift @testable import Rocket_Chat // MARK: Test Instance extension Auth { static func testInstance() -> Auth { let auth = Auth() auth.settings = AuthSettings.testInstance() auth.serverURL = "wss://open.rocket.chat/websocket" auth.serverVersion = "1.2.3" auth.userId = "auth-userid" auth.token = "auth-token" return auth } } class AuthSpec: XCTestCase, RealmTestCase { // MARK: Setup override func setUp() { super.setUp() var uniqueConfiguration = Realm.Configuration.defaultConfiguration uniqueConfiguration.inMemoryIdentifier = NSUUID().uuidString Realm.Configuration.defaultConfiguration = uniqueConfiguration Realm.executeOnMainThread({ realm in realm.deleteAll() }) } // MARK: Tests func testAuthObject() { let serverURL = "http://foobar.com" let object = Auth() object.serverURL = serverURL object.token = "123" object.tokenExpires = Date() object.lastAccess = Date() object.userId = "123" Realm.execute({ realm in realm.add(object) let results = realm.objects(Auth.self) let first = results.first XCTAssert(results.count == 1, "Auth object was created with success") XCTAssert(first?.serverURL == serverURL, "Auth object was created with success") }) } func testAPIHost() { let object = Auth() object.serverURL = "wss://team.rocket.chat/websocket" XCTAssertEqual(object.apiHost?.absoluteString, "https://team.rocket.chat/", "apiHost returns API Host correctly") } func testAPIHostOnSubdirectory() { let object = Auth() object.serverURL = "wss://team.rocket.chat/subdirectory/websocket" XCTAssertEqual(object.apiHost?.absoluteString, "https://team.rocket.chat/subdirectory/", "apiHost returns API Host correctly") } func testAPIHostInvalidServerURL() { let object = Auth() object.serverURL = "" XCTAssertNil(object.apiHost, "apiHost will be nil when serverURL is an invalid URL") } //swiftlint:disable function_body_length func testCanDeleteMessage() { let realm = testRealm() let user1 = User.testInstance() user1.identifier = "uid1" let user2 = User.testInstance() user2.identifier = "uid2" let auth = Auth.testInstance() auth.userId = user1.identifier let message = Message.testInstance() message.identifier = "mid" message.user = user1 // standard test try? realm.write { realm.add(auth) realm.add(user1) realm.add(user2) auth.settings?.messageAllowDeleting = true auth.settings?.messageAllowDeletingBlockDeleteInMinutes = 0 } XCTAssert(auth.canDeleteMessage(message) == .allowed) // invalid message try? realm.write { message.createdAt = nil } XCTAssert(auth.canDeleteMessage(message) == .unknown) // non actionable message type try? realm.write { message.createdAt = Date() message.internalType = MessageType.userJoined.rawValue } XCTAssert(auth.canDeleteMessage(message) == .notActionable) // time elapsed try? realm.write { message.internalType = MessageType.text.rawValue message.createdAt = Date(timeInterval: -1000, since: Date()) auth.settings?.messageAllowDeletingBlockDeleteInMinutes = 1 } XCTAssert(auth.canDeleteMessage(message) == .timeElapsed) // different user try? realm.write { message.user = user2 } XCTAssert(auth.canDeleteMessage(message) == .differentUser) // server blocked try? realm.write { auth.settings?.messageAllowDeleting = false message.user = user1 } XCTAssert(auth.canDeleteMessage(message) == .serverBlocked) // force-delete-message permission let forcePermission = Permission() forcePermission.identifier = PermissionType.forceDeleteMessage.rawValue forcePermission.roles.append("admin") try? realm.write { message.user = user2 realm.add(forcePermission) user1.roles.append("admin") } XCTAssert(auth.canDeleteMessage(message) == .allowed) // delete-message permission time elapsed let permission = Permission() permission.identifier = PermissionType.deleteMessage.rawValue permission.roles.append("admin") try? realm.write { forcePermission.roles.removeAll() realm.add(permission) } XCTAssert(auth.canDeleteMessage(message) == .timeElapsed) try? realm.write { auth.settings?.messageAllowDeletingBlockDeleteInMinutes = 0 } XCTAssert(auth.canDeleteMessage(message) == .allowed) } //swiftlint:disable function_body_length func testCanEditMessage() { let realm = testRealm() let user1 = User.testInstance() user1.identifier = "uid1" let user2 = User.testInstance() user2.identifier = "uid2" let auth = Auth.testInstance() auth.userId = user1.identifier let message = Message.testInstance() message.identifier = "mid" message.user = user1 // standard test try? realm.write { realm.add(auth) realm.add(user1) realm.add(user2) auth.settings?.messageAllowEditing = true auth.settings?.messageAllowEditingBlockEditInMinutes = 0 } XCTAssert(auth.canEditMessage(message) == .allowed) // invalid message try? realm.write { message.createdAt = nil } XCTAssert(auth.canEditMessage(message) == .unknown) // non actionable message type try? realm.write { message.createdAt = Date() message.internalType = MessageType.userJoined.rawValue } XCTAssert(auth.canEditMessage(message) == .notActionable) // time elapsed try? realm.write { message.internalType = MessageType.text.rawValue message.createdAt = Date(timeInterval: -1000, since: Date()) auth.settings?.messageAllowEditingBlockEditInMinutes = 1 } XCTAssert(auth.canEditMessage(message) == .timeElapsed) // different user try? realm.write { message.user = user2 } XCTAssert(auth.canEditMessage(message) == .differentUser) // server blocked try? realm.write { auth.settings?.messageAllowEditing = false message.user = user1 } XCTAssert(auth.canEditMessage(message) == .serverBlocked) // edit-message let permission = Permission() permission.identifier = PermissionType.editMessage.rawValue permission.roles.append("admin") try? realm.write { user1.roles.append("admin") message.user = user2 realm.add(permission) } XCTAssert(auth.canEditMessage(message) == .allowed) } func testCanBlockMessage() { let realm = testRealm() let user1 = User.testInstance() user1.identifier = "uid1" let user2 = User.testInstance() user2.identifier = "uid2" let auth = Auth.testInstance() auth.userId = user1.identifier let message = Message.testInstance() message.identifier = "mid" message.user = user2 // block-message try? realm.write { realm.add(auth) realm.add(user1) realm.add(user2) } XCTAssert(auth.canBlockMessage(message) == .allowed) // my own message try? realm.write { message.user = user1 } XCTAssert(auth.canBlockMessage(message) == .myOwn) // non actionable message type try? realm.write { message.createdAt = Date() message.internalType = MessageType.userJoined.rawValue } XCTAssert(auth.canBlockMessage(message) == .notActionable) } }
26.265244
134
0.600232
67d1457d4c2f6fe59abfac016553b9772ef4e244
5,627
// // registerViewController.swift // BitExplorer // // Created by David Iola on 2/25/17. // Copyright © 2017 David Iola. All rights reserved. // import UIKit import Firebase import FirebaseAuth import FirebaseDatabase class registerViewController: UIViewController { @IBOutlet weak var iconFirst: UILabel! @IBOutlet weak var iconLast: UILabel! @IBOutlet weak var iconEmail: UILabel! @IBOutlet weak var iconPass: UILabel! @IBOutlet weak var iconConfirm: UILabel! @IBOutlet weak var firstName: UITextField! @IBOutlet weak var lastName: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var confirmField: UITextField! var ref: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(registerViewController.dismissKeyboard))) iconFirst.font = UIFont.fontAwesome(ofSize: 20) iconFirst.text = String.fontAwesomeIcon(name: .user) iconLast.font = UIFont.fontAwesome(ofSize: 20) iconLast.text = String.fontAwesomeIcon(name: .user) iconEmail.font = UIFont.fontAwesome(ofSize: 18) iconEmail.text = String.fontAwesomeIcon(name: .envelope) iconPass.font = UIFont.fontAwesome(ofSize: 20) iconPass.text = String.fontAwesomeIcon(name: .unlockAlt) iconConfirm.font = UIFont.fontAwesome(ofSize: 20) iconConfirm.text = String.fontAwesomeIcon(name: .key) ref = FIRDatabase.database().reference() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancelTapped(_ sender: Any) { self.dismiss(animated: true, completion: nil); } func dismissKeyboard() { firstName.resignFirstResponder() lastName.resignFirstResponder() emailField.resignFirstResponder() passwordField.resignFirstResponder() confirmField.resignFirstResponder() } @IBAction func submitTapped(_ sender: Any) { let firstname = firstName.text; let lastname = lastName.text; let email = emailField.text; let password = passwordField.text; let confirm = confirmField.text; if ( (firstname!.isEmpty || lastname!.isEmpty || email!.isEmpty || password!.isEmpty || confirm!.isEmpty)) { //display alert message displayMyAlertMessage("All fields are required"); return; } if (password != confirm) { //Display alert message displayMyAlertMessage("Passwords do not match"); return; } // store on Firebase FIRAuth.auth()?.createUser(withEmail: email!, password: password!) { (user, error) in if error == nil { let userUID = FIRAuth.auth()?.currentUser?.uid self.ref.child("users").child(userUID!).setValue(["First" : firstname, "Last" : lastname]) let myAlert = UIAlertController(title: "Alert", message: "Registration is Successful", preferredStyle: UIAlertControllerStyle.alert); let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) { action in self.performSegue(withIdentifier: "loginSegue", sender: self); } myAlert.addAction(okAction); self.present(myAlert, animated: true, completion: nil); } else { let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } } } func displayMyAlertMessage(_ userMessage:String) { let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert); let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil); myAlert.addAction(okAction); self.present(myAlert, animated: true, completion: nil); } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
29.15544
149
0.564599
b9384167caa20120265a9d49c43f1008e192106e
2,572
/** * Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation class ImageURLModel { class func imageParameter(forClosestImageSize size:CGSize) -> String { let squareImageRequested = size.width == size.height var imageParameterID:Int = 0 if squareImageRequested { imageParameterID = imageParameter(forSquareCroppedSize: size) } return "&image_size=\(imageParameterID)" } class func imageParameter(forSquareCroppedSize size:CGSize) -> Int { var imageParameterID:Int = 0 if size.height <= 70 { imageParameterID = 1 } else if size.height <= 100 { imageParameterID = 100 } else if size.height <= 140 { imageParameterID = 2 } else if size.height <= 200 { imageParameterID = 200 } else if size.height <= 280 { imageParameterID = 3 } else if size.height <= 400 { imageParameterID = 400 } else { imageParameterID = 600 } return imageParameterID } }
38.969697
82
0.725505
4634f4c9e0ed2f4bfdccc76ace52191987b90a21
34,555
// // DropDown.swift // DropDown // // Created by Kevin Hirsch on 28/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit public typealias Index = Int public typealias Closure = () -> Void public typealias SelectionClosure = (Index, String) -> Void public typealias MultiSelectionClosure = ([Index], [String]) -> Void public typealias ConfigurationClosure = (Index, String) -> String public typealias CellConfigurationClosure = (Index, String, DropDownCell) -> Void private typealias ComputeLayoutTuple = (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat) /// Can be `UIView` or `UIBarButtonItem`. @objc public protocol AnchorView: class { var plainView: UIView { get } } extension UIView: AnchorView { public var plainView: UIView { return self } } extension UIBarButtonItem: AnchorView { public var plainView: UIView { return value(forKey: "view") as! UIView } } /// A Material Design drop down in replacement for `UIPickerView`. public final class DropDown: UIView { //TODO: handle iOS 7 landscape mode /// The dismiss mode for a drop down. public enum DismissMode { /// A tap outside the drop down is required to dismiss. case onTap /// No tap is required to dismiss, it will dimiss when interacting with anything else. case automatic /// Not dismissable by the user. case manual } /// The direction where the drop down will show from the `anchorView`. public enum Direction { /// The drop down will show below the anchor view when possible, otherwise above if there is more place than below. case any /// The drop down will show above the anchor view or will not be showed if not enough space. case top /// The drop down will show below or will not be showed if not enough space. case bottom } //MARK: - Properties /// The current visible drop down. There can be only one visible drop down at a time. public static weak var VisibleDropDown: DropDown? //MARK: UI fileprivate let dismissableView = UIView() fileprivate let tableViewContainer = UIView() fileprivate let tableView = UITableView() fileprivate var templateCell: DropDownCell! fileprivate lazy var arrowIndication: UIImageView = { UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 10), false, 0) let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 10)) path.addLine(to: CGPoint(x: 20, y: 10)) path.addLine(to: CGPoint(x: 10, y: 0)) path.addLine(to: CGPoint(x: 0, y: 10)) UIColor.black.setFill() path.fill() let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let tintImg = img?.withRenderingMode(.alwaysTemplate) let imgv = UIImageView(image: tintImg) imgv.frame = CGRect(x: 0, y: -10, width: 15, height: 10) return imgv }() /// The view to which the drop down will displayed onto. public weak var anchorView: AnchorView? { didSet { setNeedsUpdateConstraints() } } /** The possible directions where the drop down will be showed. See `Direction` enum for more info. */ public var direction = Direction.any /** The offset point relative to `anchorView` when the drop down is shown above the anchor view. By default, the drop down is showed onto the `anchorView` with the top left corner for its origin, so an offset equal to (0, 0). You can change here the default drop down origin. */ public var topOffset: CGPoint = .zero { didSet { setNeedsUpdateConstraints() } } /** The offset point relative to `anchorView` when the drop down is shown below the anchor view. By default, the drop down is showed onto the `anchorView` with the top left corner for its origin, so an offset equal to (0, 0). You can change here the default drop down origin. */ public var bottomOffset: CGPoint = .zero { didSet { setNeedsUpdateConstraints() } } /** The offset from the bottom of the window when the drop down is shown below the anchor view. DropDown applies this offset only if keyboard is hidden. */ public var offsetFromWindowBottom = CGFloat(0) { didSet { setNeedsUpdateConstraints() } } /** The width of the drop down. Defaults to `anchorView.bounds.width - offset.x`. */ public var width: CGFloat? { didSet { setNeedsUpdateConstraints() } } /** arrowIndication.x arrowIndication will be add to tableViewContainer when configured */ public var arrowIndicationX: CGFloat? { didSet { if let arrowIndicationX = arrowIndicationX { tableViewContainer.addSubview(arrowIndication) arrowIndication.tintColor = tableViewBackgroundColor arrowIndication.frame.origin.x = arrowIndicationX } else { arrowIndication.removeFromSuperview() } } } //MARK: Constraints fileprivate var heightConstraint: NSLayoutConstraint! fileprivate var widthConstraint: NSLayoutConstraint! fileprivate var xConstraint: NSLayoutConstraint! fileprivate var yConstraint: NSLayoutConstraint! //MARK: Appearance @objc public dynamic var cellHeight = DPDConstant.UI.RowHeight { willSet { tableView.rowHeight = newValue } didSet { reloadAllComponents() } } @objc fileprivate dynamic var tableViewBackgroundColor = DPDConstant.UI.BackgroundColor { willSet { tableView.backgroundColor = newValue if arrowIndicationX != nil { arrowIndication.tintColor = newValue } } } public override var backgroundColor: UIColor? { get { return tableViewBackgroundColor } set { tableViewBackgroundColor = newValue! } } /** The color of the dimmed background (behind the drop down, covering the entire screen). */ public var dimmedBackgroundColor = UIColor.clear { willSet { super.backgroundColor = newValue } } /** The background color of the selected cell in the drop down. Changing the background color automatically reloads the drop down. */ @objc public dynamic var selectionBackgroundColor = DPDConstant.UI.SelectionBackgroundColor /** The separator color between cells. Changing the separator color automatically reloads the drop down. */ @objc public dynamic var separatorColor = DPDConstant.UI.SeparatorColor { willSet { tableView.separatorColor = newValue } didSet { reloadAllComponents() } } /** The corner radius of DropDown. Changing the corner radius automatically reloads the drop down. */ @objc public dynamic var cornerRadius = DPDConstant.UI.CornerRadius { willSet { tableViewContainer.layer.cornerRadius = newValue tableView.layer.cornerRadius = newValue } didSet { reloadAllComponents() } } /** Alias method for `cornerRadius` variable to avoid ambiguity. */ @objc public dynamic func setupCornerRadius(_ radius: CGFloat) { tableViewContainer.layer.cornerRadius = radius tableView.layer.cornerRadius = radius reloadAllComponents() } /** The masked corners of DropDown. Changing the masked corners automatically reloads the drop down. */ @available(iOS 11.0, *) @objc public dynamic func setupMaskedCorners(_ cornerMask: CACornerMask) { tableViewContainer.layer.maskedCorners = cornerMask tableView.layer.maskedCorners = cornerMask reloadAllComponents() } /** The color of the shadow. Changing the shadow color automatically reloads the drop down. */ @objc public dynamic var shadowColor = DPDConstant.UI.Shadow.Color { willSet { tableViewContainer.layer.shadowColor = newValue.cgColor } didSet { reloadAllComponents() } } /** The offset of the shadow. Changing the shadow color automatically reloads the drop down. */ @objc public dynamic var shadowOffset = DPDConstant.UI.Shadow.Offset { willSet { tableViewContainer.layer.shadowOffset = newValue } didSet { reloadAllComponents() } } /** The opacity of the shadow. Changing the shadow opacity automatically reloads the drop down. */ @objc public dynamic var shadowOpacity = DPDConstant.UI.Shadow.Opacity { willSet { tableViewContainer.layer.shadowOpacity = newValue } didSet { reloadAllComponents() } } /** The radius of the shadow. Changing the shadow radius automatically reloads the drop down. */ @objc public dynamic var shadowRadius = DPDConstant.UI.Shadow.Radius { willSet { tableViewContainer.layer.shadowRadius = newValue } didSet { reloadAllComponents() } } /** The duration of the show/hide animation. */ @objc public dynamic var animationduration = DPDConstant.Animation.Duration /** The option of the show animation. Global change. */ public static var animationEntranceOptions = DPDConstant.Animation.EntranceOptions /** The option of the hide animation. Global change. */ public static var animationExitOptions = DPDConstant.Animation.ExitOptions /** The option of the show animation. Only change the caller. To change all drop down's use the static var. */ public var animationEntranceOptions: UIView.AnimationOptions = DropDown.animationEntranceOptions /** The option of the hide animation. Only change the caller. To change all drop down's use the static var. */ public var animationExitOptions: UIView.AnimationOptions = DropDown.animationExitOptions /** The downScale transformation of the tableview when the DropDown is appearing */ public var downScaleTransform = DPDConstant.Animation.DownScaleTransform { willSet { tableViewContainer.transform = newValue } } /** The color of the text for each cells of the drop down. Changing the text color automatically reloads the drop down. */ @objc public dynamic var textColor = DPDConstant.UI.TextColor { didSet { reloadAllComponents() } } /** The color of the text for selected cells of the drop down. Changing the text color automatically reloads the drop down. */ @objc public dynamic var selectedTextColor = DPDConstant.UI.SelectedTextColor { didSet { reloadAllComponents() } } /** The font of the text for each cells of the drop down. Changing the text font automatically reloads the drop down. */ @objc public dynamic var textFont = DPDConstant.UI.TextFont { didSet { reloadAllComponents() } } /** The NIB to use for DropDownCells Changing the cell nib automatically reloads the drop down. */ public var cellNib = UINib(nibName: "DropDownCell", bundle: Bundle(for: DropDownCell.self)) { didSet { tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell) templateCell = nil reloadAllComponents() } } //MARK: Content /** The data source for the drop down. Changing the data source automatically reloads the drop down. */ public var dataSource = [String]() { didSet { deselectRows(at: selectedRowIndices) reloadAllComponents() } } /** The localization keys for the data source for the drop down. Changing this value automatically reloads the drop down. This has uses for setting accibility identifiers on the drop down cells (same ones as the localization keys). */ public var localizationKeysDataSource = [String]() { didSet { dataSource = localizationKeysDataSource.map { NSLocalizedString($0, comment: "") } } } /// The indicies that have been selected fileprivate var selectedRowIndices = Set<Index>() /** The format for the cells' text. By default, the cell's text takes the plain `dataSource` value. Changing `cellConfiguration` automatically reloads the drop down. */ public var cellConfiguration: ConfigurationClosure? { didSet { reloadAllComponents() } } /** A advanced formatter for the cells. Allows customization when custom cells are used Changing `customCellConfiguration` automatically reloads the drop down. */ public var customCellConfiguration: CellConfigurationClosure? { didSet { reloadAllComponents() } } /// The action to execute when the user selects a cell. public var selectionAction: SelectionClosure? /** The action to execute when the user selects multiple cells. Providing an action will turn on multiselection mode. The single selection action will still be called if provided. */ public var multiSelectionAction: MultiSelectionClosure? /// The action to execute when the drop down will show. public var willShowAction: Closure? /// The action to execute when the user cancels/hides the drop down. public var cancelAction: Closure? /// The dismiss mode of the drop down. Default is `OnTap`. public var dismissMode = DismissMode.onTap { willSet { if newValue == .onTap { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissableViewTapped)) dismissableView.addGestureRecognizer(gestureRecognizer) } else if let gestureRecognizer = dismissableView.gestureRecognizers?.first { dismissableView.removeGestureRecognizer(gestureRecognizer) } } } fileprivate var minHeight: CGFloat { return tableView.rowHeight } fileprivate var didSetupConstraints = false //MARK: - Init's deinit { stopListeningToNotifications() } /** Creates a new instance of a drop down. Don't forget to setup the `dataSource`, the `anchorView` and the `selectionAction` at least before calling `show()`. */ public convenience init() { self.init(frame: .zero) } /** Creates a new instance of a drop down. - parameter anchorView: The view to which the drop down will displayed onto. - parameter selectionAction: The action to execute when the user selects a cell. - parameter dataSource: The data source for the drop down. - parameter topOffset: The offset point relative to `anchorView` used when drop down is displayed on above the anchor view. - parameter bottomOffset: The offset point relative to `anchorView` used when drop down is displayed on below the anchor view. - parameter cellConfiguration: The format for the cells' text. - parameter cancelAction: The action to execute when the user cancels/hides the drop down. - returns: A new instance of a drop down customized with the above parameters. */ public convenience init(anchorView: AnchorView, selectionAction: SelectionClosure? = nil, dataSource: [String] = [], topOffset: CGPoint? = nil, bottomOffset: CGPoint? = nil, cellConfiguration: ConfigurationClosure? = nil, cancelAction: Closure? = nil) { self.init(frame: .zero) self.anchorView = anchorView self.selectionAction = selectionAction self.dataSource = dataSource self.topOffset = topOffset ?? .zero self.bottomOffset = bottomOffset ?? .zero self.cellConfiguration = cellConfiguration self.cancelAction = cancelAction } override public init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } } //MARK: - Setup private extension DropDown { func setup() { tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell) DispatchQueue.main.async { //HACK: If not done in dispatch_async on main queue `setupUI` will have no effect self.updateConstraintsIfNeeded() self.setupUI() } tableView.rowHeight = cellHeight setHiddentState() isHidden = true dismissMode = .onTap tableView.delegate = self tableView.dataSource = self startListeningToKeyboard() accessibilityIdentifier = "drop_down" } func setupUI() { super.backgroundColor = dimmedBackgroundColor tableViewContainer.layer.masksToBounds = false tableViewContainer.layer.cornerRadius = cornerRadius tableViewContainer.layer.shadowColor = shadowColor.cgColor tableViewContainer.layer.shadowOffset = shadowOffset tableViewContainer.layer.shadowOpacity = shadowOpacity tableViewContainer.layer.shadowRadius = shadowRadius tableView.backgroundColor = tableViewBackgroundColor tableView.separatorColor = separatorColor tableView.layer.cornerRadius = cornerRadius tableView.layer.masksToBounds = true } } //MARK: - UI extension DropDown { public override func updateConstraints() { if !didSetupConstraints { setupConstraints() } didSetupConstraints = true let layout = computeLayout() if !layout.canBeDisplayed { super.updateConstraints() hide() return } xConstraint.constant = layout.x yConstraint.constant = layout.y widthConstraint.constant = layout.width heightConstraint.constant = layout.visibleHeight tableView.isScrollEnabled = layout.offscreenHeight > 0 DispatchQueue.main.async { [weak self] in self?.tableView.flashScrollIndicators() } super.updateConstraints() } fileprivate func setupConstraints() { translatesAutoresizingMaskIntoConstraints = false // Dismissable view addSubview(dismissableView) dismissableView.translatesAutoresizingMaskIntoConstraints = false addUniversalConstraints(format: "|[dismissableView]|", views: ["dismissableView": dismissableView]) // Table view container addSubview(tableViewContainer) tableViewContainer.translatesAutoresizingMaskIntoConstraints = false xConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) addConstraint(xConstraint) yConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) addConstraint(yConstraint) widthConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0) tableViewContainer.addConstraint(widthConstraint) heightConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0) tableViewContainer.addConstraint(heightConstraint) // Table view tableViewContainer.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false tableViewContainer.addUniversalConstraints(format: "|[tableView]|", views: ["tableView": tableView]) } public override func layoutSubviews() { super.layoutSubviews() // When orientation changes, layoutSubviews is called // We update the constraint to update the position setNeedsUpdateConstraints() let shadowPath = UIBezierPath(roundedRect: tableViewContainer.bounds, cornerRadius: cornerRadius) tableViewContainer.layer.shadowPath = shadowPath.cgPath } fileprivate func computeLayout() -> (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat, visibleHeight: CGFloat, canBeDisplayed: Bool, Direction: Direction) { var layout: ComputeLayoutTuple = (0, 0, 0, 0) var direction = self.direction guard let window = UIWindow.visibleWindow() else { return (0, 0, 0, 0, 0, false, direction) } barButtonItemCondition: if let anchorView = anchorView as? UIBarButtonItem { let isRightBarButtonItem = anchorView.plainView.frame.minX > window.frame.midX guard isRightBarButtonItem else { break barButtonItemCondition } let width = self.width ?? fittingWidth() let anchorViewWidth = anchorView.plainView.frame.width let x = -(width - anchorViewWidth) bottomOffset = CGPoint(x: x, y: 0) } if anchorView == nil { layout = computeLayoutBottomDisplay(window: window) direction = .any } else { switch direction { case .any: layout = computeLayoutBottomDisplay(window: window) direction = .bottom if layout.offscreenHeight > 0 { let topLayout = computeLayoutForTopDisplay(window: window) if topLayout.offscreenHeight < layout.offscreenHeight { layout = topLayout direction = .top } } case .bottom: layout = computeLayoutBottomDisplay(window: window) direction = .bottom case .top: layout = computeLayoutForTopDisplay(window: window) direction = .top } } constraintWidthToFittingSizeIfNecessary(layout: &layout) constraintWidthToBoundsIfNecessary(layout: &layout, in: window) let visibleHeight = tableHeight - layout.offscreenHeight let canBeDisplayed = visibleHeight >= minHeight return (layout.x, layout.y, layout.width, layout.offscreenHeight, visibleHeight, canBeDisplayed, direction) } fileprivate func computeLayoutBottomDisplay(window: UIWindow) -> ComputeLayoutTuple { var offscreenHeight: CGFloat = 0 let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - bottomOffset.x let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? window.frame.midX - (width / 2) let anchorViewY = anchorView?.plainView.windowFrame?.minY ?? window.frame.midY - (tableHeight / 2) let x = anchorViewX + bottomOffset.x let y = anchorViewY + bottomOffset.y let maxY = y + tableHeight let windowMaxY = window.bounds.maxY - DPDConstant.UI.HeightPadding - offsetFromWindowBottom let keyboardListener = KeyboardListener.sharedInstance let keyboardMinY = keyboardListener.keyboardFrame.minY - DPDConstant.UI.HeightPadding if keyboardListener.isVisible && maxY > keyboardMinY { offscreenHeight = abs(maxY - keyboardMinY) } else if maxY > windowMaxY { offscreenHeight = abs(maxY - windowMaxY) } return (x, y, width, offscreenHeight) } fileprivate func computeLayoutForTopDisplay(window: UIWindow) -> ComputeLayoutTuple { var offscreenHeight: CGFloat = 0 let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? 0 let anchorViewMaxY = anchorView?.plainView.windowFrame?.maxY ?? 0 let x = anchorViewX + topOffset.x var y = (anchorViewMaxY + topOffset.y) - tableHeight let windowY = window.bounds.minY + DPDConstant.UI.HeightPadding if y < windowY { offscreenHeight = abs(y - windowY) y = windowY } let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - topOffset.x return (x, y, width, offscreenHeight) } fileprivate func fittingWidth() -> CGFloat { if templateCell == nil { templateCell = (cellNib.instantiate(withOwner: nil, options: nil)[0] as! DropDownCell) } var maxWidth: CGFloat = 0 for index in 0..<dataSource.count { configureCell(templateCell, at: index) templateCell.bounds.size.height = cellHeight let width = templateCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width if width > maxWidth { maxWidth = width } } return maxWidth } fileprivate func constraintWidthToBoundsIfNecessary(layout: inout ComputeLayoutTuple, in window: UIWindow) { let windowMaxX = window.bounds.maxX let maxX = layout.x + layout.width if maxX > windowMaxX { let delta = maxX - windowMaxX let newOrigin = layout.x - delta if newOrigin > 0 { layout.x = newOrigin } else { layout.x = 0 layout.width += newOrigin // newOrigin is negative, so this operation is a substraction } } } fileprivate func constraintWidthToFittingSizeIfNecessary(layout: inout ComputeLayoutTuple) { guard width == nil else { return } if layout.width < fittingWidth() { layout.width = fittingWidth() } } } //MARK: - Actions extension DropDown { /** An Objective-C alias for the show() method which converts the returned tuple into an NSDictionary. - returns: An NSDictionary with a value for the "canBeDisplayed" Bool, and possibly for the "offScreenHeight" Optional(CGFloat). */ @objc(show) public func objc_show() -> NSDictionary { let (canBeDisplayed, offScreenHeight) = show() var info = [AnyHashable: Any]() info["canBeDisplayed"] = canBeDisplayed if let offScreenHeight = offScreenHeight { info["offScreenHeight"] = offScreenHeight } return NSDictionary(dictionary: info) } /** Shows the drop down if enough height. - returns: Wether it succeed and how much height is needed to display all cells at once. */ @discardableResult public func show(onTopOf window: UIWindow? = nil, beforeTransform transform: CGAffineTransform? = nil, anchorPoint: CGPoint? = nil) -> (canBeDisplayed: Bool, offscreenHeight: CGFloat?) { if self == DropDown.VisibleDropDown && DropDown.VisibleDropDown?.isHidden == false { // added condition - DropDown.VisibleDropDown?.isHidden == false -> to resolve forever hiding dropdown issue when continuous taping on button - Kartik Patel - 2016-12-29 return (true, 0) } if let visibleDropDown = DropDown.VisibleDropDown { visibleDropDown.cancel() } willShowAction?() DropDown.VisibleDropDown = self setNeedsUpdateConstraints() let visibleWindow = window != nil ? window : UIWindow.visibleWindow() visibleWindow?.addSubview(self) visibleWindow?.bringSubviewToFront(self) self.translatesAutoresizingMaskIntoConstraints = false visibleWindow?.addUniversalConstraints(format: "|[dropDown]|", views: ["dropDown": self]) let layout = computeLayout() if !layout.canBeDisplayed { hide() return (layout.canBeDisplayed, layout.offscreenHeight) } isHidden = false if anchorPoint != nil { tableViewContainer.layer.anchorPoint = anchorPoint! } if transform != nil { tableViewContainer.transform = transform! } else { tableViewContainer.transform = downScaleTransform } layoutIfNeeded() UIView.animate( withDuration: animationduration, delay: 0, options: animationEntranceOptions, animations: { [weak self] in self?.setShowedState() }, completion: nil) accessibilityViewIsModal = true UIAccessibility.post(notification: .screenChanged, argument: self) //deselectRows(at: selectedRowIndices) selectRows(at: selectedRowIndices) return (layout.canBeDisplayed, layout.offscreenHeight) } public override func accessibilityPerformEscape() -> Bool { switch dismissMode { case .automatic, .onTap: cancel() return true case .manual: return false } } /// Hides the drop down. public func hide() { if self == DropDown.VisibleDropDown { /* If one drop down is showed and another one is not but we call `hide()` on the hidden one: we don't want it to set the `VisibleDropDown` to nil. */ DropDown.VisibleDropDown = nil } if isHidden { return } UIView.animate( withDuration: animationduration, delay: 0, options: animationExitOptions, animations: { [weak self] in self?.setHiddentState() }, completion: { [weak self] finished in guard let `self` = self else { return } self.isHidden = true self.removeFromSuperview() UIAccessibility.post(notification: .screenChanged, argument: nil) }) } fileprivate func cancel() { hide() cancelAction?() } fileprivate func setHiddentState() { alpha = 0 } fileprivate func setShowedState() { alpha = 1 tableViewContainer.transform = CGAffineTransform.identity } } //MARK: - UITableView extension DropDown { /** Reloads all the cells. It should not be necessary in most cases because each change to `dataSource`, `textColor`, `textFont`, `selectionBackgroundColor` and `cellConfiguration` implicitly calls `reloadAllComponents()`. */ public func reloadAllComponents() { DispatchQueue.executeOnMainThread { self.tableView.reloadData() self.setNeedsUpdateConstraints() } } /// (Pre)selects a row at a certain index. public func selectRow(at index: Index?, scrollPosition: UITableView.ScrollPosition = .none) { if let index = index { tableView.selectRow( at: IndexPath(row: index, section: 0), animated: true, scrollPosition: scrollPosition ) selectedRowIndices.insert(index) } else { deselectRows(at: selectedRowIndices) selectedRowIndices.removeAll() } } public func selectRows(at indices: Set<Index>?) { indices?.forEach { selectRow(at: $0) } // if we are in multi selection mode then reload data so that all selections are shown if multiSelectionAction != nil { tableView.reloadData() } } public func deselectRow(at index: Index?) { guard let index = index , index >= 0 else { return } // remove from indices if let selectedRowIndex = selectedRowIndices.firstIndex(where: { $0 == index }) { selectedRowIndices.remove(at: selectedRowIndex) } tableView.deselectRow(at: IndexPath(row: index, section: 0), animated: true) } // de-selects the rows at the indices provided public func deselectRows(at indices: Set<Index>?) { indices?.forEach { deselectRow(at: $0) } } /// Returns the index of the selected row. public var indexForSelectedRow: Index? { return (tableView.indexPathForSelectedRow as NSIndexPath?)?.row } /// Returns the selected item. public var selectedItem: String? { guard let row = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row else { return nil } return dataSource[row] } /// Returns the height needed to display all cells. fileprivate var tableHeight: CGFloat { return tableView.rowHeight * CGFloat(dataSource.count) } //MARK: Objective-C methods for converting the Swift type Index @objc public func selectRow(_ index: Int, scrollPosition: UITableView.ScrollPosition = .none) { self.selectRow(at:Index(index), scrollPosition: scrollPosition) } @objc public func clearSelection() { self.selectRow(at:nil) } @objc public func deselectRow(_ index: Int) { tableView.deselectRow(at: IndexPath(row: Index(index), section: 0), animated: true) } @objc public var indexPathForSelectedRow: NSIndexPath? { return tableView.indexPathForSelectedRow as NSIndexPath? } } //MARK: - UITableViewDataSource - UITableViewDelegate extension DropDown: UITableViewDataSource, UITableViewDelegate { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: DPDConstant.ReusableIdentifier.DropDownCell, for: indexPath) as! DropDownCell let index = (indexPath as NSIndexPath).row configureCell(cell, at: index) return cell } fileprivate func configureCell(_ cell: DropDownCell, at index: Int) { if index >= 0 && index < localizationKeysDataSource.count { cell.accessibilityIdentifier = localizationKeysDataSource[index] } cell.optionLabel.textColor = textColor cell.optionLabel.font = textFont cell.selectedBackgroundColor = selectionBackgroundColor cell.highlightTextColor = selectedTextColor cell.normalTextColor = textColor if let cellConfiguration = cellConfiguration { cell.optionLabel.text = cellConfiguration(index, dataSource[index]) } else { cell.optionLabel.text = dataSource[index] } customCellConfiguration?(index, dataSource[index], cell) } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.isSelected = selectedRowIndices.first{ $0 == (indexPath as NSIndexPath).row } != nil } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedRowIndex = (indexPath as NSIndexPath).row // are we in multi-selection mode? if let multiSelectionCallback = multiSelectionAction { // if already selected then deselect if selectedRowIndices.first(where: { $0 == selectedRowIndex}) != nil { deselectRow(at: selectedRowIndex) let selectedRowIndicesArray = Array(selectedRowIndices) let selectedRows = selectedRowIndicesArray.map { dataSource[$0] } multiSelectionCallback(selectedRowIndicesArray, selectedRows) return } else { selectedRowIndices.insert(selectedRowIndex) let selectedRowIndicesArray = Array(selectedRowIndices) let selectedRows = selectedRowIndicesArray.map { dataSource[$0] } selectionAction?(selectedRowIndex, dataSource[selectedRowIndex]) multiSelectionCallback(selectedRowIndicesArray, selectedRows) tableView.reloadData() return } } // Perform single selection logic selectedRowIndices.removeAll() selectedRowIndices.insert(selectedRowIndex) selectionAction?(selectedRowIndex, dataSource[selectedRowIndex]) if let _ = anchorView as? UIBarButtonItem { // DropDown's from UIBarButtonItem are menus so we deselect the selected menu right after selection deselectRow(at: selectedRowIndex) } hide() } } //MARK: - Auto dismiss extension DropDown { public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let view = super.hitTest(point, with: event) if dismissMode == .automatic && view === dismissableView { cancel() return nil } else { return view } } @objc fileprivate func dismissableViewTapped() { cancel() } } //MARK: - Keyboard events extension DropDown { /** Starts listening to keyboard events. Allows the drop down to display correctly when keyboard is showed. */ @objc public static func startListeningToKeyboard() { KeyboardListener.sharedInstance.startListeningToKeyboard() } fileprivate func startListeningToKeyboard() { KeyboardListener.sharedInstance.startListeningToKeyboard() NotificationCenter.default.addObserver( self, selector: #selector(keyboardUpdate), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(keyboardUpdate), name: UIResponder.keyboardWillHideNotification, object: nil) } fileprivate func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } @objc fileprivate func keyboardUpdate() { self.setNeedsUpdateConstraints() } } private extension DispatchQueue { static func executeOnMainThread(_ closure: @escaping Closure) { if Thread.isMainThread { closure() } else { main.async(execute: closure) } } }
28.868003
256
0.71868
f8e11610854b3b9e203715480155912f8badc504
406
// // ScannedPatternEntity.swift // Cidaas // // Created by ganesh on 23/07/18. // import Foundation public class ScannedFaceEntity : Codable { // properties public var usage_pass: String = "" public var statusId: String = "" public var client_id: String = "" public var deviceInfo: DeviceInfoModel = DeviceInfoModel() // Constructors public init() { } }
18.454545
62
0.635468
4acd379ba01732adf302a4980ed865645bde840e
2,005
// Generated from VisitorBasic.g4 by ANTLR 4.9.3 import Antlr4 open class VisitorBasicLexer: Lexer { internal static var _decisionToDFA: [DFALexer] = { var decisionToDFA = [DFALexer]() let length = VisitorBasicLexer._ATN.getNumberOfDecisions() for i in 0..<length { decisionToDFA.append(DFA(VisitorBasicLexer._ATN.getDecisionState(i)!, i)) } return decisionToDFA }() internal static let _sharedContextCache = PredictionContextCache() public static let A=1 public static let channelNames: [String] = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ] public static let modeNames: [String] = [ "DEFAULT_MODE" ] public static let ruleNames: [String] = [ "A" ] private static let _LITERAL_NAMES: [String?] = [ nil, "'A'" ] private static let _SYMBOLIC_NAMES: [String?] = [ nil, "A" ] public static let VOCABULARY = Vocabulary(_LITERAL_NAMES, _SYMBOLIC_NAMES) override open func getVocabulary() -> Vocabulary { return VisitorBasicLexer.VOCABULARY } public required init(_ input: CharStream) { RuntimeMetaData.checkVersion("4.9.3", RuntimeMetaData.VERSION) super.init(input) _interp = LexerATNSimulator(self, VisitorBasicLexer._ATN, VisitorBasicLexer._decisionToDFA, VisitorBasicLexer._sharedContextCache) } override open func getGrammarFileName() -> String { return "VisitorBasic.g4" } override open func getRuleNames() -> [String] { return VisitorBasicLexer.ruleNames } override open func getSerializedATN() -> String { return VisitorBasicLexer._serializedATN } override open func getChannelNames() -> [String] { return VisitorBasicLexer.channelNames } override open func getModeNames() -> [String] { return VisitorBasicLexer.modeNames } override open func getATN() -> ATN { return VisitorBasicLexer._ATN } public static let _serializedATN: String = VisitorBasicLexerATN().jsonString public static let _ATN: ATN = ATNDeserializer().deserializeFromJson(_serializedATN) }
24.753086
132
0.724688
29f620f6219dac453554018f5b60647df6841e01
2,636
import MessageUI @objc(WMFHelpViewController) class HelpViewController: SinglePageWebViewController { static let faqURLString = "https://m.mediawiki.org/wiki/Wikimedia_Apps/iOS_FAQ" static let emailAddress = "[email protected]" static let emailSubject = "Bug:" @objc init?(dataStore: MWKDataStore, theme: Theme) { guard let faqURL = URL(string: HelpViewController.faqURLString) else { return nil } super.init(url: faqURL, theme: theme) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(url: URL, theme: Theme) { fatalError("init(url:theme:) has not been implemented") } required init(url: URL, theme: Theme, doesUseSimpleNavigationBar: Bool = false) { fatalError("init(url:theme:doesUseSimpleNavigationBar:) has not been implemented") } lazy var sendEmailToolbarItem: UIBarButtonItem = { return UIBarButtonItem(title: WMFLocalizedString("button-report-a-bug", value: "Report a bug", comment: "Button text for reporting a bug"), style: .plain, target: self, action: #selector(sendEmail)) }() override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = nil setupToolbar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } private func setupToolbar() { enableToolbar() toolbar.items = [UIBarButtonItem.flexibleSpaceToolbar(), sendEmailToolbarItem, UIBarButtonItem.wmf_barButtonItem(ofFixedWidth: 8)] setToolbarHidden(false, animated: false) } @objc func sendEmail() { let address = HelpViewController.emailAddress let subject = HelpViewController.emailSubject let body = "\n\n\n\nVersion: \(WikipediaAppUtils.versionedUserAgent())" let mailto = "mailto:\(address)?subject=\(subject)&body=\(body)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) guard let encodedMailto = mailto, let mailtoURL = URL(string: encodedMailto), UIApplication.shared.canOpenURL(mailtoURL) else { WMFAlertManager.sharedInstance.showErrorAlertWithMessage(WMFLocalizedString("no-email-account-alert", value: "Please setup an email account on your device and try again.", comment: "Displayed to the user when they try to send a feedback email, but they have never set up an account on their device"), sticky: false, dismissPreviousAlerts: false) return } UIApplication.shared.open(mailtoURL) } }
41.84127
357
0.693475
792bfdc748fcb996395b1fbc886c6e902c44884f
3,624
// // Parser.swift // Swimi // // Created by Kainosuke OBATA on 2019/10/05. // Copyright © 2019 kai. All rights reserved. // import Foundation public class Parser { public func input(data: [UInt8]) { data.forEach(parseByte) } public init() { } private var parsing: Bool = false private var lastStatus: StatusType? private var lastStatusByte: UInt8? public let notifier: Notifier = Notifier() private var parsingData: [UInt8] = [] private func parseByte(_ byte: UInt8) { let statusOrNil = StatusType.fromByte(byte) if let status = statusOrNil, status.isSystemRealTimeMessage { // System Real Time Message is 1 byte and can interrupt any messages. // So we'll notify this Real Time Message immediately and keep current status. notifier.notify(messageData: [byte]) return } switch (parsing, lastStatus, statusOrNil) { case (true, .some(.systemExclusive), .some(.endOfExclusive)): // parsing exclusive and receive end of exclusive -> notify parsingData.append(byte) notifier.notify(messageData: parsingData) clearData() return case (_, .some(_), .some(.endOfExclusive)): // error case: // End Of Exclusive received but not parsing System Exclusive now. // We will just ignore this. clearData() return case (true, nil, _): // impossible condition fatalError() case (false, nil, nil): // Received unkown byte before receiving StatusByte. So we'll ignore this byte. return case (false, nil, .some(_)): // Received 1st status. So start parsing 1st message. gotMessageByte(status: byte, data: nil) case (false, .some(_), nil): // Maybe running status. So start parse with previous status. gotMessageByte(status: lastStatusByte!, data: byte) case (false, .some(_), .some(_)): // Received new status. So start parse with new status. gotMessageByte(status: byte, data: nil) case (true, .some(_), nil): // Received new data byte. gotMessageByte(status: nil, data: byte) case (true, .some(_), .some(_)): // Receiving new Status while parsing current Status. // This indicates the sequence is invalid. // Obviously this is MIDI protocol violation. But we'll clear current status // and continue to parse new status instead of crash. // Or, We can consider some handler to notify protocol violation detection... clearData() gotMessageByte(status: byte, data: nil) } } private func clearData() { parsingData = [] parsing = false } private func gotMessageByte(status: UInt8?, data: UInt8?) { parsing = true if let status = status { lastStatusByte = status lastStatus = StatusType.fromByte(status)! parsingData.append(status) } if let data = data { parsingData.append(data) } if case .fixed(let dataSize) = lastStatus!.dataByteSize { if (parsingData.count - 1) == dataSize { notifier.notify(messageData: parsingData) clearData() } } } }
32.070796
91
0.557671
f7b128867a222a320f30a081a6e6274f83dca609
1,371
import Foundation public final class FbSimCtlEventWithStringSubject: FbSimCtlEventCommonFields, Decodable, Hashable, CustomStringConvertible { public let type: FbSimCtlEventType public let name: FbSimCtlEventName public let timestamp: TimeInterval public let subject: String public init( type: FbSimCtlEventType, name: FbSimCtlEventName, timestamp: TimeInterval, subject: String ) { self.type = type self.name = name self.timestamp = timestamp self.subject = subject } private enum CodingKeys: String, CodingKey { case type = "event_type" case name = "event_name" case timestamp = "timestamp" case subject = "subject" } public func hash(into hasher: inout Hasher) { hasher.combine(type) hasher.combine(name) hasher.combine(timestamp) hasher.combine(subject) } public static func == (left: FbSimCtlEventWithStringSubject, right: FbSimCtlEventWithStringSubject) -> Bool { return left.type == right.type && left.name == right.name && left.timestamp == right.timestamp && left.subject == right.subject } public var description: String { return "\(FbSimCtlEventWithStringSubject.self) \(name) \(type) \(timestamp) \(subject)" } }
29.804348
124
0.642597
2933a0a4003990bbac2f5cb19fcd754012cb7621
1,167
// // CmTableViewManager.swift // Ruling Ruler // // Created by Frederick Pietschmann on 12.11.17. // Copyright © 2017-2018 Piknotech. All rights reserved. // import UIKit final class CmTableViewManager: NSObject, UITableViewDelegate, UITableViewDataSource { // MARK: - Properties static let shared = CmTableViewManager() // MARK: - Initializers private override init() { } // MARK: - Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return MainViewController.shared.cmCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cmCell = tableView.dequeueReusableCell(withIdentifier: "CmCell") { return cmCell } let cmCell = UnitCell(mode: .centimeter, viewMode: tableView.frame.origin.x == 0 ? .left : .right, reuseIdentifier: "CmCell") return cmCell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cmCell = cell as? UnitCell { cmCell.number = indexPath.row } } }
30.710526
133
0.677806
d9e4a7f3a4c697365891a63db93f6bb4b518eb92
2,629
// // WREvent.swift // Pods // // Created by wayfinder on 2017. 4. 29.. // // import UIKit import DateToolsSwift // GP: I convered `WREvent` to a protocol `WREventType` in Jan 2021, but left the original class for backwards compatibility. public protocol WREventType { var id: String { get } var startDate: Date { get } var endDate: Date { get } // Using these will override the title, color, etc. properties below var attributedTitle: NSAttributedString? { get } var attributedSubtitle: NSAttributedString? { get } // These can be overriden by the attributedTitle type properties above var title: String { get } var titleColor: UIColor? { get } var subtitle: String? { get } var subtitleColor: UIColor? { get } // Other appearance properties var wrapText: Bool { get } // If true, multi-line labels will be used for both the title & subtitle. var backgroundColor: UIColor? { get } var borderColor: UIColor? { get } var opacity: CGFloat? { get } var canDrag: Bool { get } var cornerRadius: CGFloat { get } } public extension WREventType { var attributedTitle: NSAttributedString? { nil } var attributedSubtitle: NSAttributedString? { nil } var title: String { "" } var titleColor: UIColor? { nil } var subtitle: String? { nil } var subtitleColor: UIColor? { nil } var wrapText: Bool { false } var backgroundColor: UIColor? { nil } var borderColor: UIColor? { nil } var opacity: CGFloat? { nil } var canDrag: Bool { false } var cornerRadius: CGFloat { 4 } } @available(*, deprecated, message: "WREvent has been deprecated in favour of WREventType.") open class WREvent: TimePeriod, WREventType { open var title: String = "" open var attributedTitle: NSAttributedString? = nil // Overrides title if present. open var attributedSubtitle: NSAttributedString? = nil open var eventId: String = "" open var titleColor: UIColor? open var backgroundColor: UIColor? open var borderColor: UIColor? open var opacity: CGFloat? open var canDrag: Bool = false open var isCancelled: Bool = false // Unused open var wrapText: Bool { true } // For backwards compatibility open var subtitle: String? open var subtitleColor: UIColor? open var id: String { eventId } open var startDate: Date { beginning! } // The old open var endDate: Date { end! } open class func make(date:Date, chunk: TimeChunk, title: String) -> WREvent { let event = WREvent(beginning: date, chunk: chunk) event.title = title return event } }
32.45679
125
0.672119
0ac6b61fbcb84157777df82dd7879ab395cfece3
585
// RUN: not %target-swift-frontend %s -parse // REQUIRES: asserts // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol a { enum S) -> { } class func d enum A = T) -> String { func a")() -> Any, () -> Void>(bytes: X<d typealias e : d = b: H.B) -> T : c, Any, A { class B == d..b["A class a { func b<T: () -> T, q:Any) { func g: NSObject { struct d.E == Swift.h: T) { typealias F = c: S<T where B : P> () { } } if true { } } init <A> { f: A { let a<S : A { } }
18.870968
87
0.589744
67d4600dbdc0873b5e91cb8e017ad1f4ea8f0437
503
import Foundation import Combine class WindowControllingCoordinator: AnyModule { private static var _cancellables = Set<AnyCancellable>() private static var _observer: WrappedGlobalCGEventObserver? = nil private static var _controller: WindowScalingController? = nil static func run(app: AppDelegate) { _controller = WindowScalingController(coordinator: app.managedObjectCoordinator) _observer = GlobalKeyboardEventObservers.registerWeak(_controller!) } }
33.533333
88
0.765408
f498c24e6e8b6c03509197d1d95ce57339b4b236
2,759
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI @available(iOS 14.0, *) struct SearchBar: View { // MARK: - Properties var placeholder: String @Binding var text: String // MARK: - Private @Environment(\.theme) private var theme: ThemeSwiftUI @State private var isEditing = false var onTextChanged: ((String) -> Void)? // MARK: - Public var body: some View { HStack { TextField(placeholder, text: $text) { isEditing in self.isEditing = isEditing } .padding(8) .padding(.horizontal, 25) .background(theme.colors.navigation) .cornerRadius(8) .padding(.leading) .padding(.trailing, isEditing ? 8 : 16) .overlay( HStack { Image(systemName: "magnifyingglass") .renderingMode(.template) .foregroundColor(theme.colors.quarterlyContent) .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) if isEditing && !text.isEmpty { Button(action: { self.text = "" }) { Image(systemName: "multiply.circle.fill") .renderingMode(.template) .foregroundColor(theme.colors.quarterlyContent) } } } .padding(.horizontal, 22) ) if isEditing { Button(action: { self.isEditing = false self.text = "" UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }) { Text(VectorL10n.cancel) .font(theme.fonts.body) } .foregroundColor(theme.colors.accent) .padding(.trailing) .transition(.move(edge: .trailing)) } } .animation(.default) } }
33.646341
126
0.516854
e0fe17442263d9303ab325ab35c854b83af18d55
2,298
// // SceneDelegate.swift // Prework_Calculator // // Created by user203102 on 8/30/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.358491
147
0.714099
56e6d5afc6fde2ff78bd118d9c517772b0a97408
7,215
// // TransferMoneyViewController.swift // SberbankFamilyCash // // Created by Николай Спиридонов on 16.11.2019. // Copyright © 2019 nnick. All rights reserved. // import UIKit class TransferMoneyViewController: UIViewController { var cardMoney: Double! { didSet { title = String(cardMoney) + " ₽" } } var cardImage: UIImage! var cardNumber: Int! var bankUser: BankUser! var tableView: UITableView! private var cellIndex: Int! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = String(cardMoney) + " ₽" let cardImageView = UIImageView() cardImageView.image = cardImage cardImageView.contentMode = .scaleAspectFit view.addSubview(cardImageView) cardImageView.translatesAutoresizingMaskIntoConstraints = false cardImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true cardImageView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 5).isActive = true cardImageView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, multiplier: 0.2).isActive = true cardImageView.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.1).isActive = true let cardNumberLabel = UILabel() view.addSubview(cardNumberLabel) cardNumberLabel.translatesAutoresizingMaskIntoConstraints = false cardNumberLabel.centerYAnchor.constraint(equalTo: cardImageView.centerYAnchor).isActive = true cardNumberLabel.leadingAnchor.constraint(equalTo: cardImageView.trailingAnchor).isActive = true cardNumberLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -5).isActive = true cardNumberLabel.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.1).isActive = true cardNumberLabel.numberOfLines = 1 cardNumberLabel.textAlignment = .center cardNumberLabel.font = UIFont.boldSystemFont(ofSize: 22) cardNumberLabel.textColor = .darkGray cardNumberLabel.text = "xxxx xxxx xxxx " + String(String(cardNumber).suffix(4)) let transactionLabel = UILabel() view.addSubview(transactionLabel) transactionLabel.translatesAutoresizingMaskIntoConstraints = false transactionLabel.topAnchor.constraint(equalTo: cardImageView.bottomAnchor, constant: 20).isActive = true transactionLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -5).isActive = true transactionLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 5).isActive = true transactionLabel.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, multiplier: 0.1).isActive = true transactionLabel.numberOfLines = 2 transactionLabel.textAlignment = .center transactionLabel.font = UIFont.boldSystemFont(ofSize: 22) transactionLabel.text = "Выберете семейную копилку для пополнения" tableView = UITableView() tableView.backgroundColor = .white view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: transactionLabel.bottomAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true tableView.dataSource = self tableView.delegate = self tableView.rowHeight = 120 tableView.separatorStyle = .none tableView.bounces = false tableView.showsVerticalScrollIndicator = false tableView.register(PiggyCell.self, forCellReuseIdentifier: PiggyCell.reuseID) } init(cardMoney: Double, cardImage: UIImage, cardNumber: Int, cellIndex: Int, bankUser: BankUser) { self.cardMoney = cardMoney self.cardImage = cardImage self.cardNumber = cardNumber self.cellIndex = cellIndex self.bankUser = bankUser super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.prefersLargeTitles = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.title = "" self.navigationController?.navigationBar.prefersLargeTitles = false } } extension TransferMoneyViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bankUser.purses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: PiggyCell.reuseID, for: indexPath) as! PiggyCell cell.prepareForDataSetting() let currentPig = bankUser.purses[indexPath.row] cell.name = currentPig.name cell.haveMoney = currentPig.haveMoney cell.needMoney = currentPig.needMoney cell.selectionStyle = .gray return cell } } extension TransferMoneyViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let cell = tableView.cellForRow(at: indexPath) as? PiggyCell else { return } let alert = UIAlertController(title: "Пополнение семейной копилки", message: cell.name, preferredStyle: .alert) alert.addTextField { (field) in field.placeholder = "Сумма для перевода" } alert.addAction(UIAlertAction(title: "Пополнить", style: .default, handler: { (_) in if let requestSumString = alert.textFields?.first?.text, let requestSum = Double(requestSumString) { if requestSum > self.cardMoney { return } else { self.bankUser.purses[indexPath.row].haveMoney += requestSum self.cardMoney -= requestSum self.bankUser.cards[self.cellIndex].balance -= requestSum self.bankUser.setCardsIntoUserDefaultsFromCurrentBank() self.bankUser.setPursesIntoUserDefaultsFromCurrentBank() self.dismiss(animated: true, completion: { tableView.reloadData() }) } } })) alert.addAction(UIAlertAction(title: "Отмена", style: .cancel, handler: nil)) present(alert, animated: true) } }
43.993902
130
0.691337
d7f11c17403709f054aa49cf1a304630ed6bc077
1,392
// // APIBuilder.swift // Siwa // // Created by Mahdi on 4/20/19. // Copyright © 2019 Mahdi. All rights reserved. // import Foundation public protocol APIBuilderProtocol { func setUser(user: User) -> APIBuilderProtocol func setURLSession(urlSession: URLSession) -> APIBuilderProtocol func setRequestDelay(delay: Delay) -> APIBuilderProtocol func build() throws -> APIHandler } public class APIBuilder: APIBuilderProtocol { private var _user: User? private var _delay: Delay? private var _urlSession: URLSession? public init() { } public func setUser(user: User) -> APIBuilderProtocol { _user = user return self } public func setURLSession(urlSession: URLSession) -> APIBuilderProtocol { _urlSession = urlSession return self } public func setRequestDelay(delay: Delay) -> APIBuilderProtocol { _delay = delay return self } public func build() throws -> APIHandler { guard let user = _user else { throw SiwaErrors.authenticationRequired } if _urlSession == nil { _urlSession = URLSession(configuration: .default) } if _delay == nil { _delay = .default } return try APIHandler(user: user, urlSession: _urlSession!, delay: _delay!) } }
24.421053
83
0.62069
918e36422336817b961e499788e905485fb4e052
1,310
// // PicPickerCollectionViewCell.swift // weibo // // Created by better on 2019/8/4. // Copyright © 2019 monstar. All rights reserved. // import UIKit class PicPickerCollectionViewCell: UICollectionViewCell { //MARK: - 定义属性 var image: UIImage? { didSet { if image != nil { addPhotoButton.isHidden = true deletePhotoButton.isHidden = false photoImageView.image = image }else { photoImageView.image = nil addPhotoButton.isHidden = false deletePhotoButton.isHidden = true } } } //MARK: - 控件属性 @IBOutlet weak var addPhotoButton: UIButton! @IBOutlet weak var deletePhotoButton: UIButton! @IBOutlet weak var photoImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() } //MARK: - 事件监听 @IBAction func addPicClick() { //创建通知 NotificationCenter.default.post(name: NSNotification.Name(rawValue: picPickerAddPhotoNote), object: nil) } @IBAction func deletePhotoClick(_ sender: Any) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: picPickerDeletePhotoNote), object: photoImageView.image) } }
26.2
132
0.608397
8ad96cc3a8596abe78ba8bae730b383c4d72c2b7
1,466
// // Copyright © 2018 Schnaub. All rights reserved. // import UIKit extension CGFloat { #if targetEnvironment(macCatalyst) static let initialScaleToExpandFrom: CGFloat = 1.0 #else static let initialScaleToExpandFrom: CGFloat = 0.6 #endif static let maxScaleForExpandingOffscreen: CGFloat = 1.25 static let targetZoomForDoubleTap: CGFloat = 3 static let minFlickDismissalVelocity: CGFloat = 800 static let highScrollVelocity: CGFloat = 1_600 } extension CGSize { static func * (size: CGSize, scale: CGFloat) -> CGSize { size.applying(CGAffineTransform(scaleX: scale, y: scale)) } } extension UIView { func usesAutoLayout(_ useAutoLayout: Bool) { translatesAutoresizingMaskIntoConstraints = !useAutoLayout } var portableSafeTopInset: NSLayoutYAxisAnchor { return safeAreaLayoutGuide.topAnchor } } extension UIColor { var isLight: Bool { var white: CGFloat = 0 getWhite(&white, alpha: nil) return white > 0.5 } } extension UICollectionView { func register<T: UICollectionViewCell>(_ cell: T.Type) { register(cell, forCellWithReuseIdentifier: String(describing: cell)) } func dequeue<T: UICollectionViewCell>(indexPath: IndexPath) -> T { let id = String(describing: T.self) return dequeue(id: id, indexPath: indexPath) } func dequeue<T: UICollectionViewCell>(id: String, indexPath: IndexPath) -> T { dequeueReusableCell(withReuseIdentifier: id, for: indexPath) as! T } }
24.032787
80
0.729195
d5fa00e38075692dbe43f3a0414e6560f6468519
236
// // EmptyView+Extensions.swift // Micro Charts // // Created by Stan Stadelman on 12/5/19. // Copyright © 2019 sstadelman. All rights reserved. // import SwiftUI extension EmptyView { static let any = AnyView(EmptyView()) }
16.857143
53
0.690678
67a12bfb4b40b860fbd28b37eedbaae8a9c81fa0
4,390
// // TLLabel.swift // 007-TextKit // // Created by lichuanjun on 2017/8/6. // Copyright © 2017年 lichuanjun. All rights reserved. // import UIKit /** 1. 使用 TextKit 接管 Label 的底层实现 - 绘制 textStorage 的文本内容 2. 使用正则表达式过滤 URL,设置 URL 的特殊显示 3. 交互 - UILabel 默认不能实现垂直顶部对齐,使用 TextKit 可以 - 提示: - 在 iOS 7.0 之前,需要实现类似的效果,需要使用 CoreText 使用起来异常的繁琐 - YYModel 的作者开发了一个框架 YYText,自己建立了一套渲染系统 */ class TLLabel: UILabel { // MARK: - 重写属性 override var text: String? { didSet { // 重新准备文本内容 prepareTextContent() } } // MARK: - 构造函数 override init(frame: CGRect) { super.init(frame: frame) prepareTextSystem() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareTextSystem() } // MARK: - 交互 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // 1. 获取用户点击的位置 guard let location = touches.first?.location(in: self) else { return } // 2. 获取当前点中字符的索引 let idx = layoutManager.glyphIndex(for: location, in: textContainer) print("点我了 \(idx)") // 3. 判断 idx 是否在 urls 的 ranges 范围内,如果在,就高亮 for r in urlRanges ?? [] { // NSRange 跳入文件可见此方法 if NSLocationInRange(idx, r) { print("需要高亮") textStorage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: r) // 如果需要重绘,需要调用 setNeedsDisplay 函数,但是不是 drawRect setNeedsDisplay() } else { print("没戳着") } } } /// 绘制文本 /** - 在 iOS 中绘制工作时类似于`油画`似的,后绘制的内容,会把之前绘制的内容覆盖 - 尽量避免使用带透明度的颜色,会严重影响性能 */ override func drawText(in rect: CGRect) { let range = NSRange(location: 0, length: textStorage.length) // 绘制背景 layoutManager.drawBackground(forGlyphRange: range, at: CGPoint()) // 绘制 Glyphs 字形 layoutManager.drawGlyphs(forGlyphRange: range, at: CGPoint()) } override func layoutSubviews() { super.layoutSubviews() // 指定绘制文本的区域 textContainer.size = bounds.size } // MARK: - TextKit 的核心对象 /// 属性文本存储 fileprivate lazy var textStorage = NSTextStorage() /// 负责文本`字形`布局 fileprivate lazy var layoutManager = NSLayoutManager() /// 设定文本绘制的范围 fileprivate lazy var textContainer = NSTextContainer() } // MARK: - 设置 TextKit 核心对象 private extension TLLabel { // 准备文本系统 func prepareTextSystem() { // 0. 开启用户交互 isUserInteractionEnabled = true // 1. 准备文本内容 prepareTextContent() // 2. 设置对象的关系 textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) } /// 准备文本内容 - 使用 textStorage 结果 label 的内容 func prepareTextContent() { if let attributedText = attributedText { textStorage.setAttributedString(attributedText) } else if let text = text { textStorage.setAttributedString(NSAttributedString(string: text)) } else { textStorage.setAttributedString(NSAttributedString(string: "")) } // 遍历范围数组,设置url的文字的属性 for r in urlRanges ?? [] { textStorage.addAttributes( [ NSForegroundColorAttributeName:UIColor.red, NSBackgroundColorAttributeName: UIColor.init(white: 0.9, alpha: 1.0) ], range: r) } } } // MARK: - 正则表达式函数 private extension TLLabel { // 返回 textStorage 中的 URL range 数组 var urlRanges: [NSRange]? { // 1. 正则表达式 let pattern = "[a-zA-Z]*://[a-zA-Z0-9/\\.]*" guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else { return nil } // 2. 多重匹配 let matches = regx.matches(in: textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length)) // 3. 遍历数组,生成 range 的数组 var ranges = [NSRange]() for m in matches { ranges.append(m.rangeAt(0)) } return ranges } }
25.976331
128
0.549203
e575c7f1f6d906d0a033ac2b6d398e9d530a05b0
899
//: A UIKit based Playground for presenting user interface import SwiftUI import PlaygroundSupport struct HelloWorldView: View { var body: some View { HStack(alignment: .center, spacing: 0, content: { Text("Hello World").font(.title) Spacer() Text("Hola mundo").font(.title) }).padding([.leading, .trailing], 20) } } struct ContentView : View { var namesContainer: some View { HStack { Text("Peter").font(.body) Spacer() Text("Pedro").font(.body) }.padding([.leading, .trailing], 20) } var body: some View { VStack { HelloWorldView() Divider() namesContainer } } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())
24.297297
78
0.572859
79481463d723356d85d22cbd5591dd93e01157a1
4,184
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialMotion class MaterialExpansionExampleViewController: ExampleViewController { var runtime: MotionRuntime! override func viewDidLoad() { super.viewDidLoad() let square = center(createExampleSquareView(), within: view) square.clipsToBounds = true view.addSubview(square) let maskView = UIView(frame: view.bounds) maskView.isUserInteractionEnabled = false let mask = CALayer() mask.backgroundColor = UIColor.black.cgColor mask.frame = square.frame maskView.layer.mask = mask view.addSubview(maskView) let flood = UIView(frame: square.bounds.insetBy(dx: -square.bounds.width, dy: -square.bounds.height)) flood.layer.cornerRadius = flood.bounds.width / 2 flood.backgroundColor = .white maskView.addSubview(flood) runtime = MotionRuntime(containerView: view) let direction = createProperty(withInitialValue: TransitionDirection.backward) let tap = runtime.get(UITapGestureRecognizer()) let widthExpansion = TransitionTween(duration: 0.375, forwardValues: [square.bounds.width, square.bounds.width * 2], direction: direction, forwardKeyPositions: [0, 0.8], system: coreAnimation) let heightExpansion = TransitionTween(duration: 0.375, forwardValues: [square.bounds.height, square.bounds.height * 2], direction: direction, forwardKeyPositions: [0.2, 1.0], system: coreAnimation) let floodExpansion = Tween<CGFloat>(duration: 0.375, values: [0, 1]) floodExpansion.timingFunctions.value = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)] let fadeOut = Tween<CGFloat>(duration: 0.375, values: [0.75, 0]) fadeOut.offsets.value = [0.2, 1] runtime.add(SetPositionOnTap(.withExistingRecognizer(tap.gestureRecognizer)), to: runtime.get(flood.layer).position) runtime.add(floodExpansion, to: runtime.get(flood.layer).scale) runtime.add(fadeOut, to: runtime.get(flood.layer).opacity) for interaction in [floodExpansion, fadeOut] { runtime.start(interaction, whenActive: tap) } runtime.connect(tap.whenRecognitionState(is: .recognized).rewriteTo(direction).inverted(), to: direction) // Interactions are enabled by default, but in this case we don't want our transition to start // until the first tap. Without this setup the runtime would immediately perform a backward // transition. let startTransition = createProperty(withInitialValue: false) for interaction in [widthExpansion, heightExpansion] { runtime.connect(startTransition, to: interaction.enabled) } runtime.connect(tap.whenRecognitionState(is: .recognized).rewriteTo(true), to: startTransition) runtime.add(widthExpansion, to: runtime.get(square.layer).width) runtime.add(heightExpansion, to: runtime.get(square.layer).height) // Ensure that our mask always tracks the square. runtime.connect(runtime.get(square.layer).width, to: runtime.get(mask).width) runtime.connect(runtime.get(square.layer).height, to: runtime.get(mask).height) } override func exampleInformation() -> ExampleInfo { return .init(title: type(of: self).catalogBreadcrumbs().last!, instructions: "Tap anywhere to create an ink ripple.") } }
42.262626
109
0.684034
d9a5959ea83edcbb63cc523b307fe65e74c3a878
233
// // CardValidationState.swift // TapCardValidator // // Copyright © 2018 Tap Payments. All rights reserved. // /// Card Validation State. public enum CardValidationState { case invalid case incomplete case valid }
15.533333
55
0.699571