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
5b995910eb5a90a3cbb690ce3587e82f91066c00
511
// // ViewController.swift // instagram // // Created by Regie Daquioag on 2/21/18. // Copyright © 2018 Regie Daquioag. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.653846
80
0.671233
f840b18c379ea3c5157d5f92a2cf6567b62df889
1,868
import Basic import Foundation import TuistCore import TuistGenerator protocol ManifestTargetGenerating { func generateManifestTarget(for project: String, at path: AbsolutePath) throws -> Target } class ManifestTargetGenerator: ManifestTargetGenerating { private let manifestLoader: GraphManifestLoading private let resourceLocator: ResourceLocating init(manifestLoader: GraphManifestLoading, resourceLocator: ResourceLocating) { self.manifestLoader = manifestLoader self.resourceLocator = resourceLocator } func generateManifestTarget(for project: String, at path: AbsolutePath) throws -> Target { let settings = Settings(base: try manifestTargetBuildSettings(), configurations: Settings.default.configurations) let manifest = try manifestLoader.manifestPath(at: path, manifest: .project) return Target(name: "\(project)-Manifest", platform: .macOS, product: .staticFramework, bundleId: "io.tuist.manifests.${PRODUCT_NAME:rfc1034identifier}", settings: settings, sources: [manifest], filesGroup: .group(name: "Manifest")) } func manifestTargetBuildSettings() throws -> [String: String] { let frameworkParentDirectory = try resourceLocator.projectDescription().parentDirectory var buildSettings = [String: String]() buildSettings["FRAMEWORK_SEARCH_PATHS"] = frameworkParentDirectory.pathString buildSettings["LIBRARY_SEARCH_PATHS"] = frameworkParentDirectory.pathString buildSettings["SWIFT_INCLUDE_PATHS"] = frameworkParentDirectory.pathString buildSettings["SWIFT_VERSION"] = Constants.swiftVersion return buildSettings } }
42.454545
95
0.678266
03fe48dc739c7df9b913e77332ffdd6b62ba0cf7
476
// RUN: %target-typecheck-verify-swift // SR-1062: // Coercion in single expression closure with invalid signature caused segfault protocol SR_1062_EmptyProtocol {} struct SR_1062_EmptyStruct {} struct SR_1062_GenericStruct<T: SR_1062_EmptyProtocol> {} let _ = { (_: SR_1062_GenericStruct<SR_1062_EmptyStruct>) -> Void in // expected-error{{type 'SR_1062_EmptyStruct' does not conform to protocol 'SR_1062_EmptyProtocol'}} SR_1062_EmptyStruct() as SR_1062_EmptyStruct }
36.615385
169
0.792017
f879c5f59a269ebf84ad53e61afeab196f09bd02
135
import Foundation import vsip //public var unaryVsipOperation: Dictionary<String, (_: OpaquePointer, _:OpaquePointer?) -> Void)> = [:]
33.75
104
0.748148
eb89d02e5377ae86f73680b4932318bf5ac018a0
1,767
// // DownloadTableAudioPlayerDelegImpl.swift // MusicPlayer // // Created by Daniyar Yeralin on 5/14/17. // Copyright © 2017 Daniyar Yeralin. All rights reserved. // import Foundation import UIKit import SwiftOverlays // MARK: Download table audio player delegate implementation extension DownloadTableViewController: AudioPlayerDelegate { internal func initAudioPlayerDelegateImpl() { // TODO: Refactor, rethink delegation assignment in player impls AudioPlayer.instance.delegate = self } func getSongsArray(song: SongEntity) -> [SongEntity] { return searchSongs } internal func propagateError(title: String, error: String) { let alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) } internal func cellState(state: PlayerState, song: SongEntity) { if let cell = getCell(withSong: song) { if state == .prepare { cell.prepareSongCellState() } else if state == .play { cell.playSongCellState() } else if state == .resume { cell.resumeSongCellState() } else if state == .pause { cell.pauseSongCellState() } else if state == .stop { cell.stopSongCellState() } } } func getSongArray() -> [SongEntity] { return searchSongs } }
32.127273
84
0.57442
f4e00bd6a8bddb542348ca43ebabfda98651a26e
6,747
/* This SDK is licensed under the MIT license (MIT) Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France) 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. */ // // OrderTests.swift // import UIKit import XCTest class OrderTests: XCTestCase { var order: ATOrder! var orders: ATOrders! override func setUp() { super.setUp() order = ATOrder(tracker: ATTracker()) orders = ATOrders(tracker: order.tracker) } func testSetOrder() { order.orderId = "cmd1" order.amount.setWithAmountTaxFree(50, amountTaxIncluded: 60, taxAmount: 10) order.discount.setWithDiscountTaxFree(5, discountTaxIncluded: 10, promotionalCode: "1234") order.delivery.setWithShippingFeesTaxFree(2, shippingFeesTaxIncluded: 6, deliveryMethod: "1") order.isConfirmationRequired = true order.isNewCustomer = true order.paymentMethod = 1 order.status = 1 order.turnover = 10.123 order.customVariables.addWithId(1, value: "test") order.customVariables.addWithId(2, value: "test2") order.setEvent() XCTAssert(order.tracker.buffer.volatileParameters.count == 17, "Le nombre de paramètres volatiles doit être égal à 17") XCTAssert(order.tracker.buffer.volatileParameters[0].key == "cmd", "Le premier paramètre doit être cmd") XCTAssert((order.tracker.buffer.volatileParameters[0] as! ATParam).value() == "cmd1", "La valeur du premier paramètre doit être cmd1") XCTAssert(order.tracker.buffer.volatileParameters[1].key == "roimt", "Le second paramètre doit être roimt") XCTAssert((order.tracker.buffer.volatileParameters[1] as! ATParam).value() == "10.123", "La valeur du second paramètre doit être 10") XCTAssert(order.tracker.buffer.volatileParameters[2].key == "st", "Le 3ème paramètre doit être st") XCTAssert((order.tracker.buffer.volatileParameters[2] as! ATParam).value() == "1", "La valeur du 3ème paramètre doit être 1") XCTAssert(order.tracker.buffer.volatileParameters[3].key == "newcus", "Le 4ème paramètre doit être newcus") XCTAssert((order.tracker.buffer.volatileParameters[3] as! ATParam).value() == "1", "La valeur du 4ème paramètre doit être 1") XCTAssert(order.tracker.buffer.volatileParameters[4].key == "dscht", "Le 5ème paramètre doit être dscht") XCTAssert((order.tracker.buffer.volatileParameters[4] as! ATParam).value() == "5", "La valeur du 5ème paramètre doit être 5") XCTAssert(order.tracker.buffer.volatileParameters[5].key == "dsc", "Le 6ème paramètre doit être dsc") XCTAssert((order.tracker.buffer.volatileParameters[5] as! ATParam).value() == "10", "La valeur du 6ème paramètre doit être 10") XCTAssert(order.tracker.buffer.volatileParameters[6].key == "pcd", "Le 7ème paramètre doit être pcd") XCTAssert((order.tracker.buffer.volatileParameters[6] as! ATParam).value() == "1234", "La valeur du 7ème paramètre doit être 1234") XCTAssert(order.tracker.buffer.volatileParameters[7].key == "mtht", "Le 8ème paramètre doit être mtht") XCTAssert((order.tracker.buffer.volatileParameters[7] as! ATParam).value() == "50", "La valeur du 8ème paramètre doit être 50") XCTAssert(order.tracker.buffer.volatileParameters[8].key == "mtttc", "Le 9ème paramètre doit être mtttc") XCTAssert((order.tracker.buffer.volatileParameters[8] as! ATParam).value() == "60", "La valeur du 9ème paramètre doit être 60") XCTAssert(order.tracker.buffer.volatileParameters[9].key == "tax", "Le 10ème paramètre doit être tax") XCTAssert((order.tracker.buffer.volatileParameters[9] as! ATParam).value() == "10", "La valeur du 10ème paramètre doit être 10") XCTAssert(order.tracker.buffer.volatileParameters[10].key == "fpht", "Le 11ème paramètre doit être fpht") XCTAssert((order.tracker.buffer.volatileParameters[10] as! ATParam).value() == "2", "La valeur du 11ème paramètre doit être 2") XCTAssert(order.tracker.buffer.volatileParameters[11].key == "fp", "Le 12ème paramètre doit être fp") XCTAssert((order.tracker.buffer.volatileParameters[11] as! ATParam).value() == "6", "La valeur du 12ème paramètre doit être 6") XCTAssert(order.tracker.buffer.volatileParameters[12].key == "dl", "Le 13ème paramètre doit être dl") XCTAssert((order.tracker.buffer.volatileParameters[12] as! ATParam).value() == "1", "La valeur du 13ème paramètre doit être 1") XCTAssert(order.tracker.buffer.volatileParameters[13].key == "O1", "Le 14ème paramètre doit être O1") XCTAssert((order.tracker.buffer.volatileParameters[13] as! ATParam).value() == "test", "La valeur du 14ème paramètre doit être test") XCTAssert(order.tracker.buffer.volatileParameters[14].key == "O2", "Le 15ème paramètre doit être O2") XCTAssert((order.tracker.buffer.volatileParameters[14] as! ATParam).value() == "test2", "La valeur du 15ème paramètre doit être test2") XCTAssert(order.tracker.buffer.volatileParameters[15].key == "mp", "Le 16ème paramètre doit être mp") XCTAssert((order.tracker.buffer.volatileParameters[15] as! ATParam).value() == "1", "La valeur du 16ème paramètre doit être 1") XCTAssert(order.tracker.buffer.volatileParameters[16].key == "tp", "Le 17ème paramètre doit être tp") XCTAssert((order.tracker.buffer.volatileParameters[16] as! ATParam).value() == "pre1", "La valeur du 17ème paramètre doit être pre1") } }
56.697479
143
0.696606
61f08cae3cb43aa8e0479061f2e12f564a124a28
1,616
// // SettingUIView.swift // Card Theatre // // Created by 陆子旭 on 2019/7/12. // Copyright © 2019 陆子旭. All rights reserved. // import SwiftUI struct SettingUIView : View { @State var receive = false @State var number = 1 @State var selection = 1 @State var date = Date() @State var email = "" @State var submit = false var body: some View { NavigationView { Form { Toggle(isOn: $receive) { Text("Recieve Notifications") } Stepper(value: $number, in: 1...10) { Text("\(number) Notification\(number > 1 ? "s" : "") per week") } Picker(selection: $selection, label: Text("Favourite course")) { Text("SwiftUI").tag(1) Text("React").tag(2) } DatePicker($date) { Text("Date") } Section(header: Text("Email")) { TextField("Your email: ", text: $email) .textFieldStyle(.roundedBorder) } Button(action: { self.submit.toggle() }) { Text("Submit") } .presentation($submit, alert: { Alert(title: Text("Thanks"), message: Text("Email: \(email)")) }) } .navigationBarTitle("Settings") } } } #if DEBUG struct SettingUIView_Previews : PreviewProvider { static var previews: some View { SettingUIView() } } #endif
27.862069
83
0.46349
2faf7dc36db29561126a2d577354d83c3faf1fa2
4,195
// // MovieDetailView.swift // 190727MegaboxMovieDetailExample // // Created by 차수연 on 27/07/2019. // Copyright © 2019 차수연. All rights reserved. // import UIKit class MovieDetailView: UIView { let view = MovieDetailSectionView() var isStatus = true let tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }() let headerView: MovieDetailHeaderView = { let view = MovieDetailHeaderView() view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 350) return view }() override init(frame: CGRect) { super.init(frame: frame) setupTableView() } func setupTableView() { tableView.separatorStyle = .none tableView.backgroundColor = #colorLiteral(red: 0.9563174175, green: 0.9563174175, blue: 0.9563174175, alpha: 1) tableView.tableHeaderView = headerView // tableView.separatorInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30) tableView.dataSource = self tableView.delegate = self tableView.register(TotalAudienceCell.self, forCellReuseIdentifier: TotalAudienceCell.identifier) addSubview(tableView) tableView.topAnchor.constraint(equalTo: topAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension MovieDetailView: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch isStatus { case true: return 9 case false: return 3 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch isStatus { case true: switch indexPath.row { case 0: let cell = TotalAudienceCell() cell.selectionStyle = .none return cell case 1: let cell = SummaryCell() cell.selectionStyle = .none // cell.addButtonAction = { // cell.addButton.isSelected.toggle() // // if cell.addButton.isSelected { // self.tableView.beginUpdates() // // 코드 // // self.tableView.endUpdates() // // } else { // self.tableView.beginUpdates() // // self.tableView.endUpdates() // } // } return cell case 2: let cell = DirectorActorCell() cell.selectionStyle = .none return cell case 3: let cell = AdCell() cell.selectionStyle = .none return cell case 4: let cell = StillCutCell() cell.selectionStyle = .none return cell case 5: let cell = PreViewTitleCell() cell.selectionStyle = .none return cell case 6: let cell = PreViewCell() cell.selectionStyle = .none return cell default: let cell = PreViewCell() cell.selectionStyle = .none return cell } case false: switch indexPath.row { case 0: let cell = MoviePostCell() cell.selectionStyle = .none return cell case 1: let cell = CommentTitleCell() cell.selectionStyle = .none return cell case 2: let cell = CommentCell() cell.selectionStyle = .none return cell default: return UITableViewCell() } } } } extension MovieDetailView: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { view.delegate = self return view } } extension MovieDetailView: MovieDetailSectionViewDelegate { func didTap(isStatus: Bool) { self.isStatus = isStatus tableView.reloadData() } }
24.389535
115
0.615971
50aeabaf632798417e2cfb4b363a2cae6eef8db5
5,491
import CoreData import Foundation import MyTBAKit import TBAKit import UIKit protocol MatchQueryOptionsDelegate: AnyObject { func updateQuery(query: MatchQueryOptions) } // Backing enums to setup our table view data source private enum QuerySections: String, CaseIterable { case sort = "Sort" case filter = "Filter" } private enum SortRows: CaseIterable { case reverse } private enum FilterRows: CaseIterable { case favorites } private protocol QueryableOptions { static func defaultQuery() -> Self var isDefault: Bool { get } } // Backing structs to power our data struct MatchQueryOptions: QueryableOptions { var sort: MatchSortOptions var filter: MatchFilterOptions static func defaultQuery() -> MatchQueryOptions { return MatchQueryOptions(sort: MatchQueryOptions.MatchSortOptions.defaultQuery(), filter: MatchQueryOptions.MatchFilterOptions.defaultQuery()) } struct MatchSortOptions: QueryableOptions { var reverse: Bool static func defaultQuery() -> MatchSortOptions { return MatchSortOptions(reverse: false) } var isDefault: Bool { return reverse == false } } struct MatchFilterOptions: QueryableOptions { var favorites: Bool static func defaultQuery() -> MatchFilterOptions { return MatchFilterOptions(favorites: false) } var isDefault: Bool { return favorites == false } } var isDefault: Bool { return sort.isDefault && filter.isDefault } } class MatchQueryOptionsViewController: TBATableViewController { private var myTBA: MyTBA private var query: MatchQueryOptions weak var delegate: MatchQueryOptionsDelegate? init(query: MatchQueryOptions, myTBA: MyTBA, persistentContainer: NSPersistentContainer, tbaKit: TBAKit, userDefaults: UserDefaults) { self.query = query self.myTBA = myTBA super.init(style: .plain, persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults) title = "Match Sort/Filter" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissMatchQuery)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Table View Data Source override func numberOfSections(in tableView: UITableView) -> Int { // If myTBA isn't enabled, disable filtering for myTBA Favorites var sections = QuerySections.allCases.count if !myTBA.isAuthenticated { sections = sections - 1 } return sections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let querySection = querySection(index: section) else { fatalError("Unsupported query section") } switch querySection { case .sort: return SortRows.allCases.count case .filter: return FilterRows.allCases.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let querySection = querySection(index: indexPath.section) else { fatalError("Unsupported query section") } let cell: SwitchTableViewCell = { switch querySection { case .sort: let switchCell = SwitchTableViewCell(switchToggled: { [weak self] (_ sender: UISwitch) in guard let self = self else { return } self.query.sort.reverse = sender.isOn self.delegate?.updateQuery(query: self.query) }) switchCell.textLabel?.text = "Reverse" switchCell.detailTextLabel?.text = "Show matches in ascending order" switchCell.switchView.isOn = self.query.sort.reverse return switchCell case .filter: let switchCell = SwitchTableViewCell(switchToggled: { [weak self] (_ sender: UISwitch) in guard let self = self else { return } self.query.filter.favorites = sender.isOn self.delegate?.updateQuery(query: self.query) }) switchCell.textLabel?.text = "Favorites" switchCell.detailTextLabel?.text = "Show only matches with myTBA favorite teams playing" switchCell.detailTextLabel?.numberOfLines = 0 switchCell.switchView.isOn = self.query.filter.favorites return switchCell } }() cell.detailTextLabel?.numberOfLines = 0 cell.selectionStyle = .none return cell } // MARK: - Table View Delegate override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard let querySection = querySection(index: section) else { fatalError("Unsupported query section") } return querySection.rawValue } // MAKR: - Private Functions private func querySection(index: Int) -> QuerySections? { let sections = QuerySections.allCases return index < sections.count ? sections[index] : nil } @objc private func dismissMatchQuery() { navigationController?.dismiss(animated: true, completion: nil) } }
32.3
150
0.64633
38dee7613c48a6b3448f709868fe03aa2dcb374c
470
// // MockMainViewModel.swift // awesome-train-plannerTests // // Created by Vladimir Amiorkov on 4.05.20. // Copyright © 2020 Vladimir Amiorkov. All rights reserved. // import Foundation @testable import Awesome_train_planner class MockMainViewModel: MainViewModel { override init() { super.init() self.status = .loading self.origin = "A" self.destination = "B" self.directions = [] self.stations = [] } }
20.434783
60
0.640426
76aa9f60af69a5af8c3a9d23098baebc62949169
528
// // Copyright © 2020 Essential Developer. All rights reserved. // import XCTest import EssentialFeed class ImageCommentsEndpointTests: XCTestCase { func test_imageComments_endpointURL() { let baseURL = URL(string: "http://base-url.com")! let image = FeedImage(id: UUID(), description: nil, location: nil, url: anyURL()) let received = ImageCommentsEndpoint.get(image).url(baseURL: baseURL) let expected = URL(string: "http://base-url.com/v1/image/\(image.id)/comments")! XCTAssertEqual(received, expected) } }
27.789474
83
0.732955
e0f4d14744f0fda4cac2fe65648912f0181d663e
1,413
// // AppDelegate.swift // // Created on 6/19/20. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) 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) } @available(iOS 13.0, *) func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.184211
179
0.738146
e964454aedce55ebc962b441d1a01ac1c677a2e1
1,913
// // NetworkRequest.swift // Gallery // // Created by Srijan on 31/07/19. // Copyright © 2019 Srijan. All rights reserved. // import UIKit class NetworkRequest: NSObject { class func performHTTPRequest(urlString: String, method: String, responseResult : @escaping(_ responseDictionary: NSDictionary, _ status : Bool) -> ()) { do { //create the url with NSURL let url = NSURL(string: urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) //create the session object let session = URLSession.shared //now create the NSMutableRequest object using the url object let request = NSMutableURLRequest(url: url! as URL) request.httpMethod = method //set http method as POST //HTTP Headers request.addValue("application/json", forHTTPHeaderField: "Content-Type") //create dataTask using the session object to send data to the server let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in guard error == nil else { return } guard let data = data else { return } do { //create json object from data if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary { responseResult(json , true) } } catch let error { print(error.localizedDescription) responseResult([:],false) } }) task.resume() // return task } } }
34.781818
157
0.528489
2f0db95640fb3544af18d5d1c9b862ab6ad07b3e
277
// // HeaderCellViewModel.swift // Example // // Created by Russell Warwick on 19/07/2021. // import Foundation struct HeaderCellViewModel { var headlineText: String { return "HI, RUSSELL" } var initialsText: String { return "RW" } }
13.85
45
0.613718
d79674563ac68503da94aa352c86b5ce016bd52d
2,246
// // Collection.swift // Stockly // // Created by Victor on 6/13/19. // Copyright © 2019 com.Victor. All rights reserved. // import Foundation struct Stock: Codable { let symbol: String let companyName: String let latestPrice: Double? let open: Double? let close: Double? let high: Double? } struct StockCompany: Codable { let symbol: String let companyName: String let exchange: String let industry: String let description: String let CEO: String let employees: Int } struct Sector: Equatable { var name: String var isChosen: Bool init(name: String) { self.name = name self.isChosen = false } } struct TechRoot: Decodable { let AAPL: Batch let TSLA: Batch let FB: Batch let AMZN: Batch let BABA: Batch } struct HealthRoot: Decodable { let CELG: Batch let TEVA: Batch let ALXN: Batch let ALGN: Batch let ANTM: Batch } struct IndustrialRoot: Decodable { let HEI: Batch let DHR: Batch let TDG: Batch let ZBRA: Batch let SWK: Batch } struct Batch: Decodable { let quote: Quote let news: [News] let chart: [Chart] } struct Quote : Decodable { let symbol: String let companyName: String let latestPrice: Double? let change: Double? let changePercent: Double? let previousClose: Double? let open: Double? let iexBidPrice: Double? let iexAskPrice: Double? let high: Double? let low: Double? let close: Double? let week52Low: Double? let week52High: Double? let latestVolume: Double? let avgTotalVolume: Double? let marketCap: Double? let peRatio: Double? } struct News: Decodable { let datetime: Int? let headline: String? let source: String? let url: String? let summary: String? let related: String? } struct Chart: Decodable { let date: String? let open: Double? let high: Double? let low: Double? let close: Double? let volume: Double? let unadjustedVolume: Double? let change: Double? let changePercent: Double? let vwap: Double? let label: String? let changeOverTime: Double? } struct Logo: Decodable { let url: String }
18.561983
53
0.643811
56dd68a5cc330be8b0bab3b1f9cbe9be778234a0
673
import XCTest @testable import Notes class NotesTests71: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func NotesUnitTest() { XCTAssertEqual("/v2/top-picks/rate", "/v2/top-picks/rate") XCTAssertEqual("super", "super") XCTAssertEqual("123", "123") XCTAssertEqual("1", "1") if false { XCTAssertEqual("-420", "-420") } else { XCTAssertEqual("-480", "-480") } XCTAssertEqual("xxx", "xxx") XCTAssertEqual("xxx", "xxx") XCTAssertNotNil("xxx") } }
24.925926
67
0.514116
4be865f5cff6cc73d165bbdce9436c85942fc56f
390
// // HomeDataStore.swift // QiitaChecker // // Created by k_muta on 2020/08/03. // import RealmSwift protocol HomeDataStore { func loadSavedTags() -> Results<SavedTag> } struct HomeDataStoreImpl: HomeDataStore { func loadSavedTags() -> Results<SavedTag> { let realm = try! Realm() let savedTags = realm.objects(SavedTag.self) return savedTags } }
18.571429
52
0.664103
e081c7c90e2ecc255b32350659a3102358e6587b
3,410
// // HistoryDetailTableViewCell.swift // EmptyLine // // Created by Jose Alarcon Chacon on 4/15/19. // Copyright © 2019 Pursuit. All rights reserved. // import UIKit class HistoryDetailTableViewCell: UITableViewCell { lazy var historyshoppingListImage: UIImageView = { let image = UIImageView() image.image = UIImage(named: "placeholder") image.layer.cornerRadius = image.frame.width/2 image.clipsToBounds = true return image }() lazy var historyLabelDetail: UILabel = { let shoppingLabel = UILabel() shoppingLabel.textColor = .white shoppingLabel.font = UIFont.systemFont(ofSize: 15) shoppingLabel.backgroundColor = .white return shoppingLabel }() lazy var historypriceLabel: UILabel = { let price = UILabel() price.textColor = .black price.font = UIFont.systemFont(ofSize: 15) price.backgroundColor = .white return price }() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() setUpViewConstraints() } private func commonInit() { setUpViewConstraints() } func setUpViewConstraints() { addSubview(historyshoppingListImage) addSubview(historyLabelDetail) addSubview(historypriceLabel) shoppingListImageConstraints() shoppingListLabelConstraints() priceLabelConstraints() } func shoppingListImageConstraints() { historyshoppingListImage.translatesAutoresizingMaskIntoConstraints = false historyshoppingListImage.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true historyshoppingListImage.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true historyshoppingListImage.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -300).isActive = true historyshoppingListImage.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -10).isActive = true historyshoppingListImage.widthAnchor.constraint(equalToConstant: 50).isActive = true historyshoppingListImage.heightAnchor.constraint(equalToConstant: 50).isActive = true } func shoppingListLabelConstraints() { historyLabelDetail.translatesAutoresizingMaskIntoConstraints = false historyLabelDetail.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true historyLabelDetail.leadingAnchor.constraint(equalTo: historyshoppingListImage.trailingAnchor, constant: 20).isActive = true historyLabelDetail.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -11).isActive = true } func priceLabelConstraints() { historypriceLabel.translatesAutoresizingMaskIntoConstraints = false historypriceLabel.topAnchor.constraint(equalTo: historyLabelDetail.bottomAnchor, constant: 5).isActive = true historypriceLabel.leadingAnchor.constraint(equalTo: historyshoppingListImage.trailingAnchor, constant: 20).isActive = true historypriceLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -11).isActive = true } }
41.084337
131
0.721701
5d249e3e716ccfb06a7dc5e1432f42f055987671
437
// // EI.swift // ostrichframework // // Created by Ryan Conway on 4/5/16. // Copyright © 2016 Ryan Conway. All rights reserved. // import Foundation struct EI: Z80Instruction, LR35902Instruction { let cycleCount: Int = 0 func runOn(_ cpu: Z80) { cpu.instructionContext.lastInstructionWasEI = true } func runOn(_ cpu: LR35902) { cpu.instructionContext.lastInstructionWasEI = true } }
19
58
0.656751
117c16bd077ea2069c14e49888d04438b21ffcc8
2,958
// // ContentView.swift // MRTScheduleJakarta // // Created by Alfian Losari on 11/24/19. // Copyright © 2019 Alfian Losari. All rights reserved. // import SwiftUI struct ContentView: View { let mrtSystem = MRTSystem() @ObservedObject var locationManager = LocationManagerViewModel() var body: some View { NavigationView { VStack { if locationManager.nearestStation != nil { NavigationLink(destination: StationDetailView(station: locationManager.nearestStation!)) { VStack(alignment: .leading, spacing: 8) { HStack { HStack { Image(systemName: "location.fill") Text("Nearest Station") .font(.subheadline) } Spacer() Text(locationManager.nearestStation!.name) } if locationManager.prevStation != nil { HStack { HStack { Image(systemName: "tram.fill") Text(locationManager.prevStation!.name) .font(.subheadline) } Spacer() Text(locationManager.nearestStation!.prevDepartureTimeText) } } if locationManager.nextStation != nil { HStack { HStack { Image(systemName: "tram.fill") Text(locationManager.nextStation!.name) .font(.subheadline) } Spacer() Text(locationManager.nearestStation!.nextDepartureTimeText) } } } .padding(.all) } } List(self.mrtSystem.stations) { station in NavigationLink(destination: StationDetailView(station: station)) { Text(station.name) } } } .navigationBarTitle("MRT Jakarta") }.onAppear { self.locationManager.start() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
37.923077
110
0.375254
fc37afc636df4ad97ba7c290332d91c988720b49
4,002
// // ViewController.swift // weather // // Created by Xuanyu Wang on 2016-10-29. // // import UIKit // 3. implement delegate class ViewController: UIViewController, XMLParserDelegate,UITableViewDelegate,UITableViewDataSource { var url = NSURL() var xmlParser = XMLParser() var currentLocation: selectedLocations! var results = [String]() var dataToDetails: passToDetails! // var locationz:selectedLocations! @IBOutlet weak var currentCondition: UILabel! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // 4. set delegate xmlParser.delegate = self if currentLocation == nil{ if dataToDetails == nil { // currentCondition.text = "Please Select Your Location" }else{ currentLocation = selectedLocations() currentLocation.website = dataToDetails.website url = try! NSURL(string: currentLocation.website)! xmlParser.startParsingWithContentsOfURL(url) //display on tableview // self.results = xmlParser.contentOfTitle self.results = xmlParser.timePeriod self.tableView.delegate = self self.tableView.dataSource = self self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } }else{ url = try! NSURL(string: currentLocation.website)! xmlParser.startParsingWithContentsOfURL(url) //display on tableview // self.results = xmlParser.contentOfTitle self.results = xmlParser.timePeriod self.tableView.delegate = self self.tableView.dataSource = self self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // implement delegate func didFinishTask(sender: XMLParser) { // currentCondition.text = xmlParser.weatherInfo["Current Conditions"] print(xmlParser.weatherInfo["Current Conditions"]) } ////////////////////////////// Table View ///////////////////////////////// //show items on tableview func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identify: String = "cell" let cell = tableView.dequeueReusableCellWithIdentifier(identify, forIndexPath: indexPath) as UITableViewCell cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator // results = results.removeFirst(2) let time = self.results[indexPath.row] if time != ""{ let overview = self.xmlParser.weatherInfo[time] cell.textLabel?.text = time + ": " + overview! } // else{ // cell.textLabel?.text = self.results[indexPath.row] // } return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.results.count } //click items to jump func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { dataToDetails = passToDetails() dataToDetails.timePeriod = results[indexPath.row] dataToDetails.website = currentLocation.website performSegueWithIdentifier("showDetails", sender: dataToDetails) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetails" && dataToDetails != nil{ let detailVC:ShowDetailViewController = segue.destinationViewController as! ShowDetailViewController detailVC.dataToDetails = dataToDetails } } }
37.754717
116
0.626687
11a5d10212fe8acef2173017a3f8cfd785d63584
3,348
// // MediaViewController.swift // iOSDemo // // Created by Stan Hu on 2017/9/23. // Copyright © 2017年 Stan Hu. All rights reserved. // import UIKit import SnapKit class MediaViewController: UIViewController { var arrData = ["CaptureVideo","Add Watermark","Record Audio","Record Video","Take Photo", "Gif","Palette","Image Process"] var tbMenu = UITableView() override func loadView() { super.loadView() print("New ViewController LoadView") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white tbMenu.dataSource = self tbMenu.delegate = self tbMenu.dataSource = self tbMenu.delegate = self tbMenu.tableFooterView = UIView() view.addSubview(tbMenu) tbMenu.snp.makeConstraints { (m) in m.edges.equalTo(0) } print("New ViewController viewDidLoad") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("New ViewController viewWillAppear") } override func viewDidAppear(_ animated: Bool) { super.viewDidDisappear(animated) print("New ViewController viewDidAppear") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("New ViewController viewWillDisappear") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("New ViewController viewDidDisappear") } deinit { print("New ViewController deinit") } } extension MediaViewController:UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil{ cell = UITableViewCell(style: .default, reuseIdentifier: "cell") } cell?.textLabel?.text = arrData[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.row { case 0: navigationController?.pushViewController(CaptureVideoViewController(), animated: true) case 1: navigationController?.pushViewController(WatermarkViewController(), animated: true) case 2: navigationController?.pushViewController(SoundRecordViewController(), animated: true) case 3: navigationController?.pushViewController(VideoListViewController(), animated: true) case 4: present(TakePhotoViewController(), animated: true, completion: nil) case 5: navigationController?.pushViewController(GifViewController(), animated: true) case 6: navigationController?.pushViewController(PaletteViewController(), animated: true) case 7: navigationController?.pushViewController(CompressImageViewController(), animated: true) default: break } } }
33.148515
100
0.653226
dba9cf4ac1c9473e339cb9098e960f0004456999
298
// // iDineApp.swift // iDine // // Created by Mouhamed Dieye on 12/05/2021. // import SwiftUI @main struct iDineApp: App { @StateObject var order = Order() var body: some Scene { WindowGroup { MainView() .environmentObject(order) } } }
14.9
44
0.553691
463fa2ab0fb245bf58c23268cdc3e2113577c8c7
2,738
// Arek // // Copyright (c) 2016 Ennio Masi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import CoreBluetooth open class BluetoothPermissionDelegate: NSObject, CBPeripheralManagerDelegate { open var identifier: String = "BluetoothPermission" internal var bluetoothManager: CBPeripheralManager! internal var completion: ArekPermissionResponse? public override init() { super.init() self.bluetoothManager = CBPeripheralManager( delegate: self, queue: nil, options: [CBPeripheralManagerOptionShowPowerAlertKey: false] ) } public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { switch peripheral.state { case .unauthorized: print("[🚨 Arek 🚨] bluetooth permission denied by user ⛔️") if let completion = self.completion { return completion(.denied) } break case .poweredOn: print("[🚨 Arek 🚨] bluetooth permission authorized by user ✅") if let completion = self.completion { return completion(.authorized) } break case .unsupported, .poweredOff, .resetting: print("[🚨 Arek 🚨] bluetooth not available 🚫") if let completion = self.completion { return completion(.notAvailable) } break case .unknown: print("[🚨 Arek 🚨] bluetooth could not be determined 🤔") if let completion = self.completion { return completion(.notDetermined) } break } } }
38.027778
84
0.653397
f4a192f745e1ed3c05d5ed5df421a4456ac444bc
781
// // URL+Blank.swift // Vienna // // Copyright 2021 Tassilo Karge // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation extension URL { static let blank = URL(string: "about:blank") ?? { fatalError("blank url must exist") }() }
28.925926
76
0.702945
b93063617fcc6fdddf1ee5f1cf453373ae97df45
3,208
// // AmityColorPaletteTableViewController.swift // AmityUIKit // // Created by Nontapat Siengsanor on 28/8/2563 BE. // Copyright © 2563 Amity. All rights reserved. // import UIKit public class AmityColorPaletteTableViewController: UITableViewController { private var providedColors: [UIColor] = [ AmityColorSet.primary, AmityColorSet.secondary, AmityColorSet.alert, AmityColorSet.highlight, AmityColorSet.base, AmityColorSet.baseInverse, AmityColorSet.messageBubble, AmityColorSet.messageBubbleInverse ] private var colorTitles: [String] = [ "Primary", "Secondary", "Alert", "Highlight", "Base", "BaseInverse", "MessageBubble", "MessageBubbleInverse" ] public override func viewDidLoad() { super.viewDidLoad() tableView.register(ColorPaletteCell.self, forCellReuseIdentifier: "ColorPaletteCell") } // MARK: - Table view data source public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return providedColors.count } public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ColorPaletteCell", for: indexPath) as! ColorPaletteCell cell.configure(with: providedColors[indexPath.row], title: colorTitles[indexPath.row]) return cell } // MARK: - Table view delegate public override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } } class ColorPaletteCell: UITableViewCell { private let stackView = UIStackView(frame: .zero) override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { stackView.axis = .horizontal stackView.alignment = .fill stackView.distribution = .fillEqually stackView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(stackView) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), stackView.topAnchor.constraint(equalTo: contentView.topAnchor), stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)] ) } func configure(with color: UIColor, title: String) { let view = UIView() view.backgroundColor = color stackView.addArrangedSubview(view) textLabel?.text = title textLabel?.textColor = .lightGray for option in ColorBlendingOption.allCases { let view = UIView() view.backgroundColor = color.blend(option) stackView.addArrangedSubview(view) } } }
31.762376
121
0.666771
757e317141c59dc7b863e7621f2c158a60605577
2,800
// // DescriptionUILabel.swift // PinDit // // Created by Zachary Johnson on 11/26/20. // Copyright © 2020 Zachary Johnson. All rights reserved. // import Foundation import UIKit class DescriptionUILabel: UILabel { private var selfWidthAnchor:NSLayoutConstraint! private var selfHeightAnchor:NSLayoutConstraint! private var selfXAnchor:NSLayoutConstraint! private var selfYAnchor:NSLayoutConstraint! private var animator:UIViewPropertyAnimator! private var toggled:Bool = false override func didMoveToWindow() { if self.window != nil { translatesAutoresizingMaskIntoConstraints = false setMainViewAnchors(activeSetting: true, width: 0, height: 0, x: 0, y: 0, yAnchor: self.superview!.topAnchor, xAnchor: self.superview!.leftAnchor) }else { toggled = false } } public func toggleView(anchorTo: TitleUITextField) { if(!toggled) { toggled = !toggled setMainViewAnchors(activeSetting: true, width: 0.4, height: 0.1, x: 0, y: 10, yAnchor: anchorTo.bottomAnchor, xAnchor: anchorTo.leftAnchor) return } toggled = !toggled setMainViewAnchors(activeSetting: true, width: 0, height: 0, x: 0, y: 0, yAnchor: self.superview!.topAnchor, xAnchor: self.superview!.leftAnchor) } private func setMainViewAnchors(activeSetting: Bool, width: CGFloat, height: CGFloat, x: CGFloat, y: CGFloat, yAnchor: NSLayoutYAxisAnchor, xAnchor: NSLayoutXAxisAnchor) { if selfWidthAnchor != nil { selfWidthAnchor.isActive = false selfHeightAnchor.isActive = false selfYAnchor.isActive = false selfXAnchor.isActive = false } if(activeSetting) { selfWidthAnchor = self.widthAnchor.constraint(equalTo: self.superview!.widthAnchor, multiplier: width) selfHeightAnchor = self.heightAnchor.constraint(equalTo: self.superview!.heightAnchor, multiplier: height) selfYAnchor = self.topAnchor.constraint(equalTo: yAnchor, constant: y) selfXAnchor = self.leftAnchor.constraint(equalTo: xAnchor, constant: x) selfWidthAnchor.isActive = activeSetting selfHeightAnchor.isActive = activeSetting selfYAnchor.isActive = activeSetting selfXAnchor.isActive = activeSetting }else { selfYAnchor = self.topAnchor.constraint(equalTo: self.superview!.topAnchor, constant: y) selfXAnchor = self.leftAnchor.constraint(equalTo: self.superview!.leftAnchor, constant: x) selfYAnchor.isActive = true selfXAnchor.isActive = true } } }
36.363636
173
0.648214
f7ef0d32ba3ebc128ce6c38832c21912714907dc
273
// // ApiClient.swift // App // // Created by Shady Kahaleh on 2/2/20. // Copyright © 2020 Shady Kahaleh. All rights reserved. // import Foundation public class ApiClient { public static var shared = ApiClient() public static func execute(){ } }
16.058824
56
0.641026
f4a6af2ac514f38c72c13c107526f59be4fbf886
16,789
// // ParseOperation.swift // Parse // // Created by Florent Vilmart on 17-07-24. // Copyright © 2017 Parse. All rights reserved. // import Foundation /** A `ParseOperation` represents a modification to a value in a `ParseObject`. For example, setting, deleting, or incrementing a value are all `ParseOperation`'s. `ParseOperation` themselves can be considered to be immutable. In most cases, you do not need to create an instance of `ParseOperation` directly as it can be indirectly created from any `ParseObject` by using the respective `operation` property. */ public struct ParseOperation<T>: Savable where T: ParseObject { var target: T var operations = [String: Encodable]() var keysToNull = Set<String>() public init(target: T) { self.target = target } /** An operation that sets a field's value if it has changed from its previous value. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - value: The value to set it to. - returns: The updated operations. - Note: Set the value to "nil" if you want it to be "null" on the Parse Server. */ public func set<W>(_ key: (String, WritableKeyPath<T, W?>), value: W?) -> Self where W: Encodable { var mutableOperation = self if value == nil && target[keyPath: key.1] != nil { mutableOperation.keysToNull.insert(key.0) mutableOperation.target[keyPath: key.1] = value } else if !target[keyPath: key.1].isEqual(value) { mutableOperation.operations[key.0] = value mutableOperation.target[keyPath: key.1] = value } return mutableOperation } /** An operation that force sets a field's value. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - value: The value to set it to. - returns: The updated operations. - Note: Set the value to "nil" if you want it to be "null" on the Parse Server. */ public func forceSet<W>(_ key: (String, WritableKeyPath<T, W?>), value: W?) -> Self where W: Encodable { var mutableOperation = self if value != nil { mutableOperation.operations[key.0] = value } else { mutableOperation.keysToNull.insert(key.0) } mutableOperation.target[keyPath: key.1] = value return mutableOperation } /** An operation that increases a numeric field's value by a given amount. - Parameters: - key: The key of the object. - amount: How much to increment by. - returns: The updated operations. */ public func increment(_ key: String, by amount: Int) -> Self { var mutableOperation = self mutableOperation.operations[key] = Increment(amount: amount) return mutableOperation } /** An operation that adds a new element to an array field, only if it wasn't already present. - Parameters: - key: The key of the object. - objects: The field of objects. - returns: The updated operations. */ public func addUnique<W>(_ key: String, objects: [W]) -> Self where W: Encodable, W: Hashable { var mutableOperation = self mutableOperation.operations[key] = AddUnique(objects: objects) return mutableOperation } /** An operation that adds a new element to an array field, only if it wasn't already present. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func addUnique<V>(_ key: (String, WritableKeyPath<T, [V]>), objects: [V]) -> Self where V: Encodable, V: Hashable { var mutableOperation = self mutableOperation.operations[key.0] = AddUnique(objects: objects) var values = target[keyPath: key.1] values.append(contentsOf: objects) mutableOperation.target[keyPath: key.1] = Array(Set<V>(values)) return mutableOperation } /** An operation that adds a new element to an array field, only if it wasn't already present. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func addUnique<V>(_ key: (String, WritableKeyPath<T, [V]?>), objects: [V]) -> Self where V: Encodable, V: Hashable { var mutableOperation = self mutableOperation.operations[key.0] = AddUnique(objects: objects) var values = target[keyPath: key.1] ?? [] values.append(contentsOf: objects) mutableOperation.target[keyPath: key.1] = Array(Set<V>(values)) return mutableOperation } /** An operation that adds a new element to an array field. - Parameters: - key: The key of the object. - objects: The field of objects. - returns: The updated operations. */ public func add<W>(_ key: String, objects: [W]) -> Self where W: Encodable { var mutableOperation = self mutableOperation.operations[key] = Add(objects: objects) return mutableOperation } /** An operation that adds a new element to an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func add<V>(_ key: (String, WritableKeyPath<T, [V]>), objects: [V]) -> Self where V: Encodable { var mutableOperation = self mutableOperation.operations[key.0] = Add(objects: objects) var values = target[keyPath: key.1] values.append(contentsOf: objects) mutableOperation.target[keyPath: key.1] = values return mutableOperation } /** An operation that adds a new element to an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func add<V>(_ key: (String, WritableKeyPath<T, [V]?>), objects: [V]) -> Self where V: Encodable { var mutableOperation = self mutableOperation.operations[key.0] = Add(objects: objects) var values = target[keyPath: key.1] ?? [] values.append(contentsOf: objects) mutableOperation.target[keyPath: key.1] = values return mutableOperation } /** An operation that adds a new relation to an array field. - Parameters: - key: The key of the object. - objects: The field of objects. - returns: The updated operations. */ public func addRelation<W>(_ key: String, objects: [W]) throws -> Self where W: ParseObject { var mutableOperation = self mutableOperation.operations[key] = try AddRelation(objects: objects) return mutableOperation } /** An operation that adds a new relation to an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func addRelation<V>(_ key: (String, WritableKeyPath<T, [V]>), objects: [V]) throws -> Self where V: ParseObject { var mutableOperation = self mutableOperation.operations[key.0] = try AddRelation(objects: objects) var values = target[keyPath: key.1] values.append(contentsOf: objects) mutableOperation.target[keyPath: key.1] = values return mutableOperation } /** An operation that adds a new relation to an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func addRelation<V>(_ key: (String, WritableKeyPath<T, [V]?>), objects: [V]) throws -> Self where V: ParseObject { var mutableOperation = self mutableOperation.operations[key.0] = try AddRelation(objects: objects) var values = target[keyPath: key.1] ?? [] values.append(contentsOf: objects) mutableOperation.target[keyPath: key.1] = values return mutableOperation } /** An operation that removes every instance of an element from an array field. - Parameters: - key: The key of the object. - objects: The field of objects. - returns: The updated operations. */ public func remove<W>(_ key: String, objects: [W]) -> Self where W: Encodable { var mutableOperation = self mutableOperation.operations[key] = Remove(objects: objects) return mutableOperation } /** An operation that removes every instance of an element from an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func remove<V>(_ key: (String, WritableKeyPath<T, [V]>), objects: [V]) -> Self where V: Encodable, V: Hashable { var mutableOperation = self mutableOperation.operations[key.0] = Remove(objects: objects) let values = target[keyPath: key.1] var set = Set<V>(values) objects.forEach { set.remove($0) } mutableOperation.target[keyPath: key.1] = Array(set) return mutableOperation } /** An operation that removes every instance of an element from an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func remove<V>(_ key: (String, WritableKeyPath<T, [V]?>), objects: [V]) -> Self where V: Encodable, V: Hashable { var mutableOperation = self mutableOperation.operations[key.0] = Remove(objects: objects) let values = target[keyPath: key.1] var set = Set<V>(values ?? []) objects.forEach { set.remove($0) } mutableOperation.target[keyPath: key.1] = Array(set) return mutableOperation } /** An operation that removes every instance of a relation from an array field. - Parameters: - key: The key of the object. - objects: The field of objects. - returns: The updated operations. */ public func removeRelation<W>(_ key: String, objects: [W]) throws -> Self where W: ParseObject { var mutableOperation = self mutableOperation.operations[key] = try RemoveRelation(objects: objects) return mutableOperation } /** An operation that removes every instance of a relation from an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func removeRelation<V>(_ key: (String, WritableKeyPath<T, [V]>), objects: [V]) throws -> Self where V: ParseObject { var mutableOperation = self mutableOperation.operations[key.0] = try RemoveRelation(objects: objects) let values = target[keyPath: key.1] var set = Set<V>(values) objects.forEach { set.remove($0) } mutableOperation.target[keyPath: key.1] = Array(set) return mutableOperation } /** An operation that removes every instance of a relation from an array field. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - objects: The field of objects. - returns: The updated operations. */ public func removeRelation<V>(_ key: (String, WritableKeyPath<T, [V]?>), objects: [V]) throws -> Self where V: ParseObject { var mutableOperation = self mutableOperation.operations[key.0] = try RemoveRelation(objects: objects) let values = target[keyPath: key.1] var set = Set<V>(values ?? []) objects.forEach { set.remove($0) } mutableOperation.target[keyPath: key.1] = Array(set) return mutableOperation } /** An operation where a field is deleted from the object. - parameter key: The key of the object. - returns: The updated operations. */ public func unset(_ key: String) -> Self { var mutableOperation = self mutableOperation.operations[key] = Delete() return mutableOperation } /** An operation where a field is deleted from the object. - Parameters: - key: A tuple consisting of the key and the respective KeyPath of the object. - returns: The updated operations. */ public func unset<V>(_ key: (String, WritableKeyPath<T, V?>)) -> Self where V: Encodable { var mutableOperation = self mutableOperation.operations[key.0] = Delete() mutableOperation.target[keyPath: key.1] = nil return mutableOperation } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: RawCodingKey.self) try operations.forEach { pair in let (key, value) = pair let encoder = container.superEncoder(forKey: .key(key)) try value.encode(to: encoder) } try keysToNull.forEach { key in let encoder = container.superEncoder(forKey: .key(key)) var container = encoder.singleValueContainer() try container.encodeNil() } } } // MARK: Savable extension ParseOperation { /** Saves the operations on the `ParseObject` *synchronously* and throws an error if there's an issue. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of type `ParseError`. - returns: Returns saved `ParseObject`. */ public func save(options: API.Options = []) throws -> T { if !target.isSaved { throw ParseError(code: .missingObjectId, message: "ParseObject isn't saved.") } return try saveCommand() .execute(options: options) } /** Saves the operations on the `ParseObject` *asynchronously* and executes the given callback block. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<T, ParseError>)`. */ public func save( options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<T, ParseError>) -> Void ) { if !target.isSaved { callbackQueue.async { let error = ParseError(code: .missingObjectId, message: "ParseObject isn't saved.") completion(.failure(error)) } return } do { try self.saveCommand().executeAsync(options: options, callbackQueue: callbackQueue) { result in completion(result) } } catch { callbackQueue.async { let error = ParseError(code: .missingObjectId, message: "ParseObject isn't saved.") completion(.failure(error)) } } } func saveCommand() throws -> API.NonParseBodyCommand<ParseOperation<T>, T> { // MARK: Should be switched to ".PATCH" when server supports PATCH. API.NonParseBodyCommand(method: .PUT, path: target.endpoint, body: self) { try ParseCoding.jsonDecoder().decode(UpdateResponse.self, from: $0).apply(to: self.target) } } } // MARK: ParseOperation public extension ParseObject { /// Create a new operation. var operation: ParseOperation<Self> { return ParseOperation(target: self) } }
37.72809
103
0.613437
7576b5768e6afa751877a1499fb691467f9b642d
11,074
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module %s | %FileCheck %s // REQUIRES: objc_interop import Foundation @objc class Foo { // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3fooSiSiSic_Si1xtFTo : // CHECK: bb0([[ARG1:%.*]] : $@convention(block) (Int) -> Int, {{.*}}, [[SELF:%.*]] : $Foo): // CHECK: [[ARG1_COPY:%.*]] = copy_block [[ARG1]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @_T0SiSiIyByd_SiSiIxyd_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[ARG1_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (Int) -> Int, Int, @guaranteed Foo) -> Int // CHECK: apply [[NATIVE]]([[BRIDGED]], {{.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3fooSiSiSic_Si1xtFTo' dynamic func foo(_ f: (Int) -> Int, x: Int) -> Int { return f(x) } // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3barSSSSSSc_SS1xtFTo : $@convention(objc_method) (@convention(block) (NSString) -> @autoreleased NSString, NSString, Foo) -> @autoreleased NSString { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[NSSTRING:%.*]] : $NSString, [[SELF:%.*]] : $Foo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCABIyBya_SSSSIxxo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[BLOCK_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (@owned String) -> @owned String, @owned String, @guaranteed Foo) -> @owned String // CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3barSSSSSSc_SS1xtFTo' dynamic func bar(_ f: (String) -> String, x: String) -> String { return f(x) } // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3basSSSgSSSgSSSgc_SSSg1xtFTo : $@convention(objc_method) (@convention(block) (Optional<NSString>) -> @autoreleased Optional<NSString>, Optional<NSString>, Foo) -> @autoreleased Optional<NSString> { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (Optional<NSString>) -> @autoreleased Optional<NSString>, [[OPT_STRING:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $Foo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCSgABSgIyBya_SSSgSSSgIxxo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[BLOCK_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (@owned Optional<String>) -> @owned Optional<String>, @owned Optional<String>, @guaranteed Foo) -> @owned Optional<String> // CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] dynamic func bas(_ f: (String?) -> String?, x: String?) -> String? { return f(x) } // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}FTo // CHECK: bb0([[F:%.*]] : $@convention(c) (Int) -> Int, [[X:%.*]] : $Int, [[SELF:%.*]] : $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}F // CHECK: apply [[NATIVE]]([[F]], [[X]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] dynamic func cFunctionPointer(_ fp: @convention(c) (Int) -> Int, x: Int) -> Int { _ = fp(x) } // Blocks and C function pointers must not be reabstracted when placed in optionals. // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}FTo // CHECK: [[COPY:%.*]] = copy_block %0 // CHECK: [[BLOCK:%.*]] = unchecked_enum_data [[COPY]] // TODO: redundant reabstractions here // CHECK: [[BLOCK_THUNK:%.*]] = function_ref @_T0So8NSStringCABIyBya_SSSSIxxo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[BLOCK_THUNK]]([[BLOCK]]) // CHECK: enum $Optional<@callee_owned (@owned String) -> @owned String>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned Optional<@callee_owned (@owned String) -> @owned String>, @owned String, @guaranteed Foo) -> @owned Optional<String> // CHECK: apply [[NATIVE]] dynamic func optFunc(_ f: ((String) -> String)?, x: String) -> String? { return f?(x) } // CHECK-LABEL: sil hidden @_T020objc_blocks_bridging3FooC19optCFunctionPointer{{[_0-9a-zA-Z]*}}F // CHECK: [[FP_BUF:%.*]] = unchecked_enum_data %0 dynamic func optCFunctionPointer(_ fp: (@convention(c) (String) -> String)?, x: String) -> String? { return fp?(x) } } // => SEMANTIC SIL TODO: This test needs to be filled out more for ownership // // CHECK-LABEL: sil hidden @_T020objc_blocks_bridging10callBlocks{{[_0-9a-zA-Z]*}}F func callBlocks(_ x: Foo, f: @escaping (Int) -> Int, g: @escaping (String) -> String, h: @escaping (String?) -> String? ) -> (Int, String, String?, String?) { // CHECK: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $@callee_owned (Int) -> Int, [[ARG2:%.*]] : $@callee_owned (@owned String) -> @owned String, [[ARG3:%.*]] : $@callee_owned (@owned Optional<String>) -> @owned Optional<String>): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[FOO:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.foo!1.foreign // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[F_BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[F_BLOCK_CAPTURE:%.*]] = project_block_storage [[F_BLOCK_STORAGE]] // CHECK: store [[CLOSURE_COPY]] to [init] [[F_BLOCK_CAPTURE]] // CHECK: [[F_BLOCK_INVOKE:%.*]] = function_ref @_T0SiSiIxyd_SiSiIyByd_TR // CHECK: [[F_STACK_BLOCK:%.*]] = init_block_storage_header [[F_BLOCK_STORAGE]] : {{.*}}, invoke [[F_BLOCK_INVOKE]] // CHECK: [[F_BLOCK:%.*]] = copy_block [[F_STACK_BLOCK]] // CHECK: apply [[FOO]]([[F_BLOCK]] // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[BAR:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.bar!1.foreign // CHECK: [[G_BLOCK_INVOKE:%.*]] = function_ref @_T0SSSSIxxo_So8NSStringCABIyBya_TR // CHECK: [[G_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[G_BLOCK_INVOKE]] // CHECK: [[G_BLOCK:%.*]] = copy_block [[G_STACK_BLOCK]] // CHECK: apply [[BAR]]([[G_BLOCK]] // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[BAS:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.bas!1.foreign // CHECK: [[H_BLOCK_INVOKE:%.*]] = function_ref @_T0SSSgSSSgIxxo_So8NSStringCSgABSgIyBya_TR // CHECK: [[H_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[H_BLOCK_INVOKE]] // CHECK: [[H_BLOCK:%.*]] = copy_block [[H_STACK_BLOCK]] // CHECK: apply [[BAS]]([[H_BLOCK]] // CHECK: [[G_BLOCK:%.*]] = copy_block {{%.*}} : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: enum $Optional<@convention(block) (NSString) -> @autoreleased NSString>, #Optional.some!enumelt.1, [[G_BLOCK]] return (x.foo(f, x: 0), x.bar(g, x: "one"), x.bas(h, x: "two"), x.optFunc(g, x: "three")) } class Test: NSObject { func blockTakesBlock() -> ((Int) -> Int) -> Int {} } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0SiSiIxyd_SiIxxd_SiSiIyByd_SiIyByd_TR // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[ORIG_BLOCK:%.*]] : // CHECK: [[CLOSURE:%.*]] = partial_apply {{%.*}}([[BLOCK_COPY]]) // CHECK: [[RESULT:%.*]] = apply {{%.*}}([[CLOSURE]]) // CHECK: return [[RESULT]] func clearDraggingItemImageComponentsProvider(_ x: NSDraggingItem) { x.imageComponentsProvider = {} } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0SayypGIxo_So7NSArrayCSgIyBa_TR // CHECK: [[CONVERT:%.*]] = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF // CHECK: [[CONVERTED:%.*]] = apply [[CONVERT]] // CHECK: [[OPTIONAL:%.*]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[CONVERTED]] // CHECK: return [[OPTIONAL]] // CHECK-LABEL: sil hidden @{{.*}}bridgeNonnullBlockResult{{.*}} // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0SSIxo_So8NSStringCSgIyBa_TR // CHECK: [[CONVERT:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BRIDGED:%.*]] = apply [[CONVERT]] // CHECK: [[OPTIONAL_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: return [[OPTIONAL_BRIDGED]] func bridgeNonnullBlockResult() { nonnullStringBlockResult { return "test" } } // CHECK-LABEL: sil hidden @{{.*}}bridgeNoescapeBlock{{.*}} func bridgeNoescapeBlock() { // CHECK: function_ref @_T0Ix_IyB_TR noescapeBlockAlias { } // CHECK: function_ref @_T0Ix_IyB_TR noescapeNonnullBlockAlias { } } class ObjCClass : NSObject {} extension ObjCClass { func someDynamicMethod(closure: (() -> ()) -> ()) {} } struct GenericStruct<T> { let closure: (() -> ()) -> () func doStuff(o: ObjCClass) { o.someDynamicMethod(closure: closure) } } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0Ix_Ixx_IyB_IyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@owned @callee_owned () -> ()) -> (), @convention(block) () -> ()) -> () // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0IyB_Ix_TR : $@convention(thin) (@owned @convention(block) () -> ()) -> ()
60.184783
271
0.629673
11c75c986167b432555f286b450d06419b379d1e
391
// // MVPUser.swift // MVPSample // // Created by Yusuke Hosonuma on 2018/02/21. // Copyright © 2018 Yusuke. All rights reserved. // import FirebaseAuth import Foundation struct MVPUser { let displayName: String let email: String } extension MVPUser { init(_ user: FirebaseAuth.User) { displayName = user.displayName ?? "" email = user.email ?? "" } }
17
49
0.644501
08368cd5e0afe485179b0faecbaf6f38df1ef1bb
19,578
// RUN: %target-typecheck-verify-swift // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int), y: (Int,Int)) -> Bool { return true } func parseError1(x: Int) { switch func {} // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} expected-error {{expected identifier in function declaration}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{15-15=do }} } func parseError2(x: Int) { switch x // expected-error {{expected '{' after 'switch' subject expression}} } func parseError3(x: Int) { switch x { case // expected-error {{expected pattern}} expected-error {{expected ':' after 'case'}} } } func parseError4(x: Int) { switch x { case var z where // expected-error {{expected expression for 'where' guard of 'case'}} expected-error {{expected ':' after 'case'}} } } func parseError5(x: Int) { switch x { case let z // expected-error {{expected ':' after 'case'}} expected-warning {{immutable value 'z' was never used}} {{12-13=_}} } } func parseError6(x: Int) { switch x { default // expected-error {{expected ':' after 'default'}} } } var x: Int switch x {} // expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} switch x { case 0: x = 0 // Multiple patterns per case case 1, 2, 3: x = 0 // 'where' guard case _ where x % 2 == 0: x = 1 x = 2 x = 3 case _ where x % 2 == 0, _ where x % 3 == 0: x = 1 case 10, _ where x % 3 == 0: x = 1 case _ where x % 2 == 0, 20: x = 1 case var y where y % 2 == 0: x = y + 1 case _ where 0: // expected-error {{'Int' is not convertible to 'Bool'}} x = 0 default: x = 1 } // Multiple cases per case block switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} default: x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: x = 0 case 1: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: x = 0 default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: ; // expected-error {{';' statements are not allowed}} {{3-5=}} case 1: x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} default: x = 0 case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case 1: x = 0 } switch x { default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} } switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} x = 2 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: x = 0 case 1: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} var y = 0 default: // expected-error{{'default' label can only appear inside a 'switch' statement}} var z = 1 fallthrough // expected-error{{'fallthrough' is only allowed inside a switch}} switch x { case 0: fallthrough case 1: fallthrough default: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } // Fallthrough can transfer control anywhere within a case and can appear // multiple times in the same case. switch x { case 0: if true { fallthrough } if false { fallthrough } x += 1 default: x += 1 } // Cases cannot contain 'var' bindings if there are multiple matching patterns // attached to a block. They may however contain other non-binding patterns. var t = (1, 2) switch t { case (var a, 2), (1, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (_, 2), (var a, _): // expected-error {{'a' must be bound in every pattern}} () case (var a, 2), (1, var b): // expected-error {{'a' must be bound in every pattern}} expected-error {{'b' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, var b): // expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} () case (1, let b): // let bindings expected-warning {{immutable value 'b' was never used; consider replacing with '_' or removing it}} () case (_, 2), (let a, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{case is already handled by previous patterns; consider removing it}} () // OK case (_, 2), (1, _): () case (_, var a), (_, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} // expected-warning@-2 {{case is already handled by previous patterns; consider removing it}} () case (var a, var b), (var b, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} // expected-warning@-2 {{case is already handled by previous patterns; consider removing it}} () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, _): () } func patternVarUsedInAnotherPattern(x: Int) { switch x { case let a, // expected-error {{'a' must be bound in every pattern}} a: break } } // Fallthroughs can only transfer control into a case label with bindings if the previous case binds a superset of those vars. switch t { case (1, 2): fallthrough // expected-error {{'fallthrough' from a case which doesn't bind variable 'a'}} expected-error {{'fallthrough' from a case which doesn't bind variable 'b'}} case (var a, var b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} t = (b, a) } switch t { // specifically notice on next line that we shouldn't complain that a is unused - just never mutated case (var a, let b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} t = (b, b) fallthrough // ok - notice that subset of bound variables falling through is fine case (2, let a): t = (a, a) } func patternVarDiffType(x: Int, y: Double) { switch (x, y) { case (1, let a): // expected-error {{pattern variable bound to type 'Double', fallthrough case bound to type 'Int'}} fallthrough case (let a, _): break } } func patternVarDiffMutability(x: Int, y: Double) { switch x { case let a where a < 5, var a where a > 10: // expected-error {{'var' pattern binding must match previous 'let' pattern binding}}{{27-30=let}} break default: break } switch (x, y) { // Would be nice to have a fixit in the following line if we detect that all bindings in the same pattern have the same problem. case let (a, b) where a < 5, var (a, b) where a > 10: // expected-error 2{{'var' pattern binding must match previous 'let' pattern binding}}{{none}} break case (let a, var b) where a < 5, (let a, let b) where a > 10: // expected-error {{'let' pattern binding must match previous 'var' pattern binding}}{{44-47=var}} break case (let a, let b) where a < 5, (var a, let b) where a > 10, (let a, var b) where a == 8: // expected-error@-1 {{'var' pattern binding must match previous 'let' pattern binding}}{{37-40=let}} // expected-error@-2 {{'var' pattern binding must match previous 'let' pattern binding}}{{73-76=let}} break default: break } } func test_label(x : Int) { Gronk: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} switch x { case 42: return } } func enumElementSyntaxOnTuple() { switch (1, 1) { case .Bar: // expected-error {{pattern cannot match values of type '(Int, Int)'}} break default: break } } // sr-176 enum Whatever { case Thing } func f0(values: [Whatever]) { // expected-note {{'values' declared here}} switch value { // expected-error {{use of unresolved identifier 'value'; did you mean 'values'?}} case .Thing: // Ok. Don't emit diagnostics about enum case not found in type <<error type>>. break } } // sr-720 enum Whichever { case Thing static let title = "title" static let alias: Whichever = .Thing } func f1(x: String, y: Whichever) { switch x { case Whichever.title: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.buzz: // expected-error {{type 'Whichever' has no member 'buzz'}} break case Whichever.alias: // expected-error {{expression pattern of type 'Whichever' cannot match values of type 'String'}} break default: break } switch y { case Whichever.Thing: // Ok. break case Whichever.alias: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.title: // expected-error {{expression pattern of type 'String' cannot match values of type 'Whichever'}} break } } switch Whatever.Thing { case .Thing: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} @unknown case _: x = 0 } switch Whatever.Thing { case .Thing: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} @unknown default: x = 0 } switch Whatever.Thing { case .Thing: x = 0 @unknown case _: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} } switch Whatever.Thing { case .Thing: x = 0 @unknown default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{18-18= break}} } switch Whatever.Thing { @unknown default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case .Thing: x = 0 } switch Whatever.Thing { default: x = 0 @unknown case _: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} expected-error {{'@unknown' can only be applied to the last case in a switch}} x = 0 case .Thing: x = 0 } switch Whatever.Thing { default: x = 0 @unknown default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case .Thing: x = 0 } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case _: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } switch Whatever.Thing { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} fallthrough case .Thing: break } switch Whatever.Thing { @unknown default: fallthrough case .Thing: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break } switch Whatever.Thing { @unknown case _, _: // expected-error {{'@unknown' cannot be applied to multiple patterns}} break } switch Whatever.Thing { @unknown case _, _, _: // expected-error {{'@unknown' cannot be applied to multiple patterns}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case let value: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} _ = value } switch (Whatever.Thing, Whatever.Thing) { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '(_, _)'}} @unknown case (_, _): // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case is Whatever: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} // expected-warning@-1 {{'is' test is always true}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case .Thing: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case (_): // okay break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case _ where x == 0: // expected-error {{'where' cannot be used with '@unknown'}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown default where x == 0: // expected-error {{'default' cannot be used with a 'where' guard expression}} break } switch Whatever.Thing { case .Thing: x = 0 #if true @unknown case _: x = 0 #endif } switch x { case 0: break @garbage case _: // expected-error {{unknown attribute 'garbage'}} break } switch x { case 0: break @garbage @moreGarbage default: // expected-error {{unknown attribute 'garbage'}} expected-error {{unknown attribute 'moreGarbage'}} break } @unknown let _ = 1 // expected-error {{unknown attribute 'unknown'}} switch x { case _: @unknown let _ = 1 // expected-error {{unknown attribute 'unknown'}} } switch Whatever.Thing { case .Thing: break @unknown(garbage) case _: // expected-error {{unexpected '(' in attribute 'unknown'}} break } switch Whatever.Thing { case .Thing: break @unknown // expected-note {{attribute already specified here}} @unknown // expected-error {{duplicate attribute}} case _: break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note {{add missing case: '.Thing'}} @unknown @garbage(foobar) // expected-error {{unknown attribute 'garbage'}} case _: break } switch x { // expected-error {{switch must be exhaustive}} case 1: break @unknown case _: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}} break } switch x { // expected-error {{switch must be exhaustive}} @unknown case _: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}} break } switch x { // expected-error {{switch must be exhaustive}} @unknown default: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}} break } switch Whatever.Thing { case .Thing: break @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown case _: break } switch Whatever.Thing { case .Thing: break @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown default: break } switch Whatever.Thing { case .Thing: break @unknown default: break @unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break } switch Whatever.Thing { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown case _: break } switch Whatever.Thing { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown default: break } switch Whatever.Thing { @unknown default: break @unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break } switch x { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown case _: break } switch x { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown default: break } switch x { @unknown default: break @unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break }
31.990196
326
0.67913
11a97124e6823469b9f13e92cc96fbf0f51cabca
187
// // Vercel.swift // stts // import Foundation class Vercel: StatusPageService { let url = URL(string: "https://www.vercel-status.com/")! let statusPageID = "lvglq8h0mdyh" }
15.583333
60
0.663102
0a0f283f8bebe1d3e2bf129e4bda38b4380e5530
1,086
import UIKit public class ClockwiseAnimation :AnimationDelegate{ public func addAnimation(shapes:[CAShapeLayer], duration:CFTimeInterval) { let beginTime = CACurrentMediaTime() let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.1, 0.4,0.6, 0.8] opacityAnimation.values = [ 0.2, 0.6, 1, 0.6, 0.2] opacityAnimation.duration = duration // Aniamtion let animation = CAAnimationGroup() animation.animations = [ opacityAnimation] animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false let timeInterval = duration / Double(shapes.count ) for (index, layersector) in shapes.enumerated(){ let btime = Double(index) * timeInterval animation.beginTime = beginTime + btime layersector.add(animation, forKey: nil) } } }
37.448276
96
0.64825
d9a9b2969c7b064627a77704cf22d090b839b8f7
1,104
// // UIAlertAction+.swift // GADManager // // Created by 영준 이 on 2020/10/15. // Copyright © 2020 Y2KLab. All rights reserved. // import Foundation import UIKit extension UIAlertAction{ /** Generates UIAlertAction with default style */ public static func `default`(_ title: String, handler: ((UIAlertAction) -> Swift.Void)? = nil) -> UIAlertAction{ //case `default` return UIAlertAction.init(title: title, style: .default, handler: handler); } /** Generates UIAlertAction with cancel style */ public static func cancel(_ title: String, handler: ((UIAlertAction) -> Swift.Void)? = nil) -> UIAlertAction{ //case case return UIAlertAction.init(title: title, style: .cancel, handler: handler); } /** Generates UIAlertAction with destructive style */ public static func destructive(_ title: String, handler: ((UIAlertAction) -> Swift.Void)? = nil) -> UIAlertAction{ //case destructive return UIAlertAction.init(title: title, style: .destructive, handler: handler); } }
29.837838
118
0.64221
b9ffd12351958d0887e3dec3b3f464367a0b9117
327
// // Array+MidElement.swift // UpcomingMovies // // Created by Alonso on 5/25/20. // Copyright © 2020 Alonso. All rights reserved. // extension Array { var mid: Element? { guard count != 0 else { return nil } let midIndex = (count > 1 ? count - 1 : count) / 2 return self[midIndex] } }
17.210526
58
0.58104
23ba37c0a0f9e18e60c2d839687054b102374385
10,203
// // ViewController.swift // Kesikaran_Typist // // Created by Tomishige Ryosuke on 2020/12/19. // import Cocoa enum side { case right, left, none } class ViewController: NSViewController { // @IBOutlet weak var textField: NSTextField! // textField @IBOutlet weak var sampleSentenceLabel: NSTextField! // 数年に1回レベルの大変楽しい日本語訳を発見いたしました @IBOutlet weak var kanaSampleSentenceLabel: NSTextField! // すうねんにいっかいれへ゛るのたいへんたのしいにほんこ゛やくをはっけんいたしました! @IBOutlet weak var typedKeyCharLabel: NSTextField! // Typed: a @IBOutlet weak var typedKeyKanaLabel: NSTextField! // Kana: ち @IBOutlet weak var typedKanaSentenceLabel: NSTextField! // ちとしは // 全キーを手動で接続した。 これは大変けしからん実装である // しかし、outlet collection は macOS では使えない(大昔は使えたらしい)から無理。 // 仕方なくこの実装にした。 @IBOutlet weak var accent_grave: KeyView! // 0 @IBOutlet weak var one: KeyView! // 1 @IBOutlet weak var two: KeyView! // 2 @IBOutlet weak var three: KeyView! // 3 @IBOutlet weak var four: KeyView! // 4 @IBOutlet weak var five: KeyView! // 5 @IBOutlet weak var six: KeyView! // 6 @IBOutlet weak var seven: KeyView! // 7 @IBOutlet weak var eight: KeyView! // 8 @IBOutlet weak var nine: KeyView! // 9 @IBOutlet weak var zero: KeyView! // 10 @IBOutlet weak var A: KeyView! // 11 @IBOutlet weak var B: KeyView! // 12 @IBOutlet weak var C: KeyView! // 13 @IBOutlet weak var D: KeyView! // 14 @IBOutlet weak var E: KeyView! // 15 @IBOutlet weak var F: KeyView! // 16 @IBOutlet weak var G: KeyView! // 17 @IBOutlet weak var H: KeyView! // 18 @IBOutlet weak var I: KeyView! // 19 @IBOutlet weak var J: KeyView! // 20 @IBOutlet weak var K: KeyView! // 21 @IBOutlet weak var L: KeyView! // 22 @IBOutlet weak var M: KeyView! // 23 @IBOutlet weak var N: KeyView! // 24 @IBOutlet weak var O: KeyView! // 25 @IBOutlet weak var P: KeyView! // 26 @IBOutlet weak var Q: KeyView! // 27 @IBOutlet weak var R: KeyView! // 28 @IBOutlet weak var S: KeyView! // 29 @IBOutlet weak var T: KeyView! // 30 @IBOutlet weak var U: KeyView! // 31 @IBOutlet weak var V: KeyView! // 32 @IBOutlet weak var W: KeyView! // 33 @IBOutlet weak var X: KeyView! // 34 @IBOutlet weak var Y: KeyView! // 35 @IBOutlet weak var Z: KeyView! // 36 @IBOutlet weak var hyphen: KeyView! // 37 - @IBOutlet weak var equal: KeyView! // 38 = @IBOutlet weak var delete: KeyView! // 39 @IBOutlet weak var tab: KeyView! // 40 @IBOutlet weak var l_sq_bracket: KeyView! // 41 [ @IBOutlet weak var r_sq_bracket: KeyView! // 42 ] @IBOutlet weak var back_slash: KeyView! // 43 \ @IBOutlet weak var l_control: KeyView! // 44 Ctrl @IBOutlet weak var colon: KeyView! // 45 ; @IBOutlet weak var quotation: KeyView! // 46 ' @IBOutlet weak var returnKey: KeyView! // 47 @IBOutlet weak var l_shift: KeyView! // 48 @IBOutlet weak var comma: KeyView! // 49 , @IBOutlet weak var dot: KeyView! // 50 . @IBOutlet weak var slash: KeyView! // 51 / @IBOutlet weak var r_shift: KeyView! // 52 @IBOutlet weak var caps_lock: KeyView! // 53 @IBOutlet weak var l_option: KeyView! // 54 Opt @IBOutlet weak var l_command: KeyView! // 55 ⌘ @IBOutlet weak var spase: KeyView! // 56 @IBOutlet weak var r_command: KeyView! // 57 ⌘ @IBOutlet weak var r_option: KeyView! // 58 Opt @IBOutlet weak var r_control: KeyView! // 59 Ctrl @IBOutlet weak var Fn: KeyView! // 60 var keyViewList: Array<KeyView> = [] // shiftキーの状態を保存 var isShift: Bool = false var sideOfShift = side.none let keyDataManager = KeysDataManager.sharedInstance // keyDataが保存してあるクラスのインスタンス let sentenceManager = SentenceManager.sharedInstance // タイプされた文章を保存するクラスのインスタンス override func viewDidLoad() { super.viewDidLoad() keyViewList = [accent_grave, one, two, three, four, five, six, seven, eight, nine, zero, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, hyphen, equal, delete, tab, l_sq_bracket, r_sq_bracket, back_slash, l_control, colon, quotation, returnKey, l_shift, comma, dot, slash, r_shift, caps_lock, l_option, l_command, spase, r_command, r_option, Fn] sentenceManager.loadSampleSentence() sentenceManager.setSequentialSampleSentence() sampleSentenceLabel.stringValue = sentenceManager.nowSampleSentence.sentence kanaSampleSentenceLabel.stringValue = sentenceManager.nowSampleSentence.kanaSentence typedKanaSentenceLabel.stringValue = "|" typedKanaSentenceLabel.isSelectable = true sampleSentenceLabel.isSelectable = true kanaSampleSentenceLabel.isSelectable = true NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { self.flagsChanged(with: $0) return $0 } NSEvent.addLocalMonitorForEvents(matching: .keyDown) { self.keyDown(with: $0) return $0 } } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } func genKeycodes(keycode: UInt16) -> [Int] { // shift + ○ に対応させる // shift + 56 -> [421, 56] // 48 -> [48] if isShift { return [421, Int(keycode)] } return [Int(keycode)] } func genKeycodesforNum(keycode: UInt16) -> [Int] { // shift + ○ に対応させる (shiftの左右を区別する) // right shift + 32 -> [60, 32] // 48 -> [48] if isShift { switch sideOfShift{ case side.right: return [60, Int(keycode)] case side.left: return [56, Int(keycode)] default: return [56, Int(keycode)] } } return [Int(keycode)] } override func keyDown(with event: NSEvent) { // textField.stringValue = String(describing: event.characters!) print("KeDown: Code '\(event.keyCode)'") let typedKeyChars = keyDataManager.searchKeyChar(keyCode: genKeycodes(keycode: event.keyCode)) let typedKeyNums = keyDataManager.searchKeyNums(keyCodes: genKeycodesforNum(keycode: event.keyCode)) let typedKana = keyDataManager.searchKeyKana(keyCode: genKeycodes(keycode: event.keyCode)) print("typedKey: \(typedKeyChars)") typedKeyCharLabel.stringValue = ("Typed: \(typedKeyChars)") typedKeyKanaLabel.stringValue = ("Kana: \(typedKana)") sentenceManager.updateTypedKanaSentence(char: typedKeyChars, kana: typedKana) typedKanaSentenceLabel.stringValue = sentenceManager.typedKanaSentence kanaSampleSentenceLabel.attributedStringValue = sentenceManager.attributedKanaSampleSentence // typedKanaSentenceLabel.attributedStringValue = sentenceManager.AttributedTypedKanaSentence print("typedKeyNums: \(typedKeyNums)") // checkText(typedKey: typedChar) for keyNum in typedKeyNums { if keyNum == 61{ print("esc") }else { // タイプされたキーの色を変える keyViewList[keyNum].turnOn(color: keyColor.green) DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { self.keyViewList[keyNum].turnOffIf(color: keyColor.green) } } if sentenceManager.checkTypedSentence() { typedKanaSentenceLabel.stringValue = sentenceManager.typedKanaSentence sampleSentenceLabel.stringValue = sentenceManager.nowSampleSentence.sentence kanaSampleSentenceLabel.stringValue = sentenceManager.nowSampleSentence.kanaSentence } } for keyNum in sentenceManager.nextKeyNums { keyViewList[keyNum].turnOff() } for keyNum in sentenceManager.getNextKeyNums() { print("NextNum = \(keyNum)") keyViewList[keyNum].turnOn(color: keyColor.orange) } } override func flagsChanged(with event: NSEvent) { // print(event.keyCode) let typedKeyKana = keyDataManager.searchKeyKana(keyCode: [Int(event.keyCode)]) print("apple: \(typedKeyKana)") switch event.modifierFlags.intersection(.deviceIndependentFlagsMask) { case [.shift]: print("shift key is pressed") self.isShift = true if typedKeyKana == "left shift" { self.sideOfShift = side.left } if typedKeyKana == "right shift" { self.sideOfShift = side.right } case [.control]: print("control key is pressed") case [.option] : print("option key is pressed") case [.command]: print("Command key is pressed") case [.control, .shift]: print("control-shift keys are pressed") case [.option, .shift]: print("option-shift keys are pressed") case [.command, .shift]: print("command-shift keys are pressed") case [.control, .option]: print("control-option keys are pressed") case [.control, .command]: print("control-command keys are pressed") case [.option, .command]: print("option-command keys are pressed") case [.shift, .control, .option]: print("shift-control-option keys are pressed") case [.shift, .control, .command]: print("shift-control-command keys are pressed") case [.control, .option, .command]: print("control-option-command keys are pressed") case [.shift, .command, .option]: print("shift-command-option keys are pressed") case [.shift, .control, .option, .command]: print("shift-control-option-command keys are pressed") default: print("no modifier keys are pressed") self.isShift = false self.sideOfShift = side.none } } }
40.812
383
0.612173
26a9ec67f0a018fdfd75dc8f0095cddbf9ba420b
10,777
// // PasswordView.swift // // Created by rain on 4/21/16. // Copyright © 2016 Recruit Lifestyle Co., Ltd. All rights reserved. // import UIKit import LocalAuthentication public protocol PasswordInputCompleteProtocol: AnyObject { func passwordInputComplete(_ passwordContainerView: PasswordContainerView, input: String) func touchAuthenticationComplete(_ passwordContainerView: PasswordContainerView, success: Bool, error: Error?) } open class PasswordContainerView: UIView { //MARK: IBOutlet @IBOutlet open var passwordInputViews: [PasswordInputView]! @IBOutlet open weak var passwordDotView: PasswordDotView! @IBOutlet open weak var deleteButton: UIButton! @IBOutlet open weak var touchAuthenticationButton: UIButton! //MARK: Property open var deleteButtonLocalizedTitle: String = "" { didSet { deleteButton.setTitle(NSLocalizedString(deleteButtonLocalizedTitle, comment: ""), for: .normal) } } open weak var delegate: PasswordInputCompleteProtocol? fileprivate var touchIDContext = LAContext() fileprivate var inputString: String = "" { didSet { #if swift(>=3.2) passwordDotView.inputDotCount = inputString.count #else passwordDotView.inputDotCount = inputString.characters.count #endif checkInputComplete() } } open var isVibrancyEffect = false { didSet { configureVibrancyEffect() } } open override var tintColor: UIColor! { didSet { guard !isVibrancyEffect else { return } deleteButton.setTitleColor(tintColor, for: .normal) passwordDotView.strokeColor = tintColor touchAuthenticationButton.tintColor = tintColor passwordInputViews.forEach { $0.textColor = tintColor $0.borderColor = tintColor } } } open var highlightedColor: UIColor! { didSet { guard !isVibrancyEffect else { return } passwordDotView.fillColor = highlightedColor passwordInputViews.forEach { $0.highlightBackgroundColor = highlightedColor } } } open var isTouchAuthenticationAvailable: Bool { return touchIDContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } open var touchAuthenticationEnabled = false { didSet { let enable = (isTouchAuthenticationAvailable && touchAuthenticationEnabled) touchAuthenticationButton.alpha = enable ? 1.0 : 0.0 touchAuthenticationButton.isUserInteractionEnabled = enable } } open var touchAuthenticationReason = "Touch to unlock" //MARK: AutoLayout open var width: CGFloat = 0 { didSet { self.widthConstraint.constant = width } } fileprivate let kDefaultWidth: CGFloat = 288 fileprivate let kDefaultHeight: CGFloat = 410 fileprivate var widthConstraint: NSLayoutConstraint! fileprivate func configureConstraints() { let ratioConstraint = widthAnchor.constraint(equalTo: self.heightAnchor, multiplier: kDefaultWidth / kDefaultHeight) self.widthConstraint = widthAnchor.constraint(equalToConstant: kDefaultWidth) self.widthConstraint.priority = UILayoutPriority(rawValue: 999) NSLayoutConstraint.activate([ratioConstraint, widthConstraint]) } //MARK: VisualEffect open func rearrangeForVisualEffectView(in vc: UIViewController) { self.isVibrancyEffect = true self.passwordInputViews.forEach { passwordInputView in let label = passwordInputView.label label.removeFromSuperview() vc.view.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.addConstraints(fromView: label, toView: passwordInputView, constraintInsets: .zero) } } //MARK: Init open class func create(withDigit digit: Int) -> PasswordContainerView { let bundle = Bundle(for: self) let nib = UINib(nibName: "PasswordContainerView", bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! PasswordContainerView view.passwordDotView.totalDotCount = digit return view } open class func create(in stackView: UIStackView, digit: Int) -> PasswordContainerView { let passwordContainerView = create(withDigit: digit) stackView.addArrangedSubview(passwordContainerView) return passwordContainerView } //MARK: Life Cycle open override func awakeFromNib() { super.awakeFromNib() configureConstraints() backgroundColor = .clear passwordInputViews.forEach { $0.delegate = self } deleteButton.titleLabel?.adjustsFontSizeToFitWidth = true deleteButton.titleLabel?.minimumScaleFactor = 0.5 touchAuthenticationEnabled = true var image = touchAuthenticationButton.imageView?.image?.withRenderingMode(.alwaysTemplate) if #available(iOS 11, *) { if touchIDContext.biometryType == .faceID { let bundle = Bundle(for: type(of: self)) image = UIImage(named: "faceid", in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) } } touchAuthenticationButton.setImage(image, for: .normal) touchAuthenticationButton.tintColor = tintColor } //MARK: Input Wrong open func wrongPassword() { passwordDotView.shakeAnimationWithCompletion { self.clearInput() } } open func clearInput() { inputString = "" } //MARK: IBAction @IBAction func deleteInputString(_ sender: AnyObject) { #if swift(>=3.2) guard inputString.count > 0 && !passwordDotView.isFull else { return } inputString = String(inputString.dropLast()) #else guard inputString.characters.count > 0 && !passwordDotView.isFull else { return } inputString = String(inputString.characters.dropLast()) #endif } @IBAction func touchAuthenticationAction(_ sender: UIButton) { touchAuthentication() } open func touchAuthentication() { guard isTouchAuthenticationAvailable else { return } touchIDContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: touchAuthenticationReason) { (success, error) in DispatchQueue.main.async { if success { self.passwordDotView.inputDotCount = self.passwordDotView.totalDotCount // instantiate LAContext again for avoiding the situation that PasswordContainerView stay in memory when authenticate successfully self.touchIDContext = LAContext() } // delay delegate callback for the user can see passwordDotView input dots filled animation DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.delegate?.touchAuthenticationComplete(self, success: success, error: error) } } } } } private extension PasswordContainerView { func checkInputComplete() { #if swift(>=3.2) if inputString.count == passwordDotView.totalDotCount { delegate?.passwordInputComplete(self, input: inputString) } #else if inputString.characters.count == passwordDotView.totalDotCount { delegate?.passwordInputComplete(self, input: inputString) } #endif } func configureVibrancyEffect() { let whiteColor = UIColor.white let clearColor = UIColor.clear //delete button title color var titleColor: UIColor! //dot view stroke color var strokeColor: UIColor! //dot view fill color var fillColor: UIColor! //input view background color var circleBackgroundColor: UIColor! var highlightBackgroundColor: UIColor! var borderColor: UIColor! //input view text color var textColor: UIColor! var highlightTextColor: UIColor! if isVibrancyEffect { //delete button titleColor = whiteColor //dot view strokeColor = whiteColor fillColor = whiteColor //input view circleBackgroundColor = clearColor highlightBackgroundColor = whiteColor borderColor = clearColor textColor = whiteColor highlightTextColor = whiteColor } else { //delete button titleColor = tintColor //dot view strokeColor = tintColor fillColor = highlightedColor //input view circleBackgroundColor = whiteColor highlightBackgroundColor = highlightedColor borderColor = tintColor textColor = tintColor highlightTextColor = highlightedColor } deleteButton.setTitleColor(titleColor, for: .normal) passwordDotView.strokeColor = strokeColor passwordDotView.fillColor = fillColor touchAuthenticationButton.tintColor = strokeColor passwordInputViews.forEach { passwordInputView in passwordInputView.circleBackgroundColor = circleBackgroundColor passwordInputView.borderColor = borderColor passwordInputView.textColor = textColor passwordInputView.highlightTextColor = highlightTextColor passwordInputView.highlightBackgroundColor = highlightBackgroundColor passwordInputView.circleView.layer.borderColor = UIColor.white.cgColor //borderWidth as a flag, will recalculate in PasswordInputView.updateUI() passwordInputView.isVibrancyEffect = isVibrancyEffect } } } extension PasswordContainerView: PasswordInputViewTappedProtocol { public func passwordInputView(_ passwordInputView: PasswordInputView, tappedString: String) { #if swift(>=3.2) guard inputString.count < passwordDotView.totalDotCount else { return } #else guard inputString.characters.count < passwordDotView.totalDotCount else { return } #endif inputString += tappedString } }
36.532203
150
0.637098
e0863d37e2b9cc5c69edc75d23a45b7f14c2ac40
1,066
import Foundation enum HTTPMethod: String { case get = "GET" } protocol APIRequest { associatedtype Response var baseURL: URL { get } var path: String { get } var parameters: [String: Any]? { get } var method: HTTPMethod { get } func buildURL() -> URL func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response } extension APIRequest { var baseURL: URL { return URL(string: "https://spreadsheets.google.com/feeds/list/")! } var parameters: [String: Any]? { return nil } func buildURL() -> URL { let url = path.isEmpty ? baseURL : baseURL.appendingPathComponent(path) guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return url } if let parameters = parameters { components.queryItems = parameters.map { (key, value) in URLQueryItem(name: key, value: value as? String) } } return components.url ?? url } }
26
92
0.594747
d6a80b09c588311752081d069c6799dc63534581
2,303
// // Copyright 2016 Lionheart Software LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit public extension QuickTableViewRow where Self: RawRepresentable, Self.RawValue == Int { init(at indexPath: IndexPath) { self.init(at: indexPath.row) } init(at row: Int) { self.init(rawValue: row)! } static var count: Int { return lastRow.rawValue + 1 } static var lastRow: Self { var row = Self(rawValue: 0)! for i in 0..<Int.max { guard let _row = Self(rawValue: i) else { return row } row = _row } return row } } public extension QuickTableViewRowWithConditions where Self: RawRepresentable, Self.RawValue == Int { init(at indexPath: IndexPath, container: Container) { self.init(at: indexPath.row, container: container) } init(at row: Int, container: Container) { var row = row let _conditionalRows = Self.conditionalRows(for: container) for (conditionalRow, test) in _conditionalRows { if row >= conditionalRow.rawValue && !test { row += 1 } } self.init(rawValue: row)! } static func index(row: Self, container: Container) -> Int? { for i in 0..<count(for: container) { if row == Self(at: i, container: container) { return i } } return nil } static func count(for container: Container) -> Int { var count = lastRow.rawValue + 1 let _conditionalRows = conditionalRows(for: container) for (_, test) in _conditionalRows { if !test { count -= 1 } } return count } }
27.746988
101
0.597047
bb2f2b58813a0583348bd72a3d3f14e2dd750d1f
3,502
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation extension Model { /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used directly /// by host applications. The behavior of this may change without warning. Though it is not used by host application making any change /// to these `public` types should be backward compatible, otherwise it will be a breaking change. public static var schema: ModelSchema { // TODO load schema from JSON when this it not overridden by specific models ModelSchema(name: modelName, fields: [:]) } /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used directly /// by host applications. The behavior of this may change without warning. Though it is not used by host application making any change /// to these `public` types should be backward compatible, otherwise it will be a breaking change. public var schema: ModelSchema { type(of: self).schema } /// Utility function that enables a DSL-like `ModelSchema` definition. Instead of building /// objects individually, developers can use this to create the schema with a more fluid /// programming model. /// /// - Example: /// ```swift /// static let schema = defineSchema { model in /// model.fields( /// .field(name: "title", is: .required, ofType: .string) /// ) /// } /// ``` /// /// - Parameters /// - name: the name of the Model. Defaults to the class name /// - attributes: model attributes (aka "directives" or "annotations") /// - define: the closure used to define the model attributes and fields /// - Returns: a valid `ModelSchema` instance /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used directly /// by host applications. The behavior of this may change without warning. public static func defineSchema(name: String? = nil, attributes: ModelAttribute..., define: (inout ModelSchemaDefinition) -> Void) -> ModelSchema { var definition = ModelSchemaDefinition(name: name ?? modelName, attributes: attributes) define(&definition) return definition.build() } /// - Warning: Although this has `public` access, it is intended for internal & codegen use and should not be used directly /// by host applications. The behavior of this may change without warning. public static func rule(allow: AuthStrategy, ownerField: String? = nil, identityClaim: String? = nil, groupClaim: String? = nil, groups: [String] = [], groupsField: String? = nil, operations: [ModelOperation] = []) -> AuthRule { return AuthRule(allow: allow, ownerField: ownerField, identityClaim: identityClaim, groupClaim: groupClaim, groups: groups, groupsField: groupsField, operations: operations) } }
47.324324
140
0.599086
f5f03ce317bb84a861f12976346357e37fad12fd
705
// // AppDelegate.swift // farkle // // Created by Joe Lucero on 12/14/19. // Copyright © 2019 Joe Lucero. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // 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) } }
33.571429
179
0.748936
8aa81b417b4b6c4eb20de346af03b7c69854354c
1,382
import Foundation // 54. Spiral Matrix // https://leetcode.com/problems/spiral-matrix/ // Runtime: 0 ms // Memory Usage: 14.3 MB class Solution { func spiralOrder(_ matrix: [[Int]]) -> [Int] { guard !(matrix.isEmpty) else { return [] } var result = [Int]() var rBegin = 0, rEnd = matrix.count - 1 var cBegin = 0, cEnd = matrix[0].count - 1 while rBegin <= rEnd && cBegin <= cEnd { // MARK: Traverse right for i in stride(from: cBegin, to: cEnd + 1, by: 1) { result.append(matrix[rBegin][i]) } rBegin += 1 // MARK: Traverse down for i in stride(from: rBegin, to: rEnd + 1, by: 1) { result.append(matrix[i][cEnd]) } cEnd -= 1 // MARK: Traverse left if rBegin <= rEnd { for i in stride(from: cEnd, to: cBegin - 1, by: -1) { result.append(matrix[rEnd][i]) } } rEnd -= 1 // MARK: Traverse up if cBegin <= cEnd { for i in stride(from: rEnd, to: rBegin - 1, by: -1) { result.append(matrix[i][cBegin]) } } cBegin += 1 } return result } }
28.204082
69
0.432706
6730dafae8d017dd3da66b24c8bd3e82208c2574
208
import Foundation public extension Array { subscript(safe index: Int) -> Element? { guard index >= 0, index < endIndex else { return nil } return self[index] } }
17.333333
49
0.557692
16a785a582ff8b3f6d58f80d1f0f148a06485450
1,631
// // UEmptyDataSet.swift // ManHua // // Created by Soul on 26/11/2019. // Copyright © 2019 Soul. All rights reserved. // import Foundation import EmptyDataSet_Swift extension UIScrollView { private struct AssociatedKeys { static var uemptyKey: Void? } var uempty: UEmptyView? { get { return objc_getAssociatedObject(self, &AssociatedKeys.uemptyKey) as? UEmptyView } set { self.emptyDataSetDelegate = newValue self.emptyDataSetSource = newValue objc_setAssociatedObject(self, &AssociatedKeys.uemptyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } class UEmptyView: EmptyDataSetSource, EmptyDataSetDelegate { var image : UIImage? var allowShow: Bool = false var verticalOffset:CGFloat = 0 private var tapClosure: (() -> Void)? init(image:UIImage? = UIImage(named: "nodata"), verticalOffset: CGFloat = 0, tapClosure: (() ->Void)?) { self.image = image self.verticalOffset = verticalOffset self.tapClosure = tapClosure } func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat { return verticalOffset } internal func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? { return image } internal func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool { return allowShow } internal func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) { guard let tapClosure = tapClosure else { return } tapClosure() } }
27.183333
115
0.652974
2fb32e702c386d28d137c0c7edfbd0b4983ca08d
768
/* Copyright 2021 Microoled Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation extension Int16 { var asUInt8Array: [UInt8] { let msb = UInt8(truncatingIfNeeded: self >> 8) let lsb = UInt8(truncatingIfNeeded: self) return [msb, lsb] } }
28.444444
72
0.738281
6285964dfaff9712a6378061c28d9fb2a8bee61b
285
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { [ 1 class B<T where g: T protocol A { typealias F = B<c> ) class B<T where g T ( ) } var d { } struct c : B
19
87
0.691228
ed796c7a8a6358b6d552a9a2c69e1953a1966ca8
2,815
class OnboardingStepFlowFactory { static func viewController(for screen: ScreenType, with delegate: OnboardingFlowControllerDelegate? = nil) -> UIViewController { return getContainer(with: screen, delegate: delegate) } static func getStepperViewController(viewModel: Slider) -> UIViewController? { let storyboard = UIStoryboard(name: "OnboardingFlow", bundle: Bundle(for: SliderFlowViewController.self)) let containedViewController = storyboard.instantiateViewController(withIdentifier: String(describing: SliderFlowViewController.self)) as? SliderFlowViewController containedViewController?.setUpContentProvider(with: viewModel) return containedViewController } } private extension OnboardingStepFlowFactory { static func getContainer(with screen: ScreenType, delegate: OnboardingFlowControllerDelegate? = nil) -> UIViewController { switch screen { case .infoSlider: let storyboard = UIStoryboard(name: "OnboardingFlow", bundle: Bundle(for: SliderContainer.self)) guard let containedViewController = storyboard.instantiateViewController(withIdentifier: String(describing: SliderContainer.self)) as? SliderContainer else { return UIViewController() } containedViewController.delegate = delegate return containedViewController case .interests: let storyboard = UIStoryboard(name: "OnboardingFlow", bundle: Bundle(for: IntrestsContainer.self)) guard let containedViewController = storyboard.instantiateViewController(withIdentifier: String(describing: IntrestsContainer.self)) as? IntrestsContainer else { return UIViewController() } containedViewController.delegate = delegate return containedViewController case .discover: let storyboard = UIStoryboard(name: "OnboardingFlow", bundle: Bundle(for: DiscoverContainer.self)) guard let containedViewController = storyboard.instantiateViewController(withIdentifier: String(describing: DiscoverContainer.self)) as? DiscoverContainer else { return UIViewController() } containedViewController.delegate = delegate return containedViewController } } } public enum ScreenType: Equatable { case infoSlider case interests case discover } public enum Direction { case forward case backward } public protocol OnboardingFlowControllerDelegate: class { func didSkipOnboarding() func didCompleteOnboarding() }
51.181818
205
0.668561
fc17b39068e726efcbfb7e4ae5c9e3428fc90943
3,753
// Copyright (c) 2019 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation /// Reporter that creates an HTML report. /// It uses the html and javascript files from the Resources folder as templates public struct HtmlReporter: LogReporter { public func report(build: Any, output: ReporterOutput, rootOutput: String) throws { guard let steps = build as? BuildStep else { throw XCLogParserError.errorCreatingReport("Type not supported \(type(of: build))") } let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let json = try encoder.encode(steps.flatten()) guard let jsonString = String(data: json, encoding: .utf8) else { throw XCLogParserError.errorCreatingReport("Can't generate the JSON file.") } try writeHtmlReport(for: steps, jsonString: jsonString, output: output, rootOutput: rootOutput) } private func writeHtmlReport(for build: BuildStep, jsonString: String, output: ReporterOutput, rootOutput: String) throws { var path = "build/xclogparser/reports" if let output = output as? FileOutput { path = output.path } if !rootOutput.isEmpty { path = FileOutput(path: rootOutput).path } let fileManager = FileManager.default var buildDir = "\(path)/\(dirFor(build: build))" if !rootOutput.isEmpty { buildDir = path } try fileManager.createDirectory( atPath: "\(buildDir)/css", withIntermediateDirectories: true, attributes: nil) try fileManager.createDirectory( atPath: "\(buildDir)/js", withIntermediateDirectories: true, attributes: nil) try HtmlReporterResources.css.write(toFile: "\(buildDir)/css/styles.css", atomically: true, encoding: .utf8) try HtmlReporterResources.appJS.write(toFile: "\(buildDir)/js/app.js", atomically: true, encoding: .utf8) try HtmlReporterResources.indexHTML.write(toFile: "\(buildDir)/index.html", atomically: true, encoding: .utf8) try HtmlReporterResources.stepJS.write(toFile: "\(buildDir)/js/step.js", atomically: true, encoding: .utf8) try HtmlReporterResources.stepHTML.write(toFile: "\(buildDir)/step.html", atomically: true, encoding: .utf8) let jsContent = HtmlReporterResources.buildJS.replacingOccurrences(of: "{{build}}", with: jsonString) try jsContent.write(toFile: "\(buildDir)/js/build.js", atomically: true, encoding: .utf8) print("Report written to \(buildDir)/index.html") } private func dirFor(build: BuildStep) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYYMMddHHmmss" return dateFormatter.string(from: Date(timeIntervalSince1970: Double(build.startTimestamp))) } }
47.506329
118
0.667999
ed39d81896d7a8405e55708dba23b5b8a87ec69f
1,963
// // ItemStore.swift // loaner // // Created by Samuel Folledo on 6/20/20. // Copyright © 2020 LinnierGames. All rights reserved. // import UIKit import CoreData enum FetchItemsResult { case success([Item]) case failure(Error) } class ItemStore: NSObject { let persistentContainer: NSPersistentContainer = { // creates the NSPersistentContainer object // must be given the name of the Core Data model file “LoanedItems” let container = NSPersistentContainer(name: "LoanedItems") // load the saved database if it exists, creates it if it does not, and returns an error under failure conditions container.loadPersistentStores { (description, error) in if let error = error { print("Error setting up Core Data (\(error)).") } } return container }() // MARK: - Save Core Data Context func saveContext() { let viewContext = persistentContainer.viewContext if viewContext.hasChanges { do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } func fetchPersistedData(completion: @escaping (FetchItemsResult) -> Void) { let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest() let viewContext = persistentContainer.viewContext do { let allItems = try viewContext.fetch(fetchRequest) completion(.success(allItems)) } catch { completion(.failure(error)) } } }
33.271186
199
0.624554
9bcb8d405bfdc0b8247ab9c0b9f623d369b42c8b
3,452
// // ProductDetailViewController.swift // clojushop_client_ios // // Created by ischuetz on 07/06/2014. // Copyright (c) 2014 ivanschuetz. All rights reserved. // import Foundation class ProductDetailViewController: BaseViewController, ListViewControllerDelegate, UISplitViewControllerDelegate { @IBOutlet var productNameLabel:UILabel! @IBOutlet var productBrandLabel:UILabel! @IBOutlet var productPriceLabel:UILabel! @IBOutlet var productLongDescrLabel:UILabel! @IBOutlet var productImageview:UIImageView! @IBOutlet var addToCartButton:UIButton! @IBOutlet var pleaseSelectView:UIView! @IBOutlet var containerView:UIView! var product:Product! override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func listViewController( // lvc: ProductsListViewController, product: Product) { self.product = product if (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) { self.initViews() } } func splitViewController(svc: UISplitViewController!, willHideViewController aViewController: UIViewController!, withBarButtonItem barButtonItem: UIBarButtonItem!, forPopoverController pc: UIPopoverController!) { barButtonItem.title = "List" self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true) } func initViews() { pleaseSelectView.hidden = true self.title = product.name productNameLabel.text = product.name productBrandLabel.text = product.seller productPriceLabel.text = String(format:"%.2f", product.price) productLongDescrLabel.text = product.descr productImageview.setImageWithURL(NSURL(string: product.imgDetails)) } func splitViewController(svc: UISplitViewController!, aViewController: UIViewController!, button: UIBarButtonItem!) { if button == self.navigationItem.leftBarButtonItem { self.navigationItem.setLeftBarButtonItem(nil, animated: true) } } func showMaster() { //TODO (master visible on iPad, the first time) // [self.navigationItem.leftBarButtonItem.target performSelector:self.navigationItem.leftBarButtonItem.action withObject:self.navigationItem]; } override func viewDidLoad() { super.viewDidLoad() if UIInterfaceOrientation.Portrait == self.interfaceOrientation || UIInterfaceOrientation.PortraitUpsideDown == self.interfaceOrientation { showMaster() } if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone { self.initViews() //in phone we passed the product before launching the controller } else { pleaseSelectView.hidden = false //in ipad at start this controller is visible, and no product selected yet } } @IBAction func onAddToCartPress(sender : UIButton) { DataStore.sharedDataStore().addToCart(product.id, successHandler: {() -> Void in DialogUtils.showAlert("Success", msg: "Added!") }, failureHandler: {(Int) -> Bool in return false}) } }
36.336842
216
0.681634
335776b6d37d133d3c7ca74c8208fae4e3abec5f
3,424
import Foundation class TD3 { static let lineLength = 44 fileprivate let finalCheckDigit: String? let documentType: MRZField let countryCode: MRZField let names: MRZField let documentNumber: MRZField let nationality: MRZField let birthdate: MRZField let sex: MRZField let expiryDate: MRZField let personalNumber: MRZField fileprivate lazy var allCheckDigitsValid: Bool = { if let checkDigit = finalCheckDigit { let compositedValue = [documentNumber, birthdate, expiryDate, personalNumber].reduce("", { ($0 + $1.rawValue + $1.checkDigit!) }) let isCompositedValueValid = MRZField.isValueValid(compositedValue, checkDigit: checkDigit) return (documentNumber.isValid! && birthdate.isValid! && expiryDate.isValid! && personalNumber.isValid! && isCompositedValueValid) } else { return (documentNumber.isValid! && birthdate.isValid! && expiryDate.isValid!) } }() lazy var result: MRZResult = { let (surnames, givenNames) = names.value as! (String, String) return MRZResult( documentType: documentType.value as! String, countryCode: countryCode.value as! String, surnames: surnames, givenNames: givenNames, documentNumber: documentNumber.value as! String, nationalityCountryCode: nationality.value as! String, birthdate: birthdate.value as! Date?, sex: sex.value as! String?, expiryDate: expiryDate.value as! Date?, personalNumber: personalNumber.value as! String, personalNumber2: nil, isDocumentNumberValid: documentNumber.isValid!, isBirthdateValid: birthdate.isValid!, isExpiryDateValid: expiryDate.isValid!, isPersonalNumberValid: personalNumber.isValid, allCheckDigitsValid: allCheckDigitsValid ) }() init(from mrzLines: [String], using formatter: MRZFieldFormatter) { let (firstLine, secondLine) = (mrzLines[0], mrzLines[1]) let isVisaDocument = (firstLine.substring(0, to: 0) == "V") // MRV-A type documentType = formatter.field(.documentType, from: firstLine, at: 0, length: 2) countryCode = formatter.field(.countryCode, from: firstLine, at: 2, length: 3) names = formatter.field(.names, from: firstLine, at: 5, length: 39) documentNumber = formatter.field(.documentNumber, from: secondLine, at: 0, length: 9, checkDigitFollows: true) nationality = formatter.field(.nationality, from: secondLine, at: 10, length: 3) birthdate = formatter.field(.birthdate, from: secondLine, at: 13, length: 6, checkDigitFollows: true) sex = formatter.field(.sex, from: secondLine, at: 20, length: 1) expiryDate = formatter.field(.expiryDate, from: secondLine, at: 21, length: 6, checkDigitFollows: true) if isVisaDocument { personalNumber = formatter.field(.optionalData, from: secondLine, at: 28, length: 16) finalCheckDigit = nil } else { personalNumber = formatter.field(.personalNumber, from: secondLine, at: 28, length: 14, checkDigitFollows: true) finalCheckDigit = formatter.field(.hash, from: secondLine, at: 43, length: 1).rawValue } } }
44.467532
142
0.642523
9c581ca1ec2516a734ba3065ae3bcae815bd1e22
4,894
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest import CwlPreconditionTesting @testable import Amplify @testable import AmplifyTestCommon class ConfigurationTests: XCTestCase { override func setUp() { Amplify.reset() } // Remember, this test must be invoked with a category that doesn't include an Amplify-supplied default plugin func testPreconditionFailureInvokingWithNoPlugin() throws { let amplifyConfig = AmplifyConfiguration() try Amplify.configure(amplifyConfig) let exception: BadInstructionException? = catchBadInstruction { _ = Amplify.API.get(request: RESTRequest()) { _ in } } XCTAssertNotNil(exception) } // Remember, this test must be invoked with a category that doesn't include an Amplify-supplied default plugin func testPreconditionFailureInvokingBeforeConfig() throws { let plugin = MockAPICategoryPlugin() try Amplify.add(plugin: plugin) // Remember, this test must be invoked with a category that doesn't include an Amplify-supplied default plugin let exception: BadInstructionException? = catchBadInstruction { _ = Amplify.API.get(request: RESTRequest()) { _ in } } XCTAssertNotNil(exception) } func testConfigureDelegatesToPlugins() throws { let configureWasInvoked = expectation(description: "Plugin configure() was invoked") let plugin = MockLoggingCategoryPlugin() plugin.listeners.append { message in if message == "configure(using:)" { configureWasInvoked.fulfill() } } try Amplify.add(plugin: plugin) let loggingConfig = LoggingCategoryConfiguration( plugins: ["MockLoggingCategoryPlugin": true] ) let amplifyConfig = AmplifyConfiguration(logging: loggingConfig) try Amplify.configure(amplifyConfig) wait(for: [configureWasInvoked], timeout: 1.0) } func testMultipleConfigureCallsThrowError() throws { let amplifyConfig = AmplifyConfiguration() try Amplify.configure(amplifyConfig) XCTAssertThrowsError(try Amplify.configure(amplifyConfig), "Subsequent calls to configure should throw") { error in guard case ConfigurationError.amplifyAlreadyConfigured = error else { XCTFail("Expected ConfigurationError.amplifyAlreadyConfigured error") return } } } func testResetClearsPreviouslyAddedPlugins() throws { let plugin = MockLoggingCategoryPlugin() try Amplify.add(plugin: plugin) let loggingConfig = LoggingCategoryConfiguration( plugins: ["MockLoggingCategoryPlugin": true] ) let amplifyConfig = AmplifyConfiguration(logging: loggingConfig) try Amplify.configure(amplifyConfig) XCTAssertNotNil(try Amplify.Logging.getPlugin(for: "MockLoggingCategoryPlugin")) Amplify.reset() XCTAssertThrowsError(try Amplify.Logging.getPlugin(for: "MockLoggingCategoryPlugin"), "Plugins should be reset") { error in guard case LoggingError.configuration = error else { XCTFail("Expected PluginError.noSuchPlugin error") return } } } func testResetDelegatesToPlugins() throws { let plugin = MockLoggingCategoryPlugin() let resetWasInvoked = expectation(description: "Reset was invoked") plugin.listeners.append { message in if message == "reset" { resetWasInvoked.fulfill() } } try Amplify.add(plugin: plugin) let loggingConfig = LoggingCategoryConfiguration( plugins: ["MockLoggingCategoryPlugin": true] ) let amplifyConfig = AmplifyConfiguration(logging: loggingConfig) try Amplify.configure(amplifyConfig) Amplify.reset() wait(for: [resetWasInvoked], timeout: 1.0) } func testResetAllowsReconfiguration() throws { let amplifyConfig = AmplifyConfiguration() try Amplify.configure(amplifyConfig) Amplify.reset() XCTAssertNoThrow(try Amplify.configure(amplifyConfig)) } func testDecodeConfiguration() throws { let jsonString = """ {"UserAgent":"aws-amplify-cli/2.0","Version":"1.0","storage":{"plugins":{"MockStorageCategoryPlugin":{}}}} """ let jsonData = jsonString.data(using: .utf8)! let decoder = JSONDecoder() let config = try decoder.decode(AmplifyConfiguration.self, from: jsonData) XCTAssertNotNil(config.storage) } }
35.463768
118
0.645893
d62d00254ce2db2350487ac0116560d43cf39afc
2,663
// // RuleVariantsTest.swift // Featureflow // // Created by Max Mattini on 21/06/2017. // Copyright © 2017 Max Mattini. All rights reserved. // import XCTest @testable import featureflowiossdk class RuleVariantsTest: 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 testDefaultOnVariant() { let rule = Rule() let onId = "onId" let offId = "ioffId" rule.variantSplits = [ VariantSplit(variantKey:onId, split:100), VariantSplit(variantKey:offId, split:0)] XCTAssertEqual(onId, rule.getVariantSplitKey(contextKey: "oliver", featureKey: "f1", salt: "1")) } func testDefaultOffVariant() { let rule = Rule() let onId = "onId" let offId = "ioffId" rule.variantSplits = [ VariantSplit(variantKey:onId, split:0), VariantSplit(variantKey:offId, split:100)] XCTAssertEqual(offId, rule.getVariantSplitKey(contextKey: "oliver", featureKey: "f1", salt: "1")) } func testMultiVariant() { let rule = Rule() let id1 = "id1" let id2 = "id2" let id3 = "id3" rule.variantSplits = [ VariantSplit(variantKey:id1, split:10), VariantSplit(variantKey:id2, split:60), VariantSplit(variantKey:id3, split:30)] XCTAssertEqual(id1, rule.getVariantSplitKey(contextKey: "oliver", featureKey: "f1", salt: "1")) XCTAssertEqual(id2, rule.getVariantSplitKey(contextKey: "alan", featureKey: "f1", salt: "1")) XCTAssertEqual(id2, rule.getVariantSplitKey(contextKey: "sarah", featureKey: "f1", salt: "1")) } // NOTE this test has no assertion. Same as Java test func testGetVariantValue(){ let values = [ "alice", "bob", "charlie", "daniel", "emma", "frank", "george"] let seeds = ["1","2","3"] for seed in seeds { print("SEED is " + seed); for value in values { let rule = Rule() let hash = rule.getHash(contextKey: value, featureKey: "f1", salt: seed) let variantValue = rule.getVariantValue(hash: hash!) print("\(value) equals \(variantValue)") } } } }
31.329412
151
0.568156
46d3d19d6c3c56a02e2c2d638817f43c27378837
557
struct SomeType { private func read(json: String) -> SomeType { // do something to create a SomeType return SomeType() } public func create() -> SomeType { // when only a single line exists and it's the // return, no need for the return keyword SomeType() } public func run(_ name: String) -> Void { } public func log(message m: String) -> Void { print(m) } } // Example let someType = SomeType() someType.run("DiscardParameterName") someType.log(message: "SomeMessage")
21.423077
55
0.605027
1dffede157b3d77a2de790a5fae87e626734fb7c
2,085
// // LoginViewController.swift // Github // // Created by jewelz on 2017/3/19. // Copyright © 2017年 jewelz. All rights reserved. // import UIKit import Alamofire import ModelSwift class LoginViewController: UIViewController { // MARK: - lift cycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white let webView = UIWebView(frame: SCREEN_RECT) let request = URLRequest(url: URL(string: OAUTH_URL)!) webView.delegate = self webView.loadRequest(request) view.addSubview(webView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func signIn(with token: String) { UserManager.shared.save(token) Alamofire.request(USER_INFO_URL + token).responseJSON { response in guard let json = response.result.value else { return } //debugPrint(json) let user = (json ~> User.self)! UserManager.shared.save(user) let window = (UIApplication.shared.delegate as! AppDelegate).window window?.rootViewController = MainTabBarController() } } } extension LoginViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = (request.url?.absoluteString)! if !url.hasPrefix("app://token") { return true } let token = url.components(separatedBy: "=").last! print("token: \(token)") signIn(with: token) return false } func webViewDidFinishLoad(_ webView: UIWebView) { print("did load: \(webView.request)") } }
25.426829
130
0.593285
013d3923ba97887d99c9686286479023078edabb
23,866
// // ScriptTokenizerTests.swift // Outlander // // Created by Joe McBride on 2/18/21. // Copyright © 2021 Joe McBride. All rights reserved. // import XCTest class ScriptTokenizerTests: XCTestCase { func test_comments() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("# a comment") switch token { case let .comment(text): XCTAssertEqual(text, "# a comment") default: XCTFail("wrong token value") } } func test_echo() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("echo hello world") switch token { case let .echo(text): XCTAssertEqual(text, "hello world") default: XCTFail("wrong token value") } } func test_exit() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("exit") switch token { case .exit: XCTAssertTrue(true) default: XCTFail("wrong token value") } } func test_goto() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("goto label") switch token { case let .goto(label, args): XCTAssertEqual(label, "label") XCTAssertEqual(args, "") default: XCTFail("wrong token value") } } func test_tokenizes_goto_with_args() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("goto label arg1 arg2") switch token { case let .goto(label, args): XCTAssertEqual(label, "label") XCTAssertEqual(args, "arg1 arg2") default: XCTFail("wrong token value") } } func test_labels() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("mylabel:") switch token { case let .label(label): XCTAssertEqual(label, "mylabel") default: XCTFail("wrong token value") } } func test_ignores_text_after_label() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("mylabel: something something") switch token { case let .label(label): XCTAssertEqual(label, "mylabel") default: XCTFail("wrong token value") } } func test_match() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("match one two") switch token { case let .match(label, value): XCTAssertEqual(label, "one") XCTAssertEqual(value, "two") default: XCTFail("wrong token value") } } func test_matchre() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("matchre one two") switch token { case let .matchre(label, value): XCTAssertEqual(label, "one") XCTAssertEqual(value, "two") default: XCTFail("wrong token value: \(String(describing: token))") } } func test_put() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("put hello friends") switch token { case let .put(put): XCTAssertEqual(put, "hello friends") default: XCTFail("wrong token value") } } func test_put_with_commands() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("put #echo a message") switch token { case let .put(put): XCTAssertEqual(put, "#echo a message") default: XCTFail("wrong token value") } } func test_waitfor() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("waitfor abcd") switch token { case let .waitfor(msg): XCTAssertEqual(msg, "abcd") default: XCTFail("wrong token value") } } func test_action() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("action put hello when Sorry") switch token { case let .action(className, action, trigger): XCTAssertEqual(className, "") XCTAssertEqual(action, "put hello") XCTAssertEqual(trigger, "Sorry") default: XCTFail("wrong token value") } } func test_action_with_class() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("action (mapper) put hello when Sorry") switch token { case let .action(className, action, trigger): XCTAssertEqual(className, "mapper") XCTAssertEqual(action, "put hello") XCTAssertEqual(trigger, "Sorry") default: XCTFail("wrong token value") } } func test_action_toggle() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("action (mapper) on") switch token { case let .actionToggle(className, toggle): XCTAssertEqual(className, "mapper") XCTAssertEqual(toggle, "on") default: XCTFail("wrong token value") } } func test_action_invalid() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("action whoops") XCTAssertNil(token) } func test_action_eval() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("action put hello when eval 1==1") switch token { case let .actionEval(className, action, expression): XCTAssertEqual(className, "") XCTAssertEqual(action, "put hello") switch expression { case let .value(txt): XCTAssertEqual(txt, "1==1") default: XCTFail("wrong expression value") } default: XCTFail("wrong token value") } } func test_action_eval_with_class() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("action (myclass) put hello when eval $bleeding = 1") switch token { case let .actionEval(className, action, expression): XCTAssertEqual(className, "myclass") XCTAssertEqual(action, "put hello") switch expression { case let .value(txt): XCTAssertEqual(txt, "$bleeding = 1") default: XCTFail("wrong expression value") } default: XCTFail("wrong token value") } } func test_if_arg_0_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if_0 then echo hello") switch token { case let .ifArgSingle(number, command): XCTAssertEqual(number, 0) switch command { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong command value, found \(String(describing: command.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_arg_0_no_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if_0 echo hello") switch token { case let .ifArgSingle(number, command): XCTAssertEqual(number, 0) switch command { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong command value, found \(String(describing: command.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_arg_0_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if_0 { ") switch token { case let .ifArg(number): XCTAssertEqual(number, 0) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_arg_0_brace_with_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if_0 then { ") switch token { case let .ifArg(number): XCTAssertEqual(number, 0) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_arg_0_needs_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if_0 ") switch token { case let .ifArgNeedsBrace(number): XCTAssertEqual(number, 0) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_arg_0_needs_brace_with_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if_0 then ") switch token { case let .ifArgNeedsBrace(number): XCTAssertEqual(number, 0) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_single() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if 1==1 then echo hello ") switch token { case let .ifSingle(expression, token): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_single_parens_no_spaces() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if(1==1) then echo hello ") switch token { case let .ifSingle(expression, token): switch expression { case let .value(text): XCTAssertEqual(text, "(1==1)") switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_with_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if 1==1 {") switch token { case let .if(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_with_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if 1==1 then {") switch token { case let .if(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_with_brace_and_then_scenario_2() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if $powerwalk == 1 then {") switch token { case let .if(expression): switch expression { case let .value(text): XCTAssertEqual(text, "$powerwalk == 1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_with_brace_parens_no_spaces() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if(1==1){") switch token { case let .if(expression): switch expression { case let .value(text): XCTAssertEqual(text, "(1==1)") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_without_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if 1==1") switch token { case let .ifNeedsBrace(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_if_without_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("if 1==1 then") switch token { case let .ifNeedsBrace(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_single_line() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else if 1==1 then echo hello") switch token { case let .elseIfSingle(expression, token): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_single_line_with_brackets() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else if 1==1 { echo hello }") switch token { case let .elseIfSingle(expression, token): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_single_line_with_brackets_no_spaces() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else if 1==1 {echo hello}") switch token { case let .elseIfSingle(expression, token): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_with_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else if 1==1 {") switch token { case let .elseIf(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_with_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else if 1==1 then {") switch token { case let .elseIf(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_without_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else if 1==1") switch token { case let .elseIfNeedsBrace(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_without_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else if 1==1 then") switch token { case let .elseIfNeedsBrace(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_with_leading_brace_without_end_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("} else if 1==1 then") switch token { case let .elseIfNeedsBrace(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_if_with_leading_brace_with_end_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("} else if 1==1 then {") switch token { case let .elseIf(expression): switch expression { case let .value(text): XCTAssertEqual(text, "1==1") default: XCTFail("wrong expression value, found \(String(describing: expression.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_with_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else {") switch token { case .else: XCTAssertTrue(true) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_with_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else then {") switch token { case .else: XCTAssertTrue(true) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_without_brace() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else") switch token { case .elseNeedsBrace: XCTAssertTrue(true) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_without_brace_and_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else then") switch token { case .elseNeedsBrace: XCTAssertTrue(true) default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_single_line_with_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else then echo hello") switch token { case let .elseSingle(token): switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_single_line_without_then() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else echo hello") switch token { case let .elseSingle(token): switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } func test_else_single_line_without_then_with_brackets() throws { let tokenizer = ScriptTokenizer() let token = tokenizer.read("else { echo hello }") switch token { case let .elseSingle(token): switch token { case let .echo(text): XCTAssertEqual(text, "hello") default: XCTFail("wrong value, found \(String(describing: token.description))") } default: XCTFail("wrong token value, found \(String(describing: token?.description))") } } }
31.568783
102
0.556189
ff1f1d3d689b09eb1b162ec8add7177fec275a15
2,793
// // CardUIRow.swift // VoiceAssistant // // Created by Andrii Horishnii on 13.01.2021. // import AdaptiveCardUI import SwiftUI import DirectLine struct CardUIRow: View { private enum Constants { static let cardCornerRadius: CGFloat = 4 static let cardBorderColor = Color.primary.opacity(0.25) static let cardBorderWidth: CGFloat = 0.5 static let maxCardWidth: CGFloat = 400 } let message: MessageInfo var body: some View { if let attachmentLayout = message.attachmentLayout { if attachmentLayout == AttachmentLayout.carousel { ScrollView(.horizontal, showsIndicators: false) { HStack(alignment: .top, spacing: 4, content: { ForEach(message.adaptiveCards, id: \.self) { card in adaptiveCardView(card) } }) } } else { ScrollView(.vertical, showsIndicators: false) { VStack(alignment: .leading, spacing: 4, content: { ForEach(message.adaptiveCards, id: \.self) { card in adaptiveCardView(card) } }) } } } else { if let card = message.adaptiveCards.first { adaptiveCardView(card) } else { EmptyView() } } } func adaptiveCardView(_ adaptiveCard: AdaptiveCard) -> AnyView { AnyView(AdaptiveCardView(adaptiveCard) .clipShape(RoundedRectangle(cornerRadius: Constants.cardCornerRadius)) .overlay( RoundedRectangle(cornerRadius: Constants.cardCornerRadius) .strokeBorder(Constants.cardBorderColor, lineWidth: Constants.cardBorderWidth) ) .frame(maxWidth: Constants.maxCardWidth) .padding() .actionSetConfiguration(ActionSetConfiguration(actionsOrientation: .horizontal)) // .customCardElement { StarCountView($0) } // .customCardElement { RepoLanguageView($0) } .onImageStyle(.default, apply: RoundedImageStyle()) .buttonStyle(CapsuleButtonStyle()) .animation(.default)) } } struct RoundedImageStyle: CustomImageStyle { func makeBody(content: Content) -> some View { content.clipShape(RoundedRectangle(cornerRadius: 4)) } } struct CardUIRow_Previews: PreviewProvider { static var previews: some View { CardUIRow(message: Messages.mockAdaptiveCardMessageInfo()) } }
35.35443
106
0.548156
d93adfc3a3f2200974cfe2fc7be2976eaec98255
3,026
// // Request.swift // Movies // // Created by Prince Alvin Yusuf on 20/06/2021. // Copyright © 2021 Prince Alvin Yusuf. All rights reserved. // import UIKit class Request: NSObject { private let timeoutInterval: TimeInterval = 30 private let cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy private let headers = Headers() private enum HTTPMethod: String { case get = "GET" } private let urlString: String init(url: String) { urlString = url } func get<T: Decodable>(params: Params? = nil, completion: @escaping Response<T>) { var urlComponents = URLComponents(string: urlString) var items: [URLQueryItem] = [] if let params = params { for (key,value) in params { items.append(URLQueryItem(name: key, value: value)) } } items = items.filter{!$0.name.isEmpty} if !items.isEmpty { urlComponents?.queryItems = items } guard let url = urlComponents?.url else { return } print(url.absoluteString) var urlRequest = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval) urlRequest.httpMethod = HTTPMethod.get.rawValue urlRequest.allHTTPHeaderFields = headers.values URLSession.shared.dataTask(with: urlRequest) { data, response, error in if let httpURLResponse = response as? HTTPURLResponse, let data = data { switch httpURLResponse.statusCode { case 200...300: let jsonDecoder = JSONDecoder() do { let model = try jsonDecoder.decode(T.self, from: data) DispatchQueue.main.async { completion(Result.success(model)) } } catch { DispatchQueue.main.async { completion(Result.error(ErrorModel.defaultModel)) } } case 301...500: let jsonDecoder = JSONDecoder() do { let errorModel = try jsonDecoder.decode(ErrorModel.self, from: data) DispatchQueue.main.async { completion(Result.error(errorModel)) } } catch { DispatchQueue.main.async { completion(Result.error(ErrorModel.defaultModel)) } } default: DispatchQueue.main.async { completion(Result.error(ErrorModel.defaultModel)) } } } else { DispatchQueue.main.async { completion(Result.error(ErrorModel.defaultModel)) } } }.resume() } }
35.186047
105
0.508923
b952de7338f4129621e0745e4a48cd75be5b4a62
1,253
import XCTest @testable import xkcd_viewer class FavoritesViewModelTests: XCTestCase { // MARK: - Setup var viewModel: FavoritesViewModel! let storageService: StorageService = StorageService(fileName: Constants.Comic.storageFileName) override func setUpWithError() throws { Constants.Mode.appMode = .mock viewModel = FavoritesViewModel() } override func tearDownWithError() throws { viewModel = nil } // MARK: - Tests func test_Update_Favorites() { XCTAssertTrue(viewModel.favoriteItems.isEmpty) var favorites: [Comic]? = storageService.fetch() viewModel.updateFavorites() XCTAssertEqual(viewModel.favoriteItems.count, favorites?.count) favorites?.append(Comic(num: 4000, day: nil, month: nil, year: nil, title: nil, alt: nil, img: nil, imageData: nil)) storageService.save(object: favorites) viewModel.updateFavorites() XCTAssertEqual(viewModel.favoriteItems.count, favorites?.count) favorites = favorites?.dropLast() storageService.save(object: favorites) viewModel.updateFavorites() XCTAssertEqual(viewModel.favoriteItems.count, favorites?.count) } }
30.560976
124
0.675978
4afc627e7faf2413435625afe05dd9e068dba2c8
5,453
// // ViewController.swift // Glenna // // Created by dennis on 11/9/16. // Copyright © 2016 Dennis Xu, Vanessa Wu, William Yang. All rights reserved. // import UIKit import GoogleMaps extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } } class ViewController: UIViewController, GMSMapViewDelegate, UITableViewDelegate { @IBOutlet weak var addEventButton: UIBarButtonItem! var locations = [[String]]() var locationNames = [String]() override func loadView() { // Create a GMSCameraPosition that tells the map to display the // coordinate -33.86,151.20 at zoom level 6. let camera = GMSCameraPosition.camera(withLatitude: 36.001636, longitude: -78.9387, zoom: 16.0) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) mapView.isMyLocationEnabled = true mapView.delegate = self view = mapView getData() { (result) -> Void in self.locations = result for location in self.locations { self.locationNames.append(location[0]) } DispatchQueue.main.sync { // Creates markers for location in self.locations { self.createMarker(latitude: Double(location[1])!, longitude: Double(location[2])!, title: location[0], mapView: mapView) } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.hideKeyboardWhenTappedAround() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func createMarker(latitude: Double, longitude: Double, title: String, mapView: GMSMapView) { let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude)) marker.title = title marker.map = mapView } func mapView(_ didTapmapView: GMSMapView, didTapInfoWindowOfMarker marker: GMSMarker) -> Bool { // add code to display popup list of events var location = marker.title var parameter = [AnyObject]() parameter.append(location as AnyObject) self.performSegue(withIdentifier: "toEventPage", sender: parameter) return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "toEventPage") { let secondViewController = segue.destination as! EventsListTableViewController // let location = sender as! String let parameter = sender as! [AnyObject] secondViewController.mode = 0 secondViewController.parameters = parameter } if (segue.identifier == "toAddEvent"){ let secondViewController = segue.destination as! AddEventViewController secondViewController.locationsArr = locationNames } if (segue.identifier == "toUserEventPage"){ let secondViewController = segue.destination as! EventsListTableViewController secondViewController.mode = 1 } } func getData(withCompletionHandler:@escaping (_ result:[[String]]) -> Void){ var listofLocations = [[String]]() let requestURL: NSURL = NSURL(string: "https://cs316-glenna.herokuapp.com/locations")! let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL) urlRequest.httpMethod = "GET" let session = URLSession.shared let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) -> Void in let httpResponse = response as! HTTPURLResponse let statusCode = httpResponse.statusCode if (statusCode == 200) { //print("Everything is fine, file downloaded successfully.") do{ let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [[String:AnyObject]] for postInfo in json { var location = [String]() if let name = postInfo["name"] { location.append(name as! String) } if let x = postInfo["x"] { let xString = String(describing: x) location.append(xString) } if let y = postInfo["y"] { let yString = String(describing: y) location.append(yString) } listofLocations.append(location) } withCompletionHandler(listofLocations) }catch { print("Error with Json: \(error)") } } } task.resume() } }
37.095238
140
0.579681
bfb5d424164e9fd339f72b16d3b6040f7a808c5b
63,948
/* file: surface_or_solid_model.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -TYPE DEFINITION in EXPRESS /* TYPE surface_or_solid_model = SELECT ( solid_model (*ENTITY*), surface_model (*SELECT*) ); END_TYPE; -- surface_or_solid_model (line:5680 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES FOR SELECT /* solid_model (*ENTITY*): ATTR: offset_distance: (AMBIGUOUS (CASE LEVEL)) ATTR: slot_width: positive_length_measure ATTR: end_exit_faces: LIST [2 : 2] OF SET [0 : ?] OF face_surface ATTR: replicate_count: positive_integer ATTR: radius_list: LIST [2 : ?] OF positive_length_measure ATTR: angular_spacing: plane_angle_measure ATTR: offset1: length_measure ATTR: floor_blend_radius: non_negative_length_measure ATTR: second_trim_condition: (AMBIGUOUS (CASE LEVEL)) ATTR: offset2: length_measure ATTR: base_element: generalized_surface_select ATTR: radial_alignment: BOOLEAN ATTR: segment_radii: LIST [1 : segments] OF positive_length_measure ATTR: left_offset: BOOLEAN ATTR: row_spacing: length_measure ATTR: tip_radius: non_negative_length_measure ATTR: thickness: length_measure ATTR: reference_surface: surface ATTR: tee_section_width: positive_length_measure ATTR: fillet_radius: non_negative_length_measure ATTR: first_trim_intent: trim_intent ATTR: second_trim_intent: trim_intent ATTR: inner_radius: positive_length_measure ATTR: protrusion_height: positive_length_measure ATTR: row_count: positive_integer ATTR: pocket_length: positive_length_measure ATTR: external_groove: BOOLEAN ATTR: replicated_element: modified_solid_with_placed_configuration ATTR: swept_face: face_surface ATTR: end_conditions: LIST [2 : 2] OF blend_end_condition_select ATTR: end_param: (AMBIGUOUS (CASE LEVEL)) ATTR: conical_transitions: SET [1 : ?] OF conical_stepped_hole_transition ATTR: first_trim_condition: (AMBIGUOUS (CASE LEVEL)) ATTR: protrusion_draft_angle: plane_angle_measure ATTR: protrusion_length: positive_length_measure ATTR: point_list: LIST [2 : ?] OF point ATTR: pocket_radius: positive_length_measure ATTR: thickened_face_list: LIST [1 : ?] OF SET [1 : ?] OF face_surface ATTR: corner_radius: non_negative_length_measure ATTR: radius: (AMBIGUOUS (CASE LEVEL)) ATTR: omitted_instances: (AMBIGUOUS (CASE LEVEL)) ATTR: slot_length: positive_length_measure ATTR: rationale: text ATTR: right_offset_distance: positive_length_measure ATTR: transformation: cartesian_transformation_operator_3d ATTR: groove_width: positive_length_measure ATTR: tree_root_expression: csg_select ATTR: pocket_width: positive_length_measure ATTR: positive_side: BOOLEAN ATTR: base_solid: base_solid_select ATTR: deleted_face_set: SET [1 : ?] OF face_surface ATTR: drafted_edges: LIST [2 : ?] OF SET [1 : ?] OF edge_curve ATTR: axis_line: (AMBIGUOUS (CASE LEVEL)) ATTR: offset_angle: positive_plane_angle_measure ATTR: left_offset_distance: positive_length_measure ATTR: segment_depths: LIST [1 : segments] OF positive_length_measure ATTR: angle: (AMBIGUOUS (CASE LEVEL)) ATTR: collar_depth: positive_length_measure ATTR: axis: (AMBIGUOUS (CASE LEVEL)) ATTR: closed_ends: LIST [2 : 2] OF LOGICAL ATTR: directrix: (AMBIGUOUS (CASE LEVEL)) ATTR: reference_point: (AMBIGUOUS (CASE LEVEL)) ATTR: groove_radius: positive_length_measure ATTR: sphere_radius: positive_length_measure ATTR: first_offset: non_negative_length_measure ATTR: draft_angles: LIST [2 : ?] OF plane_angle_measure ATTR: extruded_direction: (AMBIGUOUS (CASE LEVEL)) ATTR: column_count: positive_integer ATTR: segments: positive_integer ATTR: thickness_list: LIST [1 : ?] OF length_measure ATTR: column_spacing: length_measure ATTR: protrusion_corner_radius: non_negative_length_measure ATTR: swept_area: curve_bounded_surface ATTR: sculpturing_element: generalized_surface_select ATTR: start_param: (AMBIGUOUS (CASE LEVEL)) ATTR: profile: (AMBIGUOUS (CASE LEVEL)) ATTR: thickness2: length_measure ATTR: second_offset: non_negative_length_measure ATTR: protrusion_width: positive_length_measure ATTR: protrusion_radius: positive_length_measure ATTR: slot_centreline: bounded_curve ATTR: semi_apex_angle: positive_plane_angle_measure ATTR: blended_edges: LIST [1 : ?] OF UNIQUE edge_curve ATTR: draft_angle: (AMBIGUOUS (CASE LEVEL)) ATTR: outer: closed_shell ATTR: edge_function_list: LIST [1 : ?] OF blend_radius_variation_type ATTR: exit_faces: SET [1 : ?] OF face_surface ATTR: placing: axis2_placement_3d ATTR: name: label ATTR: depth: (AMBIGUOUS (CASE LEVEL)) ATTR: parent_solid: solid_model ATTR: voids: SET [1 : ?] OF oriented_closed_shell ATTR: floor_fillet_radius: (AMBIGUOUS (CASE LEVEL)) ATTR: dim: dimension_count surface_model (*SELECT*): ATTR: fbsm_faces: SET [1 : ?] OF connected_face_set ATTR: sbsm_boundary: SET [1 : ?] OF shell ATTR: name: label ATTR: dim: dimension_count */ /** SELECT type - EXPRESS: ```express TYPE surface_or_solid_model = SELECT ( solid_model (*ENTITY*), surface_model (*SELECT*) ); END_TYPE; -- surface_or_solid_model (line:5680 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public enum sSURFACE_OR_SOLID_MODEL : SDAIValue, AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__sSURFACE_OR_SOLID_MODEL__type { /// SELECT case ``eSOLID_MODEL`` (ENTITY) in ``sSURFACE_OR_SOLID_MODEL`` case _SOLID_MODEL(eSOLID_MODEL) // (ENTITY) /// SELECT case ``sSURFACE_MODEL`` (SELECT) in ``sSURFACE_OR_SOLID_MODEL`` case _SURFACE_MODEL(sSURFACE_MODEL) // (SELECT) //MARK: - CONSTRUCTORS public init(fundamental: FundamentalType) { self = fundamental } public init?<T: SDAIUnderlyingType>(possiblyFrom underlyingType: T?){ guard let underlyingType = underlyingType else { return nil } if let base = underlyingType as? sSURFACE_MODEL { self = ._SURFACE_MODEL(base) } else if let base = sSURFACE_MODEL(possiblyFrom: underlyingType) { self = ._SURFACE_MODEL(base) } else { return nil } } public init?(possiblyFrom complex: SDAI.ComplexEntity?) { guard let complex = complex else { return nil } if let base = complex.entityReference(eSOLID_MODEL.self) {self = ._SOLID_MODEL(base) } else if let base = sSURFACE_MODEL(possiblyFrom: complex) { self = ._SURFACE_MODEL(base) } else { return nil } } public init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let select = generic else { return nil } if let fundamental = select as? Self { self.init(fundamental: fundamental) } else if let base = eSOLID_MODEL.convert(fromGeneric: select) { self = ._SOLID_MODEL(base) } else if let base = sSURFACE_MODEL.convert(fromGeneric: select) { self = ._SURFACE_MODEL(base) } else { return nil } } // InitializableByP21Parameter public static var bareTypeName: String = "SURFACE_OR_SOLID_MODEL" public init?(p21typedParam: P21Decode.ExchangeStructure.TypedParameter, from exchangeStructure: P21Decode.ExchangeStructure) { guard let keyword = p21typedParam.keyword.asStandardKeyword else { exchangeStructure.error = "unexpected p21parameter(\(p21typedParam)) while resolving \(Self.bareTypeName) select value"; return nil } switch(keyword) { case sSURFACE_MODEL.bareTypeName: guard let base = sSURFACE_MODEL(p21typedParam: p21typedParam, from: exchangeStructure) else { exchangeStructure.add(errorContext: "while resolving \(Self.bareTypeName) select value"); return nil } self = ._SURFACE_MODEL(base) default: exchangeStructure.error = "unexpected p21parameter(\(p21typedParam)) while resolving \(Self.bareTypeName) select value" return nil } } public init?(p21untypedParam: P21Decode.ExchangeStructure.UntypedParameter, from exchangeStructure: P21Decode.ExchangeStructure) { switch p21untypedParam { case .rhsOccurenceName(let rhsname): switch rhsname { case .constantEntityName(let name): guard let entity = exchangeStructure.resolve(constantEntityName: name) else {exchangeStructure.add(errorContext: "while resolving \(Self.bareTypeName) instance"); return nil } self.init(possiblyFrom: entity.complexEntity) case .entityInstanceName(let name): guard let complex = exchangeStructure.resolve(entityInstanceName: name) else {exchangeStructure.add(errorContext: "while resolving \(Self.bareTypeName) instance"); return nil } self.init(possiblyFrom: complex) default: exchangeStructure.error = "unexpected p21parameter(\(p21untypedParam)) while resolving \(Self.bareTypeName) select instance" return nil } default: exchangeStructure.error = "unexpected p21parameter(\(p21untypedParam)) while resolving \(Self.bareTypeName) select instance" return nil } } public init?(p21omittedParamfrom exchangeStructure: P21Decode.ExchangeStructure) { return nil } //MARK: - NON-ENTITY UNDERLYING TYPE REFERENCES public var super_sSURFACE_MODEL: sSURFACE_MODEL? { switch self { case ._SURFACE_MODEL(let selectValue): return selectValue default: return nil } } //MARK: - ENTITY UNDERLYING TYPE REFERENCES public var super_eFACE_BASED_SURFACE_MODEL: eFACE_BASED_SURFACE_MODEL? { switch self { case ._SURFACE_MODEL(let select): return select.super_eFACE_BASED_SURFACE_MODEL default: return nil } } public var super_eSHELL_BASED_SURFACE_MODEL: eSHELL_BASED_SURFACE_MODEL? { switch self { case ._SURFACE_MODEL(let select): return select.super_eSHELL_BASED_SURFACE_MODEL default: return nil } } public var super_eSOLID_MODEL: eSOLID_MODEL? { switch self { case ._SOLID_MODEL(let entity): return entity default: return nil } } public var super_eREPRESENTATION_ITEM: eREPRESENTATION_ITEM? { switch self { case ._SOLID_MODEL(let entity): return entity.super_eREPRESENTATION_ITEM case ._SURFACE_MODEL(let select): return select.super_eREPRESENTATION_ITEM } } public var super_eGEOMETRIC_REPRESENTATION_ITEM: eGEOMETRIC_REPRESENTATION_ITEM? { switch self { case ._SOLID_MODEL(let entity): return entity.super_eGEOMETRIC_REPRESENTATION_ITEM case ._SURFACE_MODEL(let select): return select.super_eGEOMETRIC_REPRESENTATION_ITEM } } //MARK: - ENTITY ATTRIBUTE REFERENCES /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SLOT_WIDTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.SLOT_WIDTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var END_EXIT_FACES: (SDAI.LIST<SDAI.SET<eFACE_SURFACE>/*[0:nil]*/ >/*[2:2]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.END_EXIT_FACES default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var REPLICATE_COUNT: tPOSITIVE_INTEGER? { switch self { case ._SOLID_MODEL(let entity): return entity.REPLICATE_COUNT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var RADIUS_LIST: (SDAI.LIST<tPOSITIVE_LENGTH_MEASURE>/*[2:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.RADIUS_LIST default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var ANGULAR_SPACING: tPLANE_ANGLE_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.ANGULAR_SPACING default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var OFFSET1: tLENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.OFFSET1 default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var FLOOR_BLEND_RADIUS: tNON_NEGATIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.FLOOR_BLEND_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var OFFSET2: tLENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.OFFSET2 default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var BASE_ELEMENT: sGENERALIZED_SURFACE_SELECT? { switch self { case ._SOLID_MODEL(let entity): return entity.BASE_ELEMENT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var RADIAL_ALIGNMENT: SDAI.BOOLEAN? { switch self { case ._SOLID_MODEL(let entity): return entity.RADIAL_ALIGNMENT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SEGMENT_RADII: (SDAI.LIST<tPOSITIVE_LENGTH_MEASURE>/*[1:SEGMENTS]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.SEGMENT_RADII default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var LEFT_OFFSET: SDAI.BOOLEAN? { switch self { case ._SOLID_MODEL(let entity): return entity.LEFT_OFFSET default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var ROW_SPACING: tLENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.ROW_SPACING default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var TIP_RADIUS: tNON_NEGATIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.TIP_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var THICKNESS: tLENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.THICKNESS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var REFERENCE_SURFACE: eSURFACE? { switch self { case ._SOLID_MODEL(let entity): return entity.REFERENCE_SURFACE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var TEE_SECTION_WIDTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.TEE_SECTION_WIDTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var FILLET_RADIUS: tNON_NEGATIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.FILLET_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var FIRST_TRIM_INTENT: nTRIM_INTENT? { switch self { case ._SOLID_MODEL(let entity): return entity.FIRST_TRIM_INTENT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SECOND_TRIM_INTENT: nTRIM_INTENT? { switch self { case ._SOLID_MODEL(let entity): return entity.SECOND_TRIM_INTENT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var INNER_RADIUS: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.INNER_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PROTRUSION_HEIGHT: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.PROTRUSION_HEIGHT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var ROW_COUNT: tPOSITIVE_INTEGER? { switch self { case ._SOLID_MODEL(let entity): return entity.ROW_COUNT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var POCKET_LENGTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.POCKET_LENGTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var EXTERNAL_GROOVE: SDAI.BOOLEAN? { switch self { case ._SOLID_MODEL(let entity): return entity.EXTERNAL_GROOVE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var REPLICATED_ELEMENT: eMODIFIED_SOLID_WITH_PLACED_CONFIGURATION? { switch self { case ._SOLID_MODEL(let entity): return entity.REPLICATED_ELEMENT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SWEPT_FACE: eFACE_SURFACE? { switch self { case ._SOLID_MODEL(let entity): return entity.SWEPT_FACE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var END_CONDITIONS: (SDAI.LIST<sBLEND_END_CONDITION_SELECT>/*[2:2]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.END_CONDITIONS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var CONICAL_TRANSITIONS: (SDAI.SET<eCONICAL_STEPPED_HOLE_TRANSITION>/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.CONICAL_TRANSITIONS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PROTRUSION_DRAFT_ANGLE: tPLANE_ANGLE_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.PROTRUSION_DRAFT_ANGLE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PROTRUSION_LENGTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.PROTRUSION_LENGTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var POINT_LIST: (SDAI.LIST<ePOINT>/*[2:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.POINT_LIST default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var POCKET_RADIUS: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.POCKET_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var THICKENED_FACE_LIST: (SDAI.LIST<SDAI.SET<eFACE_SURFACE>/*[1:nil]*/ >/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.THICKENED_FACE_LIST default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var CORNER_RADIUS: tNON_NEGATIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.CORNER_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SLOT_LENGTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.SLOT_LENGTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var RATIONALE: tTEXT? { switch self { case ._SOLID_MODEL(let entity): return entity.RATIONALE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var RIGHT_OFFSET_DISTANCE: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.RIGHT_OFFSET_DISTANCE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var TRANSFORMATION: eCARTESIAN_TRANSFORMATION_OPERATOR_3D? { switch self { case ._SOLID_MODEL(let entity): return entity.TRANSFORMATION default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var GROOVE_WIDTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.GROOVE_WIDTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var TREE_ROOT_EXPRESSION: sCSG_SELECT? { switch self { case ._SOLID_MODEL(let entity): return entity.TREE_ROOT_EXPRESSION default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var POCKET_WIDTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.POCKET_WIDTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var POSITIVE_SIDE: SDAI.BOOLEAN? { switch self { case ._SOLID_MODEL(let entity): return entity.POSITIVE_SIDE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var BASE_SOLID: sBASE_SOLID_SELECT? { switch self { case ._SOLID_MODEL(let entity): return entity.BASE_SOLID default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var DELETED_FACE_SET: (SDAI.SET<eFACE_SURFACE>/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.DELETED_FACE_SET default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var DRAFTED_EDGES: (SDAI.LIST<SDAI.SET<eEDGE_CURVE>/*[1:nil]*/ >/*[2:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.DRAFTED_EDGES default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var OFFSET_ANGLE: tPOSITIVE_PLANE_ANGLE_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.OFFSET_ANGLE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var LEFT_OFFSET_DISTANCE: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.LEFT_OFFSET_DISTANCE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SEGMENT_DEPTHS: (SDAI.LIST<tPOSITIVE_LENGTH_MEASURE>/*[1:SEGMENTS]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.SEGMENT_DEPTHS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var COLLAR_DEPTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.COLLAR_DEPTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var CLOSED_ENDS: (SDAI.LIST<SDAI.LOGICAL>/*[2:2]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.CLOSED_ENDS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: SELECT( ``sSURFACE_MODEL`` ) public var FBSM_FACES: (SDAI.SET<eCONNECTED_FACE_SET>/*[1:nil]*/ )? { switch self { case ._SURFACE_MODEL(let select): return select.FBSM_FACES default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var GROOVE_RADIUS: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.GROOVE_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SPHERE_RADIUS: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.SPHERE_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var FIRST_OFFSET: tNON_NEGATIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.FIRST_OFFSET default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var DRAFT_ANGLES: (SDAI.LIST<tPLANE_ANGLE_MEASURE>/*[2:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.DRAFT_ANGLES default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var COLUMN_COUNT: tPOSITIVE_INTEGER? { switch self { case ._SOLID_MODEL(let entity): return entity.COLUMN_COUNT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SEGMENTS: tPOSITIVE_INTEGER? { switch self { case ._SOLID_MODEL(let entity): return entity.SEGMENTS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var THICKNESS_LIST: (SDAI.LIST<tLENGTH_MEASURE>/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.THICKNESS_LIST default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var COLUMN_SPACING: tLENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.COLUMN_SPACING default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PROTRUSION_CORNER_RADIUS: tNON_NEGATIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.PROTRUSION_CORNER_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SWEPT_AREA: eCURVE_BOUNDED_SURFACE? { switch self { case ._SOLID_MODEL(let entity): return entity.SWEPT_AREA default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SCULPTURING_ELEMENT: sGENERALIZED_SURFACE_SELECT? { switch self { case ._SOLID_MODEL(let entity): return entity.SCULPTURING_ELEMENT default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var THICKNESS2: tLENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.THICKNESS2 default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SECOND_OFFSET: tNON_NEGATIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.SECOND_OFFSET default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PROTRUSION_WIDTH: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.PROTRUSION_WIDTH default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PROTRUSION_RADIUS: tPOSITIVE_LENGTH_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.PROTRUSION_RADIUS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SLOT_CENTRELINE: eBOUNDED_CURVE? { switch self { case ._SOLID_MODEL(let entity): return entity.SLOT_CENTRELINE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var SEMI_APEX_ANGLE: tPOSITIVE_PLANE_ANGLE_MEASURE? { switch self { case ._SOLID_MODEL(let entity): return entity.SEMI_APEX_ANGLE default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var BLENDED_EDGES: (SDAI.LIST_UNIQUE<eEDGE_CURVE>/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.BLENDED_EDGES default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: SELECT( ``sSURFACE_MODEL`` ) public var SBSM_BOUNDARY: (SDAI.SET<sSHELL>/*[1:nil]*/ )? { switch self { case ._SURFACE_MODEL(let select): return select.SBSM_BOUNDARY default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var OUTER: eCLOSED_SHELL? { switch self { case ._SOLID_MODEL(let entity): return entity.OUTER default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var EDGE_FUNCTION_LIST: (SDAI.LIST<nBLEND_RADIUS_VARIATION_TYPE>/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.EDGE_FUNCTION_LIST default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var EXIT_FACES: (SDAI.SET<eFACE_SURFACE>/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.EXIT_FACES default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PLACING: eAXIS2_PLACEMENT_3D? { switch self { case ._SOLID_MODEL(let entity): return entity.PLACING default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) /// - origin: SELECT( ``sSURFACE_MODEL`` ) public var NAME: tLABEL? { switch self { case ._SOLID_MODEL(let entity): return entity.NAME case ._SURFACE_MODEL(let select): return select.NAME } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var PARENT_SOLID: eSOLID_MODEL? { switch self { case ._SOLID_MODEL(let entity): return entity.PARENT_SOLID default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) public var VOIDS: (SDAI.SET<eORIENTED_CLOSED_SHELL>/*[1:nil]*/ )? { switch self { case ._SOLID_MODEL(let entity): return entity.VOIDS default: return nil } } /// attribute of SELECT type ``sSURFACE_OR_SOLID_MODEL`` /// - origin: ENTITY( ``eSOLID_MODEL`` ) /// - origin: SELECT( ``sSURFACE_MODEL`` ) public var DIM: tDIMENSION_COUNT? { switch self { case ._SOLID_MODEL(let entity): return entity.DIM case ._SURFACE_MODEL(let select): return select.DIM } } //MARK: - SDAIValue public func isValueEqual<T: SDAIValue>(to rhs: T) -> Bool { switch self { case ._SOLID_MODEL(let selection): return selection.value.isValueEqual(to: rhs) case ._SURFACE_MODEL(let selection): return selection.value.isValueEqual(to: rhs) } } public func isValueEqualOptionally<T: SDAIValue>(to rhs: T?) -> Bool? { switch self { case ._SOLID_MODEL(let selection): return selection.value.isValueEqualOptionally(to: rhs) case ._SURFACE_MODEL(let selection): return selection.value.isValueEqualOptionally(to: rhs) } } public func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { switch self { case ._SOLID_MODEL(let selection): selection.value.hashAsValue(into: &hasher, visited: &complexEntities) case ._SURFACE_MODEL(let selection): selection.value.hashAsValue(into: &hasher, visited: &complexEntities) } } public func isValueEqual<T: SDAIValue>(to rhs: T, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { switch self { case ._SOLID_MODEL(let selection): return selection.value.isValueEqual(to: rhs, visited: &comppairs) case ._SURFACE_MODEL(let selection): return selection.value.isValueEqual(to: rhs, visited: &comppairs) } } public func isValueEqualOptionally<T: SDAIValue>(to rhs: T?, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { switch self { case ._SOLID_MODEL(let selection): return selection.value.isValueEqualOptionally(to: rhs, visited: &comppairs) case ._SURFACE_MODEL(let selection): return selection.value.isValueEqualOptionally(to: rhs, visited: &comppairs) } } //MARK: SDAIGenericTypeBase public func copy() -> Self { switch self { case ._SOLID_MODEL(let selection): return ._SOLID_MODEL(selection.copy()) case ._SURFACE_MODEL(let selection): return ._SURFACE_MODEL(selection.copy()) } } //MARK: SDAIGenericType public var typeMembers: Set<SDAI.STRING> { var members: Set<SDAI.STRING> = [SDAI.STRING(Self.typeName)] switch self { case ._SOLID_MODEL(let selection): members.formUnion(selection.typeMembers) case ._SURFACE_MODEL(let selection): members.formUnion(selection.typeMembers) } return members } public var entityReference: SDAI.EntityReference? { switch self { case ._SOLID_MODEL(let selection): return selection.entityReference case ._SURFACE_MODEL(let selection): return selection.entityReference } } public var stringValue: SDAI.STRING? { switch self { case ._SOLID_MODEL(let selection): return selection.stringValue case ._SURFACE_MODEL(let selection): return selection.stringValue } } public var binaryValue: SDAI.BINARY? { switch self { case ._SOLID_MODEL(let selection): return selection.binaryValue case ._SURFACE_MODEL(let selection): return selection.binaryValue } } public var logicalValue: SDAI.LOGICAL? { switch self { case ._SOLID_MODEL(let selection): return selection.logicalValue case ._SURFACE_MODEL(let selection): return selection.logicalValue } } public var booleanValue: SDAI.BOOLEAN? { switch self { case ._SOLID_MODEL(let selection): return selection.booleanValue case ._SURFACE_MODEL(let selection): return selection.booleanValue } } public var numberValue: SDAI.NUMBER? { switch self { case ._SOLID_MODEL(let selection): return selection.numberValue case ._SURFACE_MODEL(let selection): return selection.numberValue } } public var realValue: SDAI.REAL? { switch self { case ._SOLID_MODEL(let selection): return selection.realValue case ._SURFACE_MODEL(let selection): return selection.realValue } } public var integerValue: SDAI.INTEGER? { switch self { case ._SOLID_MODEL(let selection): return selection.integerValue case ._SURFACE_MODEL(let selection): return selection.integerValue } } public var genericEnumValue: SDAI.GenericEnumValue? { switch self { case ._SOLID_MODEL(let selection): return selection.genericEnumValue case ._SURFACE_MODEL(let selection): return selection.genericEnumValue } } public func arrayOptionalValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY_OPTIONAL<ELEM>? { switch self { case ._SOLID_MODEL(let selection): return selection.arrayOptionalValue(elementType:elementType) case ._SURFACE_MODEL(let selection): return selection.arrayOptionalValue(elementType:elementType) } } public func arrayValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY<ELEM>? { switch self { case ._SOLID_MODEL(let selection): return selection.arrayValue(elementType:elementType) case ._SURFACE_MODEL(let selection): return selection.arrayValue(elementType:elementType) } } public func listValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.LIST<ELEM>? { switch self { case ._SOLID_MODEL(let selection): return selection.listValue(elementType:elementType) case ._SURFACE_MODEL(let selection): return selection.listValue(elementType:elementType) } } public func bagValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.BAG<ELEM>? { switch self { case ._SOLID_MODEL(let selection): return selection.bagValue(elementType:elementType) case ._SURFACE_MODEL(let selection): return selection.bagValue(elementType:elementType) } } public func setValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.SET<ELEM>? { switch self { case ._SOLID_MODEL(let selection): return selection.setValue(elementType:elementType) case ._SURFACE_MODEL(let selection): return selection.setValue(elementType:elementType) } } public func enumValue<ENUM:SDAIEnumerationType>(enumType:ENUM.Type) -> ENUM? { switch self { case ._SOLID_MODEL(let selection): return selection.enumValue(enumType:enumType) case ._SURFACE_MODEL(let selection): return selection.enumValue(enumType:enumType) } } //MARK: SDAIUnderlyingType public typealias FundamentalType = Self public static var typeName: String = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.SURFACE_OR_SOLID_MODEL" public var asFundamentalType: FundamentalType { return self } //MARK: SDAIObservableAggregateElement public var entityReferences: AnySequence<SDAI.EntityReference> { switch self { case ._SOLID_MODEL(let entity): return entity.entityReferences case ._SURFACE_MODEL(let select): return select.entityReferences } } public mutating func configure(with observer: SDAI.EntityReferenceObserver) { switch self { case ._SOLID_MODEL(let entity): entity.configure(with: observer) self = ._SOLID_MODEL(entity) case ._SURFACE_MODEL(var select): select.configure(with: observer) self = ._SURFACE_MODEL(select) } } public mutating func teardownObserver() { switch self { case ._SOLID_MODEL(let entity): entity.teardownObserver() self = ._SOLID_MODEL(entity) case ._SURFACE_MODEL(var select): select.teardownObserver() self = ._SURFACE_MODEL(select) } } //MARK: SDAIAggregationBehavior public var aggregationHiBound: Int? { switch self { case ._SURFACE_MODEL(let selection): return selection.aggregationHiBound default: return nil } } public var aggregationHiIndex: Int? { switch self { case ._SURFACE_MODEL(let selection): return selection.aggregationHiIndex default: return nil } } public var aggregationLoBound: Int? { switch self { case ._SURFACE_MODEL(let selection): return selection.aggregationLoBound default: return nil } } public var aggregationLoIndex: Int? { switch self { case ._SURFACE_MODEL(let selection): return selection.aggregationLoIndex default: return nil } } public var aggregationSize: Int? { switch self { case ._SURFACE_MODEL(let selection): return selection.aggregationSize default: return nil } } //MARK: WHERE RULE VALIDATION (SELECT TYPE) public static func validateWhereRules(instance:Self?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] { var result: [SDAI.WhereLabel:SDAI.LOGICAL] = [:] switch instance { case ._SOLID_MODEL(let selectValue): result = eSOLID_MODEL.validateWhereRules(instance:selectValue, prefix:prefix + "\\SOLID_MODEL") case ._SURFACE_MODEL(let selectValue): result = sSURFACE_MODEL.validateWhereRules(instance:selectValue, prefix:prefix + "\\SURFACE_MODEL") case nil: break } return result } } } //MARK: - SELECT TYPE HIERARCHY public protocol AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__sSURFACE_OR_SOLID_MODEL__type: SDAISelectType { //MARK: GROUP REFERENCES var super_sSURFACE_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sSURFACE_MODEL? { get } var super_eFACE_BASED_SURFACE_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_BASED_SURFACE_MODEL? { get } var super_eSHELL_BASED_SURFACE_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSHELL_BASED_SURFACE_MODEL? { get } var super_eSOLID_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSOLID_MODEL? { get } var super_eREPRESENTATION_ITEM: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eREPRESENTATION_ITEM? { get } var super_eGEOMETRIC_REPRESENTATION_ITEM: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eGEOMETRIC_REPRESENTATION_ITEM? { get } //MARK: ENTITY ATTRIBUTE REFERENCES var SLOT_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var END_EXIT_FACES: (SDAI.LIST<SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE>/*[0: nil]*/ >/*[2:2]*/ )? { get } var REPLICATE_COUNT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { get } var RADIUS_LIST: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE>/*[2: nil]*/ )? { get } var ANGULAR_SPACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPLANE_ANGLE_MEASURE? { get } var OFFSET1: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { get } var FLOOR_BLEND_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { get } var OFFSET2: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { get } var BASE_ELEMENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sGENERALIZED_SURFACE_SELECT? { get } var RADIAL_ALIGNMENT: SDAI.BOOLEAN? { get } var SEGMENT_RADII: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE>/*[1: SEGMENTS]*/ )? { get } var LEFT_OFFSET: SDAI.BOOLEAN? { get } var ROW_SPACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { get } var TIP_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { get } var THICKNESS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { get } var REFERENCE_SURFACE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSURFACE? { get } var TEE_SECTION_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var FILLET_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { get } var FIRST_TRIM_INTENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.nTRIM_INTENT? { get } var SECOND_TRIM_INTENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.nTRIM_INTENT? { get } var INNER_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var PROTRUSION_HEIGHT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var ROW_COUNT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { get } var POCKET_LENGTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var EXTERNAL_GROOVE: SDAI.BOOLEAN? { get } var REPLICATED_ELEMENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eMODIFIED_SOLID_WITH_PLACED_CONFIGURATION? { get } var SWEPT_FACE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE? { get } var END_CONDITIONS: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sBLEND_END_CONDITION_SELECT> /*[2:2]*/ )? { get } var CONICAL_TRANSITIONS: (SDAI.SET< AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCONICAL_STEPPED_HOLE_TRANSITION>/*[1:nil]*/ )? { get } var PROTRUSION_DRAFT_ANGLE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPLANE_ANGLE_MEASURE? { get } var PROTRUSION_LENGTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var POINT_LIST: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.ePOINT>/*[2:nil]*/ )? { get } var POCKET_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var THICKENED_FACE_LIST: (SDAI.LIST<SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE> /*[1:nil]*/ >/*[1:nil]*/ )? { get } var CORNER_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { get } var SLOT_LENGTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var RATIONALE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tTEXT? { get } var RIGHT_OFFSET_DISTANCE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var TRANSFORMATION: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCARTESIAN_TRANSFORMATION_OPERATOR_3D? { get } var GROOVE_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var TREE_ROOT_EXPRESSION: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sCSG_SELECT? { get } var POCKET_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var POSITIVE_SIDE: SDAI.BOOLEAN? { get } var BASE_SOLID: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sBASE_SOLID_SELECT? { get } var DELETED_FACE_SET: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE>/*[1:nil]*/ )? { get } var DRAFTED_EDGES: (SDAI.LIST<SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eEDGE_CURVE>/*[1:nil]*/ > /*[2:nil]*/ )? { get } var OFFSET_ANGLE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_PLANE_ANGLE_MEASURE? { get } var LEFT_OFFSET_DISTANCE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var SEGMENT_DEPTHS: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE>/*[ 1:SEGMENTS]*/ )? { get } var COLLAR_DEPTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var CLOSED_ENDS: (SDAI.LIST<SDAI.LOGICAL>/*[2:2]*/ )? { get } var FBSM_FACES: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCONNECTED_FACE_SET>/*[1:nil]*/ )? { get } var GROOVE_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var SPHERE_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var FIRST_OFFSET: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { get } var DRAFT_ANGLES: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPLANE_ANGLE_MEASURE>/*[2:nil]*/ )? { get } var COLUMN_COUNT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { get } var SEGMENTS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { get } var THICKNESS_LIST: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE>/*[1:nil]*/ )? { get } var COLUMN_SPACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { get } var PROTRUSION_CORNER_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { get } var SWEPT_AREA: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCURVE_BOUNDED_SURFACE? { get } var SCULPTURING_ELEMENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sGENERALIZED_SURFACE_SELECT? { get } var THICKNESS2: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { get } var SECOND_OFFSET: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { get } var PROTRUSION_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var PROTRUSION_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { get } var SLOT_CENTRELINE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eBOUNDED_CURVE? { get } var SEMI_APEX_ANGLE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_PLANE_ANGLE_MEASURE? { get } var BLENDED_EDGES: (SDAI.LIST_UNIQUE<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eEDGE_CURVE>/*[1:nil]*/ )? { get } var SBSM_BOUNDARY: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sSHELL>/*[1:nil]*/ )? { get } var OUTER: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCLOSED_SHELL? { get } var EDGE_FUNCTION_LIST: (SDAI.LIST< AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.nBLEND_RADIUS_VARIATION_TYPE>/*[1:nil]*/ )? { get } var EXIT_FACES: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE>/*[1:nil]*/ )? { get } var PLACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eAXIS2_PLACEMENT_3D? { get } var NAME: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLABEL? { get } var PARENT_SOLID: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSOLID_MODEL? { get } var VOIDS: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eORIENTED_CLOSED_SHELL>/*[1:nil]*/ )? { get } var DIM: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tDIMENSION_COUNT? { get } } public protocol AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__sSURFACE_OR_SOLID_MODEL__subtype: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__sSURFACE_OR_SOLID_MODEL__type, SDAIDefinedType where Supertype: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__sSURFACE_OR_SOLID_MODEL__type {} public extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__sSURFACE_OR_SOLID_MODEL__subtype { //MARK: CONSTRUCTORS init?(possiblyFrom complex: SDAI.ComplexEntity?) { self.init(fundamental: FundamentalType(possiblyFrom: complex)) } init?<T: SDAIUnderlyingType>(possiblyFrom underlyingType: T?) { self.init(fundamental: FundamentalType(possiblyFrom: underlyingType)) } init?<G: SDAIGenericType>(fromGeneric generic: G?) { self.init(fundamental: FundamentalType.convert(fromGeneric: generic)) } //MARK: GROUP REFERENCES var super_sSURFACE_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sSURFACE_MODEL? { rep.super_sSURFACE_MODEL } var super_eFACE_BASED_SURFACE_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_BASED_SURFACE_MODEL? { rep.super_eFACE_BASED_SURFACE_MODEL } var super_eSHELL_BASED_SURFACE_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSHELL_BASED_SURFACE_MODEL? { rep.super_eSHELL_BASED_SURFACE_MODEL } var super_eSOLID_MODEL: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSOLID_MODEL? { rep.super_eSOLID_MODEL } var super_eREPRESENTATION_ITEM: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eREPRESENTATION_ITEM? { rep.super_eREPRESENTATION_ITEM } var super_eGEOMETRIC_REPRESENTATION_ITEM: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eGEOMETRIC_REPRESENTATION_ITEM? { rep.super_eGEOMETRIC_REPRESENTATION_ITEM } //MARK: ENTITY ATTRIBUTE REFERENCES var SLOT_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.SLOT_WIDTH } var END_EXIT_FACES: (SDAI.LIST<SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE>/*[0: nil]*/ >/*[2:2]*/ )? { rep.END_EXIT_FACES } var REPLICATE_COUNT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { rep.REPLICATE_COUNT } var RADIUS_LIST: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE>/*[2: nil]*/ )? { rep.RADIUS_LIST } var ANGULAR_SPACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPLANE_ANGLE_MEASURE? { rep.ANGULAR_SPACING } var OFFSET1: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { rep.OFFSET1 } var FLOOR_BLEND_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { rep.FLOOR_BLEND_RADIUS } var OFFSET2: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { rep.OFFSET2 } var BASE_ELEMENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sGENERALIZED_SURFACE_SELECT? { rep.BASE_ELEMENT } var RADIAL_ALIGNMENT: SDAI.BOOLEAN? { rep.RADIAL_ALIGNMENT } var SEGMENT_RADII: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE>/*[1: SEGMENTS]*/ )? { rep.SEGMENT_RADII } var LEFT_OFFSET: SDAI.BOOLEAN? { rep.LEFT_OFFSET } var ROW_SPACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { rep.ROW_SPACING } var TIP_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { rep.TIP_RADIUS } var THICKNESS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { rep.THICKNESS } var REFERENCE_SURFACE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSURFACE? { rep.REFERENCE_SURFACE } var TEE_SECTION_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.TEE_SECTION_WIDTH } var FILLET_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { rep.FILLET_RADIUS } var FIRST_TRIM_INTENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.nTRIM_INTENT? { rep.FIRST_TRIM_INTENT } var SECOND_TRIM_INTENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.nTRIM_INTENT? { rep.SECOND_TRIM_INTENT } var INNER_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.INNER_RADIUS } var PROTRUSION_HEIGHT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.PROTRUSION_HEIGHT } var ROW_COUNT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { rep.ROW_COUNT } var POCKET_LENGTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.POCKET_LENGTH } var EXTERNAL_GROOVE: SDAI.BOOLEAN? { rep.EXTERNAL_GROOVE } var REPLICATED_ELEMENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eMODIFIED_SOLID_WITH_PLACED_CONFIGURATION? { rep.REPLICATED_ELEMENT } var SWEPT_FACE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE? { rep.SWEPT_FACE } var END_CONDITIONS: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sBLEND_END_CONDITION_SELECT> /*[2:2]*/ )? { rep.END_CONDITIONS } var CONICAL_TRANSITIONS: (SDAI.SET< AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCONICAL_STEPPED_HOLE_TRANSITION>/*[1:nil]*/ )? { rep.CONICAL_TRANSITIONS } var PROTRUSION_DRAFT_ANGLE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPLANE_ANGLE_MEASURE? { rep.PROTRUSION_DRAFT_ANGLE } var PROTRUSION_LENGTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.PROTRUSION_LENGTH } var POINT_LIST: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.ePOINT>/*[2:nil]*/ )? { rep.POINT_LIST } var POCKET_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.POCKET_RADIUS } var THICKENED_FACE_LIST: (SDAI.LIST<SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE> /*[1:nil]*/ >/*[1:nil]*/ )? { rep.THICKENED_FACE_LIST } var CORNER_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { rep.CORNER_RADIUS } var SLOT_LENGTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.SLOT_LENGTH } var RATIONALE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tTEXT? { rep.RATIONALE } var RIGHT_OFFSET_DISTANCE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.RIGHT_OFFSET_DISTANCE } var TRANSFORMATION: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCARTESIAN_TRANSFORMATION_OPERATOR_3D? { rep.TRANSFORMATION } var GROOVE_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.GROOVE_WIDTH } var TREE_ROOT_EXPRESSION: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sCSG_SELECT? { rep.TREE_ROOT_EXPRESSION } var POCKET_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.POCKET_WIDTH } var POSITIVE_SIDE: SDAI.BOOLEAN? { rep.POSITIVE_SIDE } var BASE_SOLID: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sBASE_SOLID_SELECT? { rep.BASE_SOLID } var DELETED_FACE_SET: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE>/*[1:nil]*/ )? { rep.DELETED_FACE_SET } var DRAFTED_EDGES: (SDAI.LIST<SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eEDGE_CURVE>/*[1:nil]*/ > /*[2:nil]*/ )? { rep.DRAFTED_EDGES } var OFFSET_ANGLE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_PLANE_ANGLE_MEASURE? { rep.OFFSET_ANGLE } var LEFT_OFFSET_DISTANCE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.LEFT_OFFSET_DISTANCE } var SEGMENT_DEPTHS: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE>/*[ 1:SEGMENTS]*/ )? { rep.SEGMENT_DEPTHS } var COLLAR_DEPTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.COLLAR_DEPTH } var CLOSED_ENDS: (SDAI.LIST<SDAI.LOGICAL>/*[2:2]*/ )? { rep.CLOSED_ENDS } var FBSM_FACES: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCONNECTED_FACE_SET>/*[1:nil]*/ )? { rep.FBSM_FACES } var GROOVE_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.GROOVE_RADIUS } var SPHERE_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.SPHERE_RADIUS } var FIRST_OFFSET: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { rep.FIRST_OFFSET } var DRAFT_ANGLES: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPLANE_ANGLE_MEASURE>/*[2:nil]*/ )? { rep.DRAFT_ANGLES } var COLUMN_COUNT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { rep.COLUMN_COUNT } var SEGMENTS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_INTEGER? { rep.SEGMENTS } var THICKNESS_LIST: (SDAI.LIST<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE>/*[1:nil]*/ )? { rep.THICKNESS_LIST } var COLUMN_SPACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { rep.COLUMN_SPACING } var PROTRUSION_CORNER_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { rep.PROTRUSION_CORNER_RADIUS } var SWEPT_AREA: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCURVE_BOUNDED_SURFACE? { rep.SWEPT_AREA } var SCULPTURING_ELEMENT: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sGENERALIZED_SURFACE_SELECT? { rep.SCULPTURING_ELEMENT } var THICKNESS2: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLENGTH_MEASURE? { rep.THICKNESS2 } var SECOND_OFFSET: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tNON_NEGATIVE_LENGTH_MEASURE? { rep.SECOND_OFFSET } var PROTRUSION_WIDTH: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.PROTRUSION_WIDTH } var PROTRUSION_RADIUS: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_LENGTH_MEASURE? { rep.PROTRUSION_RADIUS } var SLOT_CENTRELINE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eBOUNDED_CURVE? { rep.SLOT_CENTRELINE } var SEMI_APEX_ANGLE: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tPOSITIVE_PLANE_ANGLE_MEASURE? { rep.SEMI_APEX_ANGLE } var BLENDED_EDGES: (SDAI.LIST_UNIQUE<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eEDGE_CURVE>/*[1:nil]*/ )? { rep.BLENDED_EDGES } var SBSM_BOUNDARY: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.sSHELL>/*[1:nil]*/ )? { rep.SBSM_BOUNDARY } var OUTER: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eCLOSED_SHELL? { rep.OUTER } var EDGE_FUNCTION_LIST: (SDAI.LIST< AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.nBLEND_RADIUS_VARIATION_TYPE>/*[1:nil]*/ )? { rep.EDGE_FUNCTION_LIST } var EXIT_FACES: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eFACE_SURFACE>/*[1:nil]*/ )? { rep.EXIT_FACES } var PLACING: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eAXIS2_PLACEMENT_3D? { rep.PLACING } var NAME: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tLABEL? { rep.NAME } var PARENT_SOLID: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eSOLID_MODEL? { rep.PARENT_SOLID } var VOIDS: (SDAI.SET<AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.eORIENTED_CLOSED_SHELL>/*[1:nil]*/ )? { rep.VOIDS } var DIM: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.tDIMENSION_COUNT? { rep.DIM } }
43.92033
206
0.726825
33ac8e3f0b9f0aa3804a14695b9cdca878969695
7,946
// // NameTest.swift // SBVariables // // Created by Ed Gamble on 11/17/15. // Copyright © 2015 Edward B. Gamble Jr. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import XCTest @testable import SBVariables class NameTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testName() { let o1 = Named(name: "o1") let o2 = Named(name: "o2") let o3 = Named(name: "o2") XCTAssertEqual("o1", o1.name) XCTAssertEqual("o2", o2.name) XCTAssertEqual("o2", o3.name) XCTAssertEqual(o2.name, o3.name) } func testNamespace () { let n1 = Namespace<Named>(name: "n1") let o1 = Named(name: "o1") let o2 = Named(name: "o2") n1.addObjectByName(o1) XCTAssertTrue(n1.hasObjectByName(o1)) XCTAssertFalse(n1.hasObjectByName(o2)) n1.addObjectByName(o2) XCTAssertTrue(n1.hasObjectByName(o1)) XCTAssertTrue(n1.hasObjectByName(o2)) n1.remObjectByName(o1) XCTAssertFalse(n1.hasObjectByName(o1)) XCTAssertTrue(n1.hasObjectByName(o2)) XCTAssertNotNil(n1.getObjectByName(o2.name)) XCTAssertTrue(o2 === n1.getObjectByName(o2.name)!) XCTAssertNil(n1.getObjectByName(o1.name)) XCTAssertEqual("n1\(n1.separator)o2", n1.fullname(o2)) } func testNamespaceSquared () { let n1 = Namespace<Named>(name: "n1") let n2 = Namespace<Named>(name: "n2", parent: n1) let o1 = Named(name: "o1") XCTAssertEqual("n1\(n1.separator)n2\(n2.separator)o1", n2.fullname(o1)) } func testPerformanceExample() { self.measure { } } } /* @implementation SBTestNamedObject - (void) setUp {} - (void) tearDown {} - (void) testCaseNameObject_1 { // objectIsNamed: STAssertTrue ([object1 objectIsNamed: name], @"object1 should have name"); STAssertTrue ([object1 objectIsNamed: @"Object Name"], @"object1 should have name 'Object Name'"); STAssertFalse ([object1 objectIsNamed: @"Other Name"], @"object1 should not have name 'Object Name'"); // objectsShareName: STAssertTrue ([object1 objectsShareName: object1], @"object1 and object1 do not share their name"); STAssertTrue ([object1 objectsShareName: object2], @"object1 and object2 do not share their name"); STAssertTrue ([object2 objectsShareName: object1], @"object2 and object1 do not share their name"); STAssertFalse ([object1 objectsShareName: object3], @"object1 and object3 should not share their name"); STAssertFalse ([object2 objectsShareName: object3], @"object2 and object3 should not share their name"); // compareByName: STAssertTrue (NSOrderedSame == [object1 compareByName: object1], @"Missed self name"); STAssertTrue (NSOrderedSame == [object1 compareByName: object2], @"Missed self name"); STAssertTrue (NSOrderedSame != [object1 compareByName: object3], @"Missed self name"); } @end // SBTestNamedObject */ /* @implementation SBTestNamespace - (void) setUp {} - (void) tearDown {} - (void) testCaseNamespace_1 { NSString *name1 = @"Space Name 1"; SBNamespace *space1 = [[SBNamespace alloc] initWithName: name1 withSeparator: @":" inNamespace: [SBNamespace standardNamespace]]; STAssertTrue([@":" isEqualToString: space1.separator], @"The space1 separator should be ':'."); STAssertEqualObjects(space1.parent, [SBNamespace standardNamespace], @"The space1 parent should be standardNamespace"); SBNamedObject *object1 = [[SBNamedObject alloc] initWithName: @"object_1"]; SBNamedObject *object2 = [[SBNamedObject alloc] initWithName: @"object_2"]; SBNamedObject *object3 = [[SBNamedObject alloc] initWithName: @"object_3"]; STAssertNotNil (space1, @"Could not create 'space1'."); STAssertNotNil (object1, @"Could not create 'object1'."); STAssertNotNil (object2, @"Could not create 'object2'."); STAssertNotNil (object3, @"Could not create 'object3'."); // STAssertFalse (space1.name == name1, // @"The space1 name is identical to name1"); STAssertTrue ([space1.name isEqualToString: name1], @"The space1 name is not string equal ot name1"); STAssertEqualObjects (space1.name, name1, @"The space1 name and name1 are not equal"); STAssertTrue ([space1 objectIsNamed: name1], @"The space1 name should be name1"); STAssertTrue ([space1 addObjectByName: object1], @"Could not add object1 to space1"); STAssertTrue ([space1 hasObjectByName: object1], @"Space1 contains object1"); STAssertTrue ([space1 hasObjectWithName: @"object_1"], @"Space1 contains object1"); STAssertFalse ([space1 addObjectByName: object1], @"Added object1 to space1 but it is already in space1"); STAssertTrue ([space1 count] == 1, @"Space1 count is not 1"); STAssertEqualObjects(object1, [space1 objectByName: @"object_1"], @"Space1 should have object1 by name"); STAssertTrue ([space1 remObjectByName: object1], @"Could not remove object1 from space1"); STAssertFalse ([space1 hasObjectByName: object1], @"Space1 contains object1"); STAssertFalse ([space1 remObjectByName: object1], @"Removed object1 from space1 but it is not in space1"); STAssertTrue ([space1 count] == 0, @"Space1 count is not 0"); STAssertFalse (object1 == [space1 objectByName: @"object_1"], @"Space1 should not have object1 by name"); STAssertTrue ([space1 addObjectByName: object1], @"Could not add object1 to space1"); STAssertTrue ([space1 addObjectByName: object2], @"Could not add object2 to space1"); STAssertTrue ([space1 count] == 2, @"Space1 count is not 2"); STAssertEqualObjects(object1, [space1 objectByName: @"object_1"], @"Space1 should have object1 by name"); STAssertEqualObjects(object2, [space1 objectByName: @"object_2"], @"Space1 should have object2 by name"); NSArray *allNames = [space1 allNames]; STAssertTrue ([allNames containsObject: @"object_1"], @"allNames should contain object_1"); STAssertTrue ([allNames containsObject: @"object_2"], @"allNames should contain object_2"); STAssertTrue (2 == [allNames count], @"allNames count should be 2"); NSArray *allObjs = [space1 allNamedObjects]; STAssertTrue ([allObjs containsObject: object1], @"allObjs should contain object1"); STAssertTrue ([allObjs containsObject: object2], @"allObjs should contain object2"); STAssertTrue (2 == [allObjs count], @"allObjs count should be 2"); STAssertEqualObjects ([space1 fullname: object1], @"SB.Space Name 1:object_1", @"Mismatched fullname for object_1"); STAssertEqualObjects ([space1 fullname: object2], @"SB.Space Name 1:object_2", @"Mismatched fullname for object_2"); // object3 not in space1 STAssertFalse ([space1 hasObjectByName: object3], @"Space1 shouldn't have object3"); STAssertEqualObjects ([space1 fullname: object3], @"object_3", @"Mismatched fullname for object_3"); STAssertTrue ([space1 addObjectByName: object3], @"Could not add object3 to space1"); space1 = [[SBNamespace alloc] initWithName: @"Space1-2" inNamespace: [SBNamespace standardNamespace]]; } @end // SBTestNamespace */
34.103004
86
0.637931
1ef103d142fb7fcc73cdd98e9a6254c50da8970b
242
// // Copyright © 2021 Stream.io Inc. All rights reserved. // import Foundation struct UserListPayload<ExtraData: UserExtraData>: Decodable { /// A list of users response (see `UserListQuery`). let users: [UserPayload<ExtraData>] }
22
61
0.714876
f7cf60e14f9a9e9805e0463e7fa33b6c91204c4d
23
print("Hello, world!")
11.5
22
0.652174
1a08b7c3cc5f5fb42c3bbfc68efb7ae4cbde1f33
1,354
import Foundation import Basic import Utility import CLIHandler public class DopCommand: CLICommand { let toolVersion = "0.11.0" var versionOption: OptionArgument<Bool>! public convenience init() { self.init(name: "dop", summary: "Support devops workflows") } public override func setup() { versionOption = argumentParser.add(option: "--version", shortName: "-v", kind: Bool.self, usage: "Show the version") add(subcommand: InitCommand()) add(subcommand: LoginCommand()) add(subcommand: BuildToolsImageCommand()) add(subcommand: BumpVersionCommand()) add(subcommand: BuildImageCommand()) add(subcommand: RunImageCommand()) add(subcommand: RegisterImageCommand()) add(subcommand: UnregisterImageCommand()) add(subcommand: UpgradeReleaseCommand()) add(subcommand: ContainerLogsCommand()) add(subcommand: InstallExecutableCommand()) add(subcommand: CleanCommand()) } public override func run(result: ArgumentParser.Result) { if let _ = result.get(versionOption) { showVersion() } else { showUsage() } } func showVersion() { print("Version \(toolVersion)") } func showUsage() { argumentParser.printUsage(on: stdoutStream) } }
28.208333
124
0.641802
56e15a4b1ae4df19c43f2ddbcb67b74e6afd67eb
948
// // UnsplashSearch.swift // SwiftCollection // // Created by 王洋 on 2019/2/15. // Copyright © 2019 wannayoung. All rights reserved. // import UIKit import HandyJSON class UnsplashSearch: HandyJSON { var total = 0 var total_pages = 0 var results: [SearchResult] = [] required init() {} } class SearchResult: HandyJSON { var id = "" var width = 0 var height = 0 var urls = PhotoUrls() var created_at = "" var description = "" var user: UserInfo = UserInfo() required init() {} } class PhotoUrls: HandyJSON { var raw = "" var full = "" var regular = "" var small = "" var thumb = "" required init() {} } class UserInfo: HandyJSON { var name = "" var profile_image: ProfileImage = ProfileImage() required init() {} } class ProfileImage: HandyJSON { var small = "" var medium = "" var large = "" required init() {} }
16.928571
53
0.582278
22afac12a7073db8e7e350b144f6e5c701a66fc1
749
import XCTest import Steth-IO-SDK class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.827586
111
0.599466
698a0e1c6097091c6fb3876eaa194cfb2c2cc859
1,347
// // GradientView.swift // spendsterIOS // // Created by Dmytro Holovko on 5/4/19. // Copyright © 2019 KeyToTech. All rights reserved. // swiftlint:disable force_cast import Foundation import UIKit class GradientView: UIView { override class var layerClass: AnyClass { return CAGradientLayer.self } private var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } @IBInspectable var color1: UIColor = .white { didSet { updateColors() } } @IBInspectable var color2: UIColor = .white { didSet { updateColors() } } override init(frame: CGRect = .zero) { super.init(frame: frame) configureGradient() self.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureGradient() self.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] } private func configureGradient() { gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 0) updateColors() } private func updateColors() { gradientLayer.colors = [color1.cgColor, color2.cgColor] } }
24.053571
79
0.615442
03b4aab078e47ec5b9370c229f65a5b89b8a6a7e
1,011
// // GenericPasswordRowTests.swift // GenericPasswordRowTests // // Created by Diego Ernst on 9/5/16. // Copyright © 2016 Diego Ernst. All rights reserved. // import XCTest @testable import GenericPasswordRow class GenericPasswordRowTests: 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.324324
111
0.646884
e91b89be0f0c33056b393dc8986adaa0d9555f6a
11,960
// // TokenListViewController.swift // Authenticator // // Copyright (c) 2013-2016 Authenticator authors // // 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 //TODO: Replace "DigitalJetstream" with logo class TokenListViewController: UITableViewController { fileprivate let dispatchAction: (TokenList.Action) -> Void fileprivate var viewModel: TokenList.ViewModel fileprivate var ignoreTableViewUpdates = false init(viewModel: TokenList.ViewModel, dispatchAction: @escaping (TokenList.Action) -> Void) { self.viewModel = viewModel self.dispatchAction = dispatchAction super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate var searchBar = SearchField( frame: CGRect( origin: .zero, size: CGSize(width: 0, height: 44) ) ) fileprivate lazy var noTokensLabel: UILabel = { let title = "No Tokens" let message = "Tap + to add a new token" let titleAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 20, weight: UIFontWeightLight)] let messageAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 17, weight: UIFontWeightLight)] let plusAttributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 25, weight: UIFontWeightLight)] let noTokenString = NSMutableAttributedString(string: title + "\n", attributes: titleAttributes) noTokenString.append(NSAttributedString(string: message, attributes: messageAttributes)) noTokenString.addAttributes(plusAttributes, range: (noTokenString.string as NSString).range(of: "+")) let label = UILabel() label.numberOfLines = 2 label.attributedText = noTokenString label.textAlignment = .center label.textColor = UIColor.otpForegroundColor return label }() fileprivate lazy var noTokensButton: UIButton = { let button = UIButton(type: .custom) button.addTarget(self, action: #selector(addToken), for: .touchUpInside) self.noTokensLabel.frame = button.bounds self.noTokensLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] button.addSubview(self.noTokensLabel) button.accessibilityLabel = "No Tokens" button.accessibilityHint = "Double-tap to add a new token." return button }() fileprivate let backupWarningLabel: UILabel = { let linkTitle = "Learn More →" let message = "For security reasons, tokens will be stored only on this \(UIDevice.current.model), and will not be included in iCloud or unencrypted backups. \(linkTitle)" let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = 1.3 paragraphStyle.paragraphSpacing = 5 let attributedMessage = NSMutableAttributedString(string: message, attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: 15, weight: UIFontWeightLight), NSParagraphStyleAttributeName: paragraphStyle, ]) attributedMessage.addAttribute(NSFontAttributeName, value: UIFont.italicSystemFont(ofSize: 15), range: (attributedMessage.string as NSString).range(of: "not")) attributedMessage.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 15), range: (attributedMessage.string as NSString).range(of: linkTitle)) let label = UILabel() label.numberOfLines = 0 label.attributedText = attributedMessage label.textAlignment = .center label.textColor = UIColor.otpForegroundColor return label }() fileprivate lazy var backupWarning: UIButton = { let button = UIButton(type: .custom) button.addTarget(self, action: #selector(showBackupInfo), for: .touchUpInside) self.backupWarningLabel.frame = button.bounds self.backupWarningLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] button.addSubview(self.backupWarningLabel) button.accessibilityLabel = "For security reasons, tokens will be stored only on this \(UIDevice.current.model), and will not be included in iCloud or unencrypted backups." button.accessibilityHint = "Double-tap to learn more." return button }() private let infoButton = UIButton(type: .infoLight) // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.tableView.keyboardDismissMode = .interactive self.title = "DigitalJetstream" self.view.backgroundColor = UIColor.otpBackgroundColor // Configure table view self.tableView.separatorStyle = .none self.tableView.indicatorStyle = .white self.tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) self.tableView.allowsSelectionDuringEditing = true // Configure navigation bar self.navigationItem.titleView = searchBar self.searchBar.delegate = self // Configure toolbar let addAction = #selector(TokenListViewController.addToken) self.toolbarItems = [ self.editButtonItem, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(customView: infoButton), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .add, target: self, action: addAction), ] self.navigationController?.isToolbarHidden = false // Configure empty state view.addSubview(noTokensButton) view.addSubview(backupWarning) infoButton.addTarget(self, action: #selector(TokenListViewController.showLicenseInfo), for: .touchUpInside) // Update with current viewModel self.updatePeripheralViews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let searchSelector = #selector(TokenListViewController.filterTokens) searchBar.textField.addTarget(self, action: searchSelector, for: .editingChanged) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.isEditing = false } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let labelMargin: CGFloat = 20 let insetBounds = view.bounds.insetBy(dx: labelMargin, dy: labelMargin) let noTokensLabelSize = noTokensLabel.sizeThatFits(insetBounds.size) let noTokensLabelOrigin = CGPoint(x: (view.bounds.width - noTokensLabelSize.width) / 2, y: (view.bounds.height * 0.6 - noTokensLabelSize.height) / 2) noTokensButton.frame = CGRect(origin: noTokensLabelOrigin, size: noTokensLabelSize) let labelSize = backupWarningLabel.sizeThatFits(insetBounds.size) let labelOrigin = CGPoint(x: labelMargin, y: view.bounds.maxY - labelMargin - labelSize.height) backupWarning.frame = CGRect(origin: labelOrigin, size: labelSize) } // MARK: Target Actions func addToken() { dispatchAction(.beginAddToken) } func filterTokens() { guard let filter = searchBar.text else { return dispatchAction(.clearFilter) } dispatchAction(.filter(filter)) } func showBackupInfo() { dispatchAction(.showBackupInfo) } func showLicenseInfo() { dispatchAction(.showInfo) } } // MARK: UITableViewDataSource extension TokenListViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.rowModels.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithClass(TokenRowCell.self) updateCell(cell, forRowAtIndexPath: indexPath) return cell } fileprivate func updateCell(_ cell: TokenRowCell, forRowAtIndexPath indexPath: IndexPath) { let rowModel = viewModel.rowModels[indexPath.row] cell.updateWithRowModel(rowModel) cell.dispatchAction = dispatchAction } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let rowModel = viewModel.rowModels[indexPath.row] if editingStyle == .delete { dispatchAction(rowModel.deleteAction) } } override func tableView(_ tableView: UITableView, moveRowAt source: IndexPath, to destination: IndexPath) { ignoreTableViewUpdates = true dispatchAction(.moveToken(fromIndex: source.row, toIndex: destination.row)) ignoreTableViewUpdates = false } } // MARK: UITableViewDelegate extension TokenListViewController { override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 85 } } // MARK: TokenListPresenter extension TokenListViewController { func updateWithViewModel(_ viewModel: TokenList.ViewModel) { let changes = changesFrom(self.viewModel.rowModels, to: viewModel.rowModels) let filtering = viewModel.isFiltering || self.viewModel.isFiltering self.viewModel = viewModel if filtering && !changes.isEmpty { tableView.reloadData() } else if !ignoreTableViewUpdates { let sectionIndex = 0 let tableViewChanges = changes.map({ change in change.map({ row in IndexPath(row: row, section: sectionIndex) }) }) tableView.applyChanges(tableViewChanges, updateRow: { indexPath in if let cell = tableView.cellForRow(at: indexPath) as? TokenRowCell { updateCell(cell, forRowAtIndexPath: indexPath) } }) } updatePeripheralViews() } fileprivate func updatePeripheralViews() { searchBar.updateWithViewModel(viewModel) tableView.isScrollEnabled = viewModel.hasTokens editButtonItem.isEnabled = viewModel.hasTokens noTokensButton.isHidden = viewModel.hasTokens backupWarning.isHidden = viewModel.hasTokens // Exit editing mode if no tokens remain if self.isEditing && viewModel.rowModels.isEmpty { self.setEditing(false, animated: true) } } } extension TokenListViewController: UITextFieldDelegate { // Dismisses keyboard when return is pressed func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
39.084967
180
0.685702
563012e5159b8d74ce14406b0fcbb15c093f12e2
48,284
// // RpcProviderEndpointPromiseTests.swift // ArisenSwiftTests // // Created by Brandon Fancher on 4/18/19. // Copyright (c) 2017-2019 peepslabs and its contributors. All rights reserved. // import XCTest @testable import ArisenSwift import PromiseKit import OHHTTPStubs class RpcProviderEndpointPromiseTests: XCTestCase { var rpcProvider: ArisenRpcProvider? override func setUp() { super.setUp() let url = URL(string: "https://localhost") rpcProvider = ArisenRpcProvider(endpoint: url!) OHHTTPStubs.onStubActivation { (request, stub, _) in print("\(request.url!) stubbed by \(stub.name!).") } } override func tearDown() { super.tearDown() //remove all stubs on tear down OHHTTPStubs.removeAllStubs() } /// Test getInfo promise implementation. func testGetInfo(unhappy: Bool = false) { (stub(condition: isAbsoluteURLString("https://localhost/v1/chain/get_info")) { _ in let json = RpcTestConstants.infoResponseJson let data = json.data(using: .utf8) return OHHTTPStubsResponse(data: data!, statusCode: unhappy ? 500 : 200, headers: nil) }).name = "Get Info stub" let expect = expectation(description: "testGetInfo") firstly { (rpcProvider?.getInfo(.promise))! }.done { if unhappy { XCTFail("testGetInfo unhappy path should not fulfill promise!") } XCTAssertTrue($0.serverVersion == "0f6695cb") XCTAssertTrue($0.headBlockNum.value == 25260035) XCTAssertTrue($0.headBlockId == "01817003aecb618966706f2bca7e8525d814e873b5db9a95c57ad248d10d3c05") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed push_transactions") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getInfo promise happy path. func testGetInfoSuccess() { testGetInfo() } /// Test getInfo promise unhappy path. func testGetInfoFail() { testGetInfo(unhappy: true) } /// Test getBlock() promise implementation. func testGetBlock(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "Get Block Stub" let expect = expectation(description: "testGetBlock") let requestParameters = ArisenRpcBlockRequest(blockNumOrId: "25260032") firstly { (rpcProvider?.getBlock(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetBlock unhappy path should not fulfill promise!") } XCTAssertTrue($0.blockNum.value == 25260032) XCTAssertTrue($0.refBlockPrefix.value == 2249927103) XCTAssertTrue($0.id == "0181700002e623f2bf291b86a10a5cec4caab4954d4231f31f050f4f86f26116") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_block") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getBlock promise happy path. func testGetBlockSuccess() { testGetBlock() } /// Test getBlock promise unhappy path. func testGetBlockFail() { testGetBlock(unhappy: true) } /// Test getRawAbi() promise implementation. func testGetRawAbi(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let name = try? ArisenName("arisen") let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, name: name!, unhappy: unhappy ) callCount += 1 return retVal }).name = "Get RawAbi Name stub" let expect = expectation(description: "testGetRawAbi") let name = try? ArisenName("arisen") let requestParameters = ArisenRpcRawAbiRequest(accountName: name!) firstly { (rpcProvider?.getRawAbi(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetRawAbi unhappy path should not fulfill promise!") } XCTAssertTrue($0.accountName == "arisen") XCTAssertTrue($0.codeHash == "add7914493bb911bbc179b19115032bbaae1f567f733391060edfaf79a6c8096") XCTAssertTrue($0.abiHash == "d745bac0c38f95613e0c1c2da58e92de1e8e94d658d64a00293570cc251d1441") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_raw_abi") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getRawAbi promise happy path. func testGetRawAbiSuccess() { testGetRawAbi() } /// Test getRawAbi promise unhappy path. func testGetRawAbiFail() { testGetRawAbi(unhappy: true) } /// Test getRequiredKeys() promise implementation. func testGetRequiredKeys(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "Get Required Keys stub" let expect = expectation(description: "testGetRequiredKeys") let transaction = ArisenTransaction() let requestParameters = ArisenRpcRequiredKeysRequest(availableKeys: ["PUB_K1_5j67P1W2RyBXAL8sNzYcDLox3yLpxyrxgkYy1xsXzVCw1oi9eG"], transaction: transaction) firstly { (rpcProvider?.getRequiredKeys(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetRequiredKeys unhappy path should not fulfill promise!") } XCTAssertTrue($0.requiredKeys.count == 1) XCTAssertTrue($0.requiredKeys[0] == "RSN5j67P1W2RyBXAL8sNzYcDLox3yLpxyrxgkYy1xsXzVCvzbYpba") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_required_keys") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getRequiredKeys promise happy path. func testGetRequiredKeysSuccess() { testGetRequiredKeys() } /// Test getRequiredKeys promise unhappy path. func testGetRequiredKeysFail() { testGetRequiredKeys(unhappy: true) } /// Test pushTransaction() promise implementation. func testPushTransaction(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "Push Transaction stub" let expect = expectation(description: "testPushTransaction") // swiftlint:disable:next line_length let requestParameters = ArisenRpcPushTransactionRequest(signatures: ["SIG_K1_JzFA9ffefWfrTBvpwMwZi81kR6tvHF4mfsRekVXrBjLWWikg9g1FrS9WupYuoGaRew5mJhr4d39tHUjHiNCkxamtEfxi68"], compression: 0, packedContextFreeData: "", packedTrx: "C62A4F5C1CEF3D6D71BD000000000290AFC2D800EA3055000000405DA7ADBA0072CBDD956F52ACD910C3C958136D72F8560D1846BC7CF3157F5FBFB72D3001DE4597F4A1FDBECDA6D59C96A43009FC5E5D7B8F639B1269C77CEC718460DCC19CB30100A6823403EA3055000000572D3CCDCD0143864D5AF0FE294D44D19C612036CBE8C098414C4A12A5A7BB0BFE7DB155624800A6823403EA3055000000572D3CCDCD0100AEAA4AC15CFD4500000000A8ED32323B00AEAA4AC15CFD4500000060D234CD3DA06806000000000004454F53000000001A746865206772617373686F70706572206C69657320686561767900") firstly { (rpcProvider?.pushTransaction(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testPushTransaction unhappy path should not fulfill promise!") } XCTAssertTrue($0.transactionId == "ae735820e26a7b771e1b522186294d7cbba035d0c31ca88237559d6c0a3bf00a") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed push_transaction") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test pushTransaction promise happy path. func testPushTransactionSuccess() { testPushTransaction() } /// Test pushTransaction promise unhappy path. func testPushTransactionFail() { testPushTransaction(unhappy: true) } /// Test pushTransactions promise implementation. func testPushTransactions(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "PushTransactions stub" let expect = expectation(description: "testPushTransactions") // swiftlint:disable line_length let transOne = ArisenRpcPushTransactionRequest(signatures: ["SIG_K1_KfFAcqhHTSzabsxGRLpK8KQonqLEXXzMkVQXoj4XGhqNNEzdjSfsGuDVsKFtMPs2NAit8h9LpVDkm2NoAGBaZAUzSmLpVR"], compression: 0, packedContextFreeData: "", packedTrx: "2D324F5CEBFDD0C60CDD000000000290AFC2D800EA3055000000405DA7ADBA0072CBDD956F52ACD910C3C958136D72F8560D1846BC7CF3157F5FBFB72D3001DE4597F4A1FDBECDA6D59C96A43009FC5E5D7B8F639B1269C77CEC718460DCC19CB30100A6823403EA3055000000572D3CCDCD0143864D5AF0FE294D44D19C612036CBE8C098414C4A12A5A7BB0BFE7DB155624800A6823403EA3055000000572D3CCDCD0100AEAA4AC15CFD4500000000A8ED32323B00AEAA4AC15CFD4500000060D234CD3DA06806000000000004454F53000000001A746865206772617373686F70706572206C69657320686561767900") let transTwo = ArisenRpcPushTransactionRequest(signatures: ["SIG_K1_K2mRrB7aknJPquDXJRsVy5xA9wyYrHEw7bkoc8vX4mHrww5UWLV25J3ZHb5kpMnfR3LF3Z2cJk3ydULkXx4vuet7cwYYa8"], compression: 0, packedContextFreeData: "", packedTrx: "8B324F5CA8FE7CC54C3A000000000290AFC2D800EA3055000000405DA7ADBA0072CBDD956F52ACD910C3C958136D72F8560D1846BC7CF3157F5FBFB72D3001DE4597F4A1FDBECDA6D59C96A43009FC5E5D7B8F639B1269C77CEC718460DCC19CB30100A6823403EA3055000000572D3CCDCD0143864D5AF0FE294D44D19C612036CBE8C098414C4A12A5A7BB0BFE7DB155624800A6823403EA3055000000572D3CCDCD0100AEAA4AC15CFD4500000000A8ED32323B00AEAA4AC15CFD4500000060D234CD3DA06806000000000004454F53000000001A746865206772617373686F70706572206C69657320686561767900") // swiftlint:enable line_length let requestParameters = ArisenRpcPushTransactionsRequest(transactions: [transOne, transTwo]) firstly { (rpcProvider?.pushTransactions(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testPushTransactions unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssertNotNil($0.transactionResponses) XCTAssert($0.transactionResponses.count == 2) XCTAssert($0.transactionResponses[0].transactionId == "2de4cd382c2e231c8a3ac80acfcea493dd2d9e7178b46d165283cf91c2ce6121") XCTAssert($0.transactionResponses[1].transactionId == "8bddd86928d396dcec91e15d910086a4f8682167ff9616a84f23de63258c78fe") }.catch { print($0) if unhappy { XCTAssertTrue($0.ArisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed push_transactions") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test pushTransactions promise happy path. func testPushTransactionsSuccess() { testPushTransactions() } /// Test pushTransactions promise unhappy path. func testPushTransactionsFail() { testPushTransactions(unhappy: true) } /// Test getBlockHeaderState() promise implementation. // swiftlint:disable function_body_length func testGetBlockHeaderState(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetBlockHeaderState stub" let expect = expectation(description: "testGetBlockHeaderState") let requestParameters = ArisenRpcBlockHeaderStateRequest(blockNumOrId: "25260035") firstly { (rpcProvider?.getBlockHeaderState(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetBlockHeaderState unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssertNotNil($0._rawResponse) XCTAssert($0.id == "0137c067c65e9db8f8ee467c856fb6d1779dfeb0332a971754156d075c9a37ca") XCTAssert($0.header.producerSignature == "SIG_K1_K11ScNfXdat71utYJtkd8E6dFtvA7qQ3ww9K74xEpFvVCyeZhXTarwvGa7QqQTRw3CLFbsXCsWJFNCHFHLKWrnBNZ66c2m") guard let version = $0.pendingSchedule["version"] as? UInt64 else { return XCTFail("Should be able to get pendingSchedule as [String : Any].") } XCTAssert(version == 2) guard let activeSchedule = $0.activeSchedule["producers"] as? [[String: Any]] else { return XCTFail("Should be able to get activeSchedule as [String : Any].") } guard let producerName = activeSchedule.first?["producer_name"] as? String else { return XCTFail("Should be able to get producer_name as String.") } XCTAssert(producerName == "blkproducer1") guard let nodeCount = $0.blockRootMerkle["_node_count"] as? UInt64 else { return XCTFail("Should be able to get _node_count as Int.") } XCTAssert(nodeCount == 20430950) XCTAssert($0.confirmCount.count == 12) XCTAssertNotNil($0.producerToLastImpliedIrb) XCTAssert($0.producerToLastImpliedIrb.count == 2) if let irb = $0.producerToLastImpliedIrb[0] as? [Any] { XCTAssertNotNil(irb) XCTAssert(irb.count == 2) guard let name = irb[0] as? String, name == "blkproducer1" else { XCTFail("Should be able to find name.") return } guard let num = irb[1] as? UInt64, num == 20430939 else { XCTFail("Should be able to find number.") return } } else { XCTFail("Should be able to find producer to last implied irb.") } }.catch { print($0) if unhappy { XCTAssertTrue($0.ArisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_block_header_state") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } // swiftlint:enable function_body_length /// Test getBlockHeaderState promise happy path. func testGetBlockHeaderStateSuccess() { testGetBlockHeaderState() } /// Test getBlockHeaderState promise unhappy path. func testGetBlockHeaderStateFail() { testGetBlockHeaderState(unhappy: true) } /// Test getAbi() promise implementation. func testGetAbi(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetAbi stub" let expect = expectation(description: "testGetAbi") let requestParameters = ArisenRpcAbiRequest(accountName: "arisen.token") firstly { (rpcProvider?.getAbi(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetAbi unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) let abi = $0.abi if let abiVersion = abi["version"] as? String { XCTAssert(abiVersion == "arisen::abi/1.0") } else { XCTFail("Should be able to find and verify abi version.") } }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_abi") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getAbi promise happy path. func testGetAbiSuccess() { testGetAbi() } /// Test getAbi promise unhappy path. func testGetAbiFail() { testGetAbi(unhappy: true) } /// Test getAccount() promise implementation. // swiftlint:disable function_body_length func testGetAccount(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetAccount stub" let expect = expectation(description: "testGetAccount") let requestParameters = ArisenRpcAccountRequest(accountName: "cryptkeeper") firstly { (rpcProvider?.getAccount(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetAccount unhappy path should not fulfill promise!") } let arisenRpcAccountResponse = $0 XCTAssertNotNil(arisenRpcAccountResponse) XCTAssert(arisenRpcAccountResponse.accountName == "cryptkeeper") XCTAssert(arisenRpcAccountResponse.ramQuota.value == 13639863) let permissions = arisenRpcAccountResponse.permissions XCTAssertNotNil(permissions) guard let activePermission = permissions.filter({$0.permName == "active"}).first else { return XCTFail("Cannot find Active permission in permissions structure of the account") } XCTAssert(activePermission.parent == "owner") guard let keysAndWeight = activePermission.requiredAuth.keys.first else { return XCTFail("Cannot find key in keys structure of the account") } XCTAssert(keysAndWeight.key == "RSN5j67P1W2RyBXAL8sNzYcDLox3yLpxyrxgkYy1xsXzVCvzbYpba") guard let firstPermission = activePermission.requiredAuth.accounts.first else { return XCTFail("Can't find permission in keys structure of the account") } XCTAssert(firstPermission.permission.actor == "RIXaccount1") XCTAssert(firstPermission.permission.permission == "active") XCTAssert(activePermission.requiredAuth.waits.first?.waitSec.value == 259200) XCTAssertNotNil(arisenRpcAccountResponse.totalResources) if let dict = arisenRpcAccountResponse.totalResources { if let owner = dict["owner"] as? String { XCTAssert(owner == "cryptkeeper") } else { XCTFail("Should be able to get total_resources owner as String and should equal cryptkeeper.") } if let rambytes = dict["ram_bytes"] as? UInt64 { XCTAssert(rambytes == 13639863) } else { XCTFail("Should be able to get total_resources ram_bytes as UIn64 and should equal 13639863.") } } else { XCTFail("Should be able to get total_resources as [String : Any].") } }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_account") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } // swiftlint:enable function_body_length /// Test getAccount promise happy path. func testGetAccountSuccess() { testGetAccount() } /// Test getAccount promise unhappy path. func testGetAccountFail() { testGetAccount(unhappy: true) } /// Test getCurrencyBalance() promise implementation. func testGetCurrencyBalance(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetCurrencyBalance stub" let expect = expectation(description: "testGetCurrencyBalance") let requestParameters = ArisenRpcCurrencyBalanceRequest(code: "arisen.token", account: "cryptkeeper", symbol: "RIX") firstly { (rpcProvider?.getCurrencyBalance(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetCurrencyBalance unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssert($0.currencyBalance.count == 1) XCTAssert($0.currencyBalance[0].contains(words: "RIX")) }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_currency_balance") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getCurrencyBalance promise happy path. func testGetCurrencyBalanceSuccess() { testGetCurrencyBalance() } /// Test getCurrencyBalance promise unhappy path. func testGetCurrencyBalanceFail() { testGetCurrencyBalance(unhappy: true) } /// Test getCurrencyStats() promise implementation. func testGetCurrencyStats(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetCurrencyBalance stub" let expect = expectation(description: "getCurrencyStats") let requestParameters = ArisenRpcCurrencyStatsRequest(code: "arisen.token", symbol: "RIX") firstly { (rpcProvider?.getCurrencyStats(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetCurrencyStats unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssert($0.symbol == "RIX") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_currency_stats") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getCurrencyStatsRIX() promise implementation. func testGetCurrencyStatsRIX(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in if let urlString = request.url?.absoluteString { if callCount == 1 && urlString == "https://localhost/v1/chain/get_info" { callCount += 1 return RpcTestConstants.getInfoOHHTTPStubsResponse() } else if callCount == 2 && urlString == "https://localhost/v1/chain/get_currency_stats" { let json = RpcTestConstants.currencyStatsRIX let data = json.data(using: .utf8) return OHHTTPStubsResponse(data: data!, statusCode: 200, headers: nil) } else { return RpcTestConstants.getErrorOHHTTPStubsResponse(code: NSURLErrorUnknown, reason: "Unexpected call count in stub: \(callCount)") } } else { return RpcTestConstants.getErrorOHHTTPStubsResponse(reason: "No valid url string in request in stub") } }).name = "GetCurrencyStats stub" let expect = expectation(description: "getCurrencyStats") let requestParameters = ArisenRpcCurrencyStatsRequest(code: "arisen.token", symbol: "RIX") firstly { (rpcProvider?.getCurrencyStats(.promise, requestParameters: requestParameters))! }.done { XCTAssertNotNil($0._rawResponse) XCTAssert($0.symbol == "RIX") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_currency_stats") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getCurrencyStatsRIX promise happy path. func testGetCurrencyStatsSuccess() { testGetCurrencyStats() } /// Test getCurrencyStatsRIX promise unhappy path. func testGetCurrencyStatsFail() { testGetCurrencyStats(unhappy: true) } /// Test getCurrencyStatsRIX promise happy path. func testGetCurrencyStatsSuccessRIX() { testGetCurrencyStatsRIX() } /// Test getRawCodeAndAbi() promise implementation. func testGetRawCodeAndAbi(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetRawCodeAndAbis stub" let expect = expectation(description: "getRawCodeAndAbi") let requestParameters = ArisenRpcRawCodeAndAbiRequest(accountName: "arisen.token") firstly { (rpcProvider?.getRawCodeAndAbi(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetRawCodeAndAbi unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssert($0.accountName == "arisen.token") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_raw_code_and_abi") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getRawCodeAndAbi promise happy path. func testGetRawCodeAndAbiSuccess() { testGetRawCodeAndAbi() } /// Test getRawCodeAndAbi promise unhappy path. func testGetRawCodeAndAbiFail() { testGetRawCodeAndAbi(unhappy: true) } /// Test getRawCodeAndAbi() with String signature promise implementation. func testGetRawCodeAndAbiWithStringSignature(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetRawCodeAndAbis w String stub" let expect = expectation(description: "testGetRawCodeAndAbiWithStringSignature") firstly { (rpcProvider?.getRawCodeAndAbi(.promise, accountName: "arisen.token"))! }.done { if unhappy { XCTFail("testGetRawCodeAndAbiWithStringSignature unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_raw_code_and_abi with string") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getRawCodeAndAbi promise happy path. func testGetRawCodeAndAbiWithStringSignatureSuccess() { testGetRawCodeAndAbiWithStringSignature() } /// Test getRawCodeAndAbi promise unhappy path. func testGetRawCodeAndAbiWithStringSignatureFail() { testGetRawCodeAndAbiWithStringSignature(unhappy: true) } /// Test getCode() promise implementation. func testGetCode(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetCode stub" let expect = expectation(description: "testGetCode") let requestParameters = ArisenRpcCodeRequest(accountName: "tropical") firstly { (rpcProvider?.getCode(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetCode unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssert($0.accountName == "tropical") XCTAssert($0.codeHash == "68721c88e8b04dea76962d8afea28d2f39b870d72be30d1d143147cdf638baad") if let dict = $0.abi { if let version = dict["version"] as? String { XCTAssert(version == "arisen::abi/1.1") } else { XCTFail("Should be able to get abi version as String and should equal arisen::abi/1.1.") } } else { XCTFail("Should be able to get abi as [String : Any].") } }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_code") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getCode promise happy path. func testGetCodeSuccess() { testGetCode() } /// Test getCode promise unhappy path. func testGetCodeFail() { testGetCode(unhappy: true) } /// Test getCode() with String signature promise implementation. func testGetCodeWithStringSignature(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetCodeWithStringSignature stub" let expect = expectation(description: "testGetCodeWithStringSignature") firstly { (rpcProvider?.getCode(.promise, accountName: "cryptkeeper"))! }.done { if unhappy { XCTFail("testGetCodeWithStringSignature unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_code with string") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getCode with String promise happy path. func testGetCodeWithStringSignatureSuccess() { testGetCodeWithStringSignature() } /// Test getCode with String promise unhappy path. func testGetCodeWithStringSignatureFail() { testGetCodeWithStringSignature(unhappy: true) } /// Test getTableRows() promise implementation. func testGetTableRows(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetTableRows stub" let expect = expectation(description: "testGetTableRows") let requestParameters = ArisenRpcTableRowsRequest(scope: "cryptkeeper", code: "arisen.token", table: "accounts") firstly { (rpcProvider?.getTableRows(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetTableRows unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssertNotNil($0.rows) XCTAssert($0.rows.count == 1) if let row = $0.rows[0] as? [String: Any], let balance = row["balance"] as? String { XCTAssert(balance == "986420.1921 RIX") } else { XCTFail("Cannot get returned table row or balance string.") } XCTAssertFalse($0.more) }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_table_rows") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getTableRows promise happy path. func testGetTableRowsSuccess() { testGetTableRows() } /// Test getTableRows promise unhappy path. func testGetTableRowsFail() { testGetTableRows(unhappy: true) } /// Test getTableByScope() promise implementation. func testGetTableByScope(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetTableByScope stub" let expect = expectation(description: "testGetTableByScope") let requestParameters = ArisenRpcTableByScopeRequest(code: "arisen.token") firstly { (rpcProvider?.getTableByScope(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetTableByScope unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssertNotNil($0.rows) XCTAssert($0.rows.count == 10) let row = $0.rows[8] XCTAssert(row.code == "arisen.token") XCTAssert(row.scope == "arisen") XCTAssert(row.table == "accounts") XCTAssert(row.payer == "arisen") XCTAssert(row.count == 1) XCTAssert($0.more == "arisen.ramfee") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_table_by_scope") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getTableByScope promise happy path. func testGetTableByScopeSuccess() { testGetTableByScope() } /// Test getTableByScope promise unhappy path. func testGetTableByScopeFail() { testGetTableByScope(unhappy: true) } /// Test getProducers promise implementation. func testGetProducers(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetProducers stub" let expect = expectation(description: "testGetProducers") let requestParameters = ArisenRpcProducersRequest(limit: 10, lowerBound: "blkproducer2", json: true) firstly { (rpcProvider?.getProducers(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetProducers unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssertNotNil($0.rows) XCTAssert($0.rows.count == 2) XCTAssert($0.rows[0].owner == "blkproducer2") XCTAssert($0.rows[0].unpaidBlocks.value == 0) XCTAssert($0.rows[1].owner == "blkproducer3") XCTAssert($0.rows[0].isActive == 1) }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_producers") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getProducers promise happy path. func testGetProducersSuccess() { testGetProducers() } /// Test getProducers promise unhappy path. func testGetProducersFail() { testGetProducers(unhappy: true) } /// Test getActions promise implementation. func testGetActions(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetAction stub" let expect = expectation(description: "testGetActions") let requestParameters = ArisenRpcHistoryActionsRequest(position: -1, offset: -20, accountName: "cryptkeeper") firstly { (rpcProvider?.getActions(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetActions unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssertNotNil($0._rawResponse) XCTAssert($0.lastIrreversibleBlock.value == 55535908) XCTAssert($0.timeLimitExceededError == false) XCTAssert($0.actions.first?.globalActionSequence.value == 6483908013) XCTAssert($0.actions.first?.actionTrace.receipt.receiverSequence.value == 1236) XCTAssert($0.actions.first?.actionTrace.receipt.authorizationSequence.count == 1) if let firstSequence = $0.actions.first?.actionTrace.receipt.authorizationSequence.first as? [Any] { guard let accountName = firstSequence.first as? String, accountName == "powersurge22" else { return XCTFail("Should be able to find account name") } } XCTAssert($0.actions.first?.actionTrace.action.name == "transfer") XCTAssert($0.actions.first?.actionTrace.action.authorization.first?.permission == "active") XCTAssert($0.actions.first?.actionTrace.action.data["memo"] as? String == "l2sbjsdrfd.m") XCTAssert($0.actions.first?.actionTrace.action.hexData == "10826257e3ab38ad000000004800a739f3eef20b00000000044d4545544f4e450c6c3273626a736472666a2e6f") XCTAssert($0.actions.first?.actionTrace.accountRamDeltas.first?.delta.value == 472) }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_actions") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getActions promise happy path. func testGetActionsSuccess() { testGetActions() } /// Test getActions promise unhappy path. func testGetActionsFail() { testGetActions(unhappy: true) } /// Test getControlledAccounts promise implementation. func testGetControlledAccounts(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetControlledAccounts stub" let expect = expectation(description: "testGetControlledAccounts") let requestParameters = ArisenRpcHistoryControlledAccountsRequest(controllingAccount: "cryptkeeper") firstly { (rpcProvider?.getControlledAccounts(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetControlledAccounts unhappy path should not fulfill promise!") } XCTAssertNotNil($0._rawResponse) XCTAssertNotNil($0.controlledAccounts) XCTAssert($0.controlledAccounts.count == 2) XCTAssert($0.controlledAccounts[0] == "subcrypt1") XCTAssert($0.controlledAccounts[1] == "subcrypt2") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_controlled_accounts") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getControlledAccounts promise happy path. func testGetControlledAccountsSuccess() { testGetControlledAccounts() } /// Test getControlledAccounts promise unhappy path. func testGetControlledAccountsFail() { testGetControlledAccounts(unhappy: true) } /// Test getTransaction promise implementation. func testGetTransaction(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetTransaction stub" let expect = expectation(description: "testGetTransaction") let requestParameters = ArisenRpcHistoryTransactionRequest(transactionId: "ae735820e26a7b771e1b522186294d7cbba035d0c31ca88237559d6c0a3bf00a", blockNumHint: 21098575) firstly { (rpcProvider?.getTransaction(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetTransaction unhappy path should not fulfill promise!") } XCTAssert($0.id == "ae735820e26a7b771e1b522186294d7cbba035d0c31ca88237559d6c0a3bf00a") XCTAssert($0.blockNum.value == 21098575) guard let dict = $0.trx["trx"] as? [String: Any] else { XCTFail("Should find trx.trx dictionary.") return } if let refBlockNum = dict["ref_block_num"] as? UInt64 { XCTAssert(refBlockNum == 61212) } else { XCTFail("Should find trx ref_block_num and it should match.") } if let signatures = dict["signatures"] as? [String] { XCTAssert(signatures[0] == "SIG_K1_JzFA9ffefWfrTBvpwMwZi81kR6tvHF4mfsRekVXrBjLWWikg9g1FrS9WupYuoGaRew5mJhr4d39tHUjHiNCkxamtEfxi68") } else { XCTFail("Should find trx signatures and it should match.") } }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_transaction") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getTransaction promise happy path. func testGetTransactionSuccess() { testGetTransaction() } /// Test getTransaction promise unhappy path. func testGetTransactionFail() { testGetTransaction(unhappy: true) } /// Test getKeyAccounts promise implementation. func testGetKeyAccounts(unhappy: Bool = false) { var callCount = 1 (stub(condition: isHost("localhost")) { request in let retVal = RpcTestConstants.getHHTTPStubsResponse(callCount: callCount, urlRelativePath: request.url?.relativePath, unhappy: unhappy) callCount += 1 return retVal }).name = "GetKeyAccounts stub" let expect = expectation(description: "testGetKeyAccounts") let requestParameters = ArisenRpcHistoryKeyAccountsRequest(publicKey: "PUB_K1_5j67P1W2RyBXAL8sNzYcDLox3yLpxyrxgkYy1xsXzVCw1oi9eG") firstly { (rpcProvider?.getKeyAccounts(.promise, requestParameters: requestParameters))! }.done { if unhappy { XCTFail("testGetKeyAccounts unhappy path should not fulfill promise!") } XCTAssertNotNil($0.accountNames) XCTAssert($0.accountNames.count == 2) XCTAssert($0.accountNames[0] == "cryptkeeper") }.catch { print($0) if unhappy { XCTAssertTrue($0.arisenError.errorCode == ArisenErrorCode.rpcProviderError) } else { XCTFail("Failed get_key_accounts") } }.finally { expect.fulfill() } wait(for: [expect], timeout: 30) } /// Test getKeyAccounts promise happy path. func testGetKeyAccountsSuccess() { testGetKeyAccounts() } /// Test getKeyAccounts promise unhappy path. func testGetKeyAccountsFail() { testGetKeyAccounts(unhappy: true) } }
41.268376
722
0.622939
e99a95ac08b57a642580c4f55ae733d9a04f04d8
704
import Foundation extension UICollectionView { func getAllVisibleCellsAndPaths() -> [(cell: IndicatorCell, indexPath: IndexPath)] { let visibleCells = self.visibleCells let cellAndPaths: [(cell: IndicatorCell, indexPath: IndexPath)] = visibleCells.compactMap { cell in guard let indexPath = self.indexPath(for: cell) else { return nil } guard let indicatorCell = cell as? IndicatorCell else { return nil } return (indicatorCell, indexPath) }.sorted(by: { return $0.indexPath.row < $1.indexPath.row }) return cellAndPaths } }
32
107
0.573864
728899d3aec5e57145dacf554c48a2c3637928a5
651
// // CountryViewTheme.swift // CountryPickerSwift // // Created by Semen Tolkachov on 16/03/2018. // import UIKit public struct CountryViewTheme { public let countryCodeTextColor: UIColor public let countryNameTextColor: UIColor public let rowBackgroundColor: UIColor public init( countryCodeTextColor: UIColor = UIColor.gray, countryNameTextColor: UIColor = UIColor.darkGray, rowBackgroundColor: UIColor = UIColor.white ) { self.countryCodeTextColor = countryCodeTextColor self.countryNameTextColor = countryNameTextColor self.rowBackgroundColor = rowBackgroundColor } }
26.04
57
0.725038
39c5351aa9be840ee77ddc4c752d12e96bcb6e86
321
enum TransmissionRiskEnum: Int { case lowRisk = 0 case mediumRisk = 501 case highRisk = 769 } extension TransmissionRiskEnum: Codable { public init(from decoder: Decoder) throws { self = try TransmissionRiskEnum(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .lowRisk } }
26.75
115
0.71028
e87fa6cbc5406147aee8079d2a80b6c4c4e8d416
1,797
// swift-tools-version:5.5 import PackageDescription let package = Package( name: "swiftui-dynamic-forms", platforms: [ .iOS(.v14), .macOS(.v11) ], products: [ .library( name: "DynamicForms", targets: ["DynamicForms"] ), .library( name: "DynamicFormsUI", targets: ["DynamicFormsUI"] ), ], dependencies: [ .package( name: "swift-case-paths", url: "https://github.com/pointfreeco/swift-case-paths.git", .upToNextMinor(from: "0.8.0") ), .package( name: "swift-custom-dump", url: "https://github.com/pointfreeco/swift-custom-dump.git", .upToNextMinor(from: "0.3.0") ), .package( name: "swift-prelude", url: "https://github.com/capturecontext/swift-prelude.git", .branch("develop") ), .package( name: "swift-generic-color", url: "https://github.com/capturecontext/swift-generic-color.git", .branch("main") ) ], targets: [ .target( name: "DynamicForms", dependencies: [ .product( name: "CasePaths", package: "swift-case-paths" ), .product( name: "CustomDump", package: "swift-custom-dump" ), .product( name: "Prelude", package: "swift-prelude" ), .product( name: "GenericColor", package: "swift-generic-color" ) ] ), .target( name: "DynamicFormsUI", dependencies: [ .target(name: "DynamicForms") ] ), .testTarget( name: "DynamicFormsTests", dependencies: [ .target(name: "DynamicForms"), .product( name: "CustomDump", package: "swift-custom-dump" ) ] ) ] )
21.650602
71
0.524207
ebf0faa2d8068e18801f1a32be81aa37d69f2769
356
// // Operator.swift // NirCore // // Created by Mounir Ybanez on 2/14/19. // Copyright © 2019 Nir. All rights reserved. // precedencegroup Group { associativity: left } infix operator >>>: Group public func >>> <A, B, C>(_ lhs: @escaping (A) -> B, _ rhs: @escaping (B) -> C) -> (A) -> C { return { rhs(lhs($0)) } }
19.777778
66
0.539326
1c2d7c4980a9919ec9ba32e437463d68f3cbd5f6
3,389
///* // * MockedAssembler.swift // * MachinesTests // * // * Created by Callum McColl on 22/02/2017. // * Copyright © 2017 Callum McColl. All rights reserved. // * // * Redistribution and use in source and binary forms, with or without // * modification, are permitted provided that the following conditions // * are met: // * // * 1. Redistributions of source code must retain the above copyright // * notice, this list of conditions and the following disclaimer. // * // * 2. Redistributions in binary form must reproduce the above // * copyright notice, this list of conditions and the following // * disclaimer in the documentation and/or other materials // * provided with the distribution. // * // * 3. All advertising materials mentioning features or use of this // * software must display the following acknowledgement: // * // * This product includes software developed by Callum McColl. // * // * 4. Neither the name of the author nor the names of contributors // * may be used to endorse or promote products derived from this // * software without specific prior written permission. // * // * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER // * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // * // * ----------------------------------------------------------------------- // * This program is free software; you can redistribute it and/or // * modify it under the above terms or under the terms of the GNU // * General Public License as published by the Free Software Foundation; // * either version 2 of the License, or (at your option) any later version. // * // * This program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with this program; if not, see http://www.gnu.org/licenses/ // * or write to the Free Software Foundation, Inc., 51 Franklin Street, // * Fifth Floor, Boston, MA 02110-1301, USA. // * // */ // //import Foundation //@testable import SwiftMachines // //public class MockedAssembler: Assembler { // // private let _assemble: (Machine) -> (URL, [URL])? // // public init(_ f: @escaping (Machine) -> (URL, [URL])? = { _ in nil }) { // self._assemble = f // } // // public func assemble(_ machine: Machine, inDirectory _: URL) -> (URL, [URL])? { // return self._assemble(machine) // } // // public func packagePath(forMachine _: Machine, builtInDirectory _: URL) -> String { // return "" // } // //}
42.898734
89
0.683092
e083434bbeeb0a6f7f23cb874be79c927e8cacee
2,416
// // SceneDelegate.swift // TestAccountKitExample // // Created by Salah on 7/27/20. // Copyright © 2020 Salah. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? // // func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // guard let _ = (scene as? UIWindowScene) else { return } // } // // func sceneDidDisconnect(_ scene: UIScene) { // // Called as the scene is being released by the system. // // This occurs shortly after the scene enters the background, or when its session is discarded. // // Release any resources associated with this scene that can be re-created the next time the scene connects. // // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). // } // // func sceneDidBecomeActive(_ scene: UIScene) { // // Called when the scene has moved from an inactive state to an active state. // // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. // } // // func sceneWillResignActive(_ scene: UIScene) { // // Called when the scene will move from an active state to an inactive state. // // This may occur due to temporary interruptions (ex. an incoming phone call). // } // // func sceneWillEnterForeground(_ scene: UIScene) { // // Called as the scene transitions from the background to the foreground. // // Use this method to undo the changes made on entering the background. // } // // func sceneDidEnterBackground(_ scene: UIScene) { // // Called as the scene transitions from the foreground to the background. // // Use this method to save data, release shared resources, and store enough scene-specific state information // // to restore the scene back to its current state. // } }
44.740741
149
0.693295
b94ed4825021480b7ca0f41985a1176535111442
8,313
// // FloatingTabBar.swift // Pong // // Created by Ozan Mirza on 12/29/20. // Copyright © 2020 BurcuMirza. All rights reserved. // import UIKit public protocol FloatingTabBarDelegate: class { func floatingTabBarDidSelect(item: FloatingTabItem, index: Int) } open class FloatingTabBar: UIView { open weak var delegate: FloatingTabBarDelegate? open var position: CGFloat = 0 { didSet { setNeedsLayout() } } open var items: [FloatingTabItem] = [] { didSet { imageViews = items.map { (UIImageView(image: $0.selectedImage), UIImageView(image: $0.normalImage)) } } } open var spacing: CGFloat = 3 { didSet { setNeedsLayout() } } open var radius: CGFloat = 10 { didSet { setNeedsLayout() } } open var bottomRadius: CGFloat = 20 { didSet { setNeedsLayout() } } private let bottomMargin: CGFloat = 5 open var topMargin: CGFloat { return (frame.height - (bottomMargin + spacing)) / 2 - radius } override var maskPath: UIBezierPath? { set { blurView.maskPath = newValue } get { return blurView.maskPath } } open override var backgroundColor: UIColor? { set { blurView.backgroundColor = newValue } get { return blurView.backgroundColor } } open var visualEffect: UIVisualEffect? { set { blurView.effect = newValue } get { return blurView.effect } } private var imageViews: [(selected: UIImageView, deselected: UIImageView)] = [] { didSet { oldValue.forEach { $0.selected.removeFromSuperview() $0.deselected.removeFromSuperview() } imageViews.forEach { blurView.contentView.addSubview($0.selected) blurView.contentView.addSubview($0.deselected) } setNeedsLayout() } } private let blurView: UIVisualEffectView = { if #available(iOS 13.0, *) { return UIVisualEffectView(effect: UIBlurEffect(style: .systemUltraThinMaterial)) } else { return UIVisualEffectView(effect: UIBlurEffect(style: .light)) } }() public override init(frame: CGRect) { super.init(frame: frame) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowRadius = 3 layer.shadowOpacity = 0.25 isOpaque = false backgroundColor = .clear let recognizer = UITapGestureRecognizer(target: self, action: #selector(recognizeTap(with:))) addGestureRecognizer(recognizer) addSubview(blurView) } open override func layoutSubviews() { super.layoutSubviews() blurView.frame = bounds createPath() layoutIcons() } func createPath() { guard !items.isEmpty else { maskPath = UIBezierPath(roundedRect: bounds, cornerRadius: radius) return } let position = items.count > 4 ? self.position.clamped(min: 0, max: CGFloat(items.count - 1)) : self.position let circleSide: CGFloat = bounds.height - (bottomMargin + spacing) let background = UIBezierPath() let radiusH = CGPoint(x: radius, y: 0) let radiusV = CGPoint(x: 0, y: radius) let circleH = CGPoint(x: circleSide / 2, y: 0) let circleV = CGPoint(x: 0, y: circleSide / 2) let bottomH = CGPoint(x: bottomRadius, y: 0) let bottomV = CGPoint(x: 0, y: bottomRadius) let circleX = bounds.width / CGFloat(items.count + 1) * (position + 1) let topX = CGPoint(x: circleX, y: bounds.minY) background.move(to: topX - circleH - CGPoint(x: spacing, y: 0) - radiusH + circleV - radiusV) background.addArc(withCenter: topX - circleH - CGPoint(x: spacing, y: 0) - radiusH + circleV, radius: radius, startAngle: 3 * .pi / 2, endAngle: 0, clockwise: true) background.addArc(withCenter: topX + circleV, radius: circleSide / 2 + spacing, startAngle: .pi, endAngle: 0, clockwise: false) background.addArc(withCenter: topX + circleH + CGPoint(x: spacing, y: 0) + radiusH + circleV, radius: radius, startAngle: .pi, endAngle: 3 * .pi / 2, clockwise: true) background.addArc(withCenter: bounds.topRight - radiusH + circleV, radius: radius, startAngle: 3 * .pi / 2, endAngle: 0, clockwise: true) background.addLine(to: bounds.bottomRight - radiusV) background.addArc(withCenter: bounds.bottomRight - bottomH - bottomV, radius: bottomRadius, startAngle: 0, endAngle: .pi / 2, clockwise: true) background.addLine(to: bounds.bottomLeft + radiusH) background.addArc(withCenter: bounds.bottomLeft + bottomH - bottomV, radius: bottomRadius, startAngle: .pi / 2, endAngle: .pi, clockwise: true) background.addLine(to: bounds.topLeft + circleV) background.addArc(withCenter: bounds.topLeft + radiusH + circleV, radius: radius, startAngle: .pi, endAngle: 3 * .pi / 2, clockwise: true) background.close() let circleCenter = CGPoint(x: circleX, y: circleV.y) let circle = UIBezierPath(ovalIn: CGRect(center: circleCenter, size: CGSize(side: circleSide))) let path = UIBezierPath() path.append(background) path.append(circle) maskPath = path } func layoutIcons() { let position = items.count > 4 ? self.position.clamped(min: 0, max: CGFloat(items.count - 1)) : self.position let rect = bounds let circleSide: CGFloat = rect.height - (bottomMargin + spacing) let circleV = CGPoint(x: 0, y: circleSide / 2) let circleX = rect.width / CGFloat(items.count + 1) * (position + 1) let circleCenter = CGPoint(x: circleX, y: circleV.y) let topSpacing = rect.minY + circleV.y - radius let iconsYOffset = topSpacing + (rect.height - topSpacing) / 2 imageViews.enumerated().forEach { let index = CGFloat($0.offset) let selected = $0.element.selected let deselected = $0.element.deselected let distance = abs(index - position) selected.center = circleCenter deselected.center = CGPoint(x: rect.width / CGFloat(items.count + 1) * (index + 1), y: iconsYOffset) let firstStep: CGFloat = 0.5 let secondStep: CGFloat = 0.5 if distance < firstStep { selected.alpha = inverseLerp(start: firstStep, end: 0, value: distance) deselected.alpha = 0 } else if distance < secondStep { selected.alpha = 0 deselected.alpha = 0 } else if distance < 1 { selected.alpha = 0 deselected.alpha = inverseLerp(start: secondStep, end: 1, value: distance) } else { selected.alpha = 0 deselected.alpha = 1 } } } open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { return (maskPath?.contains(point) ?? true) ? self : nil } @objc func recognizeTap(with recognizer: UITapGestureRecognizer) { guard recognizer.state == .recognized, !items.isEmpty else { return } let positionX = recognizer.location(in: recognizer.view).x let index = Int(round((positionX / frame.width * CGFloat(items.count + 1)) - 1)) guard (0..<items.count).contains(index) else { return } delegate?.floatingTabBarDidSelect(item: items[index], index: index) } }
38.308756
125
0.574883
b987dbe31dc3f0dff2f66b5bac8be86e96b10071
25,750
// // ALKCreateGroupViewController.swift // // // Created by Mukesh Thawani on 04/05/17. // Copyright © 2017 Applozic. All rights reserved. // import UIKit import Kingfisher import Applozic protocol ALKCreateGroupChatAddFriendProtocol { func createGroupGetFriendInGroupList(friendsSelected: [ALKFriendViewModel],groupName:String,groupImgUrl:String, friendsAdded: [ALKFriendViewModel]) } final class ALKCreateGroupViewController: ALKBaseViewController, Localizable { enum ALKAddContactMode: Localizable { case newChat case existingChat func navigationBarTitle(localizedStringFileName: String) -> String { switch self { case .newChat: return localizedString(forKey: "CreateGroupTitle", withDefaultValue: SystemMessage.NavbarTitle.createGroupTitle, fileName: localizedStringFileName) default: return localizedString(forKey: "EditGroupTitle", withDefaultValue: SystemMessage.NavbarTitle.editGroupTitle, fileName: localizedStringFileName) } } func doneButtonTitle(localizedStringFileName: String) -> String { return localizedString(forKey: "SaveButtonTitle", withDefaultValue: SystemMessage.ButtonName.Save, fileName: localizedStringFileName) } } let cellId = "GroupMemberCell" var groupList = [ALKFriendViewModel]() var addedList = [ALKFriendViewModel]() var addContactMode: ALKAddContactMode = .newChat /// To be passed from outside for existing chat var groupDelegate: ALKCreateGroupChatAddFriendProtocol! private var groupName:String = "" var groupProfileImgUrl = "" var groupId: NSNumber = 0 @IBOutlet weak var participantsLabel: UILabel! @IBOutlet weak var editLabel: UILabel! @IBOutlet fileprivate var btnCreateGroup: UIButton! @IBOutlet fileprivate var tblParticipants: UICollectionView! @IBOutlet fileprivate var txtfGroupName: ALKGroupChatTextField! @IBOutlet fileprivate weak var viewGroupImg: UIView! @IBOutlet fileprivate weak var imgGroupProfile: UIImageView! fileprivate var tempSelectedImg:UIImage! fileprivate var cropedImage: UIImage? fileprivate let activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray) fileprivate lazy var localizedStringFileName: String = configuration.localizedStringFileName var viewModel: ALKCreateGroupViewModel! private var createGroupBGColor: UIColor { return btnCreateGroup.isEnabled ? UIColor.mainRed() : UIColor.disabledButton() } override func viewDidLoad() { super.viewDidLoad() tblParticipants.register(ALKGroupMemberCell.self) tblParticipants.register(ALKGroupMemberCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: cellId) tblParticipants.showsVerticalScrollIndicator = false viewModel = ALKCreateGroupViewModel( groupName: groupName, groupId: groupId, delegate: self, localizationFileName: localizedStringFileName, shouldShowInfoOption: configuration.showInfoOptionInGroupDetail) viewModel.fetchParticipants() setupUI() self.hideKeyboard() } override func addObserver() { NotificationCenter.default.addObserver( forName: NSNotification.Name(rawValue: "Updated_Group_Members"), object: nil, queue: nil, using: { [weak self] notification in guard let weakSelf = self, let channel = notification.object as? ALChannel, channel.key == weakSelf.groupId else { return } weakSelf.viewModel?.fetchParticipants() }) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) txtfGroupName.resignFirstResponder() //self.hideKeyboard() } // MARK: - UI controller @IBAction func dismisssPress(_ sender: Any) { _ = navigationController?.popViewController(animated: true) } @IBAction func createGroupPress(_ sender: Any) { guard var groupName = self.txtfGroupName.text?.trimmingCharacters(in: .whitespacesAndNewlines) else { let msg = localizedString(forKey: "FillGroupName", withDefaultValue: SystemMessage.Warning.FillGroupName, fileName: localizedStringFileName) alert(msg: msg) return } if groupName.lengthOfBytes(using: .utf8) < 1 { let msg = localizedString(forKey: "FillGroupName", withDefaultValue: SystemMessage.Warning.FillGroupName, fileName: localizedStringFileName) alert(msg: msg) return } groupName = self.groupName == groupName ? "" : groupName if self.groupDelegate != nil { if let image = cropedImage { //upload image first guard let uploadUrl = URL(string: ALUserDefaultsHandler.getBASEURL() + IMAGE_UPLOAD_URL) else { NSLog("NO URL TO UPLOAD GROUP PROFILE IMAGE") return } let downloadManager = ALKHTTPManager() activityIndicator.isHidden = false activityIndicator.startAnimating() btnCreateGroup.isEnabled = false downloadManager.upload(image: image, uploadURL: uploadUrl, completion: { imageUrlData in DispatchQueue.main.async { self.activityIndicator.stopAnimating() self.activityIndicator.isHidden = true self.btnCreateGroup.isEnabled = true } guard let data = imageUrlData, let imageUrl = String(data: data, encoding: .utf8) else { NSLog("GROUP PROFILE PICTURE UPDATE FAILED") return } // Pass groupName empty in case of group name update DispatchQueue.main.async { self.groupDelegate.createGroupGetFriendInGroupList(friendsSelected: self.groupList, groupName: groupName, groupImgUrl: imageUrl, friendsAdded: self.addedList) } }) } else { // Pass groupImgUrl empty in case of group name update groupDelegate.createGroupGetFriendInGroupList(friendsSelected:groupList, groupName: groupName, groupImgUrl: "", friendsAdded:addedList) } } } fileprivate func setupUI() { // Textfield Group name if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft { txtfGroupName.textAlignment = .right } activityIndicator.center = CGPoint(x: view.bounds.size.width/2, y: view.bounds.size.height/2) activityIndicator.color = UIColor.lightGray view.addSubview(activityIndicator) activityIndicator.isHidden = true txtfGroupName.layer.cornerRadius = 10 txtfGroupName.layer.borderColor = UIColor.mainRed().cgColor txtfGroupName.layer.borderWidth = 1 txtfGroupName.clipsToBounds = true txtfGroupName.delegate = self setupAttributedPlaceholder(textField: txtfGroupName) //set btns into circle viewGroupImg.layer.cornerRadius = 0.5 * viewGroupImg.frame.size.width viewGroupImg.clipsToBounds = true editLabel.text = localizedString(forKey: "Edit", withDefaultValue: SystemMessage.LabelName.Edit, fileName: localizedStringFileName) participantsLabel.text = localizedString(forKey: "Participants", withDefaultValue: SystemMessage.LabelName.Participants, fileName: localizedStringFileName) if addContactMode == .existingChat { // Button Create Group btnCreateGroup.layer.cornerRadius = 15 btnCreateGroup.clipsToBounds = true btnCreateGroup.setTitle(addContactMode.doneButtonTitle(localizedStringFileName: localizedStringFileName), for: UIControl.State.normal) } else { btnCreateGroup.isHidden = true } txtfGroupName.text = self.groupName updateCreateGroupButtonUI(contactInGroup: groupList.count, groupname: txtfGroupName.trimmedWhitespaceText()) self.tblParticipants.reloadData() self.title = addContactMode.navigationBarTitle(localizedStringFileName: localizedStringFileName) if let url = URL.init(string: groupProfileImgUrl) { let placeHolder = UIImage(named: "group_profile_picture-1", in: Bundle.applozic, compatibleWith: nil) let resource = ImageResource(downloadURL: url, cacheKey:groupProfileImgUrl) imgGroupProfile.kf.setImage(with: resource, placeholder: placeHolder) } } private func setupAttributedPlaceholder(textField: UITextField) { let style = NSMutableParagraphStyle() style.alignment = .left style.lineBreakMode = .byWordWrapping guard let font = UIFont(name: "HelveticaNeue-Italic", size: 14) else { return } let attr:[NSAttributedString.Key:Any] = [ NSAttributedString.Key.font:font, NSAttributedString.Key(rawValue: NSAttributedString.Key.paragraphStyle.rawValue):style, NSAttributedString.Key.foregroundColor: UIColor.placeholderGray() ] let typeGroupNameMsg = localizedString(forKey: "TypeGroupName", withDefaultValue: SystemMessage.LabelName.TypeGroupName, fileName: localizedStringFileName) textField.attributedPlaceholder = NSAttributedString(string: typeGroupNameMsg, attributes: attr) } @IBAction private func selectGroupImgPress(_ sender: Any) { guard let vc = ALKCustomCameraViewController.makeInstanceWith(delegate: self, and: configuration) else {return} self.present(vc, animated: false, completion: nil) } func setCurrentGroupSelected(groupId: NSNumber, groupProfile: String?, delegate: ALKCreateGroupChatAddFriendProtocol) { self.groupDelegate = delegate self.groupId = groupId self.groupName = ALChannelService().getChannelByKey(groupId)?.name ?? "" guard let image = groupProfile else { return } groupProfileImgUrl = image } private func isAtLeastOneContact(contactCount: Int) -> Bool { return viewModel.numberOfRows() != 0 } private func changeCreateGroupButtonState(isEnabled: Bool) { btnCreateGroup.isEnabled = isEnabled btnCreateGroup.backgroundColor = createGroupBGColor } fileprivate func updateCreateGroupButtonUI(contactInGroup: Int, groupname: String) { guard isAtLeastOneContact(contactCount: contactInGroup) else { changeCreateGroupButtonState(isEnabled: false) return } guard !groupname.isEmpty else { changeCreateGroupButtonState(isEnabled: false) return } changeCreateGroupButtonState(isEnabled: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToSelectFriendToAdd" { let selectParticipantViewController = segue.destination as? ALKParticipantSelectionViewContoller selectParticipantViewController?.selectParticipantDelegate = self selectParticipantViewController?.friendsInGroup = self.viewModel.membersInfo selectParticipantViewController?.configuration = configuration } } override func backTapped() { guard let createGroupViewModel = viewModel else { _ = navigationController?.popViewController(animated: true) return } guard let navigationController = navigationController else { return } let cancelTitle = localizedString(forKey: "ButtonCancel", withDefaultValue: SystemMessage.ButtonName.Cancel, fileName: localizedStringFileName) let discardTitle = localizedString(forKey: "ButtonDiscard", withDefaultValue: SystemMessage.ButtonName.Discard, fileName: localizedStringFileName) let alertTitle = localizedString(forKey: "DiscardChangeTitle", withDefaultValue: SystemMessage.LabelName.DiscardChangeTitle, fileName: localizedStringFileName) let alertMessage = localizedString(forKey: "DiscardChangeMessage", withDefaultValue: SystemMessage.Warning.DiscardChange, fileName: localizedStringFileName) UIAlertController.presentDiscardAlert(onPresenter: navigationController, alertTitle: alertTitle, alertMessage: alertMessage, cancelTitle: cancelTitle, discardTitle: discardTitle, onlyForCondition: { () -> Bool in return ( createGroupViewModel.groupName != createGroupViewModel.originalGroupName || cropedImage != nil ) }) { [weak self] in guard let weakSelf = self else { return } _ = weakSelf.navigationController?.popViewController(animated: true) } } private func changeUserRole(at index: Int, _ role: NSNumber) { print() guard ALDataNetworkConnection.checkDataNetworkAvailable() else { let notificationView = ALNotificationView() notificationView.noDataConnectionNotificationView() return } let member = viewModel.rowAt(index: index) let channelUser = ALChannelUser() channelUser.role = role channelUser.userId = member.id let indexPath = IndexPath(row: index, section: 0) let cell = tblParticipants.cellForItem(at: indexPath) as? ALKGroupMemberCell cell?.showLoading() ALChannelService().updateChannel( self.groupId, andNewName: nil, andImageURL: nil, orClientChannelKey: nil, isUpdatingMetaData: false, metadata: nil, orChildKeys: nil, orChannelUsers: [channelUser.dictionary()]) { error in guard error == nil else { print("Error while making admin \(String(describing: error))") return } self.viewModel.updateRoleAt(index: index) self.tblParticipants.performBatchUpdates({ self.tblParticipants.reloadItems(at: [indexPath]) }, completion: { _ in }) } } } extension ALKCreateGroupViewController: ALKCreateGroupViewModelDelegate { func info(at index: Int) { let member = viewModel.rowAt(index: index) let info: [String: Any] = ["Id": member.id, "Name": member.name, "Controller": self] NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UserInfoSelected"), object: info) } func remove(at index: Int) { guard ALDataNetworkConnection.checkDataNetworkAvailable() else { let notificationView = ALNotificationView() notificationView.noDataConnectionNotificationView() return } let member = viewModel.rowAt(index: index) let format = localizedString( forKey: "RemoveFromGroup", withDefaultValue: SystemMessage.GroupDetails.RemoveFromGroup, fileName: localizedStringFileName) let message = String(format: format, member.name, groupName) let optionMenu = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet) let removeButton = localizedString( forKey: "RemoveButtonName", withDefaultValue: SystemMessage.ButtonName.Remove, fileName: localizedStringFileName) let removeAction = UIAlertAction(title: removeButton, style: .destructive, handler: { (_) in let indexPath = IndexPath(row: index, section: 0) let cell = self.tblParticipants.cellForItem(at: indexPath) as? ALKGroupMemberCell cell?.showLoading() ALChannelService().removeMember(fromChannel: member.id, andChannelKey: self.groupId, orClientChannelKey: nil, withCompletion: { (error, response) in guard response != nil, error == nil else { print("Error while removing member from group \(String(describing: error))") return } self.tblParticipants.performBatchUpdates({ self.viewModel.removeAt(index: index) self.tblParticipants.deleteItems(at: [indexPath]) }, completion: { _ in }) }) }) let cancelTitle = localizedString(forKey: "Cancel", withDefaultValue: SystemMessage.LabelName.Cancel, fileName: localizedStringFileName) let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) optionMenu.addAction(removeAction) optionMenu.addAction(cancelAction) self.present(optionMenu, animated: true, completion: nil) } func makeAdmin(at index: Int) { changeUserRole(at: index, NSNumber(value: ADMIN.rawValue)) } func dismissAdmin(at index: Int) { changeUserRole(at: index, NSNumber(value: MEMBER.rawValue)) } func sendMessage(at index: Int) { let member = viewModel.rowAt(index: index) let viewModel = ALKConversationViewModel( contactId: member.id, channelKey: nil, localizedStringFileName: localizedStringFileName) let conversationVC = ALKConversationViewController(configuration: configuration) conversationVC.viewModel = viewModel self.navigationController?.pushViewController(conversationVC, animated: true) } func membersFetched() { tblParticipants.reloadData() updateCreateGroupButtonUI(contactInGroup: groupList.count, groupname: viewModel!.groupName) } } extension ALKCreateGroupViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let viewModel = viewModel, let options = viewModel.optionsForCell(at: indexPath.row) else { return } let memberInfo = viewModel.rowAt(index: indexPath.row) let optionMenu = UIAlertController(title: nil, message: memberInfo.name, preferredStyle: .actionSheet) options.forEach { optionMenu.addAction($0.value(localizationFileName: localizedStringFileName, index: indexPath.row, delegate: self)) } self.present(optionMenu, animated: true, completion: nil) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.numberOfRows() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: ALKGroupMemberCell = tblParticipants.dequeueReusableCell(forIndexPath: indexPath) guard let viewModel = viewModel else { return cell } let member = viewModel.rowAt(index: indexPath.row) cell.updateView(model: member) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return cellHeight() } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard kind == UICollectionView.elementKindSectionHeader else { return UICollectionReusableView() } let header = tblParticipants.dequeueReusableSupplementaryView( ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: cellId, for: indexPath) as! ALKGroupMemberCell let addParticipantText = localizedString( forKey: "AddParticipant", withDefaultValue: SystemMessage.GroupDetails.AddParticipant, fileName: localizedStringFileName) header.updateView(model: GroupMemberInfo(name: addParticipantText)) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(addParticipant)) tapGesture.numberOfTapsRequired = 1 header.addGestureRecognizer(tapGesture) return header } @objc func addParticipant() { guard let groupName = txtfGroupName.text?.trimmingCharacters(in: .whitespacesAndNewlines), groupName.lengthOfBytes(using: .utf8) > 1 else { let msg = localizedString(forKey: "FillGroupName", withDefaultValue: SystemMessage.Warning.FillGroupName, fileName: localizedStringFileName) let alert = UIAlertController(title: nil, message: msg, preferredStyle: .alert) let okButton = self.localizedString(forKey: "OkMessage", withDefaultValue: SystemMessage.ButtonName.ok, fileName: self.localizedStringFileName) let action = UIAlertAction(title: okButton, style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) return } self.performSegue(withIdentifier: "goToSelectFriendToAdd", sender: nil) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { guard let viewModel = viewModel, viewModel.isAddAllowed else { return CGSize(width: 0, height: 0) } return cellHeight() } private func cellHeight() -> CGSize { let height = ALKGroupMemberCell.rowHeight() if #available(iOS 11.0, *) { let safeAreaInsets = self.view.safeAreaInsets return CGSize(width: UIScreen.main.bounds.width - (safeAreaInsets.left + safeAreaInsets.right), height: height) } else { // Fallback on earlier versions return CGSize(width: UIScreen.main.bounds.width, height: height) } } } extension ALKCreateGroupViewController:ALKAddParticipantProtocol { func addParticipantAtIndex(atIndex: IndexPath) { if (atIndex.row == self.groupList.count || self.groupList.isEmpty) { txtfGroupName.resignFirstResponder() self.performSegue(withIdentifier: "goToSelectFriendToAdd", sender: nil) } } func profileTappedAt(index: IndexPath) { guard addContactMode == .existingChat, index.row < groupList.count else {return} let user = groupList[index.row] let viewModel = ALKConversationViewModel( contactId: user.friendUUID, channelKey: nil, localizedStringFileName: localizedStringFileName) let conversationVC = ALKConversationViewController(configuration: configuration) conversationVC.viewModel = viewModel self.navigationController?.pushViewController(conversationVC, animated: true) } } extension ALKCreateGroupViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.txtfGroupName?.resignFirstResponder() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let str = textField.text as NSString? if let text = str?.replacingCharacters(in: range, with: string) { updateCreateGroupButtonUI(contactInGroup: groupList.count, groupname: text) guard let viewModel = viewModel else { return true } let oldStatus = viewModel.isAddParticipantButtonEnabled() viewModel.groupName = text.trimmingCharacters(in: .whitespacesAndNewlines) let newStatus = viewModel.isAddParticipantButtonEnabled() if oldStatus != newStatus { tblParticipants.reloadData() } } return true } } extension ALKCreateGroupViewController: ALKSelectParticipantToAddProtocol { func selectedParticipant(selectedList: [ALKFriendViewModel], addedList: [ALKFriendViewModel]) { self.groupList = selectedList self.addedList = addedList self.createGroupPress(btnCreateGroup) } } extension ALKCreateGroupViewController { override func hideKeyboard() { let tap: UITapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(ALKCreateGroupViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } override func dismissKeyboard() { txtfGroupName.resignFirstResponder() view.endEditing(true) } } extension ALKCreateGroupViewController:ALKCustomCameraProtocol { func customCameraDidTakePicture(cropedImage: UIImage) { // Be back from cropiing camera page self.tempSelectedImg = self.imgGroupProfile.image self.imgGroupProfile.image = cropedImage self.cropedImage = cropedImage } }
43.423272
186
0.666447
de135f52c7c7feb5df01fd6c70d79896ca353653
117
import XCTest import ScheduleTests var tests = [XCTestCaseEntry]() tests += ScheduleTests.allTests() XCTMain(tests)
16.714286
33
0.786325
89456ce14b535f37c1e0283d29326cf3549bf5dc
3,177
// // WidgetRenderer.swift // HelloGtk // // Created by Morten Bek Ditlevsen on 27/11/2020. // import Gtk // TODO: ifdef and replace by something else on linux import Dispatch import TokamakCore // TODO: This is probably not the correct way to hold on to widgets in GTK // but I don't know any better, and it appears that they are not being retained // by being mounted in the UI hierarchy var widgets: [Widget] = [] public final class WidgetTarget: Target { public var view: AnyView var widget: Widget var children: [WidgetTarget] = [] init<V: View>(_ view: V, _ widget: Widget) { self.widget = widget self.view = AnyView(view) } } public final class WidgetRenderer: Renderer { public typealias TargetType = WidgetTarget private let application: ApplicationRef public private(set) var reconciler: StackReconciler<WidgetRenderer>? var rootTarget: WidgetTarget // TODO: Allow definition of 'app' or 'scenes' to abstract window creation public var applicationWindow: ApplicationWindowRef { let window = ApplicationWindowRef(application: application) window.title = "Hello, world" window.setDefaultSize(width: 320, height: 240) window.add(widget: rootTarget.widget) widgets.append(rootTarget.widget) return window } public init<V: View>(_ view: V, application: ApplicationRef) { self.application = application let box = Box(orientation: .vertical, spacing: 10) box.setHalign(align: .center) box.setValign(align: .center) rootTarget = WidgetTarget(view, box) reconciler = StackReconciler( view: view, target: rootTarget, environment: EnvironmentValues(), renderer: self ) { closure in // TODO: ifdef and replace by something else on linux DispatchQueue.main.async { closure() } } } public func mountTarget(before sibling: WidgetTarget?, to parent: WidgetTarget, with host: MountedHost) -> WidgetTarget? { guard let widget: Widget = mapAnyView(host.view, transform: { (v: AnyWidget) in v.create() }) else { if mapAnyView(host.view, transform: { (view: ParentView) in view }) != nil { return parent } return nil } let node = WidgetTarget(host.view, widget) widgets.append(widget) if let container = parent.widget as? Container { container.add(widget: widget) } parent.children.append(node) return node } public func update(target: WidgetTarget, with host: MountedHost) { guard let v = mapAnyView(host.view, transform: { (v: AnyWidget) in v }) else { return } v.update(target.widget) } public func unmount(target: WidgetTarget, from parent: WidgetTarget, with host: MountedHost, completion: @escaping () -> ()) { guard let container = parent.widget as? Container else { return } container.remove(widget: target.widget) widgets.removeAll(where: { target.widget === $0 }) } }
32.418367
130
0.635505
207f156c2f6322609b4527649d2d9db89ff87139
783
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import UIKit class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaTouchSubclass___ { // MARK: - Override Methods override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { } // MARK: - Private Methods // MARK: - Event Response /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
21.162162
78
0.63857
3341399f8cc91f41629c659144c991bc5d5f984c
22,524
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int, Int), y: (Int, Int)) -> Bool { return x.0 == y.0 && x.1 == y.1 } // Some fake predicates for pattern guards. func runced() -> Bool { return true } func funged() -> Bool { return true } func ansed() -> Bool { return true } func runced(x x: Int) -> Bool { return true } func funged(x x: Int) -> Bool { return true } func ansed(x x: Int) -> Bool { return true } func foo() -> Int { return 0 } func bar() -> Int { return 0 } func foobar() -> (Int, Int) { return (0, 0) } func foos() -> String { return "" } func bars() -> String { return "" } func a() {} func b() {} func c() {} func d() {} func e() {} func f() {} func g() {} func a(x x: Int) {} func b(x x: Int) {} func c(x x: Int) {} func d(x x: Int) {} func a(x x: String) {} func b(x x: String) {} func aa(x x: (Int, Int)) {} func bb(x x: (Int, Int)) {} func cc(x x: (Int, Int)) {} // CHECK-LABEL: sil hidden @_TF10switch_var10test_var_1FT_T_ func test_var_1() { // CHECK: function_ref @_TF10switch_var3fooFT_Si switch foo() { // CHECK: [[XADDR:%.*]] = alloc_box $Int // CHECK: [[X:%.*]] = project_box [[XADDR]] // CHECK-NOT: br bb case var x: // CHECK: function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: load [[X]] // CHECK: release [[XADDR]] // CHECK: br [[CONT:bb[0-9]+]] a(x: x) } // CHECK: [[CONT]]: // CHECK: function_ref @_TF10switch_var1bFT_T_ b() } // CHECK-LABEL: sil hidden @_TF10switch_var10test_var_2FT_T_ func test_var_2() { // CHECK: function_ref @_TF10switch_var3fooFT_Si switch foo() { // CHECK: [[XADDR:%.*]] = alloc_box $Int // CHECK: [[X:%.*]] = project_box [[XADDR]] // CHECK: function_ref @_TF10switch_var6runcedFT1xSi_Sb // CHECK: load [[X]] // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] // -- TODO: Clean up these empty waypoint bbs. case var x where runced(x: x): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: load [[X]] // CHECK: release [[XADDR]] // CHECK: br [[CONT:bb[0-9]+]] a(x: x) // CHECK: [[NO_CASE1]]: // CHECK: [[YADDR:%.*]] = alloc_box $Int // CHECK: [[Y:%.*]] = project_box [[YADDR]] // CHECK: function_ref @_TF10switch_var6fungedFT1xSi_Sb // CHECK: load [[Y]] // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]] case var y where funged(x: y): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF10switch_var1bFT1xSi_T_ // CHECK: load [[Y]] // CHECK: release [[YADDR]] // CHECK: br [[CONT]] b(x: y) // CHECK: [[NO_CASE2]]: // CHECK: br [[CASE3:bb[0-9]+]] case var z: // CHECK: [[CASE3]]: // CHECK: [[ZADDR:%.*]] = alloc_box $Int // CHECK: [[Z:%.*]] = project_box [[ZADDR]] // CHECK: function_ref @_TF10switch_var1cFT1xSi_T_ // CHECK: load [[Z]] // CHECK: release [[ZADDR]] // CHECK: br [[CONT]] c(x: z) } // CHECK: [[CONT]]: // CHECK: function_ref @_TF10switch_var1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF10switch_var10test_var_3FT_T_ func test_var_3() { // CHECK: function_ref @_TF10switch_var3fooFT_Si // CHECK: function_ref @_TF10switch_var3barFT_Si switch (foo(), bar()) { // CHECK: [[XADDR:%.*]] = alloc_box $(Int, Int) // CHECK: [[X:%.*]] = project_box [[XADDR]] // CHECK: function_ref @_TF10switch_var6runcedFT1xSi_Sb // CHECK: tuple_element_addr [[X]] : {{.*}}, 0 // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] case var x where runced(x: x.0): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF10switch_var2aaFT1xTSiSi__T_ // CHECK: load [[X]] // CHECK: release [[XADDR]] // CHECK: br [[CONT:bb[0-9]+]] aa(x: x) // CHECK: [[NO_CASE1]]: // CHECK: [[YADDR:%.*]] = alloc_box $Int // CHECK: [[Y:%.*]] = project_box [[YADDR]] // CHECK: [[Z:%.*]] = alloc_box $Int // CHECK: [[Z:%.*]] = project_box [[ZADDR]] // CHECK: function_ref @_TF10switch_var6fungedFT1xSi_Sb // CHECK: load [[Y]] // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]] case (var y, var z) where funged(x: y): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: load [[Y]] // CHECK: function_ref @_TF10switch_var1bFT1xSi_T_ // CHECK: load [[Z]] // CHECK: release [[ZADDR]] // CHECK: release [[YADDR]] // CHECK: br [[CONT]] a(x: y) b(x: z) // CHECK: [[NO_CASE2]]: // CHECK: [[WADDR:%.*]] = alloc_box $(Int, Int) // CHECK: [[W:%.*]] = project_box [[WADDR]] // CHECK: function_ref @_TF10switch_var5ansedFT1xSi_Sb // CHECK: tuple_element_addr [[W]] : {{.*}}, 0 // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]] case var w where ansed(x: w.0): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF10switch_var2bbFT1xTSiSi__T_ // CHECK: load [[W]] // CHECK: br [[CONT]] bb(x: w) // CHECK: [[NO_CASE3]]: // CHECK: release [[WADDR]] // CHECK: br [[CASE4:bb[0-9]+]] case var v: // CHECK: [[CASE4]]: // CHECK: [[VADDR:%.*]] = alloc_box $(Int, Int) // CHECK: [[V:%.*]] = project_box [[VADDR]] // CHECK: function_ref @_TF10switch_var2ccFT1xTSiSi__T_ // CHECK: load [[V]] // CHECK: release [[VADDR]] // CHECK: br [[CONT]] cc(x: v) } // CHECK: [[CONT]]: // CHECK: function_ref @_TF10switch_var1dFT_T_ d() } protocol P { func p() } struct X : P { func p() {} } struct Y : P { func p() {} } struct Z : P { func p() {} } // CHECK-LABEL: sil hidden @_TF10switch_var10test_var_4FT1pPS_1P__T_ func test_var_4(p p: P) { // CHECK: function_ref @_TF10switch_var3fooFT_Si switch (p, foo()) { // CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int) // CHECK: store // CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0 // CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1 // CHECK: [[PAIR_1:%.*]] = load [[T0]] : $*Int // CHECK: [[TMP:%.*]] = alloc_stack $X // CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]] // CHECK: [[IS_X]]: // CHECK: [[T0:%.*]] = load [[TMP]] : $*X // CHECK: [[XADDR:%.*]] = alloc_box $Int // CHECK: [[X:%.*]] = project_box [[XADDR]] // CHECK: store [[PAIR_1]] to [[X]] // CHECK: function_ref @_TF10switch_var6runcedFT1xSi_Sb // CHECK: load [[X]] // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] case (is X, var x) where runced(x: x): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: release [[XADDR]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[PAIR_0]] : $*P // CHECK: dealloc_stack [[PAIR]] // CHECK: br [[CONT:bb[0-9]+]] a(x: x) // CHECK: [[NO_CASE1]]: // CHECK: release [[XADDR]] // CHECK: dealloc_stack [[TMP]] // CHECK: br [[NEXT:bb[0-9]+]] // CHECK: [[IS_NOT_X]]: // CHECK: dealloc_stack [[TMP]] // CHECK: br [[NEXT]] // CHECK: [[NEXT]]: // CHECK: [[TMP:%.*]] = alloc_stack $Y // CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]] // CHECK: [[IS_Y]]: // CHECK: [[T0:%.*]] = load [[TMP]] : $*Y // CHECK: [[YADDR:%.*]] = alloc_box $Int // CHECK: [[Y:%.*]] = project_box [[YADDR]] // CHECK: store [[PAIR_1]] to [[Y]] // CHECK: function_ref @_TF10switch_var6fungedFT1xSi_Sb // CHECK: load [[Y]] // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]] case (is Y, var y) where funged(x: y): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF10switch_var1bFT1xSi_T_ // CHECK: load [[Y]] // CHECK: release [[YADDR]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[PAIR_0]] : $*P // CHECK: dealloc_stack [[PAIR]] // CHECK: br [[CONT]] b(x: y) // CHECK: [[NO_CASE2]]: // CHECK: release [[YADDR]] // CHECK: dealloc_stack [[TMP]] // CHECK: br [[NEXT:bb[0-9]+]] // CHECK: [[IS_NOT_Y]]: // CHECK: dealloc_stack [[TMP]] // CHECK: br [[NEXT]] // CHECK: [[NEXT]]: // CHECK: [[ZADDR:%.*]] = alloc_box $(P, Int) // CHECK: [[Z:%.*]] = project_box [[ZADDR]] // CHECK: function_ref @_TF10switch_var5ansedFT1xSi_Sb // CHECK: tuple_element_addr [[Z]] : {{.*}}, 1 // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]] case var z where ansed(x: z.1): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF10switch_var1cFT1xSi_T_ // CHECK: tuple_element_addr [[Z]] : {{.*}}, 1 // CHECK: release [[ZADDR]] // CHECK-NEXT: dealloc_stack [[PAIR]] // CHECK: br [[CONT]] c(x: z.1) // CHECK: [[DFLT_NO_CASE3]]: // CHECK: release [[ZADDR]] // CHECK: br [[CASE4:bb[0-9]+]] case (_, var w): // CHECK: [[CASE4]]: // CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0 // CHECK: [[WADDR:%.*]] = alloc_box $Int // CHECK: [[W:%.*]] = project_box [[WADDR]] // CHECK: function_ref @_TF10switch_var1dFT1xSi_T_ // CHECK: load [[W]] // CHECK: release [[WADDR]] // CHECK: destroy_addr [[PAIR_0]] : $*P // CHECK: dealloc_stack [[PAIR]] // CHECK: br [[CONT]] d(x: w) } e() } // CHECK-LABEL: sil hidden @_TF10switch_var10test_var_5FT_T_ : $@convention(thin) () -> () { func test_var_5() { // CHECK: function_ref @_TF10switch_var3fooFT_Si // CHECK: function_ref @_TF10switch_var3barFT_Si switch (foo(), bar()) { // CHECK: [[XADDR:%.*]] = alloc_box $(Int, Int) // CHECK: [[X:%.*]] = project_box [[XADDR]] // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] case var x where runced(x: x.0): // CHECK: [[CASE1]]: // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NO_CASE1]]: // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]] // CHECK: [[ZADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]] // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]] case (var y, var z) where funged(x: y): // CHECK: [[CASE2]]: // CHECK: release [[ZADDR]] // CHECK: release [[YADDR]] // CHECK: br [[CONT]] b() // CHECK: [[NO_CASE2]]: // CHECK: release [[ZADDR]] // CHECK: release [[YADDR]] // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]] case (_, _) where runced(): // CHECK: [[CASE3]]: // CHECK: br [[CONT]] c() // CHECK: [[NO_CASE3]]: // CHECK: br [[CASE4:bb[0-9]+]] case _: // CHECK: [[CASE4]]: // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: e() } // CHECK-LABEL: sil hidden @_TF10switch_var15test_var_returnFT_T_ : $@convention(thin) () -> () { func test_var_return() { switch (foo(), bar()) { case var x where runced(): // CHECK: [[XADDR:%[0-9]+]] = alloc_box $(Int, Int) // CHECK: [[X:%[0-9]+]] = project_box [[XADDR]] // CHECK: function_ref @_TF10switch_var1aFT_T_ // CHECK: release [[XADDR]] // CHECK: br [[EPILOG:bb[0-9]+]] a() return // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]] // CHECK: [[ZADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]] case (var y, var z) where funged(): // CHECK: function_ref @_TF10switch_var1bFT_T_ // CHECK: release [[ZADDR]] // CHECK: release [[YADDR]] // CHECK: br [[EPILOG]] b() return case var w where ansed(): // CHECK: [[WADDR:%[0-9]+]] = alloc_box $(Int, Int) // CHECK: [[W:%[0-9]+]] = project_box [[WADDR]] // CHECK: function_ref @_TF10switch_var1cFT_T_ // CHECK-NOT: release [[ZADDR]] // CHECK-NOT: release [[YADDR]] // CHECK: release [[WADDR]] // CHECK: br [[EPILOG]] c() return case var v: // CHECK: [[VADDR:%[0-9]+]] = alloc_box $(Int, Int) // CHECK: [[V:%[0-9]+]] = project_box [[VADDR]] // CHECK: function_ref @_TF10switch_var1dFT_T_ // CHECK-NOT: release [[ZADDR]] // CHECK-NOT: release [[YADDR]] // CHECK: release [[VADDR]] // CHECK: br [[EPILOG]] d() return } } // When all of the bindings in a column are immutable, don't emit a mutable // box. <rdar://problem/15873365> // CHECK-LABEL: sil hidden @_TF10switch_var8test_letFT_T_ : $@convention(thin) () -> () { func test_let() { // CHECK: [[FOOS:%.*]] = function_ref @_TF10switch_var4foosFT_SS // CHECK: [[VAL:%.*]] = apply [[FOOS]]() // CHECK: retain_value [[VAL]] // CHECK: function_ref @_TF10switch_var6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] switch foos() { case let x where runced(): // CHECK: [[CASE1]]: // CHECK: [[A:%.*]] = function_ref @_TF10switch_var1aFT1xSS_T_ // CHECK: retain_value [[VAL]] // CHECK: apply [[A]]([[VAL]]) // CHECK: release_value [[VAL]] // CHECK: release_value [[VAL]] // CHECK: br [[CONT:bb[0-9]+]] a(x: x) // CHECK: [[NO_CASE1]]: // CHECK: release_value [[VAL]] // CHECK: br [[TRY_CASE2:bb[0-9]+]] // CHECK: [[TRY_CASE2]]: // CHECK: retain_value [[VAL]] // CHECK: function_ref @_TF10switch_var6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]] case let y where funged(): // CHECK: [[CASE2]]: // CHECK: [[B:%.*]] = function_ref @_TF10switch_var1bFT1xSS_T_ // CHECK: retain_value [[VAL]] // CHECK: apply [[B]]([[VAL]]) // CHECK: release_value [[VAL]] // CHECK: release_value [[VAL]] // CHECK: br [[CONT]] b(x: y) // CHECK: [[NO_CASE2]]: // CHECK: retain_value [[VAL]] // CHECK: function_ref @_TF10switch_var4barsFT_SS // CHECK: retain_value [[VAL]] // CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]] // CHECK: [[YES_CASE3]]: // CHECK: release_value [[VAL]] // CHECK: release_value [[VAL]] // ExprPatterns implicitly contain a 'let' binding. case bars(): // CHECK: function_ref @_TF10switch_var1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[NO_CASE3]]: // CHECK: release_value [[VAL]] // CHECK: br [[LEAVE_CASE3:bb[0-9]+]] // CHECK: [[LEAVE_CASE3]]: case _: // CHECK: release_value [[VAL]] // CHECK: function_ref @_TF10switch_var1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: return } // If one of the bindings is a "var", allocate a box for the column. // CHECK-LABEL: sil hidden @_TF10switch_var18test_mixed_let_varFT_T_ : $@convention(thin) () -> () { func test_mixed_let_var() { // CHECK: [[FOOS:%.*]] = function_ref @_TF10switch_var4foosFT_SS // CHECK: [[VAL:%.*]] = apply [[FOOS]]() switch foos() { case var x where runced(): // CHECK: [[BOX:%.*]] = alloc_box $String, var, name "x" // CHECK: [[PBOX:%.*]] = project_box [[BOX]] // CHECK: store [[VAL]] to [[PBOX]] // CHECK: [[A:%.*]] = function_ref @_TF10switch_var1aFT1xSS_T_ // CHECK: [[X:%.*]] = load [[PBOX]] // CHECK: retain_value [[X]] // CHECK: apply [[A]]([[X]]) a(x: x) case let y where funged(): // CHECK: [[B:%.*]] = function_ref @_TF10switch_var1bFT1xSS_T_ // CHECK: retain_value [[VAL]] // CHECK: apply [[B]]([[VAL]]) b(x: y) case bars(): c() case _: d() } } // CHECK-LABEL: sil hidden @_TF10switch_var23test_multiple_patterns1FT_T_ : $@convention(thin) () -> () { func test_multiple_patterns1() { // CHECK: function_ref @_TF10switch_var6foobarFT_TSiSi_ switch foobar() { // CHECK-NOT: br bb case (0, let x), (let x, 0): // CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]] // CHECK: [[FIRST_MATCH_CASE]]: // CHECK: debug_value [[FIRST_X:%.*]] : // CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int) // CHECK: [[FIRST_FAIL]]: // CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]] // CHECK: [[SECOND_MATCH_CASE]]: // CHECK: debug_value [[SECOND_X:%.*]] : // CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int) // CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int): // CHECK: [[A:%.*]] = function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: apply [[A]]([[BODY_VAR]]) a(x: x) default: // CHECK: [[SECOND_FAIL]]: // CHECK: function_ref @_TF10switch_var1bFT_T_ b() } } // CHECK-LABEL: sil hidden @_TF10switch_var23test_multiple_patterns2FT_T_ : $@convention(thin) () -> () { func test_multiple_patterns2() { let t1 = 2 let t2 = 4 // CHECK: debug_value [[T1:%.*]] : // CHECK: debug_value [[T2:%.*]] : switch (0,0) { // CHECK-NOT: br bb case (_, let x) where x > t1, (let x, _) where x > t2: // CHECK: [[FIRST_X:%.*]] = tuple_extract {{%.*}} : $(Int, Int), 1 // CHECK: debug_value [[FIRST_X]] : // CHECK: apply {{%.*}}([[FIRST_X]], [[T1]]) // CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]] // CHECK: [[FIRST_MATCH_CASE]]: // CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int) // CHECK: [[FIRST_FAIL]]: // CHECK: debug_value [[SECOND_X:%.*]] : // CHECK: apply {{%.*}}([[SECOND_X]], [[T2]]) // CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]] // CHECK: [[SECOND_MATCH_CASE]]: // CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int) // CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int): // CHECK: [[A:%.*]] = function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: apply [[A]]([[BODY_VAR]]) a(x: x) default: // CHECK: [[SECOND_FAIL]]: // CHECK: function_ref @_TF10switch_var1bFT_T_ b() } } enum Foo { case A(Int, Double) case B(Double, Int) case C(Int, Int, Double) } // CHECK-LABEL: sil hidden @_TF10switch_var23test_multiple_patterns3FT_T_ : $@convention(thin) () -> () { func test_multiple_patterns3() { let f = Foo.C(0, 1, 2.0) switch f { // CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]] case .A(let x, let n), .B(let n, let x), .C(_, let x, let n): // CHECK: [[A]]({{%.*}} : $(Int, Double)): // CHECK: [[A_X:%.*]] = tuple_extract // CHECK: [[A_N:%.*]] = tuple_extract // CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double) // CHECK: [[B]]({{%.*}} : $(Double, Int)): // CHECK: [[B_N:%.*]] = tuple_extract // CHECK: [[B_X:%.*]] = tuple_extract // CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double) // CHECK: [[C]]({{%.*}} : $(Int, Int, Double)): // CHECK: [[C__:%.*]] = tuple_extract // CHECK: [[C_X:%.*]] = tuple_extract // CHECK: [[C_N:%.*]] = tuple_extract // CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double) // CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double): // CHECK: [[FUNC_A:%.*]] = function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: apply [[FUNC_A]]([[BODY_X]]) a(x: x) } } enum Bar { case Y(Foo, Int) case Z(Int, Foo) } // CHECK-LABEL: sil hidden @_TF10switch_var23test_multiple_patterns4FT_T_ : $@convention(thin) () -> () { func test_multiple_patterns4() { let b = Bar.Y(.C(0, 1, 2.0), 3) switch b { // CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]] case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _): // CHECK: [[Y]]({{%.*}} : $(Foo, Int)): // CHECK: [[Y_F:%.*]] = tuple_extract // CHECK: [[Y_X:%.*]] = tuple_extract // CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]] // CHECK: [[A]]({{%.*}} : $(Int, Double)): // CHECK: [[A_X:%.*]] = tuple_extract // CHECK: [[A_N:%.*]] = tuple_extract // CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int) // CHECK: [[B]]({{%.*}} : $(Double, Int)): // CHECK: [[B_N:%.*]] = tuple_extract // CHECK: [[B_X:%.*]] = tuple_extract // CHECK: br [[CASE_BODY]]([[B_X]] : $Int) // CHECK: [[C]]({{%.*}} : $(Int, Int, Double)): // CHECK: br [[CASE_BODY]]([[Y_X]] : $Int) // CHECK: [[Z]]({{%.*}} : $(Int, Foo)): // CHECK: [[Z_X:%.*]] = tuple_extract // CHECK: [[Z_F:%.*]] = tuple_extract // CHECK: br [[CASE_BODY]]([[Z_X]] : $Int) // CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int): // CHECK: [[FUNC_A:%.*]] = function_ref @_TF10switch_var1aFT1xSi_T_ // CHECK: apply [[FUNC_A]]([[BODY_X]]) a(x: x) } } func aaa(x x: inout Int) {} // CHECK-LABEL: sil hidden @_TF10switch_var23test_multiple_patterns5FT_T_ : $@convention(thin) () -> () { func test_multiple_patterns5() { let b = Bar.Y(.C(0, 1, 2.0), 3) switch b { // CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]] case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _): // CHECK: [[Y]]({{%.*}} : $(Foo, Int)): // CHECK: [[Y_F:%.*]] = tuple_extract // CHECK: [[Y_X:%.*]] = tuple_extract // CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]] // CHECK: [[A]]({{%.*}} : $(Int, Double)): // CHECK: [[A_X:%.*]] = tuple_extract // CHECK: [[A_N:%.*]] = tuple_extract // CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int) // CHECK: [[B]]({{%.*}} : $(Double, Int)): // CHECK: [[B_N:%.*]] = tuple_extract // CHECK: [[B_X:%.*]] = tuple_extract // CHECK: br [[CASE_BODY]]([[B_X]] : $Int) // CHECK: [[C]]({{%.*}} : $(Int, Int, Double)): // CHECK: br [[CASE_BODY]]([[Y_X]] : $Int) // CHECK: [[Z]]({{%.*}} : $(Int, Foo)): // CHECK: [[Z_X:%.*]] = tuple_extract // CHECK: [[Z_F:%.*]] = tuple_extract // CHECK: br [[CASE_BODY]]([[Z_X]] : $Int) // CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int): // CHECK: store [[BODY_X]] to [[BOX_X:%.*]] : $*Int // CHECK: [[FUNC_AAA:%.*]] = function_ref @_TF10switch_var3aaaFT1xRSi_T_ // CHECK: apply [[FUNC_AAA]]([[BOX_X]]) aaa(x: &x) } }
35.304075
161
0.53352
fc0ff0a31b21a7bd6d08820f552ed3a536c7ab5f
2,677
// // LOLViewModel.swift // DouYuTV // // Created by 小琦 on 2018/8/26. // Copyright © 2018年 单琦. All rights reserved. // import UIKit class LOLViewModel: BaseViewModel { private var count : Int = 0 lazy var lolGameModels : [ClassifyModel] = [ClassifyModel]() } extension LOLViewModel{ //pragma mark: -下拉刷新 func requestData(type: HomeStyle,_ finishCallback : @escaping () -> ()){ count = 0 //0.定义参数 let parameters = ["client_sys":"ios"] requestAnchorData(isGroupData: true, urlString: "https://apiv2.douyucdn.cn/gv2api/rkc/roomlistV1/\(type.lolID)/\(count)/20/ios", method: .get, parameters: parameters, finishedCallBack: finishCallback) } //pragma mark: -上拉加载 func requestMoreData(type: HomeStyle,_ finishCallback : @escaping () -> ()){ count += 20 let parameters = ["client_sys":"ios"] requestAnchorData(isGroupData: true, urlString: "https://apiv2.douyucdn.cn/gv2api/rkc/roomlistV1/\(type.lolID)/\(count)/20/ios", method: .get, parameters: parameters, finishedCallBack: finishCallback) } //pragma mark: -顶部滚动图片 func requestCyclePictureData(_ finishCallback : @escaping () -> ()){ requestCyclePicture(urlString: "https://apiv2.douyucdn.cn/live/Slide/getSlideLists?cate_id=1&app_ver=\(app_ver)&client_sys=ios", method: .get, finishedCallBack: finishCallback) } //pragma mark: -推荐左右滚动数据 //pragma mark: -按英雄的种类 func requestLolGameData(_ finishCallback : @escaping () -> ()){ NetworkTools.requestData(urlString: "https://apiv2.douyucdn.cn/Live/Wzry/getAllTag2List?cate2_id=1&cache=4.6.0&client_sys=ios", type: .get) { (result) in // 1.对结果进行处理 guard let resultDic = result as? [String : Any] else {return} guard let dataArray = resultDic["data"] as? [[String : Any]] else {return} for dic in dataArray{ self.lolGameModels.append(ClassifyModel(dict: dic)) } finishCallback() } } //pragma mark: -请求英雄分类 func requestHeroData(_ finishedCallBack : @escaping () -> ()){ NetworkTools.requestData(urlString: "https://apiv2.douyucdn.cn/Live/Wzry/getAllTag1WithTag2List?cate2_id=1&cache=4.6.0&client_sys=ios", type: .get) { (result) in // 1.对结果进行处理 guard let resultDic = result as? [String : Any] else {return} guard let dataArray = resultDic["data"] as? [[String : Any]] else {return} for dict in dataArray{ self.anchorClassifyModel.append(AnchorClassifyModel(dict: dict)) } finishedCallBack() } } }
41.184615
208
0.63093
18e79021d457a7ba59adb6518be26b7707557525
2,142
// // 🦠 Corona-Warn-App // import Foundation import UIKit class DiaryInfoViewController: DynamicTableViewController, ENANavigationControllerWithFooterChild { // MARK: - Init init( viewModel: DiaryInfoViewModel, onDismiss: @escaping () -> Void ) { self.viewModel = viewModel self.onDismiss = onDismiss super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() setupView() if !viewModel.hidesCloseButton { navigationItem.rightBarButtonItem = CloseBarButtonItem( onTap: { [weak self] in self?.onDismiss() } ) } navigationController?.navigationBar.prefersLargeTitles = true footerView?.primaryButton?.accessibilityIdentifier = AccessibilityIdentifiers.ExposureSubmission.primaryButton } override var navigationItem: UINavigationItem { navigationFooterItem } // MARK: - Protocol ENANavigationControllerWithFooterChild func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapPrimaryButton button: UIButton) { onDismiss() } // MARK: - Internal enum ReuseIdentifiers: String, TableViewCellReuseIdentifiers { case legalExtended = "DynamicLegalExtendedCell" } // MARK: - Private private let viewModel: DiaryInfoViewModel private let onDismiss: () -> Void private lazy var navigationFooterItem: ENANavigationFooterItem = { let item = ENANavigationFooterItem() item.primaryButtonTitle = AppStrings.ContactDiary.Information.primaryButtonTitle item.isPrimaryButtonEnabled = true item.isSecondaryButtonHidden = true item.title = AppStrings.ContactDiary.Information.title return item }() private func setupView() { view.backgroundColor = .enaColor(for: .background) tableView.register( UINib(nibName: String(describing: DynamicLegalExtendedCell.self), bundle: nil), forCellReuseIdentifier: ReuseIdentifiers.legalExtended.rawValue ) dynamicTableViewModel = viewModel.dynamicTableViewModel tableView.separatorStyle = .none } }
23.538462
125
0.764239
e5b346ca37bbc253a2fe08fd8b0168599526b77c
1,765
// // AppDelegate.swift // FlappyBird // // Created by Hristoslav-PC on 11/21/21. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. } 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. } }
43.04878
285
0.752408
2f39a389d5027171b9d46b84677218726ba8604c
926
// // ServersPack.swift // GetCoupon // // Created by Nikita Konashenko on 08.07.2020. // Copyright © 2020 Nikita Konashenko. All rights reserved. // import Foundation class ServersPack: Decodable { let defaultServer: ServerData let contactEmail: String let license: String let businessCardWebsite: String // MARK: - Decodable enum CodingKeys: CodingKey { case defaultServer, contactEmail, iosLicense, businessCardWebsite } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.defaultServer = try container.decode(ServerData.self, forKey: .defaultServer) self.contactEmail = try container.decode(String.self, forKey: .contactEmail) self.license = try container.decode(String.self, forKey: .iosLicense) self.businessCardWebsite = try container.decode(String.self, forKey: .businessCardWebsite) } }
28.9375
94
0.741901
7934ea3292fba3dbb024e1e8f274840d6dca64be
1,402
// // UIAlertController+adds.swift // myPlace // // Created by Mac on 06/12/2018. // Copyright © 2018 Unit. All rights reserved. // import UIKit extension UIAlertController { func addImage(imageO: UIImage?) { if let image = imageO { let maxSize : CGSize = CGSize(width: 240, height: 300) let imageSize = image.size var ratio: CGFloat! if (imageSize.width > imageSize.height) { ratio = maxSize.width / imageSize.width } else { ratio = maxSize.height / imageSize.height } let scaledSize = CGSize(width: imageSize.width * ratio, height: imageSize.height * ratio) var scaledImage = image.withSize(scaledSize)! if imageSize.height > imageSize.width { let left = (maxSize.width - scaledImage.size.width) / 2 scaledImage = scaledImage.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: -left, bottom: 0, right: 0)) } let imageAction = UIAlertAction(title: "", style: .default, handler: nil) imageAction.isEnabled = false imageAction.setValue(scaledImage.withRenderingMode(.alwaysOriginal), forKey: "image") self.addAction(imageAction) } } }
31.155556
121
0.552782
673d86f85ae3003ba9964fb3bf30bc0e0423f446
8,258
// Copyright (c) 2019, OpenEmu Team // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the OpenEmu Team nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import XCTest @testable import OpenEmuShaders class ConfigScannerTests: XCTestCase { func testConfigScan() { var c = ConfigScanner( """ shaders = 5 # this is a comment shader0 = "foo" alias0 = firstPass alias1 = ../this/and/that.foo scale0 = 2.0 type0 = hi_there # remaining comment type1 = "hello there" # remaining comment type2 = "hello #ignore this there" # remaining comment shadow_linear = clamp_to_border """) let expected = [ ("shaders", "5"), ("shader0", "foo"), ("alias0", "firstPass"), ("alias1", "../this/and/that.foo"), ("scale0", "2.0"), ("type0", "hi_there"), ("type1", "hello there"), ("type2", "hello #ignore this there"), ("shadow_linear", "clamp_to_border"), ] for (expKey, expVal) in expected { switch c.scan() { case .keyval(let key, let val): XCTAssertEqual(key, expKey, "unexpected key") XCTAssertEqual(val, expVal, "unexpected value") case .eof: XCTFail("unexpected .eof") } } } @available(OSX 10.15, *) func testPerformanceExample() { self.measure(metrics: [XCTCPUMetric(limitingToCurrentThread: true), XCTClockMetric()]) { var c = ConfigScanner( """ shaders = 5 # this is a comment shader0 = "foo" alias0 = firstPass alias1 = ../this/and/that.foo scale0 = 2.0 type0 = hi_there # remaining comment type1 = "hello there" # remaining comment type2 = "hello #ignore this there" # remaining comment """) scanning: while true { switch c.scan() { case .keyval: continue case .eof: break scanning } } } } } class ShaderConfigSerializationTests: XCTestCase { func testParameterGroups() { let script = """ shaders = 0 parameter_groups = "foo;bar" foo_group_desc = "Foo Desc" foo_group_parameters = "a;b;c" bar_group_parameters = "d;e" bar_group_hidden = true """ do { let res = try ShaderConfigSerialization.parseConfig(script) guard let groups = res["parameterGroups"] as? [[String: AnyObject]] else { return XCTFail("expected parameterGroups") } let checkGroup = { (group: [String: AnyObject], desc: String, hidden: Bool, params: [String]) -> Void in XCTAssertEqual(group["desc"] as? String, desc) XCTAssertEqual(group["hidden"] as? Bool, hidden) XCTAssertEqual(group["parameters"] as? [String], params) } checkGroup(groups[0], "Foo Desc", false, ["a", "b", "c"]) checkGroup(groups[1], "bar", true, ["d", "e"]) } catch { XCTFail("unexpected error: \(error.localizedDescription)") } } func testParameterGroupsWithDefaultOverride() { let script = """ shaders = 0 parameter_groups = "foo;default;bar" foo_group_desc = "Foo Desc" foo_group_parameters = "a;b;c" default_group_desc = "Overridden" bar_group_parameters = "d;e" bar_group_hidden = true """ do { let res = try ShaderConfigSerialization.parseConfig(script) guard let groups = res["parameterGroups"] as? [[String: AnyObject]] else { return XCTFail("expected parameterGroups") } let checkGroup = { (group: [String: AnyObject], desc: String, hidden: Bool, params: [String]) -> Void in XCTAssertEqual(group["desc"] as? String, desc) XCTAssertEqual(group["hidden"] as? Bool, hidden) XCTAssertEqual(group["parameters"] as? [String], params) } checkGroup(groups[0], "Foo Desc", false, ["a", "b", "c"]) checkGroup(groups[2], "bar", true, ["d", "e"]) } catch { XCTFail("unexpected error: \(error.localizedDescription)") } } func testSlangFromString() { do { let res = try ShaderConfigSerialization.parseConfig(Self.phosphorlut) print(res) } catch { XCTFail("unexpected error: \(error.localizedDescription)") } } // swiftlint:disable line_length static let phosphorlut = """ shaders = 5 shader0 = shaders/phosphorlut/scanlines-interlace-linearize.slang alias0 = firstPass scale0 = 2.0 scale_type0 = source srgb_framebuffer0 = true filter_linear0 = false shader1 = ../blurs/blur5fast-vertical.slang scale_type1 = source scale1 = 1.0 srgb_framebuffer1 = true filter_linear1 = true alias1 = blurPassV shader2 = ../blurs/blur5fast-horizontal.slang alias2 = blurPass filter_linear2 = true scale2 = 1.0 scale_type2 = source srgb_framebuffer2 = true shader3 = shaders/phosphorlut/phosphorlut-pass0.slang alias3 = phosphorPass filter_linear3 = true scale_type3 = source scale_x3 = 4.0 scale_y3 = 2.0 srgb_framebuffer3 = true shader4 = shaders/phosphorlut/phosphorlut-pass1.slang filter_linear4 = true textures = "shadow;aperture;slot" shadow = shaders/phosphorlut/luts/shadowmask.png shadow_linear = true shadow_wrap_mode = "repeat" aperture = shaders/phosphorlut/luts/aperture-grille.png aperture_linear = true aperture_wrap_mode = "repeat" slot = shaders/phosphorlut/luts/slotmask.png slot_linear = true slot_wrap_mode = "repeat" parameters = box_scale;location;in_res_x;in_res_y;TVOUT_RESOLUTION;TVOUT_COMPOSITE_CONNECTION;TVOUT_TV_COLOR_LEVELS;enable_480i;top_field_first box_scale = 2.000000 location = 0.500000 in_res_x = 240.000000 in_res_y = 160.000000 TVOUT_RESOLUTION = 512.000000 TVOUT_COMPOSITE_CONNECTION = 0.000000 TVOUT_TV_COLOR_LEVELS = 1.000000 enable_480i = 1.000000 top_field_first = 1.000000 """ }
34.843882
151
0.577622
f8d3da4667b30dc9edecc400ed3b4c84786673ff
2,655
// // NKPoint.swift // NKAdditionalGeometry // // Created by Nick Kopilovskii on 9/27/18. // import CoreGraphics public protocol NKPoint { /** Transformation of a point from one coordinate system to another - Parameters: - initial: `CGRect` of coordinate system which contains current `CGPoint` instance - destination: `CGRect` of coordinate system in which needs to get point corresponding to the current `CGPoint` instance - Returns: `CGPoint` in `destinationRect` coordinate system corresponding to current instance in `initialRect` coordinate system */ func similar(from initial: CGRect, in destination: CGRect) -> CGPoint /** - Parameters: - point: `CGPoint` to which needs to calculate difference in values of the corresponding coordinates - Returns: `CGVector` difference in values of the corresponding coordinates */ func diffence(with point: CGPoint) -> CGVector /** - Parameters: - difference: `CGVector` difference in values of the corresponding coordinates between two points - Returns: `CGPoint` by adding difference in values of the corresponding coordinates to current instance */ func point(byAdding difference: CGVector) -> CGPoint /** - Parameters: - point: `CGPoint` to which needs to calculate the distance - Returns: `CGFloat` distance between current instance and `point` */ func distance(to point: CGPoint) -> CGFloat /** - Parameters: - p1: `CGPoint` to which needs to calculate the distance - p2: `CGPoint` to which needs to calculate the distance - Returns: `CGFloat` angle between segments `instance-p1` and `instance-p2` */ func angle(with p1: CGPoint, _ p2: CGPoint) -> CGFloat /** The method calculates equidistant points from the instance with an equal radial pitch between them. In other words, the method divides the circle into equal segments - Parameters: - count: `Int` count of devide points - radius: `CGFloat` remoteness of computed points from the instance - Returns: `[CGPoint]` array of equidistant points from the instance with an equal radial pitch between them */ func devidePoints(count: Int, for radius: CGFloat) -> [CGPoint] /** The method calculates `CGPoint` at a given distance with the angle of deviation from the axis Ox - Parameters: - count: `Int` count of devide points - angle: `CGFloat` angle based on instance - Returns: `[CGPoint]` array of equidistant points from the instance with an equal radial pitch between them */ func point(on distance: CGFloat, with angle: CGFloat) -> CGPoint }
37.394366
131
0.706215
1c0ae7b0c73e89dec1bfcdb17740523cd95b7cad
2,955
// // ViewController.swift // // Copyright © 2018 BitcoinKit developers // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import BitcoinKit class ViewController: UIViewController { @IBOutlet private weak var qrCodeImageView: UIImageView! @IBOutlet private weak var addressLabel: UILabel! @IBOutlet private weak var balanceLabel: UILabel! @IBOutlet private weak var destinationAddressTextField: UITextField! private var wallet: Wallet? = Wallet() override func viewDidLoad() { super.viewDidLoad() self.createWalletIfNeeded() self.updateLabels() } func createWalletIfNeeded() { if wallet == nil { let privateKey = PrivateKey(network: .testnetBCH) wallet = Wallet(privateKey: privateKey) wallet?.save() } } func updateLabels() { qrCodeImageView.image = wallet?.address.qrImage() addressLabel.text = wallet?.address.cashaddr if let balance = wallet?.balance() { balanceLabel.text = "Balance : \(balance) satoshi" } } func updateBalance() { wallet?.reloadBalance(completion: { [weak self] (utxos) in DispatchQueue.main.async { self?.updateLabels() } }) } @IBAction func didTapReloadBalanceButton(_ sender: UIButton) { updateBalance() } @IBAction func didTapSendButton(_ sender: UIButton) { guard let addressString = destinationAddressTextField.text else { return } do { let address: BitcoinAddress = try AddressFactory.create(addressString) try wallet?.send(to: address, amount: 10000, completion: { [weak self] (response) in print(response ?? "") self?.updateBalance() }) } catch { print(error) } } }
34.764706
96
0.658545
3a456ea38f506973e9053393ea42c4522854cd09
1,259
import EthereumKit import RxSwift import BigInt class BalanceManager { weak var delegate: IBalanceManagerDelegate? private let disposeBag = DisposeBag() private let contractAddress: Address private let address: Address private var storage: ITokenBalanceStorage private let dataProvider: IDataProvider init(contractAddress: Address, address: Address, storage: ITokenBalanceStorage, dataProvider: IDataProvider) { self.contractAddress = contractAddress self.address = address self.storage = storage self.dataProvider = dataProvider } } extension BalanceManager: IBalanceManager { var balance: BigUInt? { storage.balance } func sync() { dataProvider.getBalance(contractAddress: contractAddress, address: address) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .subscribe(onSuccess: { [weak self] balance in self?.storage.balance = balance self?.delegate?.onSyncBalanceSuccess(balance: balance) }, onError: { error in self.delegate?.onSyncBalanceFailed(error: error) }) .disposed(by: disposeBag) } }
29.27907
114
0.656871
3315a0ab60de54688f96fd416c2e3fe6e4cd44c3
2,096
// // CalculationCommand.swift // UPNCalculator // // Created by holgermayer on 07.12.19. // Copyright © 2019 holgermayer. All rights reserved. // import Foundation class CalculationCommand : Command { internal var calculatorEngine : UPNEngine internal var display : Display init(calculatorEngine: UPNEngine, display : Display){ self.calculatorEngine = calculatorEngine self.display = display } func execute() -> KeyboardState { display.inputMode = .standard display.updateLastValue() do { try callEngineCalculation() display.isPushed = true display.needsOverride = false } catch CalculationError.divisionByZero { display.setError("Error : division by zero") return .Default } catch CalculationError.logTenFromZero { display.setError("Error : log10 from zero") return .Default } catch CalculationError.logFromZero { display.setError("Error : ln from zero") return .Default } catch CalculationError.factorialFromNegative { display.setError("Error : factorial from negative number") return .Default } catch CalculationError.resultToLarge { display.setError("Error : result to large") return .Default } catch { display.setError("Error during calculation") return .Default } guard let result = calculatorEngine.top else { display.setError("Error no result") return.Default } display.value = result return .Default } func callEngineCalculation() throws { } private func enterNumberFromInput(){ guard let currentValue = display.value else { display.setError("Error wrong number format") return } calculatorEngine.enterNumber(currentValue) display.isPushed = true } }
27.220779
70
0.587786
22272bd24ace27a17dd506f2d8e89ea4f15d7109
1,003
// // Copyright (c) 2021 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import UIKit /// Contains the styling customization options for an error item in a form. /// :nodoc: public struct FormErrorItemStyle: ViewStyle { /// The message style. public var message = TextStyle(font: .preferredFont(forTextStyle: .body), color: UIColor.Adyen.componentLabel, textAlignment: .natural) /// The corners style of the text item. public var cornerRounding: CornerRounding = .fixed(6) /// :nodoc: public var backgroundColor = UIColor.Adyen.errorRed.withAlphaComponent(0.1) /// Initializes the form error item style. /// /// - Parameter message: The message style. public init(message: TextStyle) { self.message = message } /// Initializes the form error item style with the default style. public init() {} }
29.5
100
0.643071
eb70dd055b0b8e16658caaf398517cacfe42d243
62
// // File.swift // UncompressExample // import Foundation
8.857143
21
0.677419
f52d350b706e4f7c6a4b1b1290fd6209ea7cc01b
221
// // Elements.swift // BodyElements macOS // // Created by Reza Ali on 7/26/21. // Copyright © 2021 Reza Ali. All rights reserved. // import Foundation struct Elements: Codable { var elements: [Element] = [] }
15.785714
51
0.656109
c14de20d97ad04852bb82d084c3a258e887f6ec1
2,882
// // Collation.swift // // Copyright 2015-present, Nike, Inc. // All rights reserved. // // This source code is licensed under the BSD-stylelicense found in the LICENSE // file in the root directory of this source tree. // import Foundation import SQLite3 extension Connection { /// A closure executed for a custom collation with a specified name. public typealias Collation = (_ lhs: String, _ rhs: String) -> ComparisonResult // MARK: - Helper Types private class CollationBox { private let name: String private let collate: Collation init(name: String, collate: @escaping Collation) { self.name = name self.collate = collate } func collate( lhsBytes: UnsafeRawPointer?, lhsCount: Int32, rhsBytes: UnsafeRawPointer?, rhsCount: Int32) -> Int32 { guard let lhsBytes = lhsBytes, let rhsBytes = rhsBytes, let lhs = String(data: Data(bytes: lhsBytes, count: Int(lhsCount)), encoding: .utf8), let rhs = String(data: Data(bytes: rhsBytes, count: Int(rhsCount)), encoding: .utf8) else { return Int32(ComparisonResult.orderedAscending.rawValue) } return Int32(collate(lhs, rhs).rawValue) } } // MARK: - Collations /// Registers the custom collation name and function with SQLite to execute when collating. /// /// For more details, please refer to the [documentation](https://www.sqlite.org/datatype3.html#collation). /// /// - Parameters: /// - name: The name of the custom collation. /// - collate: The closure used to compare the two strings. public func createCollation(named name: String, collate: @escaping Collation) { let box = CollationBox(name: name, collate: collate) let boxPointer = Unmanaged<CollationBox>.passRetained(box).toOpaque() let result = sqlite3_create_collation_v2( handle, name, SQLITE_UTF8, boxPointer, { (boxPointer: UnsafeMutableRawPointer?, lhsCount, lhsBytes, rhsCount, rhsBytes) in guard let boxPointer = boxPointer else { return -1 } // ordered ascending, but shouldn't be called let box = Unmanaged<CollationBox>.fromOpaque(boxPointer).takeUnretainedValue() return box.collate(lhsBytes: lhsBytes, lhsCount: lhsCount, rhsBytes: rhsBytes, rhsCount: rhsCount) }, { (boxPointer: UnsafeMutableRawPointer?) in guard let boxPointer = boxPointer else { return } Unmanaged<CollationBox>.fromOpaque(boxPointer).release() } ) if result != 0 { Unmanaged<CollationBox>.fromOpaque(boxPointer).release() } } }
35.580247
114
0.611728
758339cbc30600366955db62a6546509dcd8fe79
4,594
// // Preferences.swift // Nudge // // Created by Erik Gomez on 2/18/21. // import Foundation let nudgeJSONPreferences = Utils().getNudgeJSONPreferences() let nudgeDefaults = UserDefaults.standard let language = NSLocale.current.languageCode! var shouldExit = false // optionalFeatures // Even if profile is installed, return nil if in demo-mode func getOptionalFeaturesProfile() -> [String:Any]? { if Utils().demoModeEnabled() { return nil } else { return nudgeDefaults.dictionary(forKey: "optionalFeatures") } } // osVersionRequirements // Mutate the profile into our required construct and then compare currentOS against targetedOSVersions func getOSVersionRequirementsProfile() -> OSVersionRequirement? { if Utils().demoModeEnabled() { return nil } var requirements = [OSVersionRequirement]() if let osRequirements = nudgeDefaults.array(forKey: "osVersionRequirements") as? [[String:AnyObject]] { for item in osRequirements { requirements.append(OSVersionRequirement(fromDictionary: item)) } } if !requirements.isEmpty { for (_ , subPreferences) in requirements.enumerated() { if subPreferences.targetedOSVersions?.contains(OSVersion(ProcessInfo().operatingSystemVersion).description) == true { return subPreferences } } } return nil } // Loop through JSON osVersionRequirements preferences and then compare currentOS against targetedOSVersions func getOSVersionRequirementsJSON() -> OSVersionRequirement? { if Utils().demoModeEnabled() { return nil } if let requirements = nudgeJSONPreferences?.osVersionRequirements { for (_ , subPreferences) in requirements.enumerated() { if subPreferences.targetedOSVersions?.contains(OSVersion(ProcessInfo().operatingSystemVersion).description) == true { return subPreferences } } } return nil } // Compare current language against the available updateURLs func getUpdateURL() -> String? { if Utils().demoModeEnabled() { return "https://support.apple.com/en-us/HT201541" } if let updates = getOSVersionRequirementsProfile()?.aboutUpdateURLs ?? getOSVersionRequirementsJSON()?.aboutUpdateURLs { for (_, subUpdates) in updates.enumerated() { if subUpdates.language == language { return subUpdates.aboutUpdateURL ?? "" } } } return "" } // userInterface func getUserInterfaceProfile() -> [String:Any]? { if Utils().demoModeEnabled() { return nil } else { return nudgeDefaults.dictionary(forKey: "userInterface") } } func forceScreenShotIconMode() -> Bool { if Utils().forceScreenShotIconModeEnabled() { return true } else { return userInterfaceProfile?["forceScreenShotIcon"] as? Bool ?? nudgeJSONPreferences?.userInterface?.forceScreenShotIcon ?? false } } func simpleMode() -> Bool { if Utils().simpleModeEnabled() { return true } else { return userInterfaceProfile?["simpleMode"] as? Bool ?? nudgeJSONPreferences?.userInterface?.simpleMode ?? false } } // Mutate the profile into our required construct func getUserInterfaceUpdateElementsProfile() -> [String:AnyObject]? { if Utils().demoModeEnabled() { return nil } let updateElements = userInterfaceProfile?["updateElements"] as? [[String:AnyObject]] if updateElements != nil { for (_ , subPreferences) in updateElements!.enumerated() { if subPreferences["_language"] as? String == language { return subPreferences } } } return nil } // Loop through JSON userInterface -> updateElements preferences and then compare language func getUserInterfaceJSON() -> UpdateElement? { if Utils().demoModeEnabled() { return nil } let updateElements = nudgeJSONPreferences?.userInterface?.updateElements if updateElements != nil { for (_ , subPreferences) in updateElements!.enumerated() { if subPreferences.language == language { return subPreferences } } } return nil } // Returns the mainHeader func getMainHeader() -> String { if Utils().demoModeEnabled() { return "Your device requires a security update (Demo Mode)" } else { return getUserInterfaceUpdateElementsProfile()?["mainHeader"] as? String ?? getUserInterfaceJSON()?.mainHeader ?? "Your device requires a security update" } }
32.352113
162
0.669569