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
|
---|---|---|---|---|---|
e89b6e9978f04f57daad37e43062af0c5dd05c1a | 952 | //
// BLKit.h
// Pods
//
// Created by BigL on 2017/9/16.
//
import UIKit
// MARK: - open
public extension UIApplication {
/// 打开链接 (会判断 能否打开)
///
/// - Parameter url: url
public func open(url: String) {
guard let str = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: str),
UIApplication.shared.canOpenURL(url) else{ return }
unsafeOpen(url: url)
}
/// 打开链接 (不会判断 能否打开)
///
/// - Parameter url: url
public func unsafeOpen(url: String) {
guard let str = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: str) else { return }
unsafeOpen(url: url)
}
/// 打开链接 (不会判断 能否打开)
///
/// - Parameter url: url
public func unsafeOpen(url: URL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
| 21.636364 | 87 | 0.625 |
bfa3e788c4e970fedd2ce7e6fe2a8348e08ee668 | 255 | //
// DateHelperExamplesApp.swift
// Shared
//
// Created by Matías Gil Echavarría on 12/04/21.
//
import SwiftUI
@main
struct DateHelperExamplesApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 14.166667 | 50 | 0.6 |
380e1d9945cca05a37f215feddcdffe8227dff05 | 508 | //
// TableCellViewModel.swift
// LastFM
//
// Created by Durga Prasad, Sidde (623-Extern) on 05/09/20.
// Copyright © 2020 SDP. All rights reserved.
//
import Foundation
struct TablecellViewModel {
//MARK: - Properties
var album: AlbumPresentable
var name: String {
return album.name
}
var artist: String {
return album.artist
}
}
extension TablecellViewModel: AlbumPresentable {
var albumImage: String {
return album.albumImage
}
}
| 16.933333 | 60 | 0.639764 |
9cdef75ffab36909b8b390d57b8ceeee1c365450 | 870 | //
// RouteComposer
// FiguresViewController.swift
// https://github.com/ekazaev/route-composer
//
// Created by Eugene Kazaev in 2018-2022.
// Distributed under the MIT license.
//
import Foundation
import RouteComposer
import UIKit
class FiguresViewController: UIViewController, ExampleAnalyticsSupport {
let screenType = ExampleScreenTypes.empty
override func viewDidLoad() {
super.viewDidLoad()
title = "Figures"
}
@IBAction func goToCircleTapped() {
try? router.navigate(to: ConfigurationHolder.configuration.circleScreen, with: nil)
}
@IBAction func goToSquareTapped() {
try? router.navigate(to: ConfigurationHolder.configuration.squareScreen, with: nil)
}
@IBAction func goToSelfTapped() {
try? router.navigate(to: ConfigurationHolder.configuration.figuresScreen, with: nil)
}
}
| 24.166667 | 92 | 0.717241 |
0eefc810ff2e75e490fa9931e7c4c9bb5e59bc30 | 3,449 | //
// ModuleAuthenticateAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class ModuleAuthenticateAPI {
/**
* enum for parameter eSessionType
*/
public enum ESessionType_authenticateAuthenticateV2: String, CaseIterable {
case ezsignuser = "ezsignuser"
}
/**
Authenticate a user
- parameter eSessionType: (path)
- parameter authenticateAuthenticateV2Request: (body)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func authenticateAuthenticateV2(eSessionType: ESessionType_authenticateAuthenticateV2, authenticateAuthenticateV2Request: AuthenticateAuthenticateV2Request, apiResponseQueue: DispatchQueue = OpenAPIClientAPI.apiResponseQueue, completion: @escaping ((_ data: AuthenticateAuthenticateV2Response?, _ error: Error?) -> Void)) -> RequestTask {
return authenticateAuthenticateV2WithRequestBuilder(eSessionType: eSessionType, authenticateAuthenticateV2Request: authenticateAuthenticateV2Request).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Authenticate a user
- POST /2/module/authenticate/authenticate/{eSessionType}
- This endpoint authenticates a user.
- API Key:
- type: apiKey Authorization
- name: Authorization
- parameter eSessionType: (path)
- parameter authenticateAuthenticateV2Request: (body)
- returns: RequestBuilder<AuthenticateAuthenticateV2Response>
*/
open class func authenticateAuthenticateV2WithRequestBuilder(eSessionType: ESessionType_authenticateAuthenticateV2, authenticateAuthenticateV2Request: AuthenticateAuthenticateV2Request) -> RequestBuilder<AuthenticateAuthenticateV2Response> {
var localVariablePath = "/2/module/authenticate/authenticate/{eSessionType}"
let eSessionTypePreEscape = "\(eSessionType.rawValue)"
let eSessionTypePostEscape = eSessionTypePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{eSessionType}", with: eSessionTypePostEscape, options: .literal, range: nil)
let localVariableURLString = OpenAPIClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: authenticateAuthenticateV2Request)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<AuthenticateAuthenticateV2Response>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
}
| 46.608108 | 353 | 0.749493 |
16887e084c7ece050ba4265482ed9b0a9b371ef6 | 8,751 | //
// UI.swift
// eqMac
//
// Created by Roman Kisil on 24/12/2018.
// Copyright © 2018 Roman Kisil. All rights reserved.
//
import Foundation
import ReSwift
import Cocoa
import EmitterKit
import SwiftyUserDefaults
import WebKit
import Zip
import SwiftHTTP
enum UIMode: String, Codable {
case window = "window"
case popover = "popover"
}
extension UIMode {
static let allValues = [
window.rawValue,
popover.rawValue
]
}
class UI: StoreSubscriber {
static var domain = Constants.UI_ENDPOINT_URL.host!
static func unarchiveZip () {
// Unpack Archive
let fs = FileManager.default
if fs.fileExists(atPath: remoteZipPath.path) {
try! Zip.unzipFile(remoteZipPath, destination: localPath, overwrite: true, password: nil) // Unzip
} else {
if !fs.fileExists(atPath: localZipPath.path) {
Console.log("\(localZipPath.path) doesnt exist")
let bundleUIZipPath = Bundle.main.url(forResource: "ui", withExtension: "zip", subdirectory: "Embedded")!
try! fs.copyItem(at: bundleUIZipPath, to: localZipPath)
}
try! Zip.unzipFile(localZipPath, destination: localPath, overwrite: true, password: nil) // Unzip
}
}
static var localZipPath: URL {
return Application.supportPath.appendingPathComponent(
"ui-\(Application.version) (Local).zip",
isDirectory: false
)
}
static var remoteZipPath: URL {
return Application.supportPath.appendingPathComponent(
"ui-\(Application.version) (Remote).zip",
isDirectory: false
)
}
static var localPath: URL {
return Application.supportPath.appendingPathComponent("ui")
}
static let storyboard = NSStoryboard(name: "Main", bundle: nil)
static let statusItem = StatusItem(image: NSImage(named: "statusBarIcon")!)
static var windowController: NSWindowController = (storyboard.instantiateController(withIdentifier: "EQMWindowController") as! NSWindowController)
static var window: Window = (windowController.window! as! Window)
static var viewController: ViewController = window.contentViewController as! ViewController
static var popover = Popover(statusItem, viewController)
static let loadingWindowController = storyboard.instantiateController(withIdentifier: "LoadingWindow") as! NSWindowController
static let loadingWindow = loadingWindowController.window!
static let loadingViewController = (loadingWindowController.contentViewController as! LoadingViewController)
// var popover: Popover!
static var isShown: Bool {
get {
if (mode == .popover) {
return popover.isShown
} else {
return UI.window.isShown
}
}
}
static var height: Double {
get {
if (mode == .popover) {
return popover.height
} else {
return UI.window.height
}
}
set {
if (mode == .popover) {
UI.popover.height = newValue
} else {
UI.window.height = newValue
}
}
}
static var width: Double {
get {
if (mode == .popover) {
return popover.width
} else {
return UI.window.width
}
}
set {
if (mode == .popover) {
UI.popover.width = newValue
} else {
UI.window.width = newValue
}
}
}
static var mode: UIMode = .window {
willSet {
if (newValue == .popover) {
window.close()
window.contentViewController = nil
popover.popover.contentViewController = viewController
popover.show()
} else {
popover.hide()
popover.popover.contentViewController = nil
window.contentViewController = viewController
window.show()
}
}
}
static var canHide: Bool {
get {
if (mode == .popover) {
return popover.canHide
} else {
return UI.window.canHide
}
}
set {
if (mode == .popover) {
UI.popover.canHide = newValue
} else {
UI.window.canHide = newValue
}
}
}
static func toggle () {
show()
}
static func show () {
if (mode == .popover) {
popover.show()
} else {
UI.window.show()
}
NSApp.activate(ignoringOtherApps: true)
}
static func close () {
if (mode == .popover) {
popover.hide()
} else {
UI.window.close()
}
NSApp.hide(self)
}
static func hide () {
if (mode == .popover) {
popover.hide()
} else {
UI.window.performMiniaturize(nil)
}
}
static func showLoadingWindow (_ text: String) {
UI.loadingViewController.label.stringValue = text
UI.loadingWindow.makeKeyAndOrderFront(self)
UI.loadingWindow.orderFrontRegardless()
NSApp.activate(ignoringOtherApps: true)
}
static func hideLoadingWindow () {
UI.loadingWindow.orderOut(self)
NSApp.hide(self)
}
// Instance
var statusItemClickedListener: EventListener<Void>!
var bridge: Bridge!
init () {
UI.window.contentView = UI.viewController.view
({
UI.mode = Application.store.state.ui.mode
UI.width = Application.store.state.ui.width
UI.height = Application.store.state.ui.height
})()
// TODO: Fix window position state saving (need to look if the current position is still accessible, what if the monitor isn't there anymore)
// if let windowPosition = Application.store.state.ui.windowPosition {
// window.position = windowPosition
// }
setupStateListener()
setupBridge()
setupListeners()
load()
}
static func reload () {
viewController.webView.reload()
}
func setupBridge () {
bridge = Bridge(webView: UI.viewController.webView)
}
// MARK: - State
public typealias StoreSubscriberStateType = UIState
private func setupStateListener () {
Application.store.subscribe(self) { subscription in
subscription.select { state in state.ui }
}
}
func newState(state: UIState) {
if (state.height != UI.height) {
UI.height = state.height
}
if (state.width != UI.width) {
UI.width = state.width
}
if (state.mode != UI.mode) {
UI.mode = state.mode
}
}
private func setupListeners () {
statusItemClickedListener = UI.statusItem.clicked.on {_ in
UI.toggle()
}
}
private func load () {
func startUILoad (_ url: URL) {
DispatchQueue.main.async {
UI.viewController.load(url)
}
}
remoteIsReachable() { reachable in
if reachable {
Console.log("Loading Remote UI")
startUILoad(Constants.UI_ENDPOINT_URL)
self.getRemoteVersion { remoteVersion in
if remoteVersion != nil {
let fs = FileManager.default
if fs.fileExists(atPath: UI.remoteZipPath.path) {
UI.unarchiveZip()
let currentVersion = try? String(contentsOf: UI.localPath.appendingPathComponent("version.txt"))
if (currentVersion?.trim() != remoteVersion?.trim()) {
self.cacheRemote()
}
} else {
self.cacheRemote()
}
}
}
} else {
Console.log("Loading Local UI")
UI.unarchiveZip()
let url = URL(string: "\(UI.localPath)/index.html")!
startUILoad(url)
}
}
}
private func getRemoteVersion (_ completion: @escaping (String?) -> Void) {
HTTP.GET("\(Constants.UI_ENDPOINT_URL)/version.txt") { resp in
completion(resp.error != nil ? nil : resp.text?.trim())
}
}
private func remoteIsReachable (_ completion: @escaping (Bool) -> Void) {
var returned = false
Networking.isReachable(UI.domain) { reachable in
if (!reachable) {
returned = true
return completion(false)
}
HTTP.GET(Constants.UI_ENDPOINT_URL.absoluteString) { response in
returned = true
completion(response.error == nil)
}
}
Utilities.delay(1000) {
if (!returned) {
returned = true
completion(false)
}
}
}
private func cacheRemote () {
// Only download ui.zip when UI endpoint is remote
if Constants.UI_ENDPOINT_URL.absoluteString.contains(Constants.DOMAIN) {
let remoteZipUrl = "\(Constants.UI_ENDPOINT_URL)/ui.zip"
Console.log("Caching Remote UI from \(remoteZipUrl)")
let download = HTTP(URLRequest(urlString: remoteZipUrl)!)
download.run() { resp in
Console.log("Finished caching Remote UI")
if resp.error == nil {
do {
try resp.data.write(to: UI.remoteZipPath, options: .atomic)
} catch {
print(error)
}
}
}
}
}
}
| 25.814159 | 148 | 0.617872 |
ab3c1707a836f24b39f07a40e08db58ef3306614 | 258 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum e:BooleanType
func a{{
struct S<I:I.e
| 25.8 | 87 | 0.748062 |
abb7ea38742866c934c85450e3f7c3e1bb9e9c3f | 1,285 | //
// MovieListContracts.swift
// MovieListing
//
// Created by Gökhan KOCA on 24.01.2021.
//
import Foundation
// MARK: Presenter
protocol MovieListPresentationModelProtocol: BasePresentationModelProtocol {
var viewController: MovieListViewControllerProtocol? { get set }
var movieListBusinessModel: MovieListBusinessModelProtocol? { get set }
var movieDetailBusinessModel: MovieDetailBusinessModelProtocol? { get set }
var router: MovieListRouterProtocol? { get set }
func navigate(_ route: MovieListRoutes)
var items: [MovieListItem] { get set }
var filteredItems: [MovieListItem] { get set }
var currentPage: Int { get set }
func loadList()
func search(term: String)
func goToMovie(with id: Int)
}
enum MovieListPresentationModelOutput {
case didLoadItems
case favoriteStatusChanged
}
// MARK: View
protocol MovieListViewControllerProtocol: BaseViewControllerProtocol {
var presentationModel: MovieListPresentationModelProtocol? { get set }
func handleOutput(_ output: MovieListPresentationModelOutput)
}
enum LayoutStyle {
case grid
case list
}
// MARK: Router
protocol MovieListRouterProtocol: BaseRouterProtocol {
func navigate(_ route: MovieListRoutes)
}
enum MovieListRoutes {
case detail(model: MovieDetail, delegate: MovieDetailSceneDelegate?)
}
| 26.770833 | 76 | 0.792996 |
214c144d4a6e7cda763de056ed203bc61f82fe1c | 581 | //
// PrereleaseVersionResponse.swift
// AppStoreConnect-Swift-SDK
//
// Created by Pascal Edmond on 12/11/2018.
//
import Foundation
#if os(Linux)
import FoundationNetworking
#endif
/// A response containing a single resource.
public struct PrereleaseVersionResponse: Codable {
/// The resource data.
public var data: PrereleaseVersion
/// The requested relationship data.
/// Possible types: Build, App
public var included: [PreReleaseVersionRelationship]?
/// Navigational links that include the self-link.
public var links: DocumentLinks
}
| 23.24 | 57 | 0.729776 |
ed8f8a97e042590cd6a9d80edda2438f3260a122 | 251 | import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
window.makeKeyAndOrderFront(self)
}
}
| 20.916667 | 71 | 0.760956 |
dddeb170dee0b7dd92d4ae8c1365794c9aca3aa3 | 10,010 | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache 2.0
*/
import UIKit
import SoraKeystore
import SoraFoundation
import SoraUI
final class AccountImportViewController: UIViewController {
private struct Constants {
static let advancedFullHeight: CGFloat = 220.0
static let advancedTruncHeight: CGFloat = 152.0
}
var presenter: AccountImportPresenterProtocol!
@IBOutlet private var scrollView: UIScrollView!
@IBOutlet private var stackView: UIStackView!
@IBOutlet private var usernameView: UIView!
@IBOutlet private var usernameTextField: AnimatedTextField!
@IBOutlet private var usernameLabel: UILabel!
@IBOutlet private var textPlaceholderLabel: UILabel!
@IBOutlet private var textView: UITextView!
@IBOutlet private var nextButton: SoraButton!
@IBOutlet private var textContainerView: UIView!
@IBOutlet private var warningView: UIView!
@IBOutlet private var warningLabel: UILabel!
private var derivationPathModel: InputViewModelProtocol?
private var usernameViewModel: InputViewModelProtocol?
private var passwordViewModel: InputViewModelProtocol?
private var sourceViewModel: InputViewModelProtocol?
var keyboardHandler: KeyboardHandler?
var advancedAppearanceAnimator = TransitionAnimator(type: .push,
duration: 0.35,
subtype: .fromBottom,
curve: .easeOut)
var advancedDismissalAnimator = TransitionAnimator(type: .push,
duration: 0.35,
subtype: .fromTop,
curve: .easeIn)
override func viewDidLoad() {
super.viewDidLoad()
configure()
setupLocalization()
updateTextViewPlaceholder()
presenter.setup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if keyboardHandler == nil {
setupKeyboardHandler()
textView.becomeFirstResponder()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
clearKeyboardHandler()
}
private func configure() {
stackView.arrangedSubviews.forEach { $0.backgroundColor = R.color.brandWhite() }
textView.tintColor = R.color.baseContentPrimary()
usernameTextField.textField.returnKeyType = .done
usernameTextField.textField.textContentType = .nickname
usernameTextField.textField.autocapitalizationType = .none
usernameTextField.textField.autocorrectionType = .no
usernameTextField.textField.spellCheckingType = .no
usernameTextField.textField.font = UIFont.styled(for: .paragraph2)
usernameTextField.textField.textAlignment = .right
usernameTextField.addTarget(self, action: #selector(actionNameTextFieldChanged), for: .editingChanged)
usernameTextField.delegate = self
}
private func setupLocalization() {
let locale = localizationManager?.selectedLocale ?? Locale.current
title = R.string.localizable
.recoveryTitleV2(preferredLanguages: locale.rLanguages)
usernameLabel.text = R.string.localizable.personalInfoUsernameV1(preferredLanguages: locale.rLanguages)
nextButton.title = R.string.localizable
.transactionContinue(preferredLanguages: locale.rLanguages)
nextButton.invalidateLayout()
}
private func updateNextButton() {
var isEnabled: Bool = true
if let viewModel = usernameViewModel, viewModel.inputHandler.required {
isEnabled = isEnabled && !(usernameTextField.text?.isEmpty ?? true)
}
if let viewModel = sourceViewModel, viewModel.inputHandler.required {
let textViewActive = !textContainerView.isHidden && !textView.text.isEmpty
isEnabled = isEnabled && textViewActive
}
nextButton?.isEnabled = isEnabled
}
private func updateTextViewPlaceholder() {
textPlaceholderLabel.isHidden = !textView.text.isEmpty
}
@IBAction private func actionNameTextFieldChanged() {
if usernameViewModel?.inputHandler.value != usernameTextField.text {
usernameTextField.text = usernameViewModel?.inputHandler.value
}
updateNextButton()
}
@IBAction private func actionNext() {
presenter.proceed()
}
}
extension AccountImportViewController: AccountImportViewProtocol {
func setSource(type: AccountImportSource) {
switch type {
case .mnemonic:
passwordViewModel = nil
textContainerView.isHidden = false
case .seed:
textContainerView.isHidden = false
case .keystore:
textContainerView.isHidden = true
textView.text = nil
}
warningView.isHidden = true
}
func setSource(viewModel: InputViewModelProtocol) {
sourceViewModel = viewModel
textPlaceholderLabel.text = viewModel.placeholder
textView.text = viewModel.inputHandler.value
updateTextViewPlaceholder()
updateNextButton()
}
func setName(viewModel: InputViewModelProtocol) {
usernameViewModel = viewModel
usernameTextField.text = viewModel.inputHandler.value
updateNextButton()
}
func setPassword(viewModel: InputViewModelProtocol) {
passwordViewModel = viewModel
updateNextButton()
}
func setDerivationPath(viewModel: InputViewModelProtocol) {
derivationPathModel = viewModel
}
func setUploadWarning(message: String) {
warningLabel.text = message
warningView.isHidden = false
}
}
extension AccountImportViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let currentViewModel = derivationPathModel else {
return true
}
let shouldApply = currentViewModel.inputHandler.didReceiveReplacement(string, for: range)
if !shouldApply, textField.text != currentViewModel.inputHandler.value {
textField.text = currentViewModel.inputHandler.value
}
return shouldApply
}
}
extension AccountImportViewController: AnimatedTextFieldDelegate {
func animatedTextFieldShouldReturn(_ textField: AnimatedTextField) -> Bool {
textField.resignFirstResponder()
return false
}
func animatedTextField(_ textField: AnimatedTextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let viewModel: InputViewModelProtocol?
if textField === usernameTextField {
viewModel = usernameViewModel
} else {
viewModel = passwordViewModel
}
guard let currentViewModel = viewModel else {
return true
}
let shouldApply = currentViewModel.inputHandler.didReceiveReplacement(string, for: range)
if !shouldApply, textField.text != currentViewModel.inputHandler.value {
textField.text = currentViewModel.inputHandler.value
}
return shouldApply
}
}
extension AccountImportViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if textView.text != sourceViewModel?.inputHandler.value {
textView.text = sourceViewModel?.inputHandler.value
}
updateTextViewPlaceholder()
updateNextButton()
}
func textView(_ textView: UITextView,
shouldChangeTextIn range: NSRange,
replacementText text: String) -> Bool {
if text == String.returnKey {
textView.resignFirstResponder()
return false
}
guard let model = sourceViewModel else {
return false
}
let shouldApply = model.inputHandler.didReceiveReplacement(text, for: range)
if !shouldApply, textView.text != model.inputHandler.value {
textView.text = model.inputHandler.value
}
return shouldApply
}
}
extension AccountImportViewController: KeyboardAdoptable {
func updateWhileKeyboardFrameChanging(_ frame: CGRect) {
let localKeyboardFrame = view.convert(frame, from: nil)
let bottomInset = view.bounds.height - localKeyboardFrame.minY
let scrollViewOffset = view.bounds.height - scrollView.frame.maxY
var contentInsets = scrollView.contentInset
contentInsets.bottom = max(0.0, bottomInset - scrollViewOffset)
scrollView.contentInset = contentInsets
if contentInsets.bottom > 0.0 {
let targetView: UIView?
if textView.isFirstResponder {
targetView = textView
} else if usernameTextField.isFirstResponder {
targetView = usernameView
} else {
targetView = nil
}
if let firstResponderView = targetView {
let fieldFrame = scrollView.convert(firstResponderView.frame,
from: firstResponderView.superview)
scrollView.scrollRectToVisible(fieldFrame, animated: true)
}
}
}
}
extension AccountImportViewController: Localizable {
func applyLocalization() {
if isViewLoaded {
setupLocalization()
view.setNeedsLayout()
}
}
}
| 31.37931 | 111 | 0.647552 |
1c7f0e18f11f8d57de5724b57a90bde96cd07f4e | 1,503 | //
// ParticipationStatus.swift
// Asclepius
// Module: STU3
//
// Copyright (c) 2022 Bitmatic Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
The Participation status of an appointment.
URL: http://hl7.org/fhir/participationstatus
ValueSet: http://hl7.org/fhir/ValueSet/participationstatus
*/
public enum ParticipationStatus: String, AsclepiusPrimitiveType {
/// The participant has accepted the appointment.
case accepted
/// The participant has declined the appointment and will not participate in the appointment.
case declined
/// The participant has tentatively accepted the appointment. This could be automatically created by a system and
/// requires further processing before it can be accepted. There is no commitment that attendance will occur.
case tentative
/// The participant needs to indicate if they accept the appointment by changing this status to one of the other
/// statuses.
case needsAction = "needs-action"
}
| 36.658537 | 116 | 0.745176 |
bb3b2d3ba417c2e4eac2afc29d8bc99164b570db | 1,364 | //
// RequestQueueError.swift
// Requests
//
// Created by Daniel Byon on 8/5/19.
// Copyright 2019 Daniel Byon.
//
// 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
public enum RequestQueueError: Error {
case didNotReceiveData
case invalidStatusCode(statusCode: Int)
case nonEmptyData
}
| 40.117647 | 79 | 0.75 |
1425511862307c357f4f192e404bd75286f03e53 | 3,885 | import AppKit
import Foundation
// MARK: - FixedParentFitChild
public class FixedParentFitChild: NSBox {
// MARK: Lifecycle
public init() {
super.init(frame: .zero)
setUpViews()
setUpConstraints()
update()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private
private var view1View = NSBox()
private var view4View = NSBox()
private var view5View = NSBox()
private func setUpViews() {
boxType = .custom
borderType = .noBorder
contentViewMargins = .zero
view1View.boxType = .custom
view1View.borderType = .noBorder
view1View.contentViewMargins = .zero
view4View.boxType = .custom
view4View.borderType = .noBorder
view4View.contentViewMargins = .zero
view5View.boxType = .custom
view5View.borderType = .noBorder
view5View.contentViewMargins = .zero
addSubview(view1View)
view1View.addSubview(view4View)
view1View.addSubview(view5View)
fillColor = Colors.bluegrey100
view1View.fillColor = Colors.red50
view4View.fillColor = Colors.red200
view5View.fillColor = Colors.deeporange200
}
private func setUpConstraints() {
translatesAutoresizingMaskIntoConstraints = false
view1View.translatesAutoresizingMaskIntoConstraints = false
view4View.translatesAutoresizingMaskIntoConstraints = false
view5View.translatesAutoresizingMaskIntoConstraints = false
let heightAnchorConstraint = heightAnchor.constraint(equalToConstant: 600)
let view1ViewTopAnchorConstraint = view1View.topAnchor.constraint(equalTo: topAnchor, constant: 24)
let view1ViewLeadingAnchorConstraint = view1View.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 24)
let view1ViewTrailingAnchorConstraint = view1View.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -24)
let view4ViewHeightAnchorParentConstraint = view4View
.heightAnchor
.constraint(lessThanOrEqualTo: view1View.heightAnchor, constant: -48)
let view5ViewHeightAnchorParentConstraint = view5View
.heightAnchor
.constraint(lessThanOrEqualTo: view1View.heightAnchor, constant: -48)
let view4ViewLeadingAnchorConstraint = view4View
.leadingAnchor
.constraint(equalTo: view1View.leadingAnchor, constant: 24)
let view4ViewTopAnchorConstraint = view4View.topAnchor.constraint(equalTo: view1View.topAnchor, constant: 24)
let view5ViewLeadingAnchorConstraint = view5View
.leadingAnchor
.constraint(equalTo: view4View.trailingAnchor, constant: 12)
let view5ViewTopAnchorConstraint = view5View.topAnchor.constraint(equalTo: view1View.topAnchor, constant: 24)
let view4ViewHeightAnchorConstraint = view4View.heightAnchor.constraint(equalToConstant: 100)
let view4ViewWidthAnchorConstraint = view4View.widthAnchor.constraint(equalToConstant: 60)
let view5ViewHeightAnchorConstraint = view5View.heightAnchor.constraint(equalToConstant: 60)
let view5ViewWidthAnchorConstraint = view5View.widthAnchor.constraint(equalToConstant: 60)
view4ViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow
view5ViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow
NSLayoutConstraint.activate([
heightAnchorConstraint,
view1ViewTopAnchorConstraint,
view1ViewLeadingAnchorConstraint,
view1ViewTrailingAnchorConstraint,
view4ViewHeightAnchorParentConstraint,
view5ViewHeightAnchorParentConstraint,
view4ViewLeadingAnchorConstraint,
view4ViewTopAnchorConstraint,
view5ViewLeadingAnchorConstraint,
view5ViewTopAnchorConstraint,
view4ViewHeightAnchorConstraint,
view4ViewWidthAnchorConstraint,
view5ViewHeightAnchorConstraint,
view5ViewWidthAnchorConstraint
])
}
private func update() {}
}
| 37 | 119 | 0.776319 |
767d4efb814e1fe5b415457eb8051d0de9ad8219 | 31,591 | import Cocoa
import AVFoundation
/// YOLO
extension String: Error {}
/**
Convenience function for initializing an object and modifying its properties
```
let label = with(NSTextField()) {
$0.stringValue = "Foo"
$0.textColor = .systemBlue
view.addSubview($0)
}
```
*/
@discardableResult
func with<T>(_ item: T, update: (inout T) throws -> Void) rethrows -> T {
var this = item
try update(&this)
return this
}
struct Meta {
static func openSubmitFeedbackPage() {
let body =
"""
<!-- Provide your feedback here. Include as many details as possible. -->
---
\(App.name) \(App.version) (\(App.build))
macOS \(System.osVersion)
\(System.hardwareModel)
"""
let query: [String: String] = [
"body": body
]
URL(string: "https://github.com/sindresorhus/gifski-app/issues/new")!.addingDictionaryAsQuery(query).open()
}
}
/// macOS 10.14 polyfills
extension NSColor {
static let controlAccentColorPolyfill: NSColor = {
if #available(macOS 10.14, *) {
return NSColor.controlAccentColor
} else {
// swiftlint:disable:next object_literal
return NSColor(red: 0.10, green: 0.47, blue: 0.98, alpha: 1)
}
}()
}
extension NSColor {
func with(alpha: Double) -> NSColor {
return withAlphaComponent(CGFloat(alpha))
}
}
extension NSView {
func pulsate(duration: TimeInterval = 2) {
let animation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))
animation.duration = duration
animation.fromValue = 1
animation.toValue = 0.9
animation.timingFunction = .easeInOut
animation.autoreverses = true
animation.repeatCount = .infinity
wantsLayer = true
layer?.add(animation, forKey: nil)
}
func pulsateScale(duration: TimeInterval = 1.5, scale: Double = 1.05) {
pulsate(duration: duration)
let multiplier = CGFloat(scale)
var tr = CATransform3DIdentity
tr = CATransform3DTranslate(tr, bounds.size.width / 2, bounds.size.height / 2, 0)
tr = CATransform3DScale(tr, multiplier, multiplier, 1)
tr = CATransform3DTranslate(tr, -bounds.size.width / 2, -bounds.size.height / 2, 0)
let animation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
animation.toValue = NSValue(caTransform3D: tr)
animation.duration = duration
animation.timingFunction = .easeInOut
animation.autoreverses = true
animation.repeatCount = .infinity
wantsLayer = true
layer?.add(animation, forKey: nil)
}
}
/// This is useful as `awakeFromNib` is not called for programatically created views
class SSView: NSView {
var didAppearWasCalled = false
/// Meant to be overridden in subclasses
func didAppear() {}
override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
if !didAppearWasCalled {
didAppearWasCalled = true
didAppear()
}
}
}
extension NSWindow {
// Helper
private static func centeredOnScreen(rect: CGRect) -> CGRect {
guard let screen = NSScreen.main else {
return rect
}
// Looks better than perfectly centered
let yOffset = 0.12
return rect.centered(in: screen.visibleFrame, xOffsetPercent: 0, yOffsetPercent: yOffset)
}
static let defaultContentSize = CGSize(width: 480, height: 300)
/// TODO: Find a way to stack windows, so additional windows are not placed exactly on top of previous ones: https://github.com/sindresorhus/gifski-app/pull/30#discussion_r175337064
static var defaultContentRect: CGRect {
return centeredOnScreen(rect: defaultContentSize.cgRect)
}
static let defaultStyleMask: NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable]
static func centeredWindow(size: CGSize = defaultContentSize) -> NSWindow {
let window = NSWindow()
window.setContentSize(size)
window.centerNatural()
return window
}
@nonobjc
override convenience init() {
self.init(contentRect: NSWindow.defaultContentRect)
}
convenience init(contentRect: CGRect) {
self.init(contentRect: contentRect, styleMask: NSWindow.defaultStyleMask, backing: .buffered, defer: true)
}
/// Moves the window to the center of the screen, slightly more in the center than `window#center()`
func centerNatural() {
setFrame(NSWindow.centeredOnScreen(rect: frame), display: true)
}
}
extension NSWindowController {
/// Expose the `view` like in NSViewController
var view: NSView? {
return window?.contentView
}
}
extension NSView {
@discardableResult
func insertVibrancyView(
material: NSVisualEffectView.Material = .appearanceBased,
blendingMode: NSVisualEffectView.BlendingMode = .behindWindow,
appearanceName: NSAppearance.Name? = nil
) -> NSVisualEffectView {
let view = NSVisualEffectView(frame: bounds)
view.autoresizingMask = [.width, .height]
view.material = material
view.blendingMode = blendingMode
if let appearanceName = appearanceName {
view.appearance = NSAppearance(named: appearanceName)
}
addSubview(view, positioned: .below, relativeTo: nil)
return view
}
}
extension NSWindow {
func makeVibrant() {
if #available(OSX 10.14, *) {
contentView?.insertVibrancyView(material: .underWindowBackground)
}
}
}
extension NSWindow {
var toolbarView: NSView? {
return standardWindowButton(.closeButton)?.superview
}
var titlebarView: NSView? {
return toolbarView?.superview
}
var titlebarHeight: Double {
return Double(titlebarView?.bounds.height ?? 0)
}
}
extension NSWindowController: NSWindowDelegate {
public func window(_ window: NSWindow, willPositionSheet sheet: NSWindow, using rect: CGRect) -> CGRect {
// Adjust sheet position so it goes below the traffic lights
if window.styleMask.contains(.fullSizeContentView) {
return rect.offsetBy(dx: 0, dy: CGFloat(-window.titlebarHeight))
}
return rect
}
}
extension NSAlert {
/// Show a modal alert sheet on a window
/// If the window is nil, it will be a app-modal alert
@discardableResult
static func showModal(
for window: NSWindow?,
title: String,
message: String? = nil,
style: NSAlert.Style = .critical
) -> NSApplication.ModalResponse {
guard let window = window else {
return NSAlert(
title: title,
message: message,
style: style
).runModal()
}
return NSAlert(
title: title,
message: message,
style: style
).runModal(for: window)
}
/// Show a app-modal (window indepedendent) alert
@discardableResult
static func showModal(
title: String,
message: String? = nil,
style: NSAlert.Style = .critical
) -> NSApplication.ModalResponse {
return NSAlert(
title: title,
message: message,
style: style
).runModal()
}
convenience init(
title: String,
message: String? = nil,
style: NSAlert.Style = .critical
) {
self.init()
self.messageText = title
self.alertStyle = style
if let message = message {
self.informativeText = message
}
}
/// Runs the alert as a window-modal sheel
@discardableResult
func runModal(for window: NSWindow) -> NSApplication.ModalResponse {
beginSheetModal(for: window) { returnCode in
NSApp.stopModal(withCode: returnCode)
}
return NSApp.runModal(for: window)
}
}
extension AVAssetImageGenerator {
struct CompletionHandlerResult {
let image: CGImage
let requestedTime: CMTime
let actualTime: CMTime
let completedCount: Int
let totalCount: Int
let isCancelled: Bool
let isFinished: Bool
}
/// TODO: Remove this when using Swift 5 and use `CancellationError` in the cancellation case
enum Error: CancellableError {
case cancelled
var isCancelled: Bool {
return self == .cancelled
}
}
func generateCGImagesAsynchronously(
forTimePoints timePoints: [CMTime],
completionHandler: @escaping (CoreResult<CompletionHandlerResult, Error>) -> Void
) {
let times = timePoints.map { NSValue(time: $0) }
let totalCount = times.count
var completedCount = 0
generateCGImagesAsynchronously(forTimes: times) { requestedTime, image, actualTime, result, error in
switch result {
case .succeeded:
completedCount += 1
completionHandler(
.success(
CompletionHandlerResult(
image: image!,
requestedTime: requestedTime,
actualTime: actualTime,
completedCount: completedCount,
totalCount: totalCount,
isCancelled: false,
isFinished: completedCount == totalCount
)
)
)
case .failed:
completionHandler(.failure(error! as! Error))
case .cancelled:
completionHandler(.failure(.cancelled))
}
}
}
}
extension CMTimeScale {
/**
```
CMTime(seconds: 1 / fps, preferredTimescale: .video)
```
*/
static var video: CMTimeScale = 600 // This is what Apple recommends
}
extension Comparable {
/// Note: It's not possible to implement `Range` or `PartialRangeUpTo` here as we can't know what `1.1..<1.53` would be. They only work with Stridable in our case.
/// Example: 20.5.clamped(from: 10.3, to: 15)
func clamped(from lowerBound: Self, to upperBound: Self) -> Self {
return min(max(self, lowerBound), upperBound)
}
/// Example: 20.5.clamped(to: 10.3...15)
func clamped(to range: ClosedRange<Self>) -> Self {
return clamped(from: range.lowerBound, to: range.upperBound)
}
/// Example: 20.5.clamped(to: ...10.3)
/// => 10.3
func clamped(to range: PartialRangeThrough<Self>) -> Self {
return min(self, range.upperBound)
}
/// Example: 5.5.clamped(to: 10.3...)
/// => 10.3
func clamped(to range: PartialRangeFrom<Self>) -> Self {
return max(self, range.lowerBound)
}
}
extension Strideable where Stride: SignedInteger {
/// Example: 20.clamped(to: 5..<10)
/// => 9
func clamped(to range: CountableRange<Self>) -> Self {
return clamped(from: range.lowerBound, to: range.upperBound.advanced(by: -1))
}
/// Example: 20.clamped(to: 5...10)
/// => 10
func clamped(to range: CountableClosedRange<Self>) -> Self {
return clamped(from: range.lowerBound, to: range.upperBound)
}
/// Example: 20.clamped(to: ..<10)
/// => 9
func clamped(to range: PartialRangeUpTo<Self>) -> Self {
return min(self, range.upperBound.advanced(by: -1))
}
}
extension AVAsset {
var isVideoDecodable: Bool {
guard isReadable,
let firstVideoTrack = tracks(withMediaType: .video).first else {
return false
}
return firstVideoTrack.isDecodable
}
}
/// Video metadata
extension AVURLAsset {
struct VideoMetadata {
let dimensions: CGSize
let duration: Double
let frameRate: Double
let fileSize: Int
}
var videoMetadata: VideoMetadata? {
guard let track = tracks(withMediaType: .video).first else {
return nil
}
let dimensions = track.naturalSize.applying(track.preferredTransform)
return VideoMetadata(
dimensions: CGSize(width: abs(dimensions.width), height: abs(dimensions.height)),
duration: duration.seconds,
frameRate: Double(track.nominalFrameRate),
fileSize: url.fileSize
)
}
}
extension URL {
var videoMetadata: AVURLAsset.VideoMetadata? {
return AVURLAsset(url: self).videoMetadata
}
var isVideoDecodable: Bool {
return AVAsset(url: self).isVideoDecodable
}
}
extension NSView {
func center(inView view: NSView) {
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
centerXAnchor.constraint(equalTo: view.centerXAnchor),
centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
func addSubviewToCenter(_ view: NSView) {
addSubview(view)
view.center(inView: superview!)
}
}
extension NSControl {
/// Trigger the `.action` selector on the control
func triggerAction() {
sendAction(action, to: target)
}
}
extension DispatchQueue {
/**
```
DispatchQueue.main.asyncAfter(duration: 100.milliseconds) {
print("100 ms later")
}
```
*/
func asyncAfter(duration: TimeInterval, execute: @escaping () -> Void) {
asyncAfter(deadline: .now() + duration, execute: execute)
}
}
extension NSFont {
var size: CGFloat {
return fontDescriptor.object(forKey: .size) as! CGFloat
}
var traits: [NSFontDescriptor.TraitKey: AnyObject] {
return fontDescriptor.object(forKey: .traits) as! [NSFontDescriptor.TraitKey: AnyObject]
}
var weight: NSFont.Weight {
return NSFont.Weight(traits[.weight] as! CGFloat)
}
}
/**
```
let foo = Label(text: "Foo")
```
*/
class Label: NSTextField {
var text: String {
get {
return stringValue
}
set {
stringValue = newValue
}
}
/// Allow the it to be disabled like other NSControl's
override var isEnabled: Bool {
didSet {
textColor = isEnabled ? .controlTextColor : .disabledControlTextColor
}
}
/// Support setting the text later with the `.text` property
convenience init() {
self.init(labelWithString: "")
}
convenience init(text: String) {
self.init(labelWithString: text)
}
convenience init(attributedText: NSAttributedString) {
self.init(labelWithAttributedString: attributedText)
}
override func viewDidMoveToSuperview() {
guard superview != nil else {
return
}
sizeToFit()
}
}
/// Use it in Interface Builder as a class or programmatically
final class MonospacedLabel: Label {
override init(frame: NSRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
if let font = self.font {
self.font = NSFont.monospacedDigitSystemFont(ofSize: font.size, weight: font.weight)
}
}
}
extension NSView {
/// UIKit polyfill
var center: CGPoint {
get {
return frame.center
}
set {
frame.center = newValue
}
}
func centerInRect(_ rect: CGRect) {
center = CGPoint(x: rect.midX, y: rect.midY)
}
/// Passing in a window can be useful when the view is not yet added to a window
/// If you don't pass in a window, it will use the window the view is in
func centerInWindow(_ window: NSWindow? = nil) {
guard let view = (window ?? self.window)?.contentView else {
return
}
centerInRect(view.bounds)
}
}
/**
Mark unimplemented functions and have them fail with a useful message
```
func foo() {
unimplemented()
}
foo()
//=> "foo() in main.swift:1 has not been implemented"
```
*/
// swiftlint:disable:next unavailable_function
func unimplemented(function: StaticString = #function, file: String = #file, line: UInt = #line) -> Never {
fatalError("\(function) in \(file.nsString.lastPathComponent):\(line) has not been implemented")
}
extension NSPasteboard {
/// Get the file URLs from dragged and dropped files
func fileURLs(types: [String] = []) -> [URL] {
var options: [NSPasteboard.ReadingOptionKey: Any] = [
.urlReadingFileURLsOnly: true
]
if !types.isEmpty {
options[.urlReadingContentsConformToTypes] = types
}
guard let urls = readObjects(forClasses: [NSURL.self], options: options) as? [URL] else {
return []
}
return urls
}
}
/// Subclass this in Interface Builder with the title "Send Feedback…"
final class FeedbackMenuItem: NSMenuItem {
required init(coder decoder: NSCoder) {
super.init(coder: decoder)
onAction = { _ in
Meta.openSubmitFeedbackPage()
}
}
}
/// Subclass this in Interface Builder and set the `Url` field there
final class UrlMenuItem: NSMenuItem {
@IBInspectable var url: String?
required init(coder decoder: NSCoder) {
super.init(coder: decoder)
onAction = { _ in
NSWorkspace.shared.open(URL(string: self.url!)!)
}
}
}
final class AssociatedObject<T: Any> {
subscript(index: Any) -> T? {
get {
return objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T?
} set {
objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
/// Identical to above, but for NSMenuItem
extension NSMenuItem {
typealias ActionClosure = ((NSMenuItem) -> Void)
private struct AssociatedKeys {
static let onActionClosure = AssociatedObject<ActionClosure>()
}
@objc
private func callClosure(_ sender: NSMenuItem) {
onAction?(sender)
}
/**
Closure version of `.action`
```
let menuItem = NSMenuItem(title: "Unicorn")
menuItem.onAction = { sender in
print("NSMenuItem action: \(sender)")
}
```
*/
var onAction: ActionClosure? {
get {
return AssociatedKeys.onActionClosure[self]
}
set {
AssociatedKeys.onActionClosure[self] = newValue
action = #selector(callClosure)
target = self
}
}
}
extension NSControl {
typealias ActionClosure = ((NSControl) -> Void)
private struct AssociatedKeys {
static let onActionClosure = AssociatedObject<ActionClosure>()
}
@objc
private func callClosure(_ sender: NSControl) {
onAction?(sender)
}
/**
Closure version of `.action`
```
let button = NSButton(title: "Unicorn", target: nil, action: nil)
button.onAction = { sender in
print("Button action: \(sender)")
}
```
*/
var onAction: ActionClosure? {
get {
return AssociatedKeys.onActionClosure[self]
}
set {
AssociatedKeys.onActionClosure[self] = newValue
action = #selector(callClosure)
target = self
}
}
}
extension CAMediaTimingFunction {
static let `default` = CAMediaTimingFunction(name: .default)
static let linear = CAMediaTimingFunction(name: .linear)
static let easeIn = CAMediaTimingFunction(name: .easeIn)
static let easeOut = CAMediaTimingFunction(name: .easeOut)
static let easeInOut = CAMediaTimingFunction(name: .easeInEaseOut)
}
extension NSView {
/**
```
let label = NSTextField(labelWithString: "Unicorn")
view.addSubviewByFadingIn(label)
```
*/
func addSubviewByFadingIn(_ view: NSView, duration: TimeInterval = 1, completion: (() -> Void)? = nil) {
NSAnimationContext.runAnimationGroup({ context in
context.duration = duration
animator().addSubview(view)
}, completionHandler: completion)
}
func removeSubviewByFadingOut(_ view: NSView, duration: TimeInterval = 1, completion: (() -> Void)? = nil) {
NSAnimationContext.runAnimationGroup({ context in
context.duration = duration
view.animator().removeFromSuperview()
}, completionHandler: completion)
}
static func animate(
duration: TimeInterval = 1,
delay: TimeInterval = 0,
timingFunction: CAMediaTimingFunction = .default,
animations: @escaping (() -> Void),
completion: (() -> Void)? = nil
) {
DispatchQueue.main.asyncAfter(duration: delay) {
NSAnimationContext.runAnimationGroup({ context in
context.allowsImplicitAnimation = true
context.duration = duration
context.timingFunction = timingFunction
animations()
}, completionHandler: completion)
}
}
func fadeIn(duration: TimeInterval = 1, delay: TimeInterval = 0, completion: (() -> Void)? = nil) {
isHidden = true
NSView.animate(
duration: duration,
delay: delay,
animations: {
self.isHidden = false
},
completion: completion
)
}
func fadeOut(duration: TimeInterval = 1, delay: TimeInterval = 0, completion: (() -> Void)? = nil) {
isHidden = false
NSView.animate(
duration: duration,
delay: delay,
animations: {
self.alphaValue = 0
},
completion: {
self.isHidden = true
self.alphaValue = 1
completion?()
}
)
}
}
extension String {
// NSString has some useful properties that String does not
var nsString: NSString {
return self as NSString
}
}
struct App {
static let id = Bundle.main.bundleIdentifier!
static let name = Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as! String
static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
static let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
}
/// Convenience for opening URLs
extension URL {
func open() {
NSWorkspace.shared.open(self)
}
}
extension String {
/*
```
"https://sindresorhus.com".openUrl()
```
*/
func openUrl() {
URL(string: self)?.open()
}
}
struct System {
static let osVersion: String = {
let os = ProcessInfo.processInfo.operatingSystemVersion
return "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)"
}()
static let hardwareModel: String = {
var size = 0
sysctlbyname("hw.model", nil, &size, nil, 0)
var model = [CChar](repeating: 0, count: size)
sysctlbyname("hw.model", &model, &size, nil, 0)
return String(cString: model)
}()
static let supportedVideoTypes = [
AVFileType.mp4.rawValue,
AVFileType.m4v.rawValue,
AVFileType.mov.rawValue
]
}
private func escapeQuery(_ query: String) -> String {
// From RFC 3986
let generalDelimiters = ":#[]@"
let subDelimiters = "!$&'()*+,;="
var allowedCharacters = CharacterSet.urlQueryAllowed
allowedCharacters.remove(charactersIn: generalDelimiters + subDelimiters)
return query.addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? query
}
extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral {
var asQueryItems: [URLQueryItem] {
return map {
URLQueryItem(
name: escapeQuery($0 as! String),
value: escapeQuery($1 as! String)
)
}
}
var asQueryString: String {
var components = URLComponents()
components.queryItems = asQueryItems
return components.query!
}
}
extension URLComponents {
mutating func addDictionaryAsQuery(_ dict: [String: String]) {
percentEncodedQuery = dict.asQueryString
}
}
extension URL {
var directoryURL: URL {
return deletingLastPathComponent()
}
var directory: String {
return directoryURL.path
}
var filename: String {
get {
return lastPathComponent
}
set {
deleteLastPathComponent()
appendPathComponent(newValue)
}
}
var fileExtension: String {
get {
return pathExtension
}
set {
deletePathExtension()
appendPathExtension(newValue)
}
}
var filenameWithoutExtension: String {
get {
return deletingPathExtension().lastPathComponent
}
set {
let ext = pathExtension
deleteLastPathComponent()
appendPathComponent(newValue)
appendPathExtension(ext)
}
}
func changingFileExtension(to fileExtension: String) -> URL {
var url = self
url.fileExtension = fileExtension
return url
}
func addingDictionaryAsQuery(_ dict: [String: String]) -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)!
components.addDictionaryAsQuery(dict)
return components.url ?? self
}
private func resourceValue<T>(forKey key: URLResourceKey) -> T? {
guard let values = try? resourceValues(forKeys: [key]) else {
return nil
}
return values.allValues[key] as? T
}
/// File UTI
var typeIdentifier: String? {
return resourceValue(forKey: .typeIdentifierKey)
}
/// File size in bytes
var fileSize: Int {
return resourceValue(forKey: .fileSizeKey) ?? 0
}
}
extension CGSize {
static func * (lhs: CGSize, rhs: Double) -> CGSize {
return CGSize(width: lhs.width * CGFloat(rhs), height: lhs.height * CGFloat(rhs))
}
init(widthHeight: CGFloat) {
self.init(width: widthHeight, height: widthHeight)
}
var cgRect: CGRect {
return CGRect(origin: .zero, size: self)
}
}
extension CGRect {
init(origin: CGPoint = .zero, width: CGFloat, height: CGFloat) {
self.init(origin: origin, size: CGSize(width: width, height: height))
}
init(widthHeight: CGFloat) {
self.init()
self.origin = .zero
self.size = CGSize(widthHeight: widthHeight)
}
var x: CGFloat {
get {
return origin.x
}
set {
origin.x = newValue
}
}
var y: CGFloat {
get {
return origin.y
}
set {
origin.y = newValue
}
}
/// `width` and `height` are defined in Foundation as getters only. We add support for setters too.
/// These will not work when imported as a framework: https://bugs.swift.org/browse/SR-4017
var width: CGFloat {
get {
return size.width
}
set {
size.width = newValue
}
}
var height: CGFloat {
get {
return size.height
}
set {
size.height = newValue
}
}
// MARK: - Edges
var left: CGFloat {
get {
return x
}
set {
x = newValue
}
}
var right: CGFloat {
get {
return x + width
}
set {
x = newValue - width
}
}
#if os(macOS)
var top: CGFloat {
get {
return y + height
}
set {
y = newValue - height
}
}
var bottom: CGFloat {
get {
return y
}
set {
y = newValue
}
}
#else
var top: CGFloat {
get {
return y
}
set {
y = newValue
}
}
var bottom: CGFloat {
get {
return y + height
}
set {
y = newValue - height
}
}
#endif
// MARK: -
var center: CGPoint {
get {
return CGPoint(x: midX, y: midY)
}
set {
origin = CGPoint(
x: newValue.x - (size.width / 2),
y: newValue.y - (size.height / 2)
)
}
}
var centerX: CGFloat {
get {
return midX
}
set {
center = CGPoint(x: newValue, y: midY)
}
}
var centerY: CGFloat {
get {
return midY
}
set {
center = CGPoint(x: midX, y: newValue)
}
}
/**
Returns a CGRect where `self` is centered in `rect`
*/
func centered(in rect: CGRect, xOffset: Double = 0, yOffset: Double = 0) -> CGRect {
return CGRect(
x: ((rect.width - size.width) / 2) + CGFloat(xOffset),
y: ((rect.height - size.height) / 2) + CGFloat(yOffset),
width: size.width,
height: size.height
)
}
/**
Returns a CGRect where `self` is centered in `rect`
- Parameters:
- xOffsetPercent: The offset in percentage of `rect.width`
*/
func centered(in rect: CGRect, xOffsetPercent: Double, yOffsetPercent: Double) -> CGRect {
return centered(
in: rect,
xOffset: Double(rect.width) * xOffsetPercent,
yOffset: Double(rect.height) * yOffsetPercent
)
}
}
/// Polyfill for Swift 5
/// https://github.com/moiseev/swift/blob/47740c012943020aa89df93129b4fc2f33618c00/stdlib/public/core/Result.swift
/// TODO: Remove when using Swift 5
///
/// A value that represents either a success or a failure, including an
/// associated value in each case.
public enum Result<Success, Failure: Swift.Error> {
/// A success, storing a `Success` value.
case success(Success)
/// A failure, storing a `Failure` value.
case failure(Failure)
/// Returns a new result, mapping any success value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a success. The following example transforms
/// the integer success value of a result into a string:
///
/// func getNextInteger() -> Result<Int, Error> { ... }
///
/// let integerResult = getNextInteger()
/// // integerResult == .success(5)
/// let stringResult = integerResult.map({ String($0) })
/// // stringResult == .success("5")
///
/// - Parameter transform: A closure that takes the success value of this
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new success value if this instance represents a success.
public func map<NewSuccess>(
_ transform: (Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return .success(transform(success))
case let .failure(failure):
return .failure(failure)
}
}
/// Returns a new result, mapping any failure value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a failure. The following example transforms
/// the error value of a result by wrapping it in a custom `Error` type:
///
/// struct DatedError: Error {
/// var error: Error
/// var date: Date
///
/// init(_ error: Error) {
/// self.error = error
/// self.date = Date()
/// }
/// }
///
/// let result: Result<Int, Error> = ...
/// // result == .failure(<error value>)
/// let resultWithDatedError = result.mapError({ e in DatedError(e) })
/// // result == .failure(DatedError(error: <error value>, date: <date>))
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func mapError<NewFailure>(
_ transform: (Failure) -> NewFailure
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return .failure(transform(failure))
}
}
/// Returns a new result, mapping any success value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the success value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func flatMap<NewSuccess>(
_ transform: (Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}
/// Returns a new result, mapping any failure value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance, either from the closure or the previous
/// `.success`.
public func flatMapError<NewFailure>(
_ transform: (Failure) -> Result<Success, NewFailure>
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return transform(failure)
}
}
/// Returns the success value as a throwing expression.
///
/// Use this method to retrieve the value of this result if it represents a
/// success, or to catch the value if it represents a failure.
///
/// let integerResult: Result<Int, Error> = .success(5)
/// do {
/// let value = try integerResult.get()
/// print("The value is \(value).")
/// } catch error {
/// print("Error retrieving the value: \(error)")
/// }
/// // Prints "The value is 5."
///
/// - Returns: The success value, if the instance represent a success.
/// - Throws: The failure value, if the instance represents a failure.
public func get() throws -> Success {
switch self {
case let .success(success):
return success
case let .failure(failure):
throw failure
}
}
}
extension Result: Equatable where Success: Equatable, Failure: Equatable {}
extension Result: Hashable where Success: Hashable, Failure: Hashable {}
// To be able to use it in places that already have a local result
// TODO: Remove this when using Swift 5
typealias CoreResult = Result
public protocol CancellableError: Error {
/// Returns true if this Error represents a cancelled condition
var isCancelled: Bool { get }
}
public struct CancellationError: CancellableError {
public var isCancelled = true
}
extension Error {
public var isCancelled: Bool {
do {
throw self
} catch let error as CancellableError {
return error.isCancelled
} catch URLError.cancelled {
return true
} catch CocoaError.userCancelled {
return true
} catch {
#if os(macOS) || os(iOS) || os(tvOS)
let pair = { ($0.domain, $0.code) }(error as NSError)
return pair == ("SKErrorDomain", 2)
#else
return false
#endif
}
}
}
extension Result {
/**
```
switch result {
case .success(let value):
print(value)
case .failure where result.isCancelled:
print("Cancelled")
case .failure(let error):
print(error)
}
```
*/
public var isCancelled: Bool {
do {
_ = try get()
return false
} catch {
return error.isCancelled
}
}
}
| 22.958576 | 182 | 0.688266 |
7588374460ded3781fd8795701377341000250a3 | 649 | //
// p03_chronicqazxc.swift
// chronicqazxc
//
// Created by Wayne Hsiao on 2018/8/1.
//
import NinetyNineSwiftProblems
extension List {
subscript(index: Int) -> T? {
var currentItem = self
var currentIndex: Int = 0
while let nextItem = currentItem.nextItem, currentIndex != index {
currentIndex = currentIndex + 1
currentItem = nextItem
if currentIndex == index {
return currentItem.value
}
}
if currentIndex == index {
return currentItem.value
} else {
return nil
}
}
}
| 20.935484 | 74 | 0.53621 |
48784243dc313acf20bb75f3d22b96b5c76a1405 | 2,629 | import UIKit
// MARK: - Generating Random Numbers
//: Before Swift 4.2, C APIs had to be used to work with random numbers. For example, to get a random number between 0 and 9, you could call `arc4random_uniform()`
let cRandom = Int(arc4random_uniform(10))
//Swift 4.2 이전에 랜덤한 수를 생성하기 위해서는 C 언어의 arc4random을 사용했다. 이는 Foundation을 import 해야 하며 Linux에서는 작동하지 않는다.
//: While this gave a random number, you had to import Foundation, it didn't work on linux, and wasn't very random thanks to modulo bias. Now in Swift 4.2 the Standard Library includes some random API. Now to get a number between 0 and 9, use `random(in:)` on the `Int` class
let digit = Int.random(in: 0..<10)
//Swift 4.2 에서는 Standard Library에 Random API가 있다. 위의 코드와 결과가 같다. 제공된 범위에서 난수를 반환한다.
//: This returns a random number from the provided range. You can also call `randomElement()` directly on a range
if let anotherDigit = (0..<10).randomElement() { //범위에서 직접 randomElement() 메서드를 사용해 난수를 가져올 수도 있다.
//optional이므로 if let으로 바인딩 해야 한다.
print(anotherDigit)
} else {
print("Empty range.")
}
//: Asking for a random number this way on the range returns an optional, so it needs to be unwrapped with `if let`. The random method also works on `Doubles`, `Floats` and `CGFloat`, and a no-argument version exists for `Boolean` so you flip a coin with a method call
let double = Double.random(in: 0..<1)
let float = Float.random(in: 0..<1)
let cgFloat = CGFloat.random(in: 0..<1)
let bool = Bool.random()
//Double, Float, CGFloat, Bool에도 적용된다. 특히 Bool은 동전 던지기 등의 T/F에 다양하게 사용할 수 있다.
// MARK: - Shuffling Lists
//: Numbers aren't the only type to get new random features - arrays also got some attention in Swift 4.2, If I have an array of strings, `randomElement()` can be used to get a random string from the array
let playlist = ["Nothing Else Matters", "Stairway to Heaven", "I Want to Break Free", "Yesterday"]
if let song = playlist.randomElement() { //배열에서도 randomElement()로 값을 가져올 수 있다(위에서는 range).
//optional이므로 if let으로 바인딩 해야 한다.
print(song)
} else {
print("Empty playlist.")
}
//: As with `randomElement()` with numbers, this returns an optional, so it is unwrapped with `if let`.
//: Another new feature that arrays get that is related to random is the ability to shuffle. Before Swift 4.2, a feature like this had to be created by hand. Now, a simple call to `shuffled()` will do.
let shuffledPlaylist = playlist.shuffled() //shuffled()은 무작위로 순서가 변경된 배열을 반환한다.
//: This return a shuffled array. To sort in place you can simply call `shuffle()`
var names = ["Cosmin", "Oana", "Sclip", "Nori"]
names.shuffle()
| 48.685185 | 276 | 0.715101 |
f984e1ac51c3eef668bfd6b086442efbffc4f517 | 1,528 | /**
* https://leetcode.com/problems/find-the-town-judge/
*
*
*/
// Date: Sun May 10 13:24:03 PDT 2020
class Solution {
struct Degree {
var ins: Int
var outs: Int
init() {
self.ins = 0
self.outs = 0
}
mutating func trusting() {
self.outs += 1
}
mutating func trusted() {
self.ins += 1
}
}
func findJudge(_ N: Int, _ trust: [[Int]]) -> Int {
var record = Array(repeating: Degree(), count: N + 1)
for relation in trust {
let a = relation[0]
let b = relation[1]
record[a].trusting()
record[b].trusted()
}
var ret: [Int] = []
for index in 1 ... N {
if record[index].ins == N - 1, record[index].outs == 0 {
ret.append(index)
}
}
return ret.count == 1 ? ret[0] : -1
}
}
/**
* https://leetcode.com/problems/find-the-town-judge/
*
*
*/
// Date: Sun Jan 2 23:19:50 PST 2022
class Solution {
func findJudge(_ n: Int, _ trust: [[Int]]) -> Int {
var trusting = Array(repeating: 0, count: n + 1)
var trusted = Array(repeating: 0, count: n + 1)
for t in trust {
trusting[t[0]] += 1
trusted[t[1]] += 1
}
for x in 1 ... n {
if trusting[x] == 0, trusted[x] == n - 1 {
return x
}
}
return -1
}
} | 23.507692 | 68 | 0.433246 |
18681e69c05f0267dba4dd38d85d9f4ca6f52321 | 2,845 | import Foundation
import SourceKittenFramework
extension String {
internal func hasTrailingWhitespace() -> Bool {
if isEmpty {
return false
}
if let unicodescalar = unicodeScalars.last {
return CharacterSet.whitespaces.contains(unicodescalar)
}
return false
}
internal func isUppercase() -> Bool {
return self == uppercased()
}
internal func isLowercase() -> Bool {
return self == lowercased()
}
internal func nameStrippingLeadingUnderscoreIfPrivate(_ dict: [String: SourceKitRepresentable]) -> String {
if let aclString = dict.accessibility,
let acl = AccessControlLevel(identifier: aclString),
acl.isPrivate && first == "_" {
return String(self[index(after: startIndex)...])
}
return self
}
private subscript (range: Range<Int>) -> String {
let nsrange = NSRange(location: range.lowerBound,
length: range.upperBound - range.lowerBound)
if let indexRange = nsrangeToIndexRange(nsrange) {
return String(self[indexRange])
}
queuedFatalError("invalid range")
}
internal func substring(from: Int, length: Int? = nil) -> String {
if let length = length {
return self[from..<from + length]
}
return String(self[index(startIndex, offsetBy: from, limitedBy: endIndex)!...])
}
internal func lastIndex(of search: String) -> Int? {
if let range = range(of: search, options: [.literal, .backwards]) {
return distance(from: startIndex, to: range.lowerBound)
}
return nil
}
internal func nsrangeToIndexRange(_ nsrange: NSRange) -> Range<Index>? {
guard nsrange.location != NSNotFound else {
return nil
}
let from16 = utf16.index(utf16.startIndex, offsetBy: nsrange.location,
limitedBy: utf16.endIndex) ?? utf16.endIndex
let to16 = utf16.index(from16, offsetBy: nsrange.length,
limitedBy: utf16.endIndex) ?? utf16.endIndex
guard let fromIndex = Index(from16, within: self),
let toIndex = Index(to16, within: self) else {
return nil
}
return fromIndex..<toIndex
}
public func absolutePathStandardized() -> String {
return bridge().absolutePathRepresentation().bridge().standardizingPath
}
internal var isFile: Bool {
var isDirectoryObjC: ObjCBool = false
if FileManager.default.fileExists(atPath: self, isDirectory: &isDirectoryObjC) {
#if os(Linux) && !swift(>=4.1)
return !isDirectoryObjC
#else
return !isDirectoryObjC.boolValue
#endif
}
return false
}
}
| 31.611111 | 111 | 0.598594 |
cc2e930a141a69505dcbc6a4e47d796a6116ac6a | 1,426 | //
// AppDelegate.swift
// tabbar-multiple-screen
//
// Created by zhongming on 2020/4/23.
// Copyright © 2020 zhongming. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.526316 | 179 | 0.748948 |
799fd85eea2bc7555332db3886341a4b9b058239 | 743 | //
// AppDelegate.swift
// GMD Swift
//
// Created by Patrik Vaberer on 8/29/15.
// Copyright © 2015 Patrik Vaberer. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
if let font = UIFont(name: "HelveticaNeue-Light", size: 20) {
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.black]
}
return true
}
}
| 26.535714 | 153 | 0.703903 |
2966fc753ecfc6ff9c2f783aabe7a56d1539b969 | 1,600 | //
// UIView+Extension.swift
// IOS12RecordVideoTutorial
//
// Created by trioangle on 29/08/19.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import Foundation
import UIKit
extension UIView{
func activityStartAnimating(activityColor: UIColor, backgroundColor: UIColor) {
let backgroundView = UIView()
backgroundView.frame = CGRect.init(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)
backgroundView.backgroundColor = backgroundColor
backgroundView.tag = 475647
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
activityIndicator = UIActivityIndicatorView(frame: CGRect.init(x: 0, y: 0, width: 50, height: 50))
activityIndicator.center = self.center
activityIndicator.hidesWhenStopped = true
activityIndicator.style = UIActivityIndicatorView.Style.gray
activityIndicator.color = activityColor
activityIndicator.startAnimating()
self.isUserInteractionEnabled = false
DispatchQueue.main.async {
backgroundView.addSubview(activityIndicator)
self.addSubview(backgroundView)
}
}
func activityStopAnimating() {
if let background = viewWithTag(475647){
DispatchQueue.main.async {
background.removeFromSuperview()
}
}
self.isUserInteractionEnabled = true
}
}
extension Bundle {
var appName: String? {
return object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
}
}
| 31.372549 | 108 | 0.67 |
7548a571702bc6aae1b75a22681c0245c3ce353d | 689 | //
// BorderViewModifier.swift
// Kuchi
//
// Created by PH on 2021/4/11.
//
import SwiftUI
struct BorderViewModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding(EdgeInsets(top: 8, leading: 16,
bottom: 8, trailing: 16))
.background(Color.white)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(lineWidth: 2)
.foregroundColor(.blue)
)
.shadow(color: Color.gray.opacity(0.4),
radius: 3, x: 2, y: 2)
}
}
extension View {
func bordered() -> some View {
ModifiedContent(
content: self,
modifier: BorderViewModifier()
)
}
}
| 20.264706 | 51 | 0.576197 |
0a684dc19ff7b4929c3e8f93f6b0eca708518cd4 | 2,260 | //
// CurrentUserTableViewCell.swift
// ZeroMessger
//
// Created by Sandeep Mukherjee on 5/22/20.
// Copyright © 2020 Sandeep Mukherjee. All rights reserved.
//
import UIKit
class CurrentUserTableViewCell: UITableViewCell {
var icon: UIImageView = {
var icon = UIImageView()
icon.translatesAutoresizingMaskIntoConstraints = false
icon.contentMode = .scaleAspectFill
icon.layer.cornerRadius = 26
icon.layer.masksToBounds = true
icon.image = ThemeManager.currentTheme().personalStorageImage
return icon
}()
var title: UILabel = {
var title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
title.textColor = ThemeManager.currentTheme().generalTitleColor
return title
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
title.backgroundColor = backgroundColor
icon.backgroundColor = backgroundColor
contentView.addSubview(icon)
icon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0).isActive = true
icon.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15).isActive = true
icon.widthAnchor.constraint(equalToConstant: 55).isActive = true
icon.heightAnchor.constraint(equalToConstant: 55).isActive = true
contentView.addSubview(title)
title.centerYAnchor.constraint(equalTo: icon.centerYAnchor, constant: 0).isActive = true
title.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: 15).isActive = true
title.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15).isActive = true
title.heightAnchor.constraint(equalToConstant: 55).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
print("prepare for reuser")
icon.image = #imageLiteral(resourceName: "PersonalStorage")
title.text = ""
title.textColor = ThemeManager.currentTheme().generalTitleColor
}
}
| 33.235294 | 103 | 0.738053 |
f9c78b7e9cf2ef41a20c51cdc1953e4c8f992476 | 846 | //
// UINavigationItemExtensionsTests.swift
// SwifterSwift
//
// Created by Steven on 2/16/17.
// Copyright © 2017 SwifterSwift
//
@testable import SwifterSwift
import XCTest
#if canImport(UIKit) && !os(watchOS)
import UIKit
final class UINavigationItemExtensionsTests: XCTestCase {
func testReplaceTitle() {
let navigationItem = UINavigationItem()
let image = UIImage()
navigationItem.replaceTitle(with: image)
let imageView = navigationItem.titleView as? UIImageView
XCTAssertNotNil(imageView)
let frame = CGRect(x: 0, y: 0, width: 100, height: 30)
XCTAssertEqual(imageView?.frame, frame)
XCTAssertEqual(imageView?.contentMode, .scaleAspectFit)
XCTAssertEqual(imageView?.image, image)
}
}
#endif
| 25.636364 | 68 | 0.647754 |
ddff9094a5aefc3513b7051122c8b9ca8e519cd2 | 452 | //
// UserDefault.swift
// TakeSafe
//
// Created by Linus Långberg on 2020-11-14.
//
import Foundation
import Combine
@propertyWrapper
struct UserDefault<T> {
let key: String
init(_ key: String) {
self.key = key
}
var wrappedValue: T {
get {
return UserDefaults.standard.object(forKey: key) as! T
}
set {
UserDefaults.standard.set(newValue, forKey: key)
}
}
}
| 16.142857 | 66 | 0.575221 |
de48b7bbad22fc17046a35d9f7bb5c7e5f9bf3af | 445 | import XCTest
@testable import MeliApp
class SearchInteractorOutputMock: SearchInteractorOutputProtocol {
var interactorPushDataPresenterCalled = false
var interactorErrorDataPresenterCalled = false
func interactorErrorDataPresenter() {
interactorErrorDataPresenterCalled = true
}
func interactorPushDataPresenter(receivedData: [SearchViewModel]) {
interactorPushDataPresenterCalled = true
}
}
| 27.8125 | 71 | 0.768539 |
1ab4f06f7ccbad388545a6111c782e4dd775f540 | 1,462 | /*:
## Else If
What if you wanted to show a different message if a video was too long?
There is one last thing you can do with `if` and `else`. Here’s how it looks:
*/
let videoLength = 20
if videoLength < 5 {
"If I blinked, I'd miss it."
} else if videoLength > 500 {
"Don't worry, I know a good editor."
} else {
"That was lovely."
}
/*:
Using `else if` lets you add another conditional statement, which is only checked if the first conditional is `false`. If the `else if` conditional is also `false`, then the code after the final `else` is executed.
- experiment: Change the value of `videoLength` and trace the flow of the code through the conditionals.
You can add more than one `else if` statement, but the first one that is `true` will be the one that “wins”:
*/
let anotherVideoLength = 75000
if anotherVideoLength < 5 {
"If I blinked, I'd miss it."
} else if anotherVideoLength > 50000 {
"This is too long for anyone."
} else if anotherVideoLength > 500 {
"Don't worry, I know a good editor."
} else {
"That was lovely."
}
//: Notice that the final `else if` statement, even though it is `true`, does not get executed. Once a conditional is `true`, the later ones are not checked. The order of your code is very important!
//:
//: On the next page, learn how to use functions to make complicated decisions look simple.
//:
//: [Previous](@previous) | page 7 of 13 | [Next: Functions and Decisions](@next)
| 38.473684 | 215 | 0.692886 |
d99f956fb64d17b0f7a5bdade420b665e4bf3bef | 17,364 | //
// PopularViewController.swift
// Movies
//
// Created by Prince Alvin Yusuf on 20/06/2021.
// Copyright © 2021 Prince Alvin Yusuf. All rights reserved.
//
import UIKit
protocol ScrollDelegate: AnyObject {
func scrollToTop()
}
class PopularViewController: BaseViewController {
private let movieApi: MovieService
private var state: PopularVCViewState<PopularMoviesResponse> = .loading {
didSet {
changeUI(for: state, previousState: oldValue)
}
}
private var total: Int = 0
private var page: Int = 1
private var movies: [Movie] = []
private var filteredMovies: [Movie] = []
private lazy var searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = true
searchController.delegate = self
return searchController
}()
private lazy var collectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.minimumLineSpacing = 16
flowLayout.minimumInteritemSpacing = 0
let uiCollectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
uiCollectionView.backgroundColor = .clear
uiCollectionView.contentInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
uiCollectionView.dataSource = self
uiCollectionView.delegate = self
uiCollectionView.register(MovieCollectionViewCell.self,
forCellWithReuseIdentifier: MovieCollectionViewCell.reuseIdentifier)
uiCollectionView.register(MovieCollectionViewFooter.self,
forSupplementaryViewOfKind: UICollectionElementKindSectionFooter,
withReuseIdentifier: MovieCollectionViewFooter.identifier)
return uiCollectionView
}()
// Empty view layout
private let emptyView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .center
return stackView
}()
private let emptyImgView: UIImageView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "search_icon").withRenderingMode(.alwaysTemplate))
imageView.contentMode = .scaleAspectFit
return imageView
}()
private let emptyLabel: UILabel = {
let label = UILabel()
label.text = "No movies found with selected search"
label.font = UIFont.boldSystemFont(ofSize: 18)
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
return label
}()
// Error view layout
private let errorView = UIView()
private let errorLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.text = "An error occurred!"
label.font = UIFont.boldSystemFont(ofSize: 18)
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
return label
}()
private lazy var errorBtn: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Try again", for: .normal)
button.addTarget(self, action: #selector(tryAgain), for: .touchUpInside)
button.backgroundColor = Config.purple
button.tintColor = Config.black
button.layer.cornerRadius = 2.0
button.layer.borderWidth = 2.0
button.layer.borderColor = Config.black.cgColor
return button
}()
private let activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.hidesWhenStopped = true
return activityIndicator
}()
init(movieApi: MovieService) {
self.movieApi = movieApi
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Defining context for searchController
definesPresentationContext = true
getPopularMovies(page: page)
setupObservers()
}
override func setupViews() {
super.setupViews()
setupNavigationBar()
setupCollectionView()
setupEmptyView()
setupErrorView()
setupLoadingView()
}
private func changeUI(for: PopularVCViewState<PopularMoviesResponse>, previousState: PopularVCViewState<PopularMoviesResponse>) {
switch state {
case .loading:
emptyView.isHidden = true
errorView.isHidden = true
collectionView.collectionViewLayout.invalidateLayout()
if case .error(_) = previousState {
collectionView.reloadData()
}
if total == 0 {
collectionView.isHidden = true
activityIndicator.startAnimating()
} else {
collectionView.isHidden = false
activityIndicator.stopAnimating()
}
case .finished(let response):
emptyView.isHidden = true
errorView.isHidden = true
activityIndicator.stopAnimating()
collectionView.isHidden = false
if let total = response.totalPages {
self.total = total
}
if let page = response.page {
self.page = page
}
if let results = response.results {
if previousState == .empty || previousState == .filtering {
collectionView.reloadData()
return
}
let movies = Movie.getCachedMovies()
for movie in movies {
for result in results where result == movie {
result.isFavorite = true
}
}
collectionView.performBatchUpdates({
let max = self.movies.count
self.movies.append(contentsOf: results)
var items: [IndexPath] = []
for (index, _) in results.enumerated() {
let indexPath = IndexPath(item: max + index, section: 0)
items.append(indexPath)
}
self.collectionView.insertItems(at: items)
self.collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
case .filtering:
emptyView.isHidden = true
errorView.isHidden = true
activityIndicator.stopAnimating()
collectionView.isHidden = false
collectionView.reloadData()
case .empty:
emptyView.isHidden = false
errorView.isHidden = true
activityIndicator.stopAnimating()
collectionView.collectionViewLayout.invalidateLayout()
collectionView.isHidden = true
collectionView.reloadData()
case .error(_):
emptyView.isHidden = true
activityIndicator.stopAnimating()
if total == 0 {
collectionView.isHidden = true
errorView.isHidden = false
} else {
collectionView.isHidden = false
errorView.isHidden = true
collectionView.collectionViewLayout.invalidateLayout()
collectionView.reloadData()
}
}
}
}
// MARK: Layout
extension PopularViewController {
private func setupNavigationBar() {
navigationItem.title = "Movies"
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .automatic
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
}
private func setupCollectionView() {
view.addSubview(collectionView)
collectionView.fillSuperviewSafeLayoutGuide()
}
private func setupEmptyView() {
view.addSubview(emptyView)
emptyView.addArrangedSubview(emptyImgView)
emptyView.addArrangedSubview(emptyLabel)
emptyView.anchor(top: nil, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor, padding: .init(top: 0, left: 16, bottom: 0, right: 16), size: .init(width: 0, height: view.frame.height * 0.15))
emptyView.anchorCenter(to: view)
}
private func setupErrorView() {
view.addSubview(errorView)
errorView.addSubview(errorLabel)
errorView.addSubview(errorBtn)
errorView.anchor(top: nil, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor, padding: .init(top: 0, left: 16, bottom: 0, right: 16), size: .init(width: 0, height: view.frame.height * 0.15))
errorView.anchorCenter(to: view)
errorLabel.anchor(top: errorView.topAnchor, leading: errorView.leadingAnchor, bottom: errorBtn.topAnchor, trailing: errorView.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 16, right: 0), size: .zero)
errorBtn.anchor(top: nil, leading: errorView.leadingAnchor, bottom: errorView.bottomAnchor, trailing: errorView.trailingAnchor, padding: .zero, size: .zero)
}
private func setupLoadingView() {
view.addSubview(activityIndicator)
activityIndicator.anchorCenter(to: view)
}
}
// MARK: Actions
extension PopularViewController {
private func getMovieFor(indexPath: IndexPath) -> Movie {
let movie: Movie
if isFiltering() {
movie = filteredMovies[indexPath.item]
} else {
movie = movies[indexPath.item]
}
return movie
}
@objc private func tryAgain() {
let nextPage = page + 1
getPopularMovies(page: nextPage)
}
private func setupObservers() {
NotificationCenter.default.addObserver(forName: .onMovieFavorited, object: nil, queue: nil) { (notification) in
if let movie = notification.userInfo?["movie"] as? Movie {
for (index, mv) in self.movies.enumerated() {
if mv == movie {
self.movies[index] = movie
self.collectionView.reloadItems(at: [IndexPath(item: index, section: 0)])
break
}
}
for (index, mv) in self.filteredMovies.enumerated() {
if mv == movie {
self.filteredMovies[index] = movie
self.collectionView.reloadItems(at: [IndexPath(item: index, section: 0)])
break
}
}
}
}
}
}
// MARK: Movie service
extension PopularViewController {
private func getPopularMovies(page: Int) {
if total > 0, state == .loading {
return
}
if isFiltering() {
return
}
state = .loading
movieApi.getPopularMovies(page: page) { [weak self] (result) in
guard let welf = self else { return }
switch result {
case .success(let response):
if let totalResults = response.totalResults, totalResults == 0 {
welf.state = .empty
} else {
welf.state = .finished(response)
}
case .error(let error):
welf.state = .error(error)
}
}
}
}
// MARK: UICollectionViewDelegate
extension PopularViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let movie = getMovieFor(indexPath: indexPath)
let movieDetailVC = MovieDetailViewController(movie: movie, movieApi: movieApi)
movieDetailVC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(movieDetailVC, animated: true)
}
}
// MARK: UICollectionViewDataSource
extension PopularViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return isFiltering() ? filteredMovies.count : movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MovieCollectionViewCell.reuseIdentifier, for: indexPath) as! MovieCollectionViewCell
let movie = getMovieFor(indexPath: indexPath)
cell.movie = movie
cell.onToggleFavorite = { isFavorite in
movie.isFavorite = isFavorite
movie.dateAddedToFavorites = isFavorite ? Date() : nil
NotificationCenter.default.post(name: .onMovieFavorited, object: nil, userInfo: ["movie": movie])
}
if !movies.isEmpty, total > 0, indexPath.item == (movies.count - 3), movies.count < total, !isFiltering() {
if case .finished(_) = state {
let nextPage = page + 1
getPopularMovies(page: nextPage)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader: break
case UICollectionElementKindSectionFooter:
if let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: MovieCollectionViewFooter.identifier, for: indexPath) as? MovieCollectionViewFooter {
if case .error(_) = state {
footerView.state = .error
} else {
footerView.state = .loading
}
footerView.onTryAgain = {
self.tryAgain()
}
return footerView
}
default: break
}
return UICollectionReusableView()
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension PopularViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let margins: CGFloat = 24
let width = (view.frame.width / 2) - margins
return CGSize(width: width, height: MovieCollectionViewCell.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if total == 0 || isFiltering() {
return .zero
}
return CGSize(width: view.frame.width, height: MovieCollectionViewFooter.height)
}
}
// MARK: ScrollDelegate
extension PopularViewController: ScrollDelegate {
func scrollToTop() {
collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true)
}
}
// MARK: UISearchResultsUpdating
extension PopularViewController: UISearchResultsUpdating {
func searchBarIsEmpty() -> Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
func filterContentForSearchText(_ searchText: String) {
filteredMovies = movies.flatMap { movie in
guard let title = movie.title,
title.lowercased().contains(searchText.lowercased()) else {
return nil
}
return movie
}
if filteredMovies.isEmpty {
if searchBarIsEmpty() {
filteredMovies = movies
state = .filtering
} else {
state = .empty
}
} else {
state = .filtering
}
}
func isFiltering() -> Bool {
return searchController.isActive && !searchBarIsEmpty()
}
func updateSearchResults(for searchController: UISearchController) {
if searchController.isActive {
filterContentForSearchText(searchController.searchBar.text ?? "")
}
}
}
// MARK: UISearchControllerDelegate
extension PopularViewController: UISearchControllerDelegate {
func willPresentSearchController(_ searchController: UISearchController) {
filteredMovies = movies
state = .filtering
}
func willDismissSearchController(_ searchController: UISearchController) {
let response = PopularMoviesResponse()
response.results = movies
state = .finished(response)
}
}
| 37.665944 | 232 | 0.61783 |
18a2faf99fa12b1d4b1edc1ac4cc358b0f09aacc | 435 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
class PopularWeekController: CollectionContoller {
override func onPrepare() {
endpoint = APIHeaper.API_Popular_Weakly
}
override func listViewCreated() {
collectionView.registerClass(PopularFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: PopularFooterView.reuseIdentifier)
}
}
| 29 | 182 | 0.751724 |
8a663e2e19bf1b15ce10fb12bbecc8dcaa5fb63b | 3,055 | //
// PKHUDErrorAnimation.swift
// PKHUD
//
// Created by Philip Kluz on 9/27/15.
// Copyright (c) 2016 NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import UIKit
/// PKHUDErrorView provides an animated error (cross) view.
open class PKHUDErrorView: PKHUDSquareBaseView, PKHUDAnimating {
var dashOneLayer = PKHUDErrorView.generateDashLayer()
var dashTwoLayer = PKHUDErrorView.generateDashLayer()
class func generateDashLayer() -> CAShapeLayer {
let dash = CAShapeLayer()
dash.frame = CGRect(x: 0.0, y: 0.0, width: 88.0, height: 88.0)
dash.path = {
let path = UIBezierPath()
path.move(to: CGPoint(x: 0.0, y: 44.0))
path.addLine(to: CGPoint(x: 88.0, y: 44.0))
return path.cgPath
}()
dash.lineCap = .round
dash.lineJoin = .round
dash.fillColor = nil
dash.strokeColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0).cgColor
dash.lineWidth = 6
dash.fillMode = .forwards
return dash
}
public init(title: String? = nil, subtitle: String? = nil) {
super.init(title: title, subtitle: subtitle)
layer.addSublayer(dashOneLayer)
layer.addSublayer(dashTwoLayer)
dashOneLayer.position = layer.position
dashTwoLayer.position = layer.position
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.addSublayer(dashOneLayer)
layer.addSublayer(dashTwoLayer)
dashOneLayer.position = layer.position
dashTwoLayer.position = layer.position
}
func rotationAnimation(_ angle: CGFloat) -> CABasicAnimation {
var animation: CABasicAnimation
if #available(iOS 9.0, *) {
let springAnimation = CASpringAnimation(keyPath: "transform.rotation.z")
springAnimation.damping = 1.5
springAnimation.mass = 0.22
springAnimation.initialVelocity = 0.5
animation = springAnimation
} else {
animation = CABasicAnimation(keyPath: "transform.rotation.z")
}
animation.fromValue = 0.0
animation.toValue = angle * CGFloat(.pi / 180.0)
animation.duration = 1.0
animation.timingFunction = .init(name: .easeInEaseOut)
return animation
}
public func startAnimation() {
let dashOneAnimation = rotationAnimation(-45.0)
let dashTwoAnimation = rotationAnimation(45.0)
dashOneLayer.transform = CATransform3DMakeRotation(-45 * CGFloat(.pi / 180.0), 0.0, 0.0, 1.0)
dashTwoLayer.transform = CATransform3DMakeRotation(45 * CGFloat(.pi / 180.0), 0.0, 0.0, 1.0)
dashOneLayer.add(dashOneAnimation, forKey: "dashOneAnimation")
dashTwoLayer.add(dashTwoAnimation, forKey: "dashTwoAnimation")
}
public func stopAnimation() {
dashOneLayer.removeAnimation(forKey: "dashOneAnimation")
dashTwoLayer.removeAnimation(forKey: "dashTwoAnimation")
}
}
| 35.114943 | 101 | 0.639935 |
ccaebb8a65834905fce37053c51fb25723235bc4 | 514 | //
// HeightWithTrunk.swift
// SpaceXAPI-Swift
//
// Created by Sami Sharafeddine on 5/26/19.
// Copyright © 2019 Sami Sharafeddine. All rights reserved.
//
import Foundation
public class HeightWithTrunk: Codable {
public let meters: SXNumber?
public let feet: SXNumber?
enum CodingKeys: String, CodingKey {
case meters = "meters"
case feet = "feet"
}
init(meters: SXNumber?, feet: SXNumber?) {
self.meters = meters
self.feet = feet
}
}
| 19.769231 | 60 | 0.622568 |
f5acc1519065332cb9d6e2bd71a978fb8b0260d7 | 107,769 | // RUN: rm -rf %t
// RUN: mkdir -p %t
//
// RUN: %gyb %s -o %t/main.swift
// RUN: if [ %target-runtime == "objc" ]; then \
// RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o; \
// RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Set -Xfrontend -disable-access-control; \
// RUN: else \
// RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %t/main.swift -o %t/Set -Xfrontend -disable-access-control; \
// RUN: fi
//
// RUN: %line-directive %t/main.swift -- %target-run %t/Set
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
// For rand32
import SwiftPrivate
#if _runtime(_ObjC)
import Foundation
#else
// for random, srandom
import Glibc
#endif
// For experimental Set operators
import SwiftExperimental
extension Set {
func _rawIdentifier() -> Int {
return unsafeBitCast(self, to: Int.self)
}
}
// Check that the generic parameter is called 'Element'.
protocol TestProtocol1 {}
extension Set where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension SetIndex where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension SetIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
let hugeNumberArray = Array(0..<500)
var SetTestSuite = TestSuite("Set")
SetTestSuite.setUp {
resetLeaksOfDictionaryKeysValues()
#if _runtime(_ObjC)
resetLeaksOfObjCDictionaryKeysValues()
#endif
}
SetTestSuite.tearDown {
expectNoLeaksOfDictionaryKeysValues()
#if _runtime(_ObjC)
expectNoLeaksOfObjCDictionaryKeysValues()
#endif
}
func getCOWFastSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<Int> {
var s = Set<Int>(minimumCapacity: 10)
for member in members {
s.insert(member)
}
expectTrue(isNativeSet(s))
return s
}
func getCOWSlowSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<TestKeyTy> {
var s = Set<TestKeyTy>(minimumCapacity: 10)
for member in members {
s.insert(TestKeyTy(member))
}
expectTrue(isNativeSet(s))
return s
}
func helperDeleteThree(_ k1: TestKeyTy, _ k2: TestKeyTy, _ k3: TestKeyTy) {
var s1 = Set<TestKeyTy>(minimumCapacity: 10)
s1.insert(k1)
s1.insert(k2)
s1.insert(k3)
expectTrue(s1.contains(k1))
expectTrue(s1.contains(k2))
expectTrue(s1.contains(k3))
s1.remove(k1)
expectTrue(s1.contains(k2))
expectTrue(s1.contains(k3))
s1.remove(k2)
expectTrue(s1.contains(k3))
s1.remove(k3)
expectEqual(0, s1.count)
}
func uniformRandom(_ max: Int) -> Int {
return Int(rand32(exclusiveUpperBound: UInt32(max)))
}
func pickRandom<T>(_ a: [T]) -> T {
return a[uniformRandom(a.count)]
}
func equalsUnordered(_ lhs: Set<Int>, _ rhs: Set<Int>) -> Bool {
return lhs.sorted().elementsEqual(rhs.sorted()) {
$0 == $1
}
}
func isNativeSet<T : Hashable>(_ s: Set<T>) -> Bool {
switch s._variantBuffer {
case .native:
return true
case .cocoa:
return false
}
}
#if _runtime(_ObjC)
func isNativeNSSet(_ s: NSSet) -> Bool {
let className: NSString = NSStringFromClass(type(of: s)) as NSString
return ["_SwiftDeferredNSSet", "NativeSetStorage"].contains {
className.range(of: $0).length > 0
}
}
func isCocoaNSSet(_ s: NSSet) -> Bool {
let className: NSString = NSStringFromClass(type(of: s)) as NSString
return className.range(of: "NSSet").length > 0 ||
className.range(of: "NSCFSet").length > 0
}
func getBridgedEmptyNSSet() -> NSSet {
let s = Set<TestObjCKeyTy>()
let bridged = unsafeBitCast(convertSetToNSSet(s), to: NSSet.self)
expectTrue(isNativeNSSet(bridged))
return bridged
}
func isCocoaSet<T : Hashable>(_ s: Set<T>) -> Bool {
return !isNativeSet(s)
}
/// Get an NSSet of TestObjCKeyTy values
func getAsNSSet(_ members: [Int] = [1010, 2020, 3030]) -> NSSet {
let nsArray = NSMutableArray()
for member in members {
nsArray.add(TestObjCKeyTy(member))
}
return NSMutableSet(array: nsArray as [AnyObject])
}
/// Get an NSMutableSet of TestObjCKeyTy values
func getAsNSMutableSet(_ members: [Int] = [1010, 2020, 3030]) -> NSMutableSet {
let nsArray = NSMutableArray()
for member in members {
nsArray.add(TestObjCKeyTy(member))
}
return NSMutableSet(array: nsArray as [AnyObject])
}
public func convertSetToNSSet<T>(_ s: Set<T>) -> NSSet {
return s._bridgeToObjectiveC()
}
public func convertNSSetToSet<T : Hashable>(_ s: NSSet?) -> Set<T> {
if _slowPath(s == nil) { return [] }
var result: Set<T>?
Set._forceBridgeFromObjectiveC(s!, result: &result)
return result!
}
/// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by Cocoa storage
func getBridgedVerbatimSet(_ members: [Int] = [1010, 2020, 3030])
-> Set<NSObject> {
let nss = getAsNSSet(members)
let result: Set<NSObject> = convertNSSetToSet(nss)
expectTrue(isCocoaSet(result))
return result
}
/// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by native storage
func getNativeBridgedVerbatimSet(_ members: [Int] = [1010, 2020, 3030]) ->
Set<NSObject> {
let result: Set<NSObject> = Set(members.map({ TestObjCKeyTy($0) }))
expectTrue(isNativeSet(result))
return result
}
/// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by Cocoa storage
func getHugeBridgedVerbatimSet() -> Set<NSObject> {
let nss = getAsNSSet(hugeNumberArray)
let result: Set<NSObject> = convertNSSetToSet(nss)
expectTrue(isCocoaSet(result))
return result
}
/// Get a Set<TestBridgedKeyTy> backed by native storage
func getBridgedNonverbatimSet(_ members: [Int] = [1010, 2020, 3030]) ->
Set<TestBridgedKeyTy> {
let nss = getAsNSSet(members)
let _ = unsafeBitCast(nss, to: Int.self)
let result: Set<TestBridgedKeyTy> =
Swift._forceBridgeFromObjectiveC(nss, Set.self)
expectTrue(isNativeSet(result))
return result
}
/// Get a larger Set<TestBridgedKeyTy> backed by native storage
func getHugeBridgedNonverbatimSet() -> Set<TestBridgedKeyTy> {
let nss = getAsNSSet(hugeNumberArray)
let _ = unsafeBitCast(nss, to: Int.self)
let result: Set<TestBridgedKeyTy> =
Swift._forceBridgeFromObjectiveC(nss, Set.self)
expectTrue(isNativeSet(result))
return result
}
func getBridgedVerbatimSetAndNSMutableSet() -> (Set<NSObject>, NSMutableSet) {
let nss = getAsNSMutableSet()
return (convertNSSetToSet(nss), nss)
}
func getBridgedNonverbatimSetAndNSMutableSet()
-> (Set<TestBridgedKeyTy>, NSMutableSet) {
let nss = getAsNSMutableSet()
return (Swift._forceBridgeFromObjectiveC(nss, Set.self), nss)
}
func getBridgedNSSetOfRefTypesBridgedVerbatim() -> NSSet {
expectTrue(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self))
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
s.insert(TestObjCKeyTy(1010))
s.insert(TestObjCKeyTy(2020))
s.insert(TestObjCKeyTy(3030))
let bridged =
unsafeBitCast(convertSetToNSSet(s), to: NSSet.self)
expectTrue(isNativeNSSet(bridged))
return bridged
}
func getBridgedNSSet_ValueTypesCustomBridged(
numElements: Int = 3
) -> NSSet {
expectTrue(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self))
var s = Set<TestBridgedKeyTy>()
for i in 1..<(numElements + 1) {
s.insert(TestBridgedKeyTy(i * 1000 + i * 10))
}
let bridged = convertSetToNSSet(s)
expectTrue(isNativeNSSet(bridged))
return bridged
}
func getRoundtripBridgedNSSet() -> NSSet {
let items = NSMutableArray()
items.add(TestObjCKeyTy(1010))
items.add(TestObjCKeyTy(2020))
items.add(TestObjCKeyTy(3030))
let nss = NSSet(array: items as [AnyObject])
let s: Set<NSObject> = convertNSSetToSet(nss)
let bridgedBack = convertSetToNSSet(s)
expectTrue(isCocoaNSSet(bridgedBack))
// FIXME: this should be true.
//expectTrue(unsafeBitCast(nsd, to: Int.self) == unsafeBitCast(bridgedBack, to: Int.self))
return bridgedBack
}
func getBridgedNSSet_MemberTypesCustomBridged() -> NSSet {
expectFalse(_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self))
var s = Set<TestBridgedKeyTy>()
s.insert(TestBridgedKeyTy(1010))
s.insert(TestBridgedKeyTy(2020))
s.insert(TestBridgedKeyTy(3030))
let bridged = convertSetToNSSet(s)
expectTrue(isNativeNSSet(bridged))
return bridged
}
#endif // _runtime(_ObjC)
SetTestSuite.test("AssociatedTypes") {
typealias Collection = Set<MinimalHashableValue>
expectCollectionAssociatedTypes(
collectionType: Collection.self,
iteratorType: SetIterator<MinimalHashableValue>.self,
subSequenceType: Slice<Collection>.self,
indexType: SetIndex<MinimalHashableValue>.self,
indexDistanceType: Int.self,
indicesType: DefaultIndices<Collection>.self)
}
SetTestSuite.test("sizeof") {
var s = Set(["Hello", "world"])
#if arch(i386) || arch(arm)
expectEqual(4, MemoryLayout.size(ofValue: s))
#else
expectEqual(8, MemoryLayout.size(ofValue: s))
#endif
}
SetTestSuite.test("COW.Smoke") {
var s1 = Set<TestKeyTy>(minimumCapacity: 10)
for i in [1010, 2020, 3030]{ s1.insert(TestKeyTy(i)) }
var identity1 = s1._rawIdentifier()
var s2 = s1
_fixLifetime(s2)
expectEqual(identity1, s2._rawIdentifier())
s2.insert(TestKeyTy(4040))
expectNotEqual(identity1, s2._rawIdentifier())
s2.insert(TestKeyTy(5050))
expectEqual(identity1, s1._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
SetTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
s.insert(4040)
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
s.insert(TestKeyTy(4040))
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
let empty = startIndex == s.endIndex
expectNotEqual(empty, (s.startIndex < s.endIndex))
expectTrue(s.startIndex <= s.endIndex)
expectEqual(empty, (s.startIndex >= s.endIndex))
expectFalse(s.startIndex > s.endIndex)
expectEqual(identity1, s._rawIdentifier())
expectNotEqual(0, s[startIndex])
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
var startIndex = s.startIndex
let empty = startIndex == s.endIndex
expectNotEqual(empty, (s.startIndex < s.endIndex))
expectTrue(s.startIndex <= s.endIndex)
expectEqual(empty, (s.startIndex >= s.endIndex))
expectFalse(s.startIndex > s.endIndex)
expectEqual(identity1, s._rawIdentifier())
expectNotEqual(TestKeyTy(0), s[startIndex])
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.ContainsDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
expectTrue(s.contains(1010))
expectEqual(identity1, s._rawIdentifier())
do {
var s2: Set<MinimalHashableValue> = []
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashValueWasCalled = 0
expectFalse(s2.contains(MinimalHashableValue(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Slow.ContainsDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
expectTrue(s.contains(TestKeyTy(1010)))
expectEqual(identity1, s._rawIdentifier())
// Insert a new key-value pair.
s.insert(TestKeyTy(4040))
expectEqual(identity1, s._rawIdentifier())
expectEqual(4, s.count)
expectTrue(s.contains(TestKeyTy(1010)))
expectTrue(s.contains(TestKeyTy(2020)))
expectTrue(s.contains(TestKeyTy(3030)))
expectTrue(s.contains(TestKeyTy(4040)))
// Delete an existing key.
s.remove(TestKeyTy(1010))
expectEqual(identity1, s._rawIdentifier())
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(2020)))
expectTrue(s.contains(TestKeyTy(3030)))
expectTrue(s.contains(TestKeyTy(4040)))
// Try to delete a key that does not exist.
s.remove(TestKeyTy(777))
expectEqual(identity1, s._rawIdentifier())
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(2020)))
expectTrue(s.contains(TestKeyTy(3030)))
expectTrue(s.contains(TestKeyTy(4040)))
do {
var s2: Set<MinimalHashableClass> = []
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashValueWasCalled = 0
expectFalse(s2.contains(MinimalHashableClass(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Fast.InsertDoesNotReallocate") {
var s1 = getCOWFastSet()
let identity1 = s1._rawIdentifier()
let count1 = s1.count
// Inserting a redundant element should not create new storage
s1.insert(2020)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(count1, s1.count)
s1.insert(4040)
s1.insert(5050)
s1.insert(6060)
expectEqual(count1 + 3, s1.count)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("COW.Slow.InsertDoesNotReallocate") {
do {
var s1 = getCOWSlowSet()
let identity1 = s1._rawIdentifier()
let count1 = s1.count
// Inserting a redundant element should not create new storage
s1.insert(TestKeyTy(2020))
expectEqual(identity1, s1._rawIdentifier())
expectEqual(count1, s1.count)
s1.insert(TestKeyTy(4040))
s1.insert(TestKeyTy(5050))
s1.insert(TestKeyTy(6060))
expectEqual(count1 + 3, s1.count)
expectEqual(identity1, s1._rawIdentifier())
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
s2.insert(TestKeyTy(2040))
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectTrue(s1.contains(TestKeyTy(2020)))
expectTrue(s1.contains(TestKeyTy(3030)))
expectFalse(s1.contains(TestKeyTy(2040)))
expectEqual(4, s2.count)
expectTrue(s2.contains(TestKeyTy(1010)))
expectTrue(s2.contains(TestKeyTy(2020)))
expectTrue(s2.contains(TestKeyTy(3030)))
expectTrue(s2.contains(TestKeyTy(2040)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
// Replace a redundant element.
s2.update(with: TestKeyTy(2020))
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectTrue(s1.contains(TestKeyTy(2020)))
expectTrue(s1.contains(TestKeyTy(3030)))
expectEqual(3, s2.count)
expectTrue(s2.contains(TestKeyTy(1010)))
expectTrue(s2.contains(TestKeyTy(2020)))
expectTrue(s2.contains(TestKeyTy(3030)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Fast.IndexForMemberDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
// Find an existing key.
do {
var foundIndex1 = s.index(of: 1010)!
expectEqual(identity1, s._rawIdentifier())
var foundIndex2 = s.index(of: 1010)!
expectEqual(foundIndex1, foundIndex2)
expectEqual(1010, s[foundIndex1])
expectEqual(identity1, s._rawIdentifier())
}
// Try to find a key that is not present.
do {
var foundIndex1 = s.index(of: 1111)
expectNil(foundIndex1)
expectEqual(identity1, s._rawIdentifier())
}
do {
var s2: Set<MinimalHashableValue> = []
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashValueWasCalled = 0
expectNil(s2.index(of: MinimalHashableValue(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Slow.IndexForMemberDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
// Find an existing key.
do {
var foundIndex1 = s.index(of: TestKeyTy(1010))!
expectEqual(identity1, s._rawIdentifier())
var foundIndex2 = s.index(of: TestKeyTy(1010))!
expectEqual(foundIndex1, foundIndex2)
expectEqual(TestKeyTy(1010), s[foundIndex1])
expectEqual(identity1, s._rawIdentifier())
}
// Try to find a key that is not present.
do {
var foundIndex1 = s.index(of: TestKeyTy(1111))
expectNil(foundIndex1)
expectEqual(identity1, s._rawIdentifier())
}
do {
var s2: Set<MinimalHashableClass> = []
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashValueWasCalled = 0
expectNil(s2.index(of: MinimalHashableClass(42)))
// If the set is empty, we shouldn't be computing the hash value of the
// provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashValueWasCalled)
}
}
SetTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") {
do {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
let foundIndex1 = s.index(of: 1010)!
expectEqual(identity1, s._rawIdentifier())
expectEqual(1010, s[foundIndex1])
let removed = s.remove(at: foundIndex1)
expectEqual(1010, removed)
expectEqual(identity1, s._rawIdentifier())
expectNil(s.index(of: 1010))
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
var foundIndex1 = s2.index(of: 1010)!
expectEqual(1010, s2[foundIndex1])
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
let removed = s2.remove(at: foundIndex1)
expectEqual(1010, removed)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectNil(s2.index(of: 1010))
}
}
SetTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") {
do {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
let foundIndex1 = s.index(of: TestKeyTy(1010))!
expectEqual(identity1, s._rawIdentifier())
expectEqual(TestKeyTy(1010), s[foundIndex1])
let removed = s.remove(at: foundIndex1)
expectEqual(TestKeyTy(1010), removed)
expectEqual(identity1, s._rawIdentifier())
expectNil(s.index(of: TestKeyTy(1010)))
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
var foundIndex1 = s2.index(of: TestKeyTy(1010))!
expectEqual(TestKeyTy(1010), s2[foundIndex1])
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
let removed = s2.remove(at: foundIndex1)
expectEqual(TestKeyTy(1010), removed)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
expectNil(s2.index(of: TestKeyTy(1010)))
}
}
SetTestSuite.test("COW.Fast.RemoveDoesNotReallocate") {
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var deleted = s1.remove(0)
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
deleted = s1.remove(1010)
expectOptionalEqual(1010, deleted)
expectEqual(identity1, s1._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
var deleted = s2.remove(0)
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
deleted = s2.remove(1010)
expectOptionalEqual(1010, deleted)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Slow.RemoveDoesNotReallocate") {
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var deleted = s1.remove(TestKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
deleted = s1.remove(TestKeyTy(1010))
expectOptionalEqual(TestKeyTy(1010), deleted)
expectEqual(identity1, s1._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
var deleted = s2.remove(TestKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
deleted = s2.remove(TestKeyTy(1010))
expectOptionalEqual(TestKeyTy(1010), deleted)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s2._rawIdentifier())
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Fast.UnionInPlaceSmallSetDoesNotReallocate") {
var s1 = getCOWFastSet()
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
// Adding the empty set should obviously not allocate
s1.formUnion(Set<Int>())
expectEqual(identity1, s1._rawIdentifier())
// adding a small set shouldn't cause a reallocation
s1.formUnion(s2)
expectEqual(s1, s3)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") {
do {
var s = getCOWFastSet()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(1010))
s.removeAll()
// We cannot expectTrue that identity changed, since the new buffer of
// smaller size can be allocated at the same address as the old one.
var identity1 = s._rawIdentifier()
expectTrue(s._variantBuffer.asNative.capacity < originalCapacity)
expectEqual(0, s.count)
expectFalse(s.contains(1010))
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
expectFalse(s.contains(1010))
}
do {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(1010))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(1010))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(1010))
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
expectEqual(0, s2.count)
expectFalse(s2.contains(1010))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
do {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
let originalCapacity = s1._variantBuffer.asNative.capacity
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(1010))
expectEqual(originalCapacity, s2._variantBuffer.asNative.capacity)
expectEqual(0, s2.count)
expectFalse(s2.contains(1010))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") {
do {
var s = getCOWSlowSet()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(1010)))
s.removeAll()
// We cannot expectTrue that identity changed, since the new buffer of
// smaller size can be allocated at the same address as the old one.
var identity1 = s._rawIdentifier()
expectTrue(s._variantBuffer.asNative.capacity < originalCapacity)
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
}
do {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
let originalCapacity = s._variantBuffer.asNative.capacity
expectEqual(3, s.count)
expectTrue(s.contains(TestKeyTy(1010)))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(originalCapacity, s._variantBuffer.asNative.capacity)
expectEqual(0, s.count)
expectFalse(s.contains(TestKeyTy(1010)))
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestKeyTy(1010)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
do {
var s1 = getCOWSlowSet()
var identity1 = s1._rawIdentifier()
let originalCapacity = s1._variantBuffer.asNative.capacity
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, identity2)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestKeyTy(1010)))
expectEqual(originalCapacity, s2._variantBuffer.asNative.capacity)
expectEqual(0, s2.count)
expectFalse(s2.contains(TestKeyTy(1010)))
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
SetTestSuite.test("COW.Fast.FirstDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
expectNotNil(s.first)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.CountDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.FirstDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
expectNotNil(s.first)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.CountDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.GenerateDoesNotReallocate") {
var s = getCOWFastSet()
var identity1 = s._rawIdentifier()
var iter = s.makeIterator()
var items: [Int] = []
while let value = iter.next() {
items += [value]
}
expectTrue(equalsUnordered(items, [ 1010, 2020, 3030 ]))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Slow.GenerateDoesNotReallocate") {
var s = getCOWSlowSet()
var identity1 = s._rawIdentifier()
var iter = s.makeIterator()
var items: [Int] = []
while let value = iter.next() {
items.append(value.value)
}
expectTrue(equalsUnordered(items, [ 1010, 2020, 3030 ]))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = getCOWFastSet()
var identity2 = s2._rawIdentifier()
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") {
var s1 = getCOWFastSet()
var identity1 = s1._rawIdentifier()
var s2 = getCOWFastSet()
var identity2 = s2._rawIdentifier()
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
//===---
// Native set tests.
//===---
SetTestSuite.test("deleteChainCollision") {
var k1 = TestKeyTy(value: 1010, hashValue: 0)
var k2 = TestKeyTy(value: 2020, hashValue: 0)
var k3 = TestKeyTy(value: 3030, hashValue: 0)
helperDeleteThree(k1, k2, k3)
}
SetTestSuite.test("deleteChainNoCollision") {
var k1 = TestKeyTy(value: 1010, hashValue: 0)
var k2 = TestKeyTy(value: 2020, hashValue: 1)
var k3 = TestKeyTy(value: 3030, hashValue: 2)
helperDeleteThree(k1, k2, k3)
}
SetTestSuite.test("deleteChainCollision2") {
var k1_0 = TestKeyTy(value: 1010, hashValue: 0)
var k2_0 = TestKeyTy(value: 2020, hashValue: 0)
var k3_2 = TestKeyTy(value: 3030, hashValue: 2)
var k4_0 = TestKeyTy(value: 4040, hashValue: 0)
var k5_2 = TestKeyTy(value: 5050, hashValue: 2)
var k6_0 = TestKeyTy(value: 6060, hashValue: 0)
var s = Set<TestKeyTy>(minimumCapacity: 10)
s.insert(k1_0) // in bucket 0
s.insert(k2_0) // in bucket 1
s.insert(k3_2) // in bucket 2
s.insert(k4_0) // in bucket 3
s.insert(k5_2) // in bucket 4
s.insert(k6_0) // in bucket 5
s.remove(k3_2)
expectTrue(s.contains(k1_0))
expectTrue(s.contains(k2_0))
expectFalse(s.contains(k3_2))
expectTrue(s.contains(k4_0))
expectTrue(s.contains(k5_2))
expectTrue(s.contains(k6_0))
}
SetTestSuite.test("deleteChainCollisionRandomized") {
let timeNow = CUnsignedInt(time(nil))
print("time is \(timeNow)")
srandom(timeNow)
func check(_ s: Set<TestKeyTy>) {
var keys = Array(s)
for i in 0..<keys.count {
for j in 0..<i {
expectNotEqual(keys[i], keys[j])
}
}
for k in keys {
expectTrue(s.contains(k))
}
}
var collisionChainsChoices = Array(1...8)
var chainOverlapChoices = Array(0...5)
var collisionChains = pickRandom(collisionChainsChoices)
var chainOverlap = pickRandom(chainOverlapChoices)
print("chose parameters: collisionChains=\(collisionChains) chainLength=\(chainOverlap)")
let chainLength = 7
var knownKeys: [TestKeyTy] = []
func getKey(_ value: Int) -> TestKeyTy {
for k in knownKeys {
if k.value == value {
return k
}
}
let hashValue = uniformRandom(chainLength - chainOverlap) * collisionChains
let k = TestKeyTy(value: value, hashValue: hashValue)
knownKeys += [k]
return k
}
var s = Set<TestKeyTy>(minimumCapacity: 30)
for i in 1..<300 {
let key = getKey(uniformRandom(collisionChains * chainLength))
if uniformRandom(chainLength * 2) == 0 {
s.remove(key)
} else {
s.insert(TestKeyTy(key.value))
}
check(s)
}
}
#if _runtime(_ObjC)
@objc
class CustomImmutableNSSet : NSSet {
init(_privateInit: ()) {
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(objects: UnsafePointer<AnyObject>?, count: Int) {
expectUnreachable()
super.init(objects: objects, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by CustomImmutableNSSet")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> Any {
CustomImmutableNSSet.timesCopyWithZoneWasCalled += 1
return self
}
override func member(_ object: Any) -> Any? {
CustomImmutableNSSet.timesMemberWasCalled += 1
return getAsNSSet([ 1010, 1020, 1030 ]).member(object)
}
override func objectEnumerator() -> NSEnumerator {
CustomImmutableNSSet.timesObjectEnumeratorWasCalled += 1
return getAsNSSet([ 1010, 1020, 1030 ]).objectEnumerator()
}
override var count: Int {
CustomImmutableNSSet.timesCountWasCalled += 1
return 3
}
static var timesCopyWithZoneWasCalled = 0
static var timesMemberWasCalled = 0
static var timesObjectEnumeratorWasCalled = 0
static var timesCountWasCalled = 0
}
SetTestSuite.test("BridgedFromObjC.Verbatim.SetIsCopied") {
var (s, nss) = getBridgedVerbatimSetAndNSMutableSet()
expectTrue(isCocoaSet(s))
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectNotNil(nss.member(TestObjCKeyTy(1010)))
nss.remove(TestObjCKeyTy(1010))
expectNil(nss.member(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SetIsCopied") {
var (s, nss) = getBridgedNonverbatimSetAndNSMutableSet()
expectTrue(isNativeSet(s))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectNotNil(nss.member(TestBridgedKeyTy(1010) as AnyObject))
nss.remove(TestBridgedKeyTy(1010) as AnyObject)
expectNil(nss.member(TestBridgedKeyTy(1010) as AnyObject))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Verbatim.NSSetIsRetained") {
var nss: NSSet = NSSet(set: getAsNSSet([ 1010, 1020, 1030 ]))
var s: Set<NSObject> = convertNSSetToSet(nss)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.NSSetIsCopied") {
var nss: NSSet = NSSet(set: getAsNSSet([ 1010, 1020, 1030 ]))
var s: Set<TestBridgedKeyTy> = convertNSSetToSet(nss)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectNotEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.ImmutableSetIsRetained") {
var nss: NSSet = CustomImmutableNSSet(_privateInit: ())
CustomImmutableNSSet.timesCopyWithZoneWasCalled = 0
CustomImmutableNSSet.timesMemberWasCalled = 0
CustomImmutableNSSet.timesObjectEnumeratorWasCalled = 0
CustomImmutableNSSet.timesCountWasCalled = 0
var s: Set<NSObject> = convertNSSetToSet(nss)
expectEqual(1, CustomImmutableNSSet.timesCopyWithZoneWasCalled)
expectEqual(0, CustomImmutableNSSet.timesMemberWasCalled)
expectEqual(0, CustomImmutableNSSet.timesObjectEnumeratorWasCalled)
expectEqual(0, CustomImmutableNSSet.timesCountWasCalled)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableSetIsCopied") {
var nss: NSSet = CustomImmutableNSSet(_privateInit: ())
CustomImmutableNSSet.timesCopyWithZoneWasCalled = 0
CustomImmutableNSSet.timesMemberWasCalled = 0
CustomImmutableNSSet.timesObjectEnumeratorWasCalled = 0
CustomImmutableNSSet.timesCountWasCalled = 0
var s: Set<TestBridgedKeyTy> = convertNSSetToSet(nss)
expectEqual(0, CustomImmutableNSSet.timesCopyWithZoneWasCalled)
expectEqual(0, CustomImmutableNSSet.timesMemberWasCalled)
expectEqual(1, CustomImmutableNSSet.timesObjectEnumeratorWasCalled)
expectNotEqual(0, CustomImmutableNSSet.timesCountWasCalled)
var bridgedBack: NSSet = convertSetToNSSet(s)
expectNotEqual(
unsafeBitCast(nss, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nss)
_fixLifetime(s)
_fixLifetime(bridgedBack)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.IndexForMember") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
// Find an existing key.
var member = s[s.index(of: TestObjCKeyTy(1010))!]
expectEqual(TestObjCKeyTy(1010), member)
member = s[s.index(of: TestObjCKeyTy(2020))!]
expectEqual(TestObjCKeyTy(2020), member)
member = s[s.index(of: TestObjCKeyTy(3030))!]
expectEqual(TestObjCKeyTy(3030), member)
// Try to find a key that does not exist.
expectNil(s.index(of: TestObjCKeyTy(4040)))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForMember") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
do {
var member = s[s.index(of: TestBridgedKeyTy(1010))!]
expectEqual(TestBridgedKeyTy(1010), member)
member = s[s.index(of: TestBridgedKeyTy(2020))!]
expectEqual(TestBridgedKeyTy(2020), member)
member = s[s.index(of: TestBridgedKeyTy(3030))!]
expectEqual(TestBridgedKeyTy(3030), member)
}
expectNil(s.index(of: TestBridgedKeyTy(4040)))
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Insert") {
do {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectFalse(s.contains(TestObjCKeyTy(2040)))
s.insert(TestObjCKeyTy(2040))
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectTrue(s.contains(TestObjCKeyTy(2040)))
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Insert") {
do {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectFalse(s.contains(TestBridgedKeyTy(2040)))
s.insert(TestObjCKeyTy(2040) as TestBridgedKeyTy)
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(2040)))
}
}
SetTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
var members = [Int]()
for i in s.indices {
var foundMember: AnyObject = s[i]
let member = foundMember as! TestObjCKeyTy
members.append(member.value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectTrue(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectFalse(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
var members = [Int]()
for i in s.indices {
var foundMember: AnyObject = s[i] as NSObject
let member = foundMember as! TestObjCKeyTy
members.append(member.value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") {
var s = getBridgedVerbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectEqual(startIndex, endIndex)
expectFalse(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectTrue(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") {
var s = getBridgedNonverbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var startIndex = s.startIndex
var endIndex = s.endIndex
expectEqual(startIndex, endIndex)
expectFalse(startIndex < endIndex)
expectTrue(startIndex <= endIndex)
expectTrue(startIndex >= endIndex)
expectFalse(startIndex > endIndex)
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Contains") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectEqual(identity1, s._rawIdentifier())
// Inserting an item should now create storage unique from the bridged set.
s.insert(TestObjCKeyTy(4040))
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Verify items are still present.
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectTrue(s.contains(TestObjCKeyTy(4040)))
// Insert a redundant item to the set.
// A copy should *not* occur here.
s.insert(TestObjCKeyTy(1010))
expectEqual(identity2, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Again, verify items are still present.
expectTrue(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectTrue(s.contains(TestObjCKeyTy(4040)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Contains") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectEqual(identity1, s._rawIdentifier())
// Inserting an item should now create storage unique from the bridged set.
s.insert(TestBridgedKeyTy(4040))
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Verify items are still present.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
// Insert a redundant item to the set.
// A copy should *not* occur here.
s.insert(TestBridgedKeyTy(1010))
expectEqual(identity2, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Again, verify items are still present.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithMember") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectEqual(identity1, s._rawIdentifier())
// Insert a new member.
// This should trigger a copy.
s.insert(TestBridgedKeyTy(4040))
var identity2 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Verify all items in place.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
// Insert a redundant member.
// This should *not* trigger a copy.
s.insert(TestBridgedKeyTy(1010))
expectEqual(identity2, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(4, s.count)
// Again, verify all items in place.
expectTrue(s.contains(TestBridgedKeyTy(1010)))
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
expectTrue(s.contains(TestBridgedKeyTy(4040)))
}
SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") {
var s = getBridgedVerbatimSet()
let identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
let foundIndex1 = s.index(of: TestObjCKeyTy(1010))!
expectEqual(TestObjCKeyTy(1010), s[foundIndex1])
expectEqual(identity1, s._rawIdentifier())
let removedElement = s.remove(at: foundIndex1)
expectNotEqual(identity1, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(2, s.count)
expectEqual(TestObjCKeyTy(1010), removedElement)
expectNil(s.index(of: TestObjCKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") {
var s = getBridgedNonverbatimSet()
let identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
let foundIndex1 = s.index(of: TestBridgedKeyTy(1010))!
expectEqual(1010, s[foundIndex1].value)
expectEqual(identity1, s._rawIdentifier())
let removedElement = s.remove(at: foundIndex1)
expectEqual(identity1, s._rawIdentifier())
expectTrue(isNativeSet(s))
expectEqual(1010, removedElement.value)
expectEqual(2, s.count)
expectNil(s.index(of: TestBridgedKeyTy(1010)))
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Remove") {
do {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var deleted: AnyObject? = s.remove(TestObjCKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s._rawIdentifier())
expectTrue(isCocoaSet(s))
deleted = s.remove(TestObjCKeyTy(1010))
expectEqual(1010, deleted!.value)
var identity2 = s._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(2, s.count)
expectFalse(s.contains(TestObjCKeyTy(1010)))
expectTrue(s.contains(TestObjCKeyTy(2020)))
expectTrue(s.contains(TestObjCKeyTy(3030)))
expectEqual(identity2, s._rawIdentifier())
}
do {
var s1 = getBridgedVerbatimSet()
var identity1 = s1._rawIdentifier()
var s2 = s1
expectTrue(isCocoaSet(s1))
expectTrue(isCocoaSet(s2))
var deleted: AnyObject? = s2.remove(TestObjCKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
expectTrue(isCocoaSet(s1))
expectTrue(isCocoaSet(s2))
deleted = s2.remove(TestObjCKeyTy(1010))
expectEqual(1010, deleted!.value)
var identity2 = s2._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isCocoaSet(s1))
expectTrue(isNativeSet(s2))
expectEqual(2, s2.count)
expectTrue(s1.contains(TestObjCKeyTy(1010)))
expectTrue(s1.contains(TestObjCKeyTy(2020)))
expectTrue(s1.contains(TestObjCKeyTy(3030)))
expectEqual(identity1, s1._rawIdentifier())
expectFalse(s2.contains(TestObjCKeyTy(1010)))
expectTrue(s2.contains(TestObjCKeyTy(2020)))
expectTrue(s2.contains(TestObjCKeyTy(3030)))
expectEqual(identity2, s2._rawIdentifier())
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Remove") {
do {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
// Trying to remove something not in the set should
// leave it completely unchanged.
var deleted = s.remove(TestBridgedKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s._rawIdentifier())
expectTrue(isNativeSet(s))
// Now remove an item that is in the set. This should
// not create a new set altogether, however.
deleted = s.remove(TestBridgedKeyTy(1010))
expectEqual(1010, deleted!.value)
var identity2 = s._rawIdentifier()
expectEqual(identity1, identity2)
expectTrue(isNativeSet(s))
expectEqual(2, s.count)
// Double-check - the removed member should not be found.
expectFalse(s.contains(TestBridgedKeyTy(1010)))
// ... but others not removed should be found.
expectTrue(s.contains(TestBridgedKeyTy(2020)))
expectTrue(s.contains(TestBridgedKeyTy(3030)))
// Triple-check - we should still be working with the same object.
expectEqual(identity2, s._rawIdentifier())
}
do {
var s1 = getBridgedNonverbatimSet()
let identity1 = s1._rawIdentifier()
var s2 = s1
expectTrue(isNativeSet(s1))
expectTrue(isNativeSet(s2))
var deleted = s2.remove(TestBridgedKeyTy(0))
expectNil(deleted)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
expectTrue(isNativeSet(s1))
expectTrue(isNativeSet(s2))
deleted = s2.remove(TestBridgedKeyTy(1010))
expectEqual(1010, deleted!.value)
let identity2 = s2._rawIdentifier()
expectNotEqual(identity1, identity2)
expectTrue(isNativeSet(s1))
expectTrue(isNativeSet(s2))
expectEqual(2, s2.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
expectTrue(s1.contains(TestBridgedKeyTy(2020)))
expectTrue(s1.contains(TestBridgedKeyTy(3030)))
expectEqual(identity1, s1._rawIdentifier())
expectFalse(s2.contains(TestBridgedKeyTy(1010)))
expectTrue(s2.contains(TestBridgedKeyTy(2020)))
expectTrue(s2.contains(TestBridgedKeyTy(3030)))
expectEqual(identity2, s2._rawIdentifier())
}
}
SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") {
do {
var s = getBridgedVerbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectEqual(0, s.count)
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
}
do {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject))
s.removeAll()
expectEqual(0, s.count)
expectFalse(s.contains(TestBridgedKeyTy(1010) as NSObject))
}
do {
var s1 = getBridgedVerbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isCocoaSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestBridgedKeyTy(1010) as NSObject))
}
do {
var s1 = getBridgedVerbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isCocoaSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject))
expectEqual(0 , s2.count)
expectFalse(s2.contains(TestBridgedKeyTy(1010) as NSObject))
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") {
do {
var s = getBridgedNonverbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(0, s.count)
s.removeAll()
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
}
do {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010)))
s.removeAll()
expectEqual(0, s.count)
expectFalse(s.contains(TestBridgedKeyTy(1010)))
}
do {
var s1 = getBridgedNonverbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestBridgedKeyTy(1010)))
}
do {
var s1 = getBridgedNonverbatimSet()
var identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
expectEqual(3, s1.count)
expectTrue(s1.contains(TestBridgedKeyTy(1010)))
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity2, identity1)
expectEqual(3, s1.count)
expectTrue(s1.contains(TestObjCKeyTy(1010) as TestBridgedKeyTy))
expectEqual(0, s2.count)
expectFalse(s2.contains(TestObjCKeyTy(1010) as TestBridgedKeyTy))
}
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Count") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Count") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
expectEqual(3, s.count)
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Generate") {
var s = getBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var iter = s.makeIterator()
var members: [Int] = []
while let member = iter.next() {
members.append((member as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") {
var s = getBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var iter = s.makeIterator()
var members: [Int] = []
while let member = iter.next() {
members.append(member.value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") {
var s = getBridgedVerbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var iter = s.makeIterator()
expectNil(iter.next())
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") {
var s = getBridgedNonverbatimSet([])
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var iter = s.makeIterator()
expectNil(iter.next())
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") {
var s = getHugeBridgedVerbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isCocoaSet(s))
var iter = s.makeIterator()
var members = [Int]()
while let member = iter.next() {
members.append((member as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered(members, hugeNumberArray))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") {
var s = getHugeBridgedNonverbatimSet()
var identity1 = s._rawIdentifier()
expectTrue(isNativeSet(s))
var iter = s.makeIterator()
var members = [Int]()
while let member = iter.next() as AnyObject? {
members.append((member as! TestBridgedKeyTy).value)
}
expectTrue(equalsUnordered(members, hugeNumberArray))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
expectNil(iter.next())
expectNil(iter.next())
expectNil(iter.next())
expectEqual(identity1, s._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") {
var s1 = getBridgedVerbatimSet([])
expectTrue(isCocoaSet(s1))
var s2 = getBridgedVerbatimSet([])
expectTrue(isCocoaSet(s2))
expectEqual(s1, s2)
s2.insert(TestObjCKeyTy(4040))
expectTrue(isNativeSet(s2))
expectNotEqual(s1, s2)
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") {
var s1 = getBridgedNonverbatimSet([])
var identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
var s2 = getBridgedNonverbatimSet([])
var identity2 = s2._rawIdentifier()
expectTrue(isNativeSet(s2))
expectNotEqual(identity1, identity2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
s2.insert(TestObjCKeyTy(4040) as TestBridgedKeyTy)
expectTrue(isNativeSet(s2))
expectEqual(identity2, s2._rawIdentifier())
expectNotEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") {
var s1 = getBridgedVerbatimSet()
let identity1 = s1._rawIdentifier()
expectTrue(isCocoaSet(s1))
var s2 = getBridgedVerbatimSet()
let identity2 = s2._rawIdentifier()
expectTrue(isCocoaSet(s2))
expectNotEqual(identity1, identity2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Small") {
var s1 = getBridgedNonverbatimSet()
let identity1 = s1._rawIdentifier()
expectTrue(isNativeSet(s1))
var s2 = getBridgedNonverbatimSet()
let identity2 = s2._rawIdentifier()
expectTrue(isNativeSet(s2))
expectNotEqual(identity1, identity2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
SetTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfSets") {
var nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSSet([1 + i, 2 + i, 3 + i]))
}
var a = nsa as [AnyObject] as! [Set<NSObject>]
for i in 0..<3 {
var s = a[i]
var iter = s.makeIterator()
var items: [Int] = []
while let value = iter.next() {
let v = (value as! TestObjCKeyTy).value
items.append(v)
}
var expectedItems = [1 + i, 2 + i, 3 + i]
expectTrue(equalsUnordered(items, expectedItems))
}
}
SetTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfSets") {
var nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSSet([1 + i, 2 + i, 3 + i]))
}
var a = nsa as [AnyObject] as! [Set<TestBridgedKeyTy>]
for i in 0..<3 {
var d = a[i]
var iter = d.makeIterator()
var items: [Int] = []
while let value = iter.next() {
items.append(value.value)
}
var expectedItems = [1 + i, 2 + i, 3 + i]
expectTrue(equalsUnordered(items, expectedItems))
}
}
//===---
// Dictionary -> NSDictionary bridging tests.
//
// Value is bridged verbatim.
//===---
SetTestSuite.test("BridgedToObjC.Verbatim.Count") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
expectEqual(3, s.count)
}
SetTestSuite.test("BridgedToObjC.Verbatim.Contains") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
var v: AnyObject? = s.member(TestObjCKeyTy(1010)).map { $0 as AnyObject }
expectEqual(1010, (v as! TestObjCKeyTy).value)
let idValue10 = unsafeBitCast(v, to: UInt.self)
v = s.member(TestObjCKeyTy(2020)).map { $0 as AnyObject }
expectEqual(2020, (v as! TestObjCKeyTy).value)
let idValue20 = unsafeBitCast(v, to: UInt.self)
v = s.member(TestObjCKeyTy(3030)).map { $0 as AnyObject }
expectEqual(3030, (v as! TestObjCKeyTy).value)
let idValue30 = unsafeBitCast(v, to: UInt.self)
expectNil(s.member(TestObjCKeyTy(4040)))
// NSSet can store mixed key types. Swift's Set is typed, but when bridged
// to NSSet, it should behave like one, and allow queries for mismatched key
// types.
expectNil(s.member(TestObjCInvalidKeyTy()))
for i in 0..<3 {
expectEqual(idValue10,
unsafeBitCast(s.member(TestObjCKeyTy(1010)).map { $0 as AnyObject }, to: UInt.self))
expectEqual(idValue20,
unsafeBitCast(s.member(TestObjCKeyTy(2020)).map { $0 as AnyObject }, to: UInt.self))
expectEqual(idValue30,
unsafeBitCast(s.member(TestObjCKeyTy(3030)).map { $0 as AnyObject }, to: UInt.self))
}
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgingRoundtrip") {
let s = getRoundtripBridgedNSSet()
let enumerator = s.objectEnumerator()
var items: [Int] = []
while let value = enumerator.nextObject() {
let v = (value as! TestObjCKeyTy).value
items.append(v)
}
expectTrue(equalsUnordered([1010, 2020, 3030], items))
}
SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration_Empty") {
let s = getBridgedEmptyNSSet()
checkSetFastEnumerationFromSwift(
[], s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
checkSetFastEnumerationFromObjC(
[], s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.ObjectEnumerator.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSet_MemberTypesCustomBridged()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Custom.ObjectEnumerator.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSet_MemberTypesCustomBridged()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s.objectEnumerator() },
{ ($0 as! TestObjCKeyTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") {
let s = getBridgedEmptyNSSet()
checkSetFastEnumerationFromSwift(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
checkSetFastEnumerationFromObjC(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") {
let s = getBridgedNSSet_ValueTypesCustomBridged()
checkSetFastEnumerationFromSwift(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") {
let s = getBridgedNSSet_ValueTypesCustomBridged()
checkSetFastEnumerationFromObjC(
[ 1010, 2020, 3030 ],
s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") {
let s = getBridgedNSSet_ValueTypesCustomBridged(
numElements: 0)
checkSetFastEnumerationFromSwift(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
checkSetFastEnumerationFromObjC(
[], s, { s },
{ ($0 as! TestObjCKeyTy).value })
}
SetTestSuite.test("BridgedToObjC.Count") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
expectEqual(3, s.count)
}
SetTestSuite.test("BridgedToObjC.ObjectEnumerator.NextObject") {
let s = getBridgedNSSetOfRefTypesBridgedVerbatim()
let enumerator = s.objectEnumerator()
var members = [Int]()
while let nextObject = enumerator.nextObject() {
members.append((nextObject as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered([1010, 2020, 3030], members))
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("BridgedToObjC.ObjectEnumerator.NextObject.Empty") {
let s = getBridgedEmptyNSSet()
let enumerator = s.objectEnumerator()
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
expectNil(enumerator.nextObject())
}
//
// Set -> NSSet Bridging
//
SetTestSuite.test("BridgedToObjC.MemberTypesCustomBridged") {
let s = getBridgedNSSet_MemberTypesCustomBridged()
let enumerator = s.objectEnumerator()
var members = [Int]()
while let nextObject = enumerator.nextObject() {
members.append((nextObject as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered([1010, 2020, 3030], members))
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
//
// NSSet -> Set -> NSSet Round trip bridging
//
SetTestSuite.test("BridgingRoundTrip") {
let s = getRoundtripBridgedNSSet()
let enumerator = s.objectEnumerator()
var members = [Int]()
while let nextObject = enumerator.nextObject() {
members.append((nextObject as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered([1010, 2020, 3030] ,members))
}
//
// NSSet -> Set implicit conversion
//
SetTestSuite.test("NSSetToSetConversion") {
let nsArray = NSMutableArray()
for i in [1010, 2020, 3030] {
nsArray.add(TestObjCKeyTy(i))
}
let nss = NSSet(array: nsArray as [AnyObject])
let s = nss as Set
var members = [Int]()
for member: AnyObject in s {
members.append((member as! TestObjCKeyTy).value)
}
expectTrue(equalsUnordered(members, [1010, 2020, 3030]))
}
SetTestSuite.test("SetToNSSetConversion") {
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
let nss: NSSet = s as NSSet
expectTrue(equalsUnordered(Array(s).map { $0.value }, [1010, 2020, 3030]))
}
//
// Set Casts
//
SetTestSuite.test("SetUpcastEntryPoint") {
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
var sAsAnyObject: Set<NSObject> = _setUpCast(s)
expectEqual(3, sAsAnyObject.count)
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(1010)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(2020)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(3030)))
}
SetTestSuite.test("SetUpcast") {
var s = Set<TestObjCKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
var sAsAnyObject: Set<NSObject> = s
expectEqual(3, sAsAnyObject.count)
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(1010)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(2020)))
expectTrue(sAsAnyObject.contains(TestObjCKeyTy(3030)))
}
SetTestSuite.test("SetUpcastBridgedEntryPoint") {
var s = Set<TestBridgedKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestBridgedKeyTy(i))
}
do {
var s: Set<NSObject> = _setBridgeToObjectiveC(s)
expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(2020) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(3030) as NSObject))
}
do {
var s: Set<TestObjCKeyTy> = _setBridgeToObjectiveC(s)
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(2020) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(3030) as TestObjCKeyTy))
}
}
SetTestSuite.test("SetUpcastBridged") {
var s = Set<TestBridgedKeyTy>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestBridgedKeyTy(i))
}
do {
var s = s as! Set<NSObject>
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(2020) as NSObject))
expectTrue(s.contains(TestBridgedKeyTy(3030) as NSObject))
}
do {
var s = s as Set<TestObjCKeyTy>
expectEqual(3, s.count)
expectTrue(s.contains(TestBridgedKeyTy(1010) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(2020) as TestObjCKeyTy))
expectTrue(s.contains(TestBridgedKeyTy(3030) as TestObjCKeyTy))
}
}
//
// Set downcasts
//
SetTestSuite.test("SetDowncastEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCC: Set<TestObjCKeyTy> = _setDownCast(s)
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("SetDowncast") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCC = s as! Set<TestObjCKeyTy>
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("SetDowncastConditionalEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sCC = _setDownCastConditional(s) as Set<TestObjCKeyTy>? {
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcast
s.insert("Hello, world" as NSString)
if let sCC = _setDownCastConditional(s) as Set<TestObjCKeyTy>? {
expectTrue(false)
}
}
SetTestSuite.test("SetDowncastConditional") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sCC = s as? Set<TestObjCKeyTy> {
expectEqual(3, sCC.count)
expectTrue(sCC.contains(TestObjCKeyTy(1010)))
expectTrue(sCC.contains(TestObjCKeyTy(2020)))
expectTrue(sCC.contains(TestObjCKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcast
s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString)
if let sCC = s as? Set<TestObjCKeyTy> {
expectTrue(false)
}
}
SetTestSuite.test("SetBridgeFromObjectiveCEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCV: Set<TestBridgedKeyTy> = _setBridgeFromObjectiveC(s)
do {
expectEqual(3, sCV.count)
expectTrue(sCV.contains(TestBridgedKeyTy(1010)))
expectTrue(sCV.contains(TestBridgedKeyTy(2020)))
expectTrue(sCV.contains(TestBridgedKeyTy(3030)))
}
}
SetTestSuite.test("SetBridgeFromObjectiveC") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
let sCV = s as! Set<TestObjCKeyTy>
do {
expectEqual(3, sCV.count)
expectTrue(sCV.contains(TestObjCKeyTy(1010)))
expectTrue(sCV.contains(TestObjCKeyTy(2020)))
expectTrue(sCV.contains(TestObjCKeyTy(3030)))
}
// Successful downcast.
let sVC = s as! Set<TestBridgedKeyTy>
do {
expectEqual(3, sVC.count)
expectTrue(sVC.contains(TestBridgedKeyTy(1010)))
expectTrue(sVC.contains(TestBridgedKeyTy(2020)))
expectTrue(sVC.contains(TestBridgedKeyTy(3030)))
}
expectAutoreleasedKeysAndValues(unopt: (3, 0))
}
SetTestSuite.test("SetBridgeFromObjectiveCConditionalEntryPoint") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sVC = _setBridgeFromObjectiveCConditional(s) as Set<TestBridgedKeyTy>? {
expectEqual(3, sVC.count)
expectTrue(sVC.contains(TestBridgedKeyTy(1010)))
expectTrue(sVC.contains(TestBridgedKeyTy(2020)))
expectTrue(sVC.contains(TestBridgedKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcasts
s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString)
if let sVC = _setBridgeFromObjectiveCConditional(s) as Set<TestBridgedKeyTy>? {
expectTrue(false)
}
}
SetTestSuite.test("SetBridgeFromObjectiveCConditional") {
var s = Set<NSObject>(minimumCapacity: 32)
for i in [1010, 2020, 3030] {
s.insert(TestObjCKeyTy(i))
}
// Successful downcast.
if let sCV = s as? Set<TestObjCKeyTy> {
expectEqual(3, sCV.count)
expectTrue(sCV.contains(TestObjCKeyTy(1010)))
expectTrue(sCV.contains(TestObjCKeyTy(2020)))
expectTrue(sCV.contains(TestObjCKeyTy(3030)))
} else {
expectTrue(false)
}
// Successful downcast.
if let sVC = s as? Set<TestBridgedKeyTy> {
expectEqual(3, sVC.count)
expectTrue(sVC.contains(TestBridgedKeyTy(1010)))
expectTrue(sVC.contains(TestBridgedKeyTy(2020)))
expectTrue(sVC.contains(TestBridgedKeyTy(3030)))
} else {
expectTrue(false)
}
// Unsuccessful downcasts
s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString)
if let sCm = s as? Set<TestObjCKeyTy> {
expectTrue(false)
}
if let sVC = s as? Set<TestBridgedKeyTy> {
expectTrue(false)
}
if let sVm = s as? Set<TestBridgedKeyTy> {
expectTrue(false)
}
}
#endif // _runtime(_ObjC)
// Public API
SetTestSuite.test("init(Sequence:)") {
let s1 = Set([1010, 2020, 3030])
var s2 = Set<Int>()
s2.insert(1010)
s2.insert(2020)
s2.insert(3030)
expectEqual(s1, s2)
// Test the uniquing capabilities of a set
let s3 = Set([
1010, 1010, 1010, 1010, 1010, 1010,
1010, 1010, 1010, 1010, 1010, 1010,
2020, 2020, 2020, 3030, 3030, 3030
])
expectEqual(s1, s3)
}
SetTestSuite.test("init(arrayLiteral:)") {
let s1: Set<Int> = [1010, 2020, 3030, 1010, 2020, 3030]
let s2 = Set([1010, 2020, 3030])
var s3 = Set<Int>()
s3.insert(1010)
s3.insert(2020)
s3.insert(3030)
expectEqual(s1, s2)
expectEqual(s2, s3)
}
SetTestSuite.test("isSubsetOf.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(Set<Int>().isSubset(of: s1))
expectFalse(s1.isSubset(of: Set<Int>()))
expectTrue(s1.isSubset(of: s1))
expectTrue(s2.isSubset(of: s1))
}
SetTestSuite.test("⊆.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(Set<Int>().isSubset(of: s1))
expectFalse(s1 ⊆ Set<Int>())
expectTrue(s1 ⊆ s1)
expectTrue(s2 ⊆ s1)
}
SetTestSuite.test("⊈.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectFalse(Set<Int>() ⊈ s1)
expectTrue(s1 ⊈ Set<Int>())
expectFalse(s1 ⊈ s1)
expectFalse(s2 ⊈ s1)
}
SetTestSuite.test("isSubsetOf.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(Set<Int>().isSubset(of: s1))
expectFalse(s1.isSubset(of: Set<Int>()))
expectTrue(s1.isSubset(of: s1))
}
SetTestSuite.test("⊆.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(Set<Int>().isSubset(of: s1))
expectFalse(s1 ⊆ Set<Int>())
expectTrue(s1 ⊆ s1)
}
SetTestSuite.test("⊈.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectFalse(Set<Int>() ⊈ s1)
expectTrue(s1 ⊈ Set<Int>())
expectFalse(s1 ⊈ s1)
}
SetTestSuite.test("isStrictSubsetOf.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(Set<Int>().isStrictSubset(of: s1))
expectFalse(s1.isStrictSubset(of: Set<Int>()))
expectFalse(s1.isStrictSubset(of: s1))
}
SetTestSuite.test("⊂.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(Set<Int>() ⊂ s1)
expectFalse(s1 ⊂ Set<Int>())
expectFalse(s1 ⊂ s1)
}
SetTestSuite.test("⊄.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectFalse(Set<Int>() ⊄ s1)
expectTrue(s1 ⊄ Set<Int>())
expectTrue(s1 ⊄ s1)
}
SetTestSuite.test("isStrictSubsetOf.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(Set<Int>().isStrictSubset(of: s1))
expectFalse(s1.isStrictSubset(of: Set<Int>()))
expectFalse(s1.isStrictSubset(of: s1))
}
SetTestSuite.test("⊂.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(Set<Int>() ⊂ s1)
expectFalse(s1 ⊂ Set<Int>())
expectFalse(s1 ⊂ s1)
}
SetTestSuite.test("⊄.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectFalse(Set<Int>() ⊄ s1)
expectTrue(s1 ⊄ Set<Int>())
expectTrue(s1 ⊄ s1)
}
SetTestSuite.test("isSupersetOf.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(s1.isSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s2))
expectFalse(Set<Int>().isSuperset(of: s1))
}
SetTestSuite.test("⊇.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(s1 ⊇ Set<Int>())
expectFalse(Set<Int>() ⊇ s1)
expectTrue(s1 ⊇ s1)
expectTrue(s1 ⊇ s2)
expectFalse(Set<Int>() ⊇ s1)
}
SetTestSuite.test("⊉.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectFalse(s1 ⊉ Set<Int>())
expectTrue(Set<Int>() ⊉ s1)
expectFalse(s1 ⊉ s1)
expectFalse(s1 ⊉ s2)
expectTrue(Set<Int>() ⊉ s1)
}
SetTestSuite.test("isSupersetOf.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(s1.isSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s1))
expectTrue(s1.isSuperset(of: s2))
expectFalse(Set<Int>().isSuperset(of: s1))
}
SetTestSuite.test("⊇.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(s1 ⊇ Set<Int>())
expectFalse(Set<Int>() ⊇ s1)
expectTrue(s1 ⊇ s1)
expectTrue(s1 ⊇ s2)
expectFalse(Set<Int>() ⊇ s1)
}
SetTestSuite.test("⊉.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectFalse(s1 ⊉ Set<Int>())
expectTrue(Set<Int>() ⊉ s1)
expectFalse(s1 ⊉ s1)
expectFalse(s1 ⊉ s2)
expectTrue(Set<Int>() ⊉ s1)
}
SetTestSuite.test("strictSuperset.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(s1.isStrictSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isStrictSuperset(of: s1))
expectFalse(s1.isStrictSuperset(of: s1))
expectTrue(s1.isStrictSuperset(of: s2))
}
SetTestSuite.test("⊃.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectTrue(s1 ⊃ Set<Int>())
expectFalse(Set<Int>() ⊃ s1)
expectFalse(s1 ⊃ s1)
expectTrue(s1 ⊃ s2)
}
SetTestSuite.test("⊅.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
expectFalse(s1 ⊅ Set<Int>())
expectTrue(Set<Int>() ⊅ s1)
expectTrue(s1 ⊅ s1)
expectFalse(s1 ⊅ s2)
}
SetTestSuite.test("strictSuperset.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(s1.isStrictSuperset(of: Set<Int>()))
expectFalse(Set<Int>().isStrictSuperset(of: s1))
expectFalse(s1.isStrictSuperset(of: s1))
expectTrue(s1.isStrictSuperset(of: s2))
}
SetTestSuite.test("⊃.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectTrue(s1 ⊃ Set<Int>())
expectFalse(Set<Int>() ⊃ s1)
expectFalse(s1 ⊃ s1)
expectTrue(s1 ⊃ s2)
}
SetTestSuite.test("⊅.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
expectFalse(s1 ⊅ Set<Int>())
expectTrue(Set<Int>() ⊅ s1)
expectTrue(s1 ⊅ s1)
expectFalse(s1 ⊅ s2)
}
SetTestSuite.test("Equatable.Native.Native") {
let s1 = getCOWFastSet()
let s2 = getCOWFastSet([1010, 2020, 3030, 4040, 5050, 6060])
checkEquatable(true, s1, s1)
checkEquatable(false, s1, Set<Int>())
checkEquatable(true, Set<Int>(), Set<Int>())
checkEquatable(false, s1, s2)
}
#if _runtime(_ObjC)
SetTestSuite.test("Equatable.Native.BridgedVerbatim") {
let s1 = getNativeBridgedVerbatimSet()
let bvs1 = getBridgedVerbatimSet()
let bvs2 = getBridgedVerbatimSet([1010, 2020, 3030, 4040, 5050, 6060])
let bvsEmpty = getBridgedVerbatimSet([])
checkEquatable(true, s1, bvs1)
checkEquatable(false, s1, bvs2)
checkEquatable(false, s1, bvsEmpty)
}
SetTestSuite.test("Equatable.BridgedVerbatim.BridgedVerbatim") {
let bvs1 = getBridgedVerbatimSet()
let bvs2 = getBridgedVerbatimSet([1010, 2020, 3030, 4040, 5050, 6060])
let bvsEmpty = getBridgedVerbatimSet([])
checkEquatable(true, bvs1, bvs1)
checkEquatable(false, bvs1, bvs2)
checkEquatable(false, bvs1, bvsEmpty)
}
SetTestSuite.test("Equatable.BridgedNonverbatim.BridgedNonverbatim") {
let bnvs1 = getBridgedNonverbatimSet()
let bnvs2 = getBridgedNonverbatimSet([1010, 2020, 3030, 4040, 5050, 6060])
let bnvsEmpty = getBridgedNonverbatimSet([])
checkEquatable(true, bnvs1, bnvs1)
checkEquatable(false, bnvs1, bnvs2)
checkEquatable(false, bnvs1, bnvsEmpty)
checkEquatable(false, bnvs2, bnvsEmpty)
}
#endif // _runtime(_ObjC)
SetTestSuite.test("isDisjointWith.Set.Set") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
let s3 = Set([7070, 8080, 9090])
expectTrue(s1.isDisjoint(with: s3))
expectFalse(s1.isDisjoint(with: s2))
expectTrue(Set<Int>().isDisjoint(with: s1))
expectTrue(Set<Int>().isDisjoint(with: Set<Int>()))
}
SetTestSuite.test("isDisjointWith.Set.Sequence") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = AnySequence([1010, 2020, 3030])
let s3 = AnySequence([7070, 8080, 9090])
expectTrue(s1.isDisjoint(with: s3))
expectFalse(s1.isDisjoint(with: s2))
expectTrue(Set<Int>().isDisjoint(with: s1))
expectTrue(Set<Int>().isDisjoint(with: Set<Int>()))
}
SetTestSuite.test("insert") {
// These are anagrams - they should amount to the same sets.
var s1 = Set<TestKeyTy>([1010, 2020, 3030])
let fortyForty: TestKeyTy = 4040
do {
// Inserting an element that isn't present
let (inserted, currentMember) = s1.insert(fortyForty)
expectTrue(inserted)
expectTrue(currentMember === fortyForty)
}
do {
// Inserting an element that is already present
let (inserted, currentMember) = s1.insert(4040)
expectFalse(inserted)
expectTrue(currentMember === fortyForty)
}
expectEqual(4, s1.count)
expectTrue(s1.contains(1010))
expectTrue(s1.contains(2020))
expectTrue(s1.contains(3030))
expectTrue(s1.contains(4040))
}
SetTestSuite.test("replace") {
// These are anagrams - they should amount to the same sets.
var s1 = Set<TestKeyTy>([1010, 2020, 3030])
let fortyForty: TestKeyTy = 4040
do {
// Replacing an element that isn't present
let oldMember = s1.update(with: fortyForty)
expectNil(oldMember)
}
do {
// Replacing an element that is already present
let oldMember = s1.update(with: 4040)
expectTrue(oldMember === fortyForty)
}
expectEqual(4, s1.count)
expectTrue(s1.contains(1010))
expectTrue(s1.contains(2020))
expectTrue(s1.contains(3030))
expectTrue(s1.contains(4040))
}
SetTestSuite.test("union") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
let s4 = s1.union(s2)
expectEqual(s4, s3)
// s1 should be unchanged
expectEqual(identity1, s1._rawIdentifier())
expectEqual(Set([1010, 2020, 3030]), s1)
// s4 should be a fresh set
expectNotEqual(identity1, s4._rawIdentifier())
expectEqual(s4, s3)
let s5 = s1.union(s1)
expectEqual(s5, s1)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s1.union(Set<Int>()))
expectEqual(s1, Set<Int>().union(s1))
}
SetTestSuite.test("∪") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
let s4 = s1 ∪ s2
expectEqual(s4, s3)
// s1 should be unchanged
expectEqual(identity1, s1._rawIdentifier())
expectEqual(Set([1010, 2020, 3030]), s1)
// s4 should be a fresh set
expectNotEqual(identity1, s4._rawIdentifier())
expectEqual(s4, s3)
let s5 = s1 ∪ s1
expectEqual(s5, s1)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s1 ∪ Set<Int>())
expectEqual(s1, Set<Int>() ∪ s1)
}
SetTestSuite.test("formUnion") {
// These are anagrams - they should amount to the same sets.
var s1 = Set("the morse code".characters)
let s2 = Set("here come dots".characters)
let s3 = Set("and then dashes".characters)
let identity1 = s1._rawIdentifier()
s1.formUnion("".characters)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s2)
s1.formUnion(s2)
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
s1.formUnion(s3)
expectNotEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("∪=") {
// These are anagrams - they should amount to the same sets.
var s1 = Set("the morse code".characters)
let s2 = Set("here come dots".characters)
let s3 = Set("and then dashes".characters)
let identity1 = s1._rawIdentifier()
s1 ∪= "".characters
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s2)
s1 ∪= s2
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
s1 ∪= s3
expectNotEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("subtract") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
// Subtracting a disjoint set should not create a
// unique reference
let s4 = s1.subtracting(s2)
expectEqual(s1, s4)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s4._rawIdentifier())
// Subtracting a superset will leave the set empty
let s5 = s1.subtracting(s3)
expectTrue(s5.isEmpty)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s5._rawIdentifier())
// Subtracting the empty set does nothing
expectEqual(s1, s1.subtracting(Set<Int>()))
expectEqual(Set<Int>(), Set<Int>().subtracting(s1))
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("∖") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
// Subtracting a disjoint set should not create a
// unique reference
let s4 = s1 ∖ s2
expectEqual(s1, s4)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s4._rawIdentifier())
// Subtracting a superset will leave the set empty
let s5 = s1 ∖ s3
expectTrue(s5.isEmpty)
expectEqual(identity1, s1._rawIdentifier())
expectNotEqual(identity1, s5._rawIdentifier())
// Subtracting the empty set does nothing
expectEqual(s1, s1 ∖ Set<Int>())
expectEqual(Set<Int>(), Set<Int>() ∖ s1)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("subtract") {
var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
let s3 = Set([4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
s1.subtract(Set<Int>())
expectEqual(identity1, s1._rawIdentifier())
s1.subtract(s3)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("∖=") {
var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010, 2020, 3030])
let s3 = Set([4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
s1 ∖= Set<Int>()
expectEqual(identity1, s1._rawIdentifier())
s1 ∖= s3
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("intersect") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
var s4 = Set([1010, 2020, 3030])
let identity1 = s1._rawIdentifier()
expectEqual(Set([1010, 2020, 3030]),
Set([1010, 2020, 3030]).intersection(Set([1010, 2020, 3030])) as Set<Int>)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s1.intersection(s3))
expectEqual(identity1, s1._rawIdentifier())
expectEqual(Set<Int>(), Set<Int>().intersection(Set<Int>()))
expectEqual(Set<Int>(), s1.intersection(Set<Int>()))
expectEqual(Set<Int>(), Set<Int>().intersection(s1))
}
SetTestSuite.test("∩") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
var s4 = Set([1010, 2020, 3030])
let identity1 = s1._rawIdentifier()
expectEqual(Set([1010, 2020, 3030]),
Set([1010, 2020, 3030]) ∩ Set([1010, 2020, 3030]) as Set<Int>)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, s1 ∩ s3)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(Set<Int>(), Set<Int>() ∩ Set<Int>())
expectEqual(Set<Int>(), s1 ∩ Set<Int>())
expectEqual(Set<Int>(), Set<Int>() ∩ s1)
}
SetTestSuite.test("formIntersection") {
var s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
var s4 = Set([1010, 2020, 3030])
let identity1 = s1._rawIdentifier()
s1.formIntersection(s4)
expectEqual(s1, s4)
expectEqual(identity1, s1._rawIdentifier())
s4.formIntersection(s2)
expectEqual(Set<Int>(), s4)
let identity2 = s3._rawIdentifier()
s3.formIntersection(s2)
expectEqual(s3, s2)
expectTrue(s1.isDisjoint(with: s3))
expectNotEqual(identity1, s3._rawIdentifier())
var s5 = Set<Int>()
s5.formIntersection(s5)
expectEqual(s5, Set<Int>())
s5.formIntersection(s1)
expectEqual(s5, Set<Int>())
}
SetTestSuite.test("∩=") {
var s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060])
var s4 = Set([1010, 2020, 3030])
let identity1 = s1._rawIdentifier()
s1 ∩= s4
expectEqual(s1, s4)
expectEqual(identity1, s1._rawIdentifier())
s4 ∩= s2
expectEqual(Set<Int>(), s4)
let identity2 = s3._rawIdentifier()
s3 ∩= s2
expectEqual(s3, s2)
expectTrue(s1.isDisjoint(with: s3))
expectNotEqual(identity1, s3._rawIdentifier())
var s5 = Set<Int>()
s5 ∩= s5
expectEqual(s5, Set<Int>())
s5 ∩= s1
expectEqual(s5, Set<Int>())
}
SetTestSuite.test("symmetricDifference") {
// Overlap with 4040, 5050, 6060
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([4040, 5050, 6060, 7070, 8080, 9090])
let result = Set([1010, 2020, 3030, 7070, 8080, 9090])
let universe = Set([1010, 2020, 3030, 4040, 5050, 6060,
7070, 8080, 9090])
let identity1 = s1._rawIdentifier()
let s3 = s1.symmetricDifference(s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s3, result)
expectEqual(s1.symmetricDifference(s2),
s1.union(s2).intersection(universe.subtracting(s1.intersection(s2))))
expectEqual(s1.symmetricDifference(s2),
s1.intersection(universe.subtracting(s2)).union(universe.subtracting(s1).intersection(s2)))
expectTrue(s1.symmetricDifference(s1).isEmpty)
}
SetTestSuite.test("⨁") {
// Overlap with 4040, 5050, 6060
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([4040, 5050, 6060, 7070, 8080, 9090])
let result = Set([1010, 2020, 3030, 7070, 8080, 9090])
let universe = Set([1010, 2020, 3030, 4040, 5050, 6060,
7070, 8080, 9090])
let identity1 = s1._rawIdentifier()
let s3 = s1 ⨁ s2
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s3, result)
expectEqual(s1 ⨁ s2,
(s1 ∪ s2) ∩ (universe ∖ (s1 ∩ s2)))
expectEqual(s1 ⨁ s2,
s1 ∩ (universe ∖ s2) ∪ (universe ∖ s1) ∩ s2)
expectTrue((s1 ⨁ s1).isEmpty)
}
SetTestSuite.test("formSymmetricDifference") {
// Overlap with 4040, 5050, 6060
var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010])
let result = Set([2020, 3030, 4040, 5050, 6060])
// s1 ⨁ s2 == result
let identity1 = s1._rawIdentifier()
s1.formSymmetricDifference(s2)
// Removing just one element shouldn't cause an identity change
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, result)
// A ⨁ A == {}
s1.formSymmetricDifference(s1)
expectTrue(s1.isEmpty)
// Removing all elements should cause an identity change
expectNotEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("⨁=") {
// Overlap with 4040, 5050, 6060
var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s2 = Set([1010])
let result = Set([2020, 3030, 4040, 5050, 6060])
let identity1 = s1._rawIdentifier()
s1 ⨁= s2
// Removing just one element shouldn't cause an identity change
expectEqual(identity1, s1._rawIdentifier())
expectEqual(s1, result)
s1 ⨁= s1
expectTrue(s1.isEmpty)
// Removing all elements should cause an identity change
expectNotEqual(identity1, s1._rawIdentifier())
}
SetTestSuite.test("removeFirst") {
var s1 = Set([1010, 2020, 3030])
let s2 = s1
let empty = Set<Int>()
let a1 = s1.removeFirst()
expectFalse(s1.contains(a1))
expectTrue(s2.contains(a1))
expectNotEqual(s1._rawIdentifier(), s2._rawIdentifier())
expectTrue(s1.isSubset(of: s2))
expectNil(empty.first)
}
SetTestSuite.test("remove(member)") {
let s1 : Set<TestKeyTy> = [1010, 2020, 3030]
var s2 = Set<TestKeyTy>(minimumCapacity: 10)
for i in [1010, 2020, 3030] {
s2.insert(TestKeyTy(i))
}
let identity1 = s2._rawIdentifier()
// remove something that's not there.
let fortyForty = s2.remove(4040)
expectEqual(s2, s1)
expectNil(fortyForty)
expectEqual(identity1, s2._rawIdentifier())
// Remove things that are there.
let thirtyThirty = s2.remove(3030)
expectEqual(3030, thirtyThirty)
expectEqual(identity1, s2._rawIdentifier())
s2.remove(2020)
expectEqual(identity1, s2._rawIdentifier())
s2.remove(1010)
expectEqual(identity1, s2._rawIdentifier())
expectEqual(Set(), s2)
expectTrue(s2.isEmpty)
}
SetTestSuite.test("contains") {
let s1 = Set([1010, 2020, 3030])
expectTrue(s1.contains(1010))
expectFalse(s1.contains(999))
}
SetTestSuite.test("∈") {
let s1 = Set([1010, 2020, 3030])
expectTrue(1010 ∈ s1)
expectFalse(999 ∈ s1)
}
SetTestSuite.test("∉") {
let s1 = Set([1010, 2020, 3030])
expectFalse(1010 ∉ s1)
expectTrue(999 ∉ s1)
}
SetTestSuite.test("memberAtIndex") {
let s1 = Set([1010, 2020, 3030])
let foundIndex = s1.index(of: 1010)!
expectEqual(1010, s1[foundIndex])
}
SetTestSuite.test("first") {
let s1 = Set([1010, 2020, 3030])
let emptySet = Set<Int>()
expectTrue(s1.contains(s1.first!))
expectNil(emptySet.first)
}
SetTestSuite.test("isEmpty") {
let s1 = Set([1010, 2020, 3030])
expectFalse(s1.isEmpty)
let emptySet = Set<Int>()
expectTrue(emptySet.isEmpty)
}
#if _runtime(_ObjC)
@objc
class MockSetWithCustomCount : NSSet {
init(count: Int) {
self._count = count
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(objects: UnsafePointer<AnyObject>?, count: Int) {
expectUnreachable()
super.init(objects: objects, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by MockSetWithCustomCount")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this set produces an object of the same
// dynamic type.
return self
}
override func member(_ object: Any) -> Any? {
expectUnreachable()
return object
}
override func objectEnumerator() -> NSEnumerator {
expectUnreachable()
return getAsNSSet([1010, 1020, 1030]).objectEnumerator()
}
override var count: Int {
MockSetWithCustomCount.timesCountWasCalled += 1
return _count
}
var _count: Int = 0
static var timesCountWasCalled = 0
}
func getMockSetWithCustomCount(count: Int)
-> Set<NSObject> {
return MockSetWithCustomCount(count: count) as Set
}
func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool {
return collection.isEmpty
}
SetTestSuite.test("isEmpty/ImplementationIsCustomized") {
do {
var d = getMockSetWithCustomCount(count: 0)
MockSetWithCustomCount.timesCountWasCalled = 0
expectTrue(d.isEmpty)
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockSetWithCustomCount(count: 0)
MockSetWithCustomCount.timesCountWasCalled = 0
expectTrue(callGenericIsEmpty(d))
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockSetWithCustomCount(count: 4)
MockSetWithCustomCount.timesCountWasCalled = 0
expectFalse(d.isEmpty)
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockSetWithCustomCount(count: 4)
MockSetWithCustomCount.timesCountWasCalled = 0
expectFalse(callGenericIsEmpty(d))
expectEqual(1, MockSetWithCustomCount.timesCountWasCalled)
}
}
#endif // _runtime(_ObjC)
SetTestSuite.test("count") {
let s1 = Set([1010, 2020, 3030])
var s2 = Set([4040, 5050, 6060])
expectEqual(0, Set<Int>().count)
expectEqual(3, s1.count)
}
SetTestSuite.test("contains") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
expectTrue(s1.contains(1010))
expectFalse(s1.contains(999))
expectFalse(Set<Int>().contains(1010))
}
SetTestSuite.test("_customContainsEquatableElement") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
expectTrue(s1._customContainsEquatableElement(1010)!)
expectFalse(s1._customContainsEquatableElement(999)!)
expectFalse(Set<Int>()._customContainsEquatableElement(1010)!)
}
SetTestSuite.test("index(of:)") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let foundIndex1 = s1.index(of: 1010)!
expectEqual(1010, s1[foundIndex1])
expectNil(s1.index(of: 999))
}
SetTestSuite.test("popFirst") {
// Empty
do {
var s = Set<Int>()
let popped = s.popFirst()
expectNil(popped)
expectTrue(s.isEmpty)
}
do {
var popped = [Int]()
var s = Set([1010, 2020, 3030])
let expected = Array(s)
while let element = s.popFirst() {
popped.append(element)
}
expectEqualSequence(expected, Array(popped))
expectTrue(s.isEmpty)
}
}
SetTestSuite.test("removeAt") {
// Test removing from the startIndex, the middle, and the end of a set.
for i in 1...3 {
var s = Set<Int>([1010, 2020, 3030])
let removed = s.remove(at: s.index(of: i*1010)!)
expectEqual(i*1010, removed)
expectEqual(2, s.count)
expectNil(s.index(of: i*1010))
let origKeys: [Int] = [1010, 2020, 3030]
expectEqual(origKeys.filter { $0 != (i*1010) }, [Int](s).sorted())
}
}
SetTestSuite.test("_customIndexOfEquatableElement") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let foundIndex1 = s1._customIndexOfEquatableElement(1010)!!
expectEqual(1010, s1[foundIndex1])
expectNil(s1._customIndexOfEquatableElement(999)!)
}
SetTestSuite.test("commutative") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([2020, 3030])
expectTrue(equalsUnordered(s1.intersection(s2), s2.intersection(s1)))
expectTrue(equalsUnordered(s1.union(s2), s2.union(s1)))
}
SetTestSuite.test("associative") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([2020, 3030])
let s3 = Set([1010, 2020, 3030])
let s4 = Set([2020, 3030])
let s5 = Set([7070, 8080, 9090])
expectTrue(equalsUnordered(s1.intersection(s2).intersection(s3),
s1.intersection(s2.intersection(s3))))
expectTrue(equalsUnordered(s3.union(s4).union(s5), s3.union(s4.union(s5))))
}
SetTestSuite.test("distributive") {
let s1 = Set([1010])
let s2 = Set([1010, 2020, 3030, 4040, 5050, 6060])
let s3 = Set([2020, 3030])
expectTrue(equalsUnordered(s1.union(s2.intersection(s3)),
s1.union(s2).intersection(s1.union(s3))))
let s4 = Set([2020, 3030])
expectTrue(equalsUnordered(s4.intersection(s1.union(s3)),
s4.intersection(s1).union(s4.intersection(s3))))
}
SetTestSuite.test("idempotent") {
let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060])
expectTrue(equalsUnordered(s1, s1.intersection(s1)))
expectTrue(equalsUnordered(s1, s1.union(s1)))
}
SetTestSuite.test("absorption") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([4040, 5050, 6060])
let s3 = Set([2020, 3030])
expectTrue(equalsUnordered(s1, s1.union(s1.intersection(s2))))
expectTrue(equalsUnordered(s1, s1.intersection(s1.union(s3))))
}
SetTestSuite.test("misc") {
// Set with other types
do {
var s = Set([1.1, 2.2, 3.3])
s.insert(4.4)
expectTrue(s.contains(1.1))
expectTrue(s.contains(2.2))
expectTrue(s.contains(3.3))
}
do {
var s = Set(["Hello", "world"])
expectTrue(s.contains("Hello"))
expectTrue(s.contains("world"))
}
}
SetTestSuite.test("Hashable") {
let s1 = Set([1010])
let s2 = Set([2020])
checkHashable([s1, s2], equalityOracle: { $0 == $1 })
// Explicit types help the type checker quite a bit.
let ss1 = Set([Set([1010] as [Int]), Set([2020] as [Int]), Set([3030] as [Int])])
let ss11 = Set([Set([2020] as [Int]), Set([3030] as [Int]), Set([2020] as [Int])])
let ss2 = Set([Set([9090] as [Int])])
checkHashable([ss1, ss11, ss2], equalityOracle: { $0 == $1 })
}
SetTestSuite.test("Operator.Precedence") {
let s1 = Set([1010, 2020, 3030])
let s2 = Set([3030, 4040, 5050])
let s3 = Set([6060, 7070, 8080])
let s4 = Set([8080, 9090, 100100])
// intersection higher precedence than union
expectEqual(s1 ∪ (s2 ∩ s3) ∪ s4, s1 ∪ s2 ∩ s3 ∪ s4 as Set<Int>)
// intersection higher precedence than complement
expectEqual(s1 ∖ (s2 ∩ s3) ∖ s4, s1 ∖ s2 ∩ s3 ∖ s4 as Set<Int>)
// intersection higher precedence than exclusive-or
expectEqual(s1 ⨁ (s2 ∩ s3) ⨁ s4, s1 ⨁ s2 ∩ s3 ⨁ s4 as Set<Int>)
// union/complement/exclusive-or same precedence
expectEqual((((s1 ∪ s3) ∖ s2) ⨁ s4), s1 ∪ s3 ∖ s2 ⨁ s4 as Set<Int>)
// ∪= should happen last.
var s5 = Set([1010, 2020, 3030])
s5 ∪= Set([4040, 5050, 6060]) ∪ [7070]
expectEqual(Set([1010, 2020, 3030, 4040, 5050, 6060, 7070]), s5)
// ∩= should happen last.
var s6 = Set([1010, 2020, 3030])
s6 ∩= Set([1010, 2020, 3030]) ∩ [3030]
expectEqual(Set([3030]), s6)
// ⨁= should happen last.
var s7 = Set([1010, 2020, 3030])
s7 ⨁= Set([1010, 2020, 3030]) ⨁ [1010, 3030]
expectEqual(Set([1010, 3030]), s7)
// ∖= should happen last.
var s8 = Set([1010, 2020, 3030])
s8 ∖= Set([2020, 3030]) ∖ [3030]
expectEqual(Set([1010, 3030]), s8)
}
//===---
// Check that iterators traverse a snapshot of the collection.
//===---
SetTestSuite.test("mutationDoesNotAffectIterator/remove,1") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
expectOptionalEqual(1010, set.remove(1010))
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
SetTestSuite.test("mutationDoesNotAffectIterator/remove,all") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
expectOptionalEqual(1010, set.remove(1010))
expectOptionalEqual(1020, set.remove(1020))
expectOptionalEqual(1030, set.remove(1030))
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
SetTestSuite.test("mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
set.removeAll(keepingCapacity: false)
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
SetTestSuite.test("mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") {
var set = Set([1010, 1020, 1030])
var iter = set.makeIterator()
set.removeAll(keepingCapacity: true)
expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter)))
}
runAllTests()
| 28.285827 | 278 | 0.706019 |
879e36735c540e8f2482af9a688ac99173ad7bac | 372 | import Foundation
import Firebase
class FMain
{
static let sharedInstance:FMain = FMain()
let analytics:FAnalytics
let db:FDb
let storage:FStorage
private init()
{
FirebaseApp.configure()
analytics = FAnalytics()
db = FDb()
storage = FStorage()
}
//MARK: public
func load()
{
}
}
| 14.88 | 45 | 0.561828 |
727291d78db1f13e0790f804f96a06f73d12d98c | 809 | //
// TableViewCell.swift
// AssigmentWeek1
//
// Created by Ngoc Do on 3/12/16.
// Copyright © 2016 com.appable. All rights reserved.
//
import UIKit
import Spring
class TableViewCell: UITableViewCell {
// @IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblTitle: SpringLabel!
@IBOutlet weak var filmImage: SpringImageView!
@IBOutlet weak var lblContent: UILabel!
override func awakeFromNib() {
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
//set background if selected
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor(red: 237.0/255, green: 85.0/255, blue: 8/255, alpha: 1.0)
self.selectedBackgroundView = bgColorView
}
}
| 23.794118 | 103 | 0.673671 |
6a00a914aebf929cae9e4d8f87a58172a8167e51 | 171 | //
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import Domain
protocol HasClipQueryService {
var clipQueryService: ClipQueryServiceProtocol { get }
}
| 17.1 | 58 | 0.74269 |
266efd4f8e0e7802711c76ec34a397a6e5efd6b7 | 1,511 | //
// GameViewController.swift
// Hero
//
// Created by 关东升 on 2017/1/20.
// 本书网站:http://www.51work6.com
// 智捷课堂在线课堂:http://www.zhijieketang.com/
// 智捷课堂微信公共号:zhijieketang
// 作者微博:@tony_关东升
// 作者微信:tony关东升
// QQ:569418560 邮箱:[email protected]
// QQ交流群:162030268
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//配置视图
if let view = self.view as! SKView? {
// 从GameScene.sks文件创建场景对象
if let scene = SKScene(fileNamed: "GameScene") {
// 设置缩放到屏幕的模式
scene.scaleMode = .aspectFill
// 呈现场景
view.presentScene(scene)
}
//渲染时忽略兄弟节点顺序,渲染进行优化,以提高性能
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| 23.984127 | 77 | 0.56585 |
280c1adefaa2b0aee6fb351a5d4a034198ffaf6d | 1,911 | //
// NewsListTests.swift
// NewsViperTests
//
// Created by Saul Moreno Abril on 09/09/2018.
// Copyright © 2018 Saul Moreno Abril. All rights reserved.
//
import XCTest
import Nimble
@testable import NewsViper
class NewsListTests: XCTestCase {
var presenter:NewsListPresenterMock!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
presenter = NewsListPresenterMock()
let interactor: NewsListInteractorInputProtocol & NewsListRemoteDataManagerOutputProtocol = NewsListInteractor()
let dataRemote: NewsListRemoteDataManagerInputProtocol = NewsListRemoteDataManagerStub()
presenter.interactor = interactor
interactor.presenter = presenter
interactor.remoteDatamanager = dataRemote
dataRemote.remoteRequestHandler = interactor
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testNewsListProvider_retrievingNews() {
// Retrieve news list to update view
presenter.viewNeedsUpdated()
expect(self.presenter.wasRetrievedNews).to(beTrue())
}
func testNewsListProvider_countingNews() {
// Retrieve news list to update view
presenter.viewNeedsUpdated()
expect(self.presenter.newsCount).to(equal(27))
}
func testNewsListProvider_errorRetrievingNews() {
// Retrieve news list to update view
let remoteDataManager = presenter.interactor?.remoteDatamanager as! NewsListRemoteDataManagerStub
remoteDataManager.simulateError = true
presenter.viewNeedsUpdated()
expect(self.presenter.wasGettingError).to(beTrue())
}
}
| 31.327869 | 120 | 0.683412 |
fcc8c3514f6695c6e961e8b3737059ad5f6f023f | 1,955 | //
// ResultViewController.swift
// gourmetsearch
//
// Created by 原隆幸 on 2018/07/31.
// Copyright © 2018年 Penguin. All rights reserved.
//
import UIKit
import SnapKit
import XLPagerTabStrip
class ResultViewController: SegmentedPagerTabStripViewController {
// MARK: - Properties
let scroll = UIScrollView()
let segmented = UISegmentedControl()
// MARK: - Lifecycle Methods
override func viewDidLoad() {
beforeViewDidLoad()
super.viewDidLoad()
view.setNeedsUpdateConstraints()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func updateViewConstraints() {
setupConstraints()
super.updateViewConstraints()
}
// MARK: - Public Methods
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let firstVC = ResultListViewController()
let secondVC = ResultMapViewController()
let childViewControllers: [UIViewController] = [firstVC, secondVC]
return childViewControllers
}
// MARK: - Private Methods
private func beforeViewDidLoad() {
// XLPagerTabStrip を使用するためにviewDidLoad()の前に行う処理
view.addSubview(segmented)
containerView = scroll
segmentedControl = segmented
}
private func setupConstraints() {
segmentedControl.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
make.centerX.equalToSuperview()
make.size.equalTo(CGSize(width: 300, height: 30))
}
scroll.snp.makeConstraints { make in
make.top.equalTo(segmented.snp.bottom).offset(4)
make.centerX.equalToSuperview()
make.width.equalToSuperview()
make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
}
}
}
| 28.75 | 115 | 0.670077 |
18ae5f10e5eda60a1912eb68b33c0f839f31b8d4 | 6,357 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import AWSAPIGateway
enum APIGatewayTestsError: Error {
case noRestApi
}
//testing restjson service
class APIGatewayTests: XCTestCase {
static let apiGateway = APIGateway(
credentialProvider: TestEnvironment.credentialProvider,
region: .euwest1,
endpoint: TestEnvironment.getEndPoint(environment: "APIGATEWAY_ENDPOINT", default: "http://localhost:4566"),
middlewares: TestEnvironment.middlewares,
httpClientProvider: .createNew
)
static let restApiName: String = "awssdkswift-APIGatewayTests"
static var restApiId: String!
override class func setUp() {
if TestEnvironment.isUsingLocalstack {
print("Connecting to Localstack")
} else {
print("Connecting to AWS")
}
/// If we create a rest api for each test, when we delete them APIGateway will throttle and we will most likely not delete the all APIs
/// So we create one API to be used by all tests
let eventLoop = self.apiGateway.client.eventLoopGroup.next()
let createResult = createRestApi(name: restApiName, on: eventLoop)
.flatMapThrowing { response in
return try XCTUnwrap(response.id)
}
.flatMapErrorThrowing { error in
print("Failed to create APIGateway rest api, error: \(error)")
throw error
}
XCTAssertNoThrow(Self.restApiId = try createResult.wait())
}
override class func tearDown() {
XCTAssertNoThrow(_ = try deleteRestApi(id: restApiId).wait())
}
static func createRestApi(name: String, on eventLoop: EventLoop) -> EventLoopFuture<APIGateway.RestApi> {
let request = APIGateway.GetRestApisRequest()
return self.apiGateway.getRestApis(request)
.flatMap { response in
if let restApi = response.items?.first(where: { $0.name == name }) {
return eventLoop.makeSucceededFuture(restApi)
} else {
let request = APIGateway.CreateRestApiRequest(
description: "\(name) API",
endpointConfiguration: APIGateway.EndpointConfiguration(types: [.regional]),
name: name
)
return Self.apiGateway.createRestApi(request)
}
}
}
static func deleteRestApi(id: String) -> EventLoopFuture<Void> {
let request = APIGateway.DeleteRestApiRequest(restApiId: id)
return apiGateway.deleteRestApi(request).map {}
}
/// create Rest api with supplied name and run supplied closure with rest api id
func testRestApi(body: @escaping (String) -> EventLoopFuture<Void>) -> EventLoopFuture<Void> {
body(Self.restApiId)
}
//MARK: TESTS
func testGetRestApis() {
let response = testRestApi() { id in
let request = APIGateway.GetRestApisRequest()
return Self.apiGateway.getRestApis(request)
.map { response in
let restApi = response.items?.first(where: { $0.id == id })
XCTAssertNotNil(restApi)
XCTAssertEqual(restApi?.name, Self.restApiName)
}
}
XCTAssertNoThrow(try response.wait())
}
func testGetRestApi() {
let response = testRestApi() { id in
let request = APIGateway.GetRestApiRequest(restApiId: id)
return Self.apiGateway.getRestApi(request)
.map { response in
XCTAssertEqual(response.name, Self.restApiName)
}
}
XCTAssertNoThrow(try response.wait())
}
func testCreateGetResource() {
let response = testRestApi() { id in
// get parent resource
let request = APIGateway.GetResourcesRequest(restApiId: id)
return Self.apiGateway.getResources(request)
.flatMapThrowing { response throws -> String in
let items = try XCTUnwrap(response.items)
XCTAssertEqual(items.count, 1)
let parentId = try XCTUnwrap(items[0].id)
return parentId
}
// create new resource
.flatMap { parentId -> EventLoopFuture<APIGateway.Resource> in
let request = APIGateway.CreateResourceRequest(parentId: parentId, pathPart: "test", restApiId: id)
return Self.apiGateway.createResource(request)
}
// extract resource id
.flatMapThrowing { (response) throws -> String in
let resourceId = try XCTUnwrap(response.id)
return resourceId
}
// get resource
.flatMap { resourceId -> EventLoopFuture<APIGateway.Resource> in
let request = APIGateway.GetResourceRequest(resourceId: resourceId, restApiId: id)
return Self.apiGateway.getResource(request)
}
// verify resource is correct
.map { response in
XCTAssertEqual(response.pathPart, "test")
}
}
XCTAssertNoThrow(try response.wait())
}
func testError() {
let response = Self.apiGateway.getModels(.init(restApiId: "invalid-rest-api-id"))
.map { _ in }
.flatMapErrorThrowing { error in
switch error {
case APIGatewayErrorType.notFoundException(_):
return
default:
// local stack is returning a duff error at the moment
if TestEnvironment.isUsingLocalstack {
return
}
throw error
}
}
XCTAssertNoThrow(try response.wait())
}
}
| 38.527273 | 143 | 0.579204 |
0a3c0ee1e8423e5482ec3623a8717fed4af268b8 | 283 | //: Playground - noun: a place where people can play
import UIKit
//三目运算符
var x = 2
if x > 2{
print("hahahah")
}
var result = x > 2 ? "11" : "111"
//区间运算符 ...
for index in 1...10{
index
// index属于常量,不能再循环体内被修改!
//index = 3
}
for index in 0..<10{
index
} | 12.863636 | 52 | 0.55477 |
0a9fbcee80aa89e7d40e3b8ca657f4fb8a128c2a | 3,684 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class HomeViewControllerWithBannerWrapperViewController: UIViewController, MXKViewControllerActivityHandling, BannerPresentationProtocol, MasterTabBarItemDisplayProtocol {
@objc let homeViewController: HomeViewController
private var bannerContainerView: UIView!
private var stackView: UIStackView!
init(viewController: HomeViewController) {
self.homeViewController = viewController
super.init(nibName: nil, bundle: nil)
extendedLayoutIncludesOpaqueBars = true
self.tabBarItem.tag = viewController.tabBarItem.tag
self.tabBarItem.image = viewController.tabBarItem.image
self.accessibilityLabel = viewController.accessibilityLabel
}
required init?(coder: NSCoder) {
fatalError("Not implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
homeViewController.willMove(toParent: self)
view.backgroundColor = .clear
stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
view.vc_addSubViewMatchingParent(stackView)
addChild(homeViewController)
stackView.addArrangedSubview(homeViewController.view)
homeViewController.didMove(toParent: self)
}
// MARK: - BannerPresentationProtocol
func presentBannerView(_ bannerView: UIView, animated: Bool) {
bannerView.alpha = 0.0
bannerView.isHidden = true
self.stackView.insertArrangedSubview(bannerView, at: 0)
self.stackView.layoutIfNeeded()
UIView.animate(withDuration: (animated ? 0.25 : 0.0)) {
bannerView.alpha = 1.0
bannerView.isHidden = false
self.stackView.layoutIfNeeded()
}
}
func dismissBannerView(animated: Bool) {
guard stackView.arrangedSubviews.count > 1, let bannerView = self.stackView.arrangedSubviews.first else {
return
}
UIView.animate(withDuration: (animated ? 0.25 : 0.0)) {
bannerView.alpha = 0.0
bannerView.isHidden = true
self.stackView.layoutIfNeeded()
} completion: { _ in
bannerView.removeFromSuperview()
}
}
// MARK: - MXKViewControllerActivityHandling
var activityIndicator: UIActivityIndicatorView! {
get {
return homeViewController.activityIndicator
}
set {
homeViewController.activityIndicator = newValue
}
}
var providesCustomActivityIndicator: Bool {
return homeViewController.providesCustomActivityIndicator
}
func startActivityIndicator() {
homeViewController.startActivityIndicator()
}
func stopActivityIndicator() {
homeViewController.stopActivityIndicator()
}
// MARK: - MasterTabBarItemDisplayProtocol
var masterTabBarItemTitle: String {
return VectorL10n.titleHome
}
}
| 31.487179 | 171 | 0.664767 |
fb89d1aefa211901c5efa481e4bce11926f1c0f8 | 770 | import AppKit
import JavaScriptCore
import Quartz
import AVKit
import CoreMedia
import CoreSpotlight
import CoreImage
import CoreGraphics
import Foundation
// Interface
/**
- Selector: NSDeleteCommand
*/
@objc(NSDeleteCommand) protocol NSDeleteCommandExports: JSExport, NSScriptCommandExports {
// Static Methods
/**
- Selector: currentCommand
*/
@objc (currentCommand) static func current() -> NSScriptCommand?
// Instance Methods
/**
- Selector: setReceiversSpecifier:
*/
@objc func setReceiversSpecifier(_ p0: NSScriptObjectSpecifier?)
// Own Instance Properties
/**
- Selector: keySpecifier
*/
@objc var keySpecifier: NSScriptObjectSpecifier { @objc get }
}
extension NSDeleteCommand: NSDeleteCommandExports {
}
| 18.333333 | 90 | 0.738961 |
8f31522dce4b1bebcf71f689c4b98236671b4fde | 292 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a{
func b{
{
{
{ {
{
({
{ (( )
:
{
{
{
{
{ :
func {
}
[ {
{
[:
{
{ {
{{
{
[ { a
[{
a {
"
func a{
}
typealias b:a{
| 8.342857 | 87 | 0.571918 |
7adf82976497d43ab13c0a74e643e6a7b9157e11 | 758 | //: [Previous](@previous)
import ColorPack
/*:
## 2. COLOR MODELS
ColorPack implements three color models; Int RGB, Percentage RGB and HSL.
Every model has `alpha` value, from 0% to 100%. Not 0.0 to 1.0!
### (1) Int RGB
Specified by Int values, from 0 to 255.
*/
IntRGBColor(rawValue: (red: 0, green: 128, blue: 255), alpha: 100)
/*:
### (2) Percentage RGB
Specified by percentage values, from 0% to 100%.
*/
DoubleRGBColor(rawValue: (red: 0, green: 50, blue: 100), alpha: 100)
/*:
### (3) HSL
Hue: Specified by degrees or nil (automatically changed to between 0 and 360)
Saturation, Lightness: Specified by percentage values, from 0% to 100%.
*/
HSLColor(rawValue: (hue: -150, saturation: 100, lightness: 50), alpha: 100)
//: [Next](@next)
| 30.32 | 78 | 0.674142 |
f73ba740e9bb449fb8ee3a6efe37ee317ffb3d1c | 7,454 | //
// UIDeviceExtension.swift
// appdb
//
// Created by ned on 07/05/2018.
// Copyright © 2018 ned. All rights reserved.
//
// Credits: Johannes Schickling (https://github.com/schickling/Device.swift)
import Foundation
import UIKit
/// Enum representing the different types of iOS devices available
public enum InternalDeviceType: String, CaseIterable {
case iPhone2G
case iPhone3G
case iPhone3GS
case iPhone4
case iPhone4S
case iPhone5
case iPhone5C
case iPhone5S
case iPhone6
case iPhone6Plus
case iPhone6S
case iPhone6SPlus
case iPhoneSE
case iPhone7
case iPhone7Plus
case iPhone8
case iPhone8Plus
case iPhoneX
case iPhoneXS
case iPhoneXSMax
case iPhoneXR
case iPodTouch1G
case iPodTouch2G
case iPodTouch3G
case iPodTouch4G
case iPodTouch5G
case iPodTouch6G
case iPad
case iPad2
case iPad3
case iPad4
case iPad5
case iPad6
case iPadMini
case iPadMiniRetina
case iPadMini3
case iPadMini4
case iPadAir
case iPadAir2
case iPadPro9Inch
case iPadPro10p5Inch
case iPadPro11Inch
case iPadPro12Inch
case simulator
case notAvailable
// MARK: Constants
/// The current device type
public static var current: InternalDeviceType {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
let mirror = Mirror(reflecting: machine)
var identifier = ""
for child in mirror.children {
if let value = child.value as? Int8, value != 0 {
identifier.append(String(UnicodeScalar(UInt8(value))))
}
}
return InternalDeviceType(identifier: identifier)
}
// MARK: Variables
/// The display name of the device type
public var displayName: String {
switch self {
case .iPhone2G: return "iPhone 2G"
case .iPhone3G: return "iPhone 3G"
case .iPhone3GS: return "iPhone 3GS"
case .iPhone4: return "iPhone 4"
case .iPhone4S: return "iPhone 4S"
case .iPhone5: return "iPhone 5"
case .iPhone5C: return "iPhone 5C"
case .iPhone5S: return "iPhone 5S"
case .iPhone6Plus: return "iPhone 6 Plus"
case .iPhone6: return "iPhone 6"
case .iPhone6S: return "iPhone 6s"
case .iPhone6SPlus: return "iPhone 6s Plus"
case .iPhoneSE: return "iPhone SE"
case .iPhone7: return "iPhone 7"
case .iPhone7Plus: return "iPhone 7 Plus"
case .iPhone8: return "iPhone 8"
case .iPhone8Plus: return "iPhone 8 Plus"
case .iPhoneX: return "iPhone X"
case .iPhoneXS: return "iPhone XS"
case .iPhoneXSMax: return "iPhone XS Max"
case .iPhoneXR: return "iPhone XR"
case .iPodTouch1G: return "iPod Touch 1G"
case .iPodTouch2G: return "iPod Touch 2G"
case .iPodTouch3G: return "iPod Touch 3G"
case .iPodTouch4G: return "iPod Touch 4G"
case .iPodTouch5G: return "iPod Touch 5G"
case .iPodTouch6G: return "iPod Touch 6G"
case .iPad: return "iPad"
case .iPad2: return "iPad 2"
case .iPad3: return "iPad 3"
case .iPad4: return "iPad 4"
case .iPad5: return "iPad 5"
case .iPad6: return "iPad 6"
case .iPadMini: return "iPad Mini"
case .iPadMiniRetina: return "iPad Mini Retina"
case .iPadMini3: return "iPad Mini 3"
case .iPadMini4: return "iPad Mini 4"
case .iPadAir: return "iPad Air"
case .iPadAir2: return "iPad Air 2"
case .iPadPro9Inch: return "iPad Pro 9 Inch"
case .iPadPro10p5Inch: return "iPad Pro 10.5 Inch"
case .iPadPro11Inch: return "iPad Pro 11 Inch"
case .iPadPro12Inch: return "iPad Pro 12 Inch"
case .simulator: return "Simulator"
case .notAvailable: return "Not Available"
}
}
/// The identifiers associated with each device type
internal var identifiers: [String] {
switch self {
case .notAvailable: return []
case .simulator: return ["i386", "x86_64"]
case .iPhone2G: return ["iPhone1,1"]
case .iPhone3G: return ["iPhone1,2"]
case .iPhone3GS: return ["iPhone2,1"]
case .iPhone4: return ["iPhone3,1", "iPhone3,2", "iPhone3,3"]
case .iPhone4S: return ["iPhone4,1"]
case .iPhone5: return ["iPhone5,1", "iPhone5,2"]
case .iPhone5C: return ["iPhone5,3", "iPhone5,4"]
case .iPhone5S: return ["iPhone6,1", "iPhone6,2"]
case .iPhone6: return ["iPhone7,2"]
case .iPhone6Plus: return ["iPhone7,1"]
case .iPhone6S: return ["iPhone8,1"]
case .iPhone6SPlus: return ["iPhone8,2"]
case .iPhoneSE: return ["iPhone8,4"]
case .iPhone7: return ["iPhone9,1", "iPhone9,3"]
case .iPhone7Plus: return ["iPhone9,2", "iPhone9,4"]
case .iPhone8: return ["iPhone10,1", "iPhone10,4"]
case .iPhone8Plus: return ["iPhone10,2", "iPhone10,5"]
case .iPhoneX: return ["iPhone10,3", "iPhone10,6"]
case .iPhoneXS: return ["iPhone11,2"]
case .iPhoneXSMax: return ["iPhone11,4", "iPhone11,6"]
case .iPhoneXR: return ["iPhone11,8"]
case .iPodTouch1G: return ["iPod1,1"]
case .iPodTouch2G: return ["iPod2,1"]
case .iPodTouch3G: return ["iPod3,1"]
case .iPodTouch4G: return ["iPod4,1"]
case .iPodTouch5G: return ["iPod5,1"]
case .iPodTouch6G: return ["iPod7,1"]
case .iPad: return ["iPad1,1", "iPad1,2"]
case .iPad2: return ["iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4"]
case .iPad3: return ["iPad3,1", "iPad3,2", "iPad3,3"]
case .iPad4: return ["iPad3,4", "iPad3,5", "iPad3,6"]
case .iPad5: return ["iPad6,11", "iPad6,12"]
case .iPad6: return ["iPad7,5", "iPad7,6"]
case .iPadMini: return ["iPad2,5", "iPad2,6", "iPad2,7"]
case .iPadMiniRetina: return ["iPad4,4", "iPad4,5", "iPad4,6"]
case .iPadMini3: return ["iPad4,7", "iPad4,8", "iPad4,9"]
case .iPadMini4: return ["iPad5,1", "iPad5,2"]
case .iPadAir: return ["iPad4,1", "iPad4,2", "iPad4,3"]
case .iPadAir2: return ["iPad5,3", "iPad5,4"]
case .iPadPro9Inch: return ["iPad6,3", "iPad6,4"]
case .iPadPro10p5Inch: return ["iPad7,3", "iPad7,4"]
case .iPadPro11Inch: return ["iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4"]
case .iPadPro12Inch: return ["iPad6,7", "iPad6,8", "iPad7,1", "iPad7,2", "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8"]
}
}
// MARK: Inits
/// Creates a device type
///
/// - Parameter identifier: The identifier of the device
internal init(identifier: String) {
for device in InternalDeviceType.allCases {
for deviceId in device.identifiers {
guard identifier == deviceId else { continue }
self = device
return
}
}
self = .notAvailable
}
}
// MARK: -
public extension UIDevice {
/// The `InternalDeviceType` of the device in use
var deviceType: InternalDeviceType {
return InternalDeviceType.current
}
}
| 31.854701 | 124 | 0.59069 |
226e19d74c963491e2d952a71b59f10848245a9d | 15,502 | //
// TypesConversionBasicTests.swift
//
// Copyright (c) 2016 David Mohundro
//
// 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 SWXMLHash
import XCTest
// swiftlint:disable force_try
// swiftlint:disable variable_name
class TypeConversionBasicTypesTests: XCTestCase {
var parser: XMLIndexer?
let xmlWithBasicTypes = "<root>" +
" <string>the string value</string>" +
" <int>100</int>" +
" <double>100.45</double>" +
" <float>44.12</float>" +
" <bool1>0</bool1>" +
" <bool2>true</bool2>" +
" <empty></empty>" +
" <basicItem>" +
" <name>the name of basic item</name>" +
" <price>99.14</price>" +
" </basicItem>" +
" <attr string=\"stringValue\" int=\"200\" double=\"200.15\" float=\"205.42\" bool1=\"0\" bool2=\"true\"/>" +
" <attributeItem name=\"the name of attribute item\" price=\"19.99\"/>" +
"</root>"
override func setUp() {
parser = SWXMLHash.parse(xmlWithBasicTypes)
}
func testShouldConvertValueToNonOptional() {
let value: String = try! parser!["root"]["string"].value()
XCTAssertEqual(value, "the string value")
}
func testShouldConvertEmptyToNonOptional() {
let value: String = try! parser!["root"]["empty"].value()
XCTAssertEqual(value, "")
}
func testShouldThrowWhenConvertingMissingToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["missing"].value() as String)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldConvertValueToOptional() {
let value: String? = try! parser!["root"]["string"].value()
XCTAssertEqual(value, "the string value")
}
func testShouldConvertEmptyToOptional() {
let value: String? = try! parser!["root"]["empty"].value()
XCTAssertEqual(value, "")
}
func testShouldConvertMissingToOptional() {
let value: String? = try! parser!["root"]["missing"].value()
XCTAssertNil(value)
}
func testShouldConvertAttributeToNonOptional() {
let value: String = try! parser!["root"]["attr"].value(ofAttribute: "string")
XCTAssertEqual(value, "stringValue")
}
func testShouldConvertAttributeToOptional() {
let value: String? = parser!["root"]["attr"].value(ofAttribute: "string")
XCTAssertEqual(value, "stringValue")
}
func testShouldThrowWhenConvertingMissingAttributeToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["attr"].value(ofAttribute: "missing") as String)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testShouldConvertMissingAttributeToOptional() {
let value: String? = parser!["root"]["attr"].value(ofAttribute: "missing")
XCTAssertNil(value)
}
func testIntShouldConvertValueToNonOptional() {
let value: Int = try! parser!["root"]["int"].value()
XCTAssertEqual(value, 100)
}
func testIntShouldThrowWhenConvertingEmptyToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Int)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testIntShouldThrowWhenConvertingMissingToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["missing"].value() as Int)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testIntShouldConvertValueToOptional() {
let value: Int? = try! parser!["root"]["int"].value()
XCTAssertEqual(value, 100)
}
func testIntShouldConvertEmptyToOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Int?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testIntShouldConvertMissingToOptional() {
let value: Int? = try! parser!["root"]["missing"].value()
XCTAssertNil(value)
}
func testIntShouldConvertAttributeToNonOptional() {
let value: Int = try! parser!["root"]["attr"].value(ofAttribute: "int")
XCTAssertEqual(value, 200)
}
func testIntShouldConvertAttributeToOptional() {
let value: Int? = parser!["root"]["attr"].value(ofAttribute: "int")
XCTAssertEqual(value, 200)
}
func testDoubleShouldConvertValueToNonOptional() {
let value: Double = try! parser!["root"]["double"].value()
XCTAssertEqual(value, 100.45)
}
func testDoubleShouldThrowWhenConvertingEmptyToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Double)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testDoubleShouldThrowWhenConvertingMissingToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["missing"].value() as Double)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testDoubleShouldConvertValueToOptional() {
let value: Double? = try! parser!["root"]["double"].value()
XCTAssertEqual(value, 100.45)
}
func testDoubleShouldConvertEmptyToOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Double?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testDoubleShouldConvertMissingToOptional() {
let value: Double? = try! parser!["root"]["missing"].value()
XCTAssertNil(value)
}
func testDoubleShouldConvertAttributeToNonOptional() {
let value: Double = try! parser!["root"]["attr"].value(ofAttribute: "double")
XCTAssertEqual(value, 200.15)
}
func testDoubleShouldConvertAttributeToOptional() {
let value: Double? = parser!["root"]["attr"].value(ofAttribute: "double")
XCTAssertEqual(value, 200.15)
}
func testFloatShouldConvertValueToNonOptional() {
let value: Float = try! parser!["root"]["float"].value()
XCTAssertEqual(value, 44.12)
}
func testFloatShouldThrowWhenConvertingEmptyToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Float)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testFloatShouldThrowWhenConvertingMissingToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["missing"].value() as Float)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testFloatShouldConvertValueToOptional() {
let value: Float? = try! parser!["root"]["float"].value()
XCTAssertEqual(value, 44.12)
}
func testFloatShouldConvertEmptyToOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Float?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testFloatShouldConvertMissingToOptional() {
let value: Float? = try! parser!["root"]["missing"].value()
XCTAssertNil(value)
}
func testFloatShouldConvertAttributeToNonOptional() {
let value: Float = try! parser!["root"]["attr"].value(ofAttribute: "float")
XCTAssertEqual(value, 205.42)
}
func testFloatShouldConvertAttributeToOptional() {
let value: Float? = parser!["root"]["attr"].value(ofAttribute: "float")
XCTAssertEqual(value, 205.42)
}
func testBoolShouldConvertValueToNonOptional() {
let value1: Bool = try! parser!["root"]["bool1"].value()
let value2: Bool = try! parser!["root"]["bool2"].value()
XCTAssertFalse(value1)
XCTAssertTrue(value2)
}
func testBoolShouldThrowWhenConvertingEmptyToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Bool)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testBoolShouldThrowWhenConvertingMissingToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["missing"].value() as Bool)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testBoolShouldConvertValueToOptional() {
let value1: Bool? = try! parser!["root"]["bool1"].value()
XCTAssertEqual(value1, false)
let value2: Bool? = try! parser!["root"]["bool2"].value()
XCTAssertEqual(value2, true)
}
func testBoolShouldConvertEmptyToOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as Bool?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testBoolShouldConvertMissingToOptional() {
let value: Bool? = try! parser!["root"]["missing"].value()
XCTAssertNil(value)
}
func testBoolShouldConvertAttributeToNonOptional() {
let value: Bool = try! parser!["root"]["attr"].value(ofAttribute: "bool1")
XCTAssertEqual(value, false)
}
func testBoolShouldConvertAttributeToOptional() {
let value: Bool? = parser!["root"]["attr"].value(ofAttribute: "bool2")
XCTAssertEqual(value, true)
}
let correctBasicItem = BasicItem(name: "the name of basic item", price: 99.14)
func testBasicItemShouldConvertBasicitemToNonOptional() {
let value: BasicItem = try! parser!["root"]["basicItem"].value()
XCTAssertEqual(value, correctBasicItem)
}
func testBasicItemShouldThrowWhenConvertingEmptyToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as BasicItem)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testBasicItemShouldThrowWhenConvertingMissingToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["missing"].value() as BasicItem)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testBasicItemShouldConvertBasicitemToOptional() {
let value: BasicItem? = try! parser!["root"]["basicItem"].value()
XCTAssertEqual(value, correctBasicItem)
}
func testBasicItemShouldConvertEmptyToOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as BasicItem?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testBasicItemShouldConvertMissingToOptional() {
let value: BasicItem? = try! parser!["root"]["missing"].value()
XCTAssertNil(value)
}
let correctAttributeItem = AttributeItem(name: "the name of attribute item", price: 19.99)
func testAttributeItemShouldConvertAttributeItemToNonOptional() {
let value: AttributeItem = try! parser!["root"]["attributeItem"].value()
XCTAssertEqual(value, correctAttributeItem)
}
func testAttributeItemShouldThrowWhenConvertingEmptyToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as AttributeItem)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testAttributeItemShouldThrowWhenConvertingMissingToNonOptional() {
XCTAssertThrowsError(try (parser!["root"]["missing"].value() as AttributeItem)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testAttributeItemShouldConvertAttributeItemToOptional() {
let value: AttributeItem? = try! parser!["root"]["attributeItem"].value()
XCTAssertEqual(value, correctAttributeItem)
}
func testAttributeItemShouldConvertEmptyToOptional() {
XCTAssertThrowsError(try (parser!["root"]["empty"].value() as AttributeItem?)) { error in
guard error is XMLDeserializationError else {
XCTFail("Wrong type of error")
return
}
}
}
func testAttributeItemShouldConvertMissingToOptional() {
let value: AttributeItem? = try! parser!["root"]["missing"].value()
XCTAssertNil(value)
}
}
struct BasicItem: XMLIndexerDeserializable {
let name: String
let price: Double
static func deserialize(node: XMLIndexer) throws -> BasicItem {
return try BasicItem(
name: node["name"].value(),
price: node["price"].value()
)
}
}
extension BasicItem: Equatable {}
func == (a: BasicItem, b: BasicItem) -> Bool {
return a.name == b.name && a.price == b.price
}
struct AttributeItem: XMLElementDeserializable {
let name: String
let price: Double
static func deserialize(element: XMLElement) throws -> AttributeItem {
return try AttributeItem(
name: element.value(ofAttribute: "name"),
price: element.value(ofAttribute: "price")
)
}
}
extension AttributeItem: Equatable {}
func == (a: AttributeItem, b: AttributeItem) -> Bool {
return a.name == b.name && a.price == b.price
}
| 34.757848 | 118 | 0.619017 |
08e9e8f25d432c3ff492e638d890d7056b7c4aae | 1,618 |
public struct DTOCreditReportInfo: Codable {
public private(set) var score: Int?
public private(set) var scoreBand: Int?
public private(set) var clientRef: String?
public private(set) var status: String?
public private(set) var maxScoreValue: Int?
public private(set) var minScoreValue: Int?
public private(set) var monthsSinceLastDefaulted: Int?
public private(set) var hasEverDefaulted: Bool?
public private(set) var monthsSinceLastDelinquent: Int?
public private(set) var hasEverBeenDelinquent: Bool?
public private(set) var percentageCreditUsed: Int?
public private(set) var percentageCreditUsedDirectionFlag: Int?
public private(set) var changedScore: Int?
public private(set) var currentShortTermDebt: Int?
public private(set) var currentShortTermNonPromotionalDebt: Int?
public private(set) var currentShortTermCreditLimit: Int?
public private(set) var currentShortTermCreditUtilisation: Int?
public private(set) var changeInShortTermDebt: Int?
public private(set) var currentLongTermDebt: Int?
public private(set) var currentLongTermNonPromotionalDebt: Int?
public private(set) var currentLongTermCreditLimit: Int?
public private(set) var currentLongTermCreditUtilisation: Int?
public private(set) var changeInLongTermDebt: Int?
public private(set) var numPositiveScoreFactors: Int?
public private(set) var numNegativeScoreFactors: Int?
public private(set) var equifaxScoreBand: Int?
public private(set) var equifaxScoreBandDescription: String?
public private(set) var daysUntilNextReport: Int?
}
| 50.5625 | 68 | 0.76885 |
d9cbdb69c664dd9f484937b3f9ddf8d222086523 | 1,719 | //
// RefreshGifHeader.swift
// ATRefresh
//
// Created by 凯文马 on 25/12/2017.
//
import UIKit
open class RefreshGifHeader: RefreshHeader {
private var stateImages : [String : [UIImage]] = [:]
private var lastState : RefreshState?
open var animationDuration : TimeInterval = 0.3
private lazy var imageView : UIImageView = {
let iv = UIImageView.init(frame: self.bounds)
iv.contentMode = .center
self.addSubview(iv)
return iv
}()
open func setAnimationImages(_ images: [UIImage], for state: RefreshState) {
stateImages[state.rawValue] = images
}
override open func stateDidUpdate(state: RefreshState, percent: CGFloat) {
let images = stateImages[state.rawValue]
let count = images?.count ?? 0
switch state {
case .idle,.isPulling:
imageView.stopAnimating()
var index = -1
if count > 1 {
index = min(Int(CGFloat(count - 1) * pullingPercent), count - 1)
} else if count == 1 {
index = 0
}
if index >= 0 {
imageView.image = images?[index]
}
break
case .willRefresh,.isRefreshing:
if lastState == state { return }
imageView.animationImages = images
imageView.animationDuration = animationDuration
imageView.startAnimating()
break
default:
imageView.stopAnimating()
break
}
lastState = state
}
open override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
}
}
| 26.859375 | 80 | 0.557301 |
6288a880e427d051176f48118e6af97dcb8ca2ef | 4,482 | // Copyright © 2020 Brad Howes. All rights reserved.
import AudioUnit
import SoundFontsFramework
import os
/// Definitions for the runtime parameters of the audio unit.
public struct AudioUnitParameters {
private let log = Logging.logger("AudioUnitParameters")
enum Address: AUParameterAddress {
case time = 1
case feedback
case cutoff
case wetDryMix
}
public let time: AUParameter = {
let param = AUParameterTree.createParameter(
withIdentifier: "time", name: "Time", address: Address.time.rawValue, min: 0.0, max: 2.0, unit: .seconds,
unitName: nil, flags: [.flag_IsReadable, .flag_IsWritable], valueStrings: nil, dependentParameters: nil)
param.value = 1.0
return param
}()
public let feedback: AUParameter = {
let param = AUParameterTree.createParameter(
withIdentifier: "feedback", name: "Feedback", address: Address.feedback.rawValue, min: -100.0, max: 100.0,
unit: .percent, unitName: nil, flags: [.flag_IsReadable, .flag_IsWritable], valueStrings: nil,
dependentParameters: nil)
param.value = 50.0
return param
}()
public let cutoff: AUParameter = {
let param = AUParameterTree.createParameter(
withIdentifier: "cutoff", name: "Cutoff", address: Address.cutoff.rawValue, min: 10.0, max: 20_000.0,
unit: .hertz, unitName: nil, flags: [.flag_IsReadable, .flag_IsWritable, .flag_DisplayLogarithmic],
valueStrings: nil, dependentParameters: nil)
param.value = 18_000.0
return param
}()
public let wetDryMix: AUParameter = {
let param = AUParameterTree.createParameter(
withIdentifier: "wetDryMix", name: "Mix", address: Address.wetDryMix.rawValue, min: 0.0, max: 100.0,
unit: .percent, unitName: nil, flags: [.flag_IsReadable, .flag_IsWritable], valueStrings: nil,
dependentParameters: nil)
param.value = 30.0
return param
}()
/// AUParameterTree created with the parameter definitions for the audio unit
public let parameterTree: AUParameterTree
/**
Create a new AUParameterTree for the defined filter parameters.
Installs three closures in the tree:
- one for providing values
- one for accepting new values from other sources
- and one for obtaining formatted string values
- parameter parameterHandler the object to use to handle the AUParameterTree requests
*/
public init(parameterHandler: AUParameterHandler) {
// Define a new parameter tree with the parameter definitions
parameterTree = AUParameterTree.createTree(withChildren: [time, feedback, cutoff, wetDryMix])
// Provide a way for the tree to change values in the AudioUnit
parameterTree.implementorValueObserver = parameterHandler.set
// Provide a way for the tree to obtain the current value of a parameter from the AudioUnit
parameterTree.implementorValueProvider = parameterHandler.get
// Provide a way to obtain String values for the current settings.
let log = self.log
parameterTree.implementorStringFromValueCallback = { param, value in
let formatted: String = {
switch Address(rawValue: param.address) {
case .time: return String(format: "%.2f", param.value) + "s"
case .feedback: return String(format: "%.2f", param.value) + "%"
case .cutoff: return String(format: "%.2f", param.value) + "Hz"
case .wetDryMix: return String(format: "%.2f", param.value) + "%"
default: return "?"
}
}()
os_log(.debug, log: log, "parameter %d as string: %d %f %{public}s", param.address, param.value, formatted)
return formatted
}
}
func setConfig(_ config: DelayConfig) {
os_log(.info, log: log, "setConfig")
self.time.setValue(config.time, originator: nil)
self.feedback.setValue(config.feedback, originator: nil)
self.cutoff.setValue(config.cutoff, originator: nil)
self.wetDryMix.setValue(config.wetDryMix, originator: nil)
}
func set(_ address: Address, value: AUValue, originator: AUParameterObserverToken?) {
switch address {
case .time: time.setValue(value, originator: originator)
case .feedback: feedback.setValue(value, originator: originator)
case .cutoff: cutoff.setValue(value, originator: originator)
case .wetDryMix: wetDryMix.setValue(value, originator: originator)
}
}
}
extension AUParameterTree {
func parameter(withAddress: AudioUnitParameters.Address) -> AUParameter? {
parameter(withAddress: withAddress.rawValue)
}
}
| 37.983051 | 113 | 0.707943 |
0167a2d4da601d9424d5c66244d386561d4e9593 | 820 | //
// TemplateScrollVStack.swift
//
//
// Created by emp-mac-yosuke-fujii on 2021/12/09.
//
import SwiftUI
public struct TemplateScrollVStack<Content: View>: View {
let title: String
let spacing: CGFloat
@ViewBuilder let content: () -> Content
public init(title: String, spacing: CGFloat = 8.0, @ViewBuilder content: @escaping () -> Content) {
self.title = title
self.spacing = spacing
self.content = content
}
public var body: some View {
ScrollView {
VStack(spacing: 16.0) {
Text(title).font(.title.weight(.semibold))
LazyVStack(spacing: spacing) {
content()
}
}
.padding(16.0)
}
.background(Color(UIColor.systemBackground))
}
}
| 23.428571 | 103 | 0.558537 |
76eb2f11e46f8b2c87cd909e5ec581d24810fcc7 | 1,714 | /*
/*foo:unknown*/foo() is not /*foo:unknown*/foo(first:)
*/
/// This describes /*foo:unknown*/foo and /*foo:unknown*/foo
func /*foo:def*/foo() {
let /*foo:def*/foo = "Here is /*foo:unknown*/foo"
// /*foo:unknown*/foo's return
#selector(Struct . /*foo:unknown*/foo(_:aboveSubview:))
#selector(/*foo:unknown*/foo(_:))
#selector(#selector(/*foo:unknown*/foo))
#if true
/*foo*/foo = 2
/*foo*/foo()
/*foo:call*/foo()
/*foo:unknown*/foo = 3
/*foo:unknown*/foo()
#if false
/*foo:unknown*/foo += 2
/*foo:unknown*/foo()
#endif
#else
/*foo:unknown*/foo = 4
#endif
return 1
}
#if false
class /*MyClass:unknown*/MyClass {}
_ = /*MyClass:unknown*/Mismatch()
_ = /*MyClass:unknown*/MyClass()
#else
class /*MyClass:unknown*/MyClass {}
_ = /*MyClass:unknown*/Mismatch()
_ = /*MyClass:unknown*/MyClass()
#endif
// RUN: %empty-directory(%t.result)
// RUN: %refactor -syntactic-rename -source-filename %s -pos="foo" -is-function-like -old-name "foo" -new-name "bar" >> %t.result/textual_foo.swift
// RUN: diff -u %S/Outputs/textual/foo.swift.expected %t.result/textual_foo.swift
// RUN: %refactor -syntactic-rename -source-filename %s -pos="MyClass" -is-non-protocol-type -old-name "MyClass" -new-name "YourClass" >> %t.result/textual_MyClass.swift
// RUN: diff -u %S/Outputs/textual/MyClass.swift.expected %t.result/textual_MyClass.swift
// RUN: %empty-directory(%t.ranges)
// RUN: %refactor -find-rename-ranges -source-filename %s -pos="foo" -is-function-like -old-name "foo" >> %t.ranges/textual_foo.swift
// RUN: diff -u %S/FindRangeOutputs/textual/foo.swift.expected %t.ranges/textual_foo.swift
| 36.468085 | 169 | 0.636523 |
69cbf9a9c14973d8871e5c795ecf2425b66107b6 | 3,034 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
An extension of `DataItem` that provides a static array of sample `DataItem`s.
*/
import Foundation
extension DataItem {
/// A static sample set of `DataItem`s.
static var sampleItems: [DataItem] = {
return [
DataItem(group: .Scenery, number: 1, title: "Scenery 1"),
DataItem(group: .Scenery, number: 2, title: "Scenery 2"),
DataItem(group: .Scenery, number: 3, title: "Scenery 3"),
DataItem(group: .Scenery, number: 4, title: "Scenery 4"),
DataItem(group: .Scenery, number: 5, title: "Scenery 5"),
DataItem(group: .Scenery, number: 6, title: "Scenery 6"),
DataItem(group: .Iceland, number: 1, title: "Iceland 1"),
DataItem(group: .Iceland, number: 2, title: "Iceland 2"),
DataItem(group: .Iceland, number: 3, title: "Iceland 3"),
DataItem(group: .Iceland, number: 4, title: "Iceland 4"),
DataItem(group: .Iceland, number: 5, title: "Iceland 5"),
DataItem(group: .Iceland, number: 6, title: "Iceland 6"),
DataItem(group: .Iceland, number: 7, title: "Iceland 7"),
DataItem(group: .Iceland, number: 8, title: "Iceland 8"),
DataItem(group: .Lola, number: 1, title: "Roll Over"),
DataItem(group: .Lola, number: 2, title: "Tug-of-war"),
DataItem(group: .Lola, number: 3, title: "Face Off"),
DataItem(group: .Lola, number: 4, title: "Favorite Toy"),
DataItem(group: .Baby, number: 1, title: "Baby 1"),
DataItem(group: .Baby, number: 2, title: "Baby 2"),
DataItem(group: .Baby, number: 3, title: "Baby 3"),
DataItem(group: .Baby, number: 4, title: "Baby 4"),
DataItem(group: .Baby, number: 5, title: "Baby 5"),
DataItem(group: .Baby, number: 6, title: "Baby 6"),
DataItem(group: .Baby, number: 7, title: "Baby 7"),
DataItem(group: .Baby, number: 8, title: "Baby 8")
]
}()
/// A static sample set of `DataItem`s to show on the Top Shelf with inset style.
static var sampleItemsForInsetTopShelfItems: [DataItem] = {
// Limit the items we show to the first 4 items in the `Lola` group.
let lolaItems = DataItem.sampleItems.filter { $0.group == .Lola }
return Array(lolaItems.prefix(4))
}()
/// A static sample set of `DataItem`s to show on the Top Shelf with sectioned style.
static var sampleItemsForSectionedTopShelfItems: [[DataItem]] = {
/*
Limit the items we show to the first 2 items in the `Lola` and
`Iceland` groups.
*/
return [DataItem.Group.Lola, DataItem.Group.Iceland].map { group in
let currentGroupItems = DataItem.sampleItems.filter { $0.group == group }
return Array(currentGroupItems.prefix(2))
}
}()
} | 46.676923 | 89 | 0.588332 |
90b3ddd1ec4d6bcef80cacc843f83a6784858b1f | 1,846 | //
// MenuViewController.swift
// WalrusKitExampleApp
//
// Created by Aleksei Smirnov on 29.10.2020.
//
import SwiftUI
final class MenuViewController: UIViewController {
private enum Row: String, CaseIterable {
case colors = "Colors"
case typography = "Typography"
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Design System"
let tableView = UITableView(frame: view.frame, style: .insetGrouped)
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
}
}
extension MenuViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
Row.allCases.count
}
func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = Row.allCases[indexPath.row].rawValue
cell.textLabel?.font = .boldSystemFont(ofSize: 16)
cell.accessoryType = .disclosureIndicator
return cell
}
func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let title = Row.allCases[indexPath.row].rawValue
let viewController: UIViewController
switch Row.allCases[indexPath.row] {
case .colors:
viewController = ColorsViewController()
case .typography:
viewController = TypographyViewController()
}
viewController.title = title
navigationController?.pushViewController(viewController, animated: true)
}
}
| 27.969697 | 80 | 0.652221 |
283d9c8a6483f9308cb3ef4a422d715720c777c3 | 2,055 | //
// ZHAudioProcessing.swift
// ZHWaveform_Example
//
// Created by wow250250 on 2018/1/2.
// Copyright © 2018年 wow250250. All rights reserved.
//
import UIKit
import AVFoundation
struct ZHAudioProcessing {
typealias BufferRefSuccessHandler = (NSMutableData) -> Swift.Void
typealias BufferRefFailureHandler = (Error?) -> Swift.Void
public static func bufferRef(
asset: AVAsset,
track: AVAssetTrack,
success: BufferRefSuccessHandler?,
failure: BufferRefFailureHandler?
) {
let data = NSMutableData()
let dict: [String: Any] = [AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsFloatKey: false,
AVLinearPCMBitDepthKey: 16]
do {
let reader: AVAssetReader = try AVAssetReader(asset: asset)
let output: AVAssetReaderTrackOutput = AVAssetReaderTrackOutput(track: track, outputSettings: dict)
reader.add(output)
reader.startReading()
while reader.status == .reading {
if let sampleBuffer: CMSampleBuffer = output.copyNextSampleBuffer() {
if let blockBuffer: CMBlockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) {
let length: Int = CMBlockBufferGetDataLength(blockBuffer)
var sampleBytes = [Int16](repeating: Int16(), count: length)
CMBlockBufferCopyDataBytes(blockBuffer, atOffset: 0, dataLength: length, destination: &sampleBytes)
data.append(&sampleBytes, length: length)
CMSampleBufferInvalidate(sampleBuffer)
}
}
}
if reader.status == .completed {
print("读取结束")
success?(data)
} else {
failure?(nil)
}
} catch let err {
failure?(err)
}
}
}
| 37.363636 | 123 | 0.565937 |
7145fc3941f26fc8e1dcd02565fa362cf10bf4c0 | 1,451 | //
// MagiLocalDataSource.swift
// MagiPhotoBrowser_Example
//
// Created by anran on 2018/10/26.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
public class MagiLocalDataSource: NSObject, MagiPhotoBrowserDataSource {
/// 弱引用 PhotoBrowser
public weak var browser: MagiPhotoBrowser?
/// 共有多少项
public var numberOfItemsCallback: () -> Int
/// 每一项的图片对象
public var localImageCallback: (Int) -> UIImage?
public init(numberOfItems: @escaping () -> Int,
localImage: @escaping (Int) -> UIImage?) {
self.numberOfItemsCallback = numberOfItems
self.localImageCallback = localImage
}
public func registerCell(for collectionView: UICollectionView) {
collectionView.magiPhotoBrowser.registerCell(MagiPhotoBrowserBaseCell.self)
}
// MARK: - UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItemsCallback()
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.magiPhotoBrowser.dequeueReusableCell(MagiPhotoBrowserBaseCell.self, for: indexPath)
cell.imageView.image = localImageCallback(indexPath.item)
cell.setNeedsLayout()
return cell
}
}
| 30.87234 | 128 | 0.702274 |
ddecbe843dc3e335972550dcfad9439b07a6a3ab | 5,728 | // Copyright (c) 2022 Razeware LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
// distribute, sublicense, create a derivative work, and/or sell copies of the
// Software in any work that is designed, intended, or marketed for pedagogical or
// instructional purposes related to programming, coding, application development,
// or information technology. Permission for such use, copying, modification,
// merger, publication, distribution, sublicensing, creation of derivative works,
// or sale is expressly withheld.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import SwiftUI
struct LibraryView: View {
@EnvironmentObject private var downloadService: DownloadService
@ObservedObject private var filters: Filters
@ObservedObject private var libraryRepository: LibraryRepository
@State private var filtersPresented = false
init(
filters: Filters,
libraryRepository: LibraryRepository
) {
self.filters = filters
self.libraryRepository = libraryRepository
}
var body: some View {
contentView
.navigationTitle(Text(String.library))
.sheet(isPresented: $filtersPresented) {
FiltersView(libraryRepository: libraryRepository, filters: filters)
.background(Color.background.edgesIgnoringSafeArea(.all))
}
}
}
// MARK: - private
private extension LibraryView {
var contentControlsSection: some View {
VStack {
searchAndFilterControls
.padding(.top, 15)
if !libraryRepository.currentAppliedFilters.isEmpty {
filtersView
.padding(.top, 10)
}
numberAndSortView
.padding(.vertical, 10)
}
.padding(.horizontal, .sidePadding)
.background(Color.background)
}
var searchField: some View {
SearchFieldView(searchString: filters.searchStr) { searchString in
filters.searchStr = searchString
updateFilters()
}
}
var searchAndFilterControls: some View {
HStack {
searchField
Spacer()
Button {
filtersPresented = true
} label: {
Image("filter")
.foregroundColor(.iconButton)
.frame(width: .filterButtonSide, height: .filterButtonSide)
}
.accessibility(label: Text("Filter Library"))
.padding([.horizontal], .searchFilterPadding)
}
}
var numberAndSortView: some View {
HStack {
Text("\(libraryRepository.totalContentNum) \(String.tutorials.capitalized)")
.font(.uiLabelBold)
.foregroundColor(.contentText)
Spacer()
Button {
changeSort()
} label: {
HStack {
Image("sort")
.foregroundColor(.textButtonText)
if [.loading, .loadingAdditional].contains(libraryRepository.state) {
Text(filters.sortFilter.name)
.font(.uiLabel)
.foregroundColor(.gray)
} else {
Text(filters.sortFilter.name)
.font(.uiLabelBold)
.foregroundColor(.textButtonText)
}
}
}.disabled([.loading, .loadingAdditional].contains(libraryRepository.state))
}
}
var filtersView: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: .filterSpacing) {
if filters.applied.count > 1 {
AppliedFilterTagButton(name: String.resetFilters, type: .destructive) {
filters.removeAll()
libraryRepository.filters = filters
}
}
ForEach(filters.applied, id: \.self) { filter in
AppliedFilterTagButton(name: filter.filterName, type: .default) {
if filter.isSearch {
filters.searchQuery = nil
} else {
filter.isOn.toggle()
filters.all.update(with: filter)
}
filters.commitUpdates()
libraryRepository.filters = filters
}
}
}
.padding([.horizontal], .sidePadding)
}
.padding([.horizontal], -.sidePadding)
}
func updateFilters() {
filters.searchQuery = filters.searchStr
libraryRepository.filters = filters
}
func changeSort() {
filters.changeSortFilter()
libraryRepository.filters = filters
}
var contentView: some View {
ContentListView(
contentRepository: libraryRepository,
downloadAction: downloadService,
contentScreen: .library,
header: contentControlsSection
)
}
}
private extension CGFloat {
static let filterButtonSide: CGFloat = 27
static let searchFilterPadding: CGFloat = 15
static let filterSpacing: CGFloat = 6
static let filtersPaddingTop: CGFloat = 12
}
| 31.646409 | 82 | 0.670042 |
ffd114aebd5d0ff88b5a7b066a413bbe3a57ed79 | 844 | //
// Strain.swift
// BaseProject
//
// Copyright © 2018 Wave. All rights reserved.
//
import UIKit
import ObjectMapper
class AttachmentMapper: Mappable {
var attachment: String?
var created_at : String?
var poster : String?
var id:NSNumber?
var strain_id:NSNumber?
var strain_review_id:NSNumber?
var type:String?
var updated_at:String?
var user_id:NSNumber?
required init?(map: Map){
}
func mapping(map: Map){
attachment <- map["attachment"]
created_at <- map["created_at"]
id <- map["id"]
poster <- map["poster"]
strain_id <- map["strain_id"]
strain_review_id <- map["strain_review_id"]
type <- map["type"]
updated_at <- map["updated_at"]
user_id <- map["user_id"]
}
}
| 19.627907 | 51 | 0.577014 |
f7faf94936dd9379902e1eabe00addc45ba778c4 | 214 | //
// AndesTagViewDelegate.swift
// AndesUI
//
// Created by Samuel Sainz on 6/11/20.
//
import Foundation
protocol AndesTagViewDelegate: AnyObject {
func didTapTagRightButton()
func didTapTagView()
}
| 15.285714 | 42 | 0.714953 |
f91b5f55dd93e0f6ef2cf7287ace79ffb368f71d | 7,768 | //
// GitMapLauncherApp.swift
// GGITCommon iOS
//
// Created by Kelvin Leong on 26/11/2018.
// Copyright © 2018 Grace Generation Information Technology. All Rights Reserved. All rights reserved.
//
public enum GitMapLauncherApp: String {
case appleMaps
case googleMaps // https://developers.google.com/maps/documentation/ios/urlscheme
case citymapper
case transit // http://thetransitapp.com/developers
case lyft
case uber
case navigon // http://www.navigon.com/portal/common/faq/files/NAVIGON_AppInteract.pdf
case waze
case dbnavigator
case yandex
case moovit
static var all: [GitMapLauncherApp] {
return [
.appleMaps,
.googleMaps,
.citymapper,
.transit,
.lyft,
.uber,
.navigon,
.waze,
.dbnavigator,
.yandex,
.moovit
]
}
var urlScheme: String {
switch self {
case .appleMaps: return "" // Uses System APIs, so this is just a placeholder
case .googleMaps: return "comgooglemaps://"
case .citymapper: return "citymapper://"
case .transit: return "transit://"
case .lyft: return "lyft://"
case .uber: return "uber://"
case .navigon: return "navigon://"
case .waze: return "waze://"
case .dbnavigator: return "dbnavigator://"
case .yandex: return "yandexnavi://"
case .moovit: return "moovit://"
}
}
public var name: String {
switch self {
case .appleMaps: return "Apple Maps"
case .googleMaps: return "Google Maps"
case .citymapper: return "Citymapper"
case .transit: return "Transit App"
case .lyft: return "Lyft"
case .uber: return "Uber"
case .navigon: return "Navigon"
case .waze: return "Waze"
case .dbnavigator: return "DB Navigator"
case .yandex: return "Yandex.Navi"
case .moovit: return "Moovit"
}
}
/// Validates if an app supports a mode. The given mode is optional and this defaults to `true`
/// if the mode is `nil`.
func supports(mode: GitMapLauncherMode?) -> Bool {
guard let mode = mode else {
return true
}
switch self {
case .appleMaps:
return mode != .bicycling
case .googleMaps:
return true
case .citymapper, .transit:
return mode == .transit
case .lyft, .uber:
return mode == .taxi
case .navigon:
return mode == .driving || mode == .walking
case .waze:
return mode == .driving
case .dbnavigator:
return mode == .transit
case .yandex:
return true
case .moovit:
return true
}
}
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
/// Build a query string for this app using the parameters. Returns nil if a mode is specified,
/// but not supported by this app.
func queryString(origin: GitMapLauncherLocationRepresentable?,
destination: GitMapLauncherLocationRepresentable,
mode: GitMapLauncherMode?) -> String? {
guard self.supports(mode: mode) else {
// if a mode is present, validate if the app supports it, otherwise we don't care
return nil
}
var parameters = [String: String]()
switch self {
case .appleMaps:
// Apple Maps gets special handling, since it uses System APIs
return nil
case .googleMaps:
parameters.set("saddr", origin?.coordString)
parameters.set("daddr", destination.coordString)
let modeIdentifier = mode?.identifier(for: self) as? String
parameters.set("directionsmode", modeIdentifier)
return "\(self.urlScheme)maps?\(parameters.urlParameters)"
case .citymapper:
parameters.set("endcoord", destination.coordString)
parameters.set("startcoord", origin?.coordString)
parameters.set("startname", origin?.name)
parameters.set("startaddress", origin?.address)
parameters.set("endname", destination.name)
parameters.set("endaddress", destination.address)
return "\(self.urlScheme)directions?\(parameters.urlParameters)"
case .transit:
parameters.set("from", origin?.coordString)
parameters.set("to", destination.coordString)
return "\(self.urlScheme)directions?\(parameters.urlParameters)"
case .lyft:
parameters.set("pickup[latitude]", origin?.latitude)
parameters.set("pickup[longitude]", origin?.longitude)
parameters.set("destination[latitude]", destination.latitude)
parameters.set("destination[longitude]", destination.longitude)
return "\(self.urlScheme)ridetype?id=lyft&\(parameters.urlParameters)"
case .uber:
parameters.set("action", "setPickup")
if let origin = origin {
parameters.set("pickup[latitude]", origin.latitude)
parameters.set("pickup[longitude]", origin.longitude)
} else {
parameters.set("pickup", "my_location")
}
parameters.set("dropoff[latitude]", destination.latitude)
parameters.set("dropoff[longitude]", destination.longitude)
parameters.set("dropoff[nickname]", destination.name)
return "\(self.urlScheme)?\(parameters.urlParameters)"
case .navigon:
// Docs are unclear about the name being omitted
let name = destination.name ?? "Destination"
// swiftlint:disable:next line_length
return "\(self.urlScheme)coordinate/\(name.urlQuery ?? "")/\(destination.longitude)/\(destination.latitude)"
case .waze:
// swiftlint:disable:next line_length
return "\(self.urlScheme)?ll=\(destination.latitude),\(destination.longitude)&navigate=yes"
case .dbnavigator:
if let origin = origin {
parameters.set("SKOORD", 1)
parameters.set("SNAME", origin.name)
parameters.set("SY", Int(origin.latitude * 1_000_000))
parameters.set("SX", Int(origin.longitude * 1_000_000))
}
parameters.set("ZKOORD", 1)
parameters.set("ZNAME", destination.name)
parameters.set("ZY", Int(destination.latitude * 1_000_000))
parameters.set("ZX", Int(destination.longitude * 1_000_000))
return "\(self.urlScheme)query?\(parameters.urlParameters)&start"
case .yandex:
parameters.set("lat_from", origin?.latitude)
parameters.set("lon_from", origin?.longitude)
parameters.set("lat_to", destination.latitude)
parameters.set("lon_to", destination.longitude)
return "\(self.urlScheme)build_route_on_map?\(parameters.urlParameters)"
case .moovit:
parameters.set("origin_lat", origin?.latitude)
parameters.set("origin_lon", origin?.longitude)
parameters.set("orig_name", origin?.name)
parameters.set("dest_lat", destination.latitude)
parameters.set("dest_lon", destination.longitude)
parameters.set("dest_name", destination.name)
return "\(self.urlScheme)directions?\(parameters.urlParameters)"
}
}
// swiftlint:enable function_body_length
// swiftlint:enable cyclomatic_complexity
}
| 40.248705 | 120 | 0.59346 |
3abe87ce3f61cdbcd207088c3be4543700938a97 | 629 | //
// ContentBlockerRequestHandler.swift
// MyMacContentBlocker
//
// Created by Jeff Kelley on 3/16/17.
// Copyright © 2017 Jeff Kelley. All rights reserved.
//
import Foundation
class ContentBlockerRequestHandler: NSObject, NSExtensionRequestHandling {
func beginRequest(with context: NSExtensionContext) {
let attachment = NSItemProvider(contentsOf: Bundle.main.url(forResource: "blockerList", withExtension: "json"))!
let item = NSExtensionItem()
item.attachments = [attachment]
context.completeRequest(returningItems: [item], completionHandler: nil)
}
}
| 27.347826 | 120 | 0.702703 |
fb407f1739890fa691c6c6533fb2e3c95cd0b396 | 772 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
re g{ enum b = c("))
let a{}()
}class A {
a
B<T where g:b(")
class d>(_ = c{
import Foundation
func f.C{let:T? = [Void{
class A {
class d<f<T : {
init()
var b<T : T
if true{
T] {
init()
class A{
if tocol c(){
struct S <T.c
var a
struct Q<T where H:T.c()
class A : {enum b {
class B:P{
end " ( 1 ]
var a{
struct c(){
class B<C<d<d<d<T{}struct S< C {
func c(_ = F>()
struct A<
class C<T {
struct S< {
class B< g<T where T.e: {let v{{}
b{{
var b:T.c{ enum b<T{
let c{
var b(_ = 0
B
func f<T : T.c{ enum b = e
class A : a {
if true {}class B:P{
class C{
struct
| 16.083333 | 87 | 0.61658 |
878ba7ac723021660419c4e242824a5d2f2a2d44 | 2,673 | //
// SceneDelegate.swift
// SwiftUI Transforms and Animations
//
// Created by Ben Scheirman on 7/9/19.
// Copyright © 2019 Fickle Bits. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.112903 | 147 | 0.708567 |
5bb16f74242513f2720b7478ecb489457477bd41 | 2,300 | //
// SceneDelegate.swift
// GithubUserListInfinite
//
// Created by Hafiz on 22/06/2021.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.396226 | 147 | 0.714348 |
3aca606591a0d43bc95396acda8a017879bfd20c | 601 | //
// ViewController.swift
// Settings
//
// Created by Daniel Henshaw on 8/5/19.
// Copyright © 2019 Dan Henshaw. All rights reserved.
//
import UIKit
@nonobjc extension UIViewController {
func add(_ child: UIViewController) {
addChild(child)
child.view.frame = CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: 0)
view.addSubview(child.view)
child.didMove(toParent: self)
}
func remove() {
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}
| 22.259259 | 117 | 0.62396 |
1ae5c8ecadadc3b3d1b04ed687691219f75c34cb | 596 | //
// ACRouterRequest.swift
// ACRouter
//
// Created by SnowCheng on 11/03/2017.
// Copyright © 2017 Archerlly. All rights reserved.
//
import Foundation
class ACRouterRequest: ACRouterParser {
var urlString: String
var sheme: String
var paths: [String]
var queries: [String: AnyObject]
init(_ urlString: String) {
self.urlString = urlString
self.sheme = ACRouterRequest.parserSheme(urlString)
let result = ACRouterRequest.parser(urlString)
self.paths = result.paths
self.queries = result.queries
}
}
| 21.285714 | 59 | 0.645973 |
dda6fcc2a4d853c014a3c173a490119cbb68fdc7 | 6,874 | //
// YouBikeManager.swift
// YouBike
//
// Created by Sarah on 5/4/16.
// Copyright © 2016 AppWorks School Sarah Lee. All rights reserved.
//
import UIKit
import Alamofire
import JWT
import CoreData
import UILoadControl
protocol YouBikeManagerDelegate: class {
func getStationsDidFinish()
func didFinishPostRequest()
}
//MARK: - Data Storage
class StationDatas{
var titleCn: String = ""
var titleEn: String = ""
var locationCn: String = ""
var locationEn: String = ""
var available: Int = 0
var lat: Double = 0.0
var lng: Double = 0.0
init(){
}
init(titleCn:String, titleEn:String, locationCn: String, locationEn:String, available: Int, lat: Double, lng: Double){
self.titleCn = titleCn
self.titleEn = titleEn
self.locationCn = locationCn
self.locationEn = locationEn
self.available = available
self.lat = lat
self.lng = lng
}
}
extension StationDatas {
var title: String {
let currentLanguage = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) ?? "en"
return (currentLanguage as? String == "zh") ? titleCn : titleEn
}
var location: String {
let currentLanguage = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) ?? "en"
return (currentLanguage as? String == "zh") ? locationCn : locationEn
}
}
// MARK - YouBikeManager
class YouBikeManager{
static let sharedManager = YouBikeManager()
var stations = [StationDatas]()
weak var tableViewDelegate: YouBikeManagerDelegate?
weak var collectionViewDelegate: YouBikeManagerDelegate?
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var stationNextToken: String?
var stationPreviousToken: String?
var commentNextToken: String?
var commentPreviousToken: String?
func YouBikeGetJsonRequest(){
let URL = "http://data.taipei/youbike"
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
Alamofire.request(
.GET,
URL,
encoding: .JSON)
.validate()
.responseJSON {
response in
if let stationdatas = response.result.value as? [String: AnyObject] {
self.cleanUpStation()
self.readJSONObject(stationdatas)
}else{
print("Parsing Json file failed...")
}
self.readStation()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableViewDelegate?.getStationsDidFinish()
})
}
})
}
func readJSONObject(objects: [String: AnyObject]){
for objects in objects.values{
guard let data = objects as? [String: AnyObject] else { return }
for object in data.values {
guard let station = object as? [String: AnyObject] else { return }
if let sna = station["sna"] as? String,
let snaen = station["snaen"] as? String,
let ar = station["ar"] as? String,
let aren = station["aren"] as? String,
let ssbi = station["sbi"] as? String,
let sbi = Int(ssbi),
let llat = station["lat"] as? String,
let lat = Double(llat),
let llng = station["lng"] as? String,
let lng = Double(llng) {
self.addStation(
titleCn: sna,
titleEn: snaen,
locationCn: ar,
locationEn: aren,
available: sbi,
lat: lat,
lng: lng
)
}
}
}
}
}
// MARK: - Core Data CRUD
extension YouBikeManager{
func addStation(titleCn titleCn: String, titleEn: String, locationCn: String, locationEn: String, available: Int, lat: Double, lng: Double){
let station = NSEntityDescription.insertNewObjectForEntityForName("Station", inManagedObjectContext: self.moc) as! Station
station.titleCn = titleCn
station.titleEn = titleEn
station.locationCn = locationCn
station.locationEn = locationEn
station.available = available
station.lat = lat
station.lng = lng
do{
// the new entity is store in the memory now, use save() to save into disk
try self.moc.save()
}catch{
fatalError("Failed to save context: \(error)")
}
}
func cleanUpStation(){
let request = NSFetchRequest(entityName: "Station")
do{
let results = try moc.executeFetchRequest(request) as! [Station]
for result in results{
moc.deleteObject(result)
}
do{
try moc.save()
}catch{
fatalError("Failed to save context: \(error)")
}
}catch{
fatalError("failed to fetch data: \(error)")
}
}
func readStation(){
let request = NSFetchRequest(entityName: "Station")
do{
let stations = try moc.executeFetchRequest(request) as! [Station]
for station in stations {
guard
let titleCn = station.titleCn,
let titleEn = station.titleEn,
let locationCn = station.locationCn,
let locationEn = station.locationEn,
let available = station.available as? Int,
let lat = station.lat as? Double,
let lng = station.lng as? Double
else { continue }
YouBikeManager.sharedManager.stations.append(
StationDatas(
titleCn: titleCn,
titleEn: titleEn,
locationCn: locationCn,
locationEn: locationEn,
available: available,
lat: lat,
lng: lng
)
)
}
}catch{
fatalError("Failed to fetch data: \(error)")
}
}
}
| 28.641667 | 144 | 0.502619 |
fc29dbd1465a3172797821c355c60efb56b020e7 | 222 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts
_ = [0,1,2,3].lazy.map { String($0)+"hi" }.sorted(by: { $0 > $1 })
// expected-error@-1 {{reasonable time}}
| 37 | 74 | 0.666667 |
6a3faf448c699d976ee859361c65c8ed9a745e6b | 17,469 | //
// PerfectLibTests.swift
// PerfectLibTests
//
// Created by Kyle Jessup on 2015-10-19.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import XCTest
@testable import PerfectLib
#if os(Linux)
import SwiftGlibc
import Foundation
#endif
class PerfectLibTests: XCTestCase {
override func setUp() {
super.setUp()
#if os(Linux)
SwiftGlibc.srand(UInt32(time(nil)))
#endif
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testJSONConvertibleObject1() {
class Test: JSONConvertibleObject {
static let registerName = "test"
var one = 0
override func setJSONValues(_ values: [String : Any]) {
self.one = getJSONValue(named: "One", from: values, defaultValue: 42)
}
override func getJSONValues() -> [String : Any] {
return [JSONDecoding.objectIdentifierKey:Test.registerName, "One":1]
}
}
JSONDecoding.registerJSONDecodable(name: Test.registerName, creator: { return Test() })
do {
let encoded = try Test().jsonEncodedString()
let decoded = try encoded.jsonDecode() as? Test
XCTAssert(decoded != nil)
XCTAssert(decoded!.one == 1)
} catch {
XCTAssert(false, "Exception \(error)")
}
}
func testJSONConvertibleObject2() {
class User: JSONConvertibleObject {
static let registerName = "user"
var firstName = ""
var lastName = ""
var age = 0
override func setJSONValues(_ values: [String : Any]) {
self.firstName = getJSONValue(named: "firstName", from: values, defaultValue: "")
self.lastName = getJSONValue(named: "lastName", from: values, defaultValue: "")
self.age = getJSONValue(named: "age", from: values, defaultValue: 0)
}
override func getJSONValues() -> [String : Any] {
return [
JSONDecoding.objectIdentifierKey:User.registerName,
"firstName":firstName,
"lastName":lastName,
"age":age
]
}
}
// register the class. do this once
JSONDecoding.registerJSONDecodable(name: User.registerName, creator: { return User() })
// encode and decode the object
let user = User()
user.firstName = "Donnie"
user.lastName = "Darko"
user.age = 17
do {
let encoded = try user.jsonEncodedString()
guard let user2 = try encoded.jsonDecode() as? User else {
return XCTAssert(false, "Invalid object \(encoded)")
}
XCTAssert(user.firstName == user2.firstName)
XCTAssert(user.lastName == user2.lastName)
XCTAssert(user.age == user2.age)
} catch {}
}
func testJSONEncodeDecode() {
let srcAry: [[String:Any]] = [["i": -41451, "i2": 41451, "d": -42E+2, "t": true, "f": false, "n": nil as String? as Any, "a":[1, 2, 3, 4]], ["another":"one"]]
var encoded = ""
var decoded: [Any]?
do {
encoded = try srcAry.jsonEncodedString()
} catch let e {
XCTAssert(false, "Exception while encoding JSON \(e)")
return
}
do {
decoded = try encoded.jsonDecode() as? [Any]
} catch let e {
XCTAssert(false, "Exception while decoding JSON \(e)")
return
}
XCTAssert(decoded != nil)
let resAry = decoded!
XCTAssert(srcAry.count == resAry.count)
for index in 0..<srcAry.count {
let d1 = srcAry[index]
let d2 = resAry[index] as? [String:Any]
for (key, value) in d1 {
let value2 = d2![key]
XCTAssert(value2 != nil)
switch value {
case let i as Int:
XCTAssert(i == value2 as! Int)
case let d as Double:
XCTAssert(d == value2 as! Double)
case let s as String:
XCTAssert(s == value2 as! String)
case let s as Bool:
XCTAssert(s == value2 as! Bool)
default:
()
// does not go on to test sub-sub-elements
}
}
}
}
func testIntegerTypesEncode(){
let i8:Int8 = -12
let i16:Int16 = -1234
let i32:Int32 = -1234567890
let i64:Int64 = -123456789012345678
let u8:UInt8 = 12
let u16:UInt16 = 1234
let u32:UInt32 = 1234567890
let u64:UInt64 = 123456789012345678
var srcDict:[String:Any] = [String:Any]()
var destDict:[String:Any]?
srcDict["i8"] = i8
srcDict["i16"] = i8
srcDict["i32"] = i8
srcDict["i64"] = i8
srcDict["u8"] = i8
srcDict["u16"] = i8
srcDict["u32"] = i8
srcDict["u64"] = i8
var encoded = ""
do {
encoded = try i8.jsonEncodedString()
XCTAssert(encoded == String(i8), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding i8 \(e)")
return
}
do {
encoded = try i16.jsonEncodedString()
XCTAssert(encoded == String(i16), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding i16 \(e)")
return
}
do {
encoded = try i32.jsonEncodedString()
XCTAssert(encoded == String(i32), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding i32 \(e)")
return
}
do {
encoded = try i64.jsonEncodedString()
XCTAssert(encoded == String(i64), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding i64 \(e)")
return
}
do {
encoded = try u8.jsonEncodedString()
XCTAssert(encoded == String(u8), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding u8 \(e)")
return
}
do {
encoded = try u16.jsonEncodedString()
XCTAssert(encoded == String(u16), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding u16 \(e)")
return
}
do {
encoded = try u32.jsonEncodedString()
XCTAssert(encoded == String(u32), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding u32 \(e)")
return
}
do {
encoded = try u64.jsonEncodedString()
XCTAssert(encoded == String(u64), "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding u64 \(e)")
return
}
do {
encoded = ""
encoded = try srcDict.jsonEncodedString()
XCTAssert(encoded != "", "Invalid result")
} catch let e {
XCTAssert(false, "Exception while encoding srcDict \(e)")
}
do {
destDict = try encoded.jsonDecode() as? [String:Any]
} catch let e {
XCTAssert(false, "Exception while decoding into destDict \(e)" )
}
for (key, value) in destDict! {
let value2 = srcDict[key]
XCTAssert(value2 != nil)
switch value2 {
case let i as Int8:
XCTAssert(value as! Int == Int(i))
case let i as Int16:
XCTAssert(value as! Int == Int(i))
case let i as Int32:
XCTAssert(value as! Int == Int(i))
case let i as Int64:
XCTAssert(value as! Int == Int(i))
case let i as UInt8:
XCTAssert(value as! Int == Int(i))
case let i as UInt16:
XCTAssert(value as! Int == Int(i))
case let i as UInt32:
XCTAssert(value as! Int == Int(i))
case let i as UInt64:
XCTAssert(value as! Int == Int(i))
default:
()
}
}
}
func testJSONDecodeUnicode() {
var decoded: [String: Any]?
let jsonStr = "{\"emoji\": \"\\ud83d\\ude33\"}" // {"emoji": "\ud83d\ude33"}
do {
decoded = try jsonStr.jsonDecode() as? [String: Any]
} catch let e {
XCTAssert(false, "Exception while decoding JSON \(e)")
return
}
XCTAssert(decoded != nil)
let value = decoded!["emoji"]
XCTAssert(value != nil)
let emojiStr = decoded!["emoji"] as! String
XCTAssert(emojiStr == "😳")
}
func testSysProcess() {
do {
let proc = try SysProcess("ls", args:["-l", "/"], env:[("PATH", "/usr/bin:/bin")])
XCTAssertTrue(proc.isOpen())
XCTAssertNotNil(proc.stdin)
let fileOut = proc.stdout!
let data = try fileOut.readSomeBytes(count: 4096)
XCTAssertTrue(data.count > 0)
let waitRes = try proc.wait()
XCTAssert(0 == waitRes, "\(waitRes) \(UTF8Encoding.encode(bytes: data))")
proc.close()
} catch {
XCTAssert(false, "Exception running SysProcess test: \(error)")
}
}
func testSysProcessGroup() {
do {
let proc = try SysProcess("sh", args: ["-c", "(sleep 10s &) ; (sleep 10s &) ; sleep 10s"], env: [("PATH", "/usr/bin:/bin")], newGroup: true)
XCTAssert(proc.isOpen())
XCTAssertNotEqual(-1, proc.pid)
XCTAssertNotEqual(-1, proc.gid)
// Ensure that the process group is different from the test process
#if os(Linux)
let testGid = SwiftGlibc.getpgrp()
#else
let testGid = Darwin.getpgrp()
#endif
XCTAssertNotEqual(testGid, proc.gid)
let savedGid = proc.gid
XCTAssertTrue(try hasChildProcesses(gid: savedGid))
_ = try proc.killGroup()
XCTAssertFalse(try hasChildProcesses(gid: savedGid))
} catch {
XCTAssert(false, "Exception running SysProcess group test: \(error)")
}
}
private func hasChildProcesses(gid: pid_t) throws -> Bool {
let proc = try SysProcess("sh", args: ["-c", "ps -e -o pgid,comm | grep \(gid)"], env: [("PATH", "/usr/bin:/bin")])
_ = try proc.wait()
if let bytes = try proc.stdout?.readSomeBytes(count: 4096) {
return bytes.count > 0
} else {
return false
}
}
func testStringByEncodingHTML() {
let src = "<b>\"quoted\" '& ☃"
let res = src.stringByEncodingHTML
XCTAssertEqual(res, "<b>"quoted" '& ☃")
}
func testStringByEncodingURL() {
let src = "This has \"weird\" characters & ßtuff"
let res = src.stringByEncodingURL
XCTAssertEqual(res, "This%20has%20%22weird%22%20characters%20&%20%C3%9Ftuff")
}
func testStringByDecodingURL() {
let src = "This has \"weird\" characters & ßtuff"
let mid = src.stringByEncodingURL
guard let res = mid.stringByDecodingURL else {
XCTAssert(false, "Got nil String")
return
}
XCTAssert(res == src, "Bad URL decoding")
}
func testStringByDecodingURL2() {
let src = "This is badly%PWencoded"
let res = src.stringByDecodingURL
XCTAssert(res == nil, "Bad URL decoding")
}
func testStringByReplacingString() {
let src = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
let test = "ABCFEDGHIJKLMNOPQRSTUVWXYZABCFEDGHIJKLMNOPQRSTUVWXYZABCFEDGHIJKLMNOPQRSTUVWXYZ"
let find = "DEF"
let rep = "FED"
let res = src.stringByReplacing(string: find, withString: rep)
XCTAssert(res == test)
}
func testStringByReplacingString2() {
let src = ""
let find = "DEF"
let rep = "FED"
let res = src.stringByReplacing(string: find, withString: rep)
XCTAssert(res == src)
}
func testStringByReplacingString3() {
let src = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
let find = ""
let rep = "FED"
let res = src.stringByReplacing(string: find, withString: rep)
XCTAssert(res == src)
}
func testStringBeginsWith() {
let a = "123456"
XCTAssert(a.begins(with: "123"))
XCTAssert(!a.begins(with: "abc"))
}
func testStringEndsWith() {
let a = "123456"
XCTAssert(a.ends(with: "456"))
XCTAssert(!a.ends(with: "abc"))
}
func testDeletingPathExtension() {
let path = "/a/b/c.txt"
let del = path.deletingFileExtension
XCTAssert("/a/b/c" == del)
}
func testGetPathExtension() {
let path = "/a/b/c.txt"
let ext = path.filePathExtension
XCTAssert("txt" == ext)
}
func testDirCreate() {
let path = "/tmp/a/b/c/d/e/f/g"
do {
try Dir(path).create()
XCTAssert(Dir(path).exists)
var unPath = path
while unPath != "/tmp" {
try Dir(unPath).delete()
unPath = unPath.deletingLastFilePathComponent
}
} catch {
XCTAssert(false, "Error while creating dirs: \(error)")
}
}
func testDirCreateRel() {
let path = "a/b/c/d/e/f/g"
do {
try Dir(path).create()
XCTAssert(Dir(path).exists)
var unPath = path
repeat {
try Dir(unPath).delete()
// this was killing linux on the final path component
//unPath = unPath.stringByDeletingLastPathComponent
var splt = unPath.split(separator: "/").map(String.init)
splt.removeLast()
unPath = splt.joined(separator: "/")
} while !unPath.isEmpty
} catch {
XCTAssert(false, "Error while creating dirs: \(error)")
}
}
func testDirForEach() {
let dirs = ["a/", "b/", "c/"]
do {
try Dir("/tmp/a").create()
for d in dirs {
try Dir("/tmp/a/\(d)").create()
}
var ta = [String]()
try Dir("/tmp/a").forEachEntry {
name in
ta.append(name)
}
ta.sort()
XCTAssert(ta == dirs, "\(ta) == \(dirs)")
for d in dirs {
try Dir("/tmp/a/\(d)").delete()
}
try Dir("/tmp/a").delete()
} catch {
XCTAssert(false, "Error while creating dirs: \(error)")
}
}
func testFilePerms() {
let fileName = "/tmp/\(UUID().uuidString)"
let file = File(fileName)
do {
try file.open(.readWrite, permissions: [.readUser, .writeUser])
defer {
file.delete()
}
let res = file.perms.contains([.readUser, .writeUser])
XCTAssert(res, "\(file.perms) != \([File.PermissionMode.readUser, File.PermissionMode.writeUser])")
} catch {
XCTAssert(false, "Error testing file perms: \(error)")
}
}
func testDirPerms() {
let fileName = "/tmp/\(UUID().uuidString)"
let file = Dir(fileName)
do {
try file.create(perms: [.readUser, .writeUser])
let res = file.perms.contains([.readUser, .writeUser])
XCTAssert(res, "\(file.perms) != \([File.PermissionMode.readUser, File.PermissionMode.writeUser])")
try file.delete()
} catch {
XCTAssert(false, "Error testing file perms: \(error)")
}
}
func testDirWorkDir() {
let workDir = File("/tmp").realPath.replacingOccurrences(of: "//", with: "/") + "/"
let dir = Dir(workDir)
do {
try dir.setAsWorkingDir()
let fetch = Dir.workingDir.path
XCTAssertEqual(workDir, fetch)
} catch {
XCTAssert(false, "Error testing file perms: \(error)")
}
}
func testBytesIO() {
let i8 = 254 as UInt8
let i16 = 54045 as UInt16
let i32 = 4160745471 as UInt32
let i64 = 17293541094125989887 as UInt64
let bytes = Bytes()
bytes.import64Bits(from: i64)
.import32Bits(from: i32)
.import16Bits(from: i16)
.import8Bits(from: i8)
let bytes2 = Bytes()
bytes2.importBytes(from: bytes)
XCTAssert(i64 == bytes2.export64Bits())
XCTAssert(i32 == bytes2.export32Bits())
XCTAssert(i16 == bytes2.export16Bits())
bytes2.position -= MemoryLayout<UInt16>.size
XCTAssert(i16 == bytes2.export16Bits())
XCTAssert(bytes2.availableExportBytes == 1)
XCTAssert(i8 == bytes2.export8Bits())
}
func testSymlink() {
let f1 = File("./foo")
let f2 = File("./foo2")
do {
f2.delete()
try f1.open(.truncate)
try f1.write(string: "test")
f1.close()
defer {
f1.delete()
f2.delete()
}
let newF2 = try f1.linkTo(path: f2.path)
XCTAssert(try newF2.readString() == "test")
XCTAssert(newF2.isLink)
} catch {
XCTAssert(false, "\(error)")
}
}
}
extension PerfectLibTests {
static var allTests : [(String, (PerfectLibTests) -> () throws -> Void)] {
return [
("testJSONConvertibleObject1", testJSONConvertibleObject1),
("testJSONConvertibleObject2", testJSONConvertibleObject2),
("testJSONEncodeDecode", testJSONEncodeDecode),
("testJSONDecodeUnicode", testJSONDecodeUnicode),
("testSysProcess", testSysProcess),
("testSysProcessGroup", testSysProcessGroup),
("testStringByEncodingHTML", testStringByEncodingHTML),
("testStringByEncodingURL", testStringByEncodingURL),
("testStringByDecodingURL", testStringByDecodingURL),
("testStringByDecodingURL2", testStringByDecodingURL2),
("testStringByReplacingString", testStringByReplacingString),
("testStringByReplacingString2", testStringByReplacingString2),
("testStringByReplacingString3", testStringByReplacingString3),
("testDeletingPathExtension", testDeletingPathExtension),
("testGetPathExtension", testGetPathExtension),
("testDirCreate", testDirCreate),
("testDirCreateRel", testDirCreateRel),
("testDirForEach", testDirForEach),
("testFilePerms", testFilePerms),
("testDirPerms", testDirPerms),
("testBytesIO", testBytesIO),
("testIntegerTypesEncode", testIntegerTypesEncode)
]
}
}
| 25.841716 | 160 | 0.604156 |
117469ca0d69363d18868093e7d4b3978a79161a | 1,979 | //
// LoggedOutInteractor.swift
// TicTacToe
//
// Created by L.Grigoreva on 04.08.2021.
// Copyright © 2021 Uber. All rights reserved.
//
import RIBs
import RxSwift
protocol LoggedOutRouting: ViewableRouting {
// TODO: Declare methods the interactor can invoke to manage sub-tree via the router.
}
protocol LoggedOutPresentable: Presentable {
var listener: LoggedOutPresentableListener? { get set }
// TODO: Declare methods the interactor can invoke the presenter to present data.
}
protocol LoggedOutListener: AnyObject {
// TODO: Declare methods the interactor can invoke to communicate with other RIBs.
}
final class LoggedOutInteractor: PresentableInteractor<LoggedOutPresentable>, LoggedOutInteractable, LoggedOutPresentableListener {
weak var router: LoggedOutRouting?
weak var listener: LoggedOutListener?
// TODO: Add additional dependencies to constructor. Do not perform any logic
// in constructor.
override init(presenter: LoggedOutPresentable) {
super.init(presenter: presenter)
presenter.listener = self
}
override func didBecomeActive() {
super.didBecomeActive()
// TODO: Implement business logic here.
}
override func willResignActive() {
super.willResignActive()
// TODO: Pause any business logic.
}
// MARK: - LoggedOutPresentableListener
func login(withPlayer1Name player1Name: String?, player2Name: String?) {
let player1NameWithDefault = playerName(player1Name, withDefaultName: "Player 1")
let player2NameWithDefault = playerName(player2Name, withDefaultName: "Player 2")
print("\(player1NameWithDefault) vs \(player2NameWithDefault)")
}
private func playerName(_ name: String?, withDefaultName defaultName: String) -> String {
if let name = name {
return name.isEmpty ? defaultName : name
} else {
return defaultName
}
}
}
| 31.412698 | 131 | 0.698332 |
e9161ca31f460e2d323a8e1286e0932c2e20350d | 6,037 | import Foundation
import ExpressiveCasting
import PackageManagerKit
import ATVersionKit
import ATPathSpec
public class Action : LRManifestBasedObject {
public let container: ActionContainer
public let identifier: String
public let name: String
public var kind: ActionKind
public let ruleType: Rule.Type
public let rowClassName: String
private let fakeChangeExtension: String?
public let combinedIntrinsicInputPathSpec: ATPathSpec
public private(set) var packageConfigurations: [LRAssetPackageConfiguration]!
public private(set) var manifestLayers: [LRManifestLayer]!
public var primaryVersionSpace: LRVersionSpace?
public let compilableFileTag: Tag?
public let taggers: [Tagger]
public private(set) var derivers: [Deriver]!
public init(manifest: [String: AnyObject], container: ActionContainer) {
self.container = container
let identifier = manifest["id"]~~~ ?? ""
self.identifier = identifier
name = manifest["name"]~~~ ?? identifier
// if (_identifier.length == 0)
// [self addErrorMessage:@"'id' attribute is required"];
// if (_kind == ActionKindUnknown)
// [self addErrorMessage:[NSString stringWithFormat:@"'kind' attribute is required and must be one of %@", LRValidActionKindStrings()]];
let type = manifest["type"]~~~ ?? ""
switch type {
case "filter":
kind = .Filter
ruleType = FilterRule.self
rowClassName = "FilterRuleRow"
case "compile-file":
kind = .Compiler
ruleType = CompileFileRule.self
rowClassName = "CompileFileRuleRow"
case "compile-folder":
kind = .Postproc
ruleType = CompileFolderRule.self
rowClassName = "FilterRuleRow"
case "run-tests":
kind = .Postproc
ruleType = RunTestsRule.self
rowClassName = "FilterRuleRow"
case "custom-command":
kind = .Postproc
ruleType = CustomCommandRule.self
rowClassName = "CustomCommandRuleRow"
case "user-script":
kind = .Postproc
ruleType = UserScriptRule.self
rowClassName = "UserScriptRuleRow"
default:
fatalError("Missing or unknown action type")
}
if let inputPathSpecString: String = manifest["input"]~~~ {
combinedIntrinsicInputPathSpec = ATPathSpec(string: inputPathSpecString, syntaxOptions:.FlavorExtended)
} else {
combinedIntrinsicInputPathSpec = ATPathSpec.emptyPathSpec()
}
if let outputSpecString: String = manifest["output"]~~~ {
if (outputSpecString == "*.css") {
fakeChangeExtension = "css"
} else {
fakeChangeExtension = nil
}
} else {
fakeChangeExtension = nil
}
var taggers: [Tagger] = []
if kind == .Compiler {
compilableFileTag = Tag(name: "compilable.\(identifier)")
taggers.append(FileSpecTagger(spec: combinedIntrinsicInputPathSpec, tag: compilableFileTag!))
} else {
compilableFileTag = nil
}
self.taggers = taggers
super.init(manifest: manifest, errorSink: nil)
var derivers: [Deriver] = []
if kind == .Compiler {
derivers.append(CompileFileRuleDeriver(action: self))
}
self.derivers = derivers
// Manifests
let packageManager = ActionKitSingleton.sharedActionKit.packageManager
let versionInfo = (manifest["versionInfo"] as? [String: AnyObject]) ?? [:]
let versionInfoLayers = versionInfo.mapIf { (packageRefString, info) -> LRManifestLayer? in
// no idea what this check means
if packageRefString.hasPrefix("__") {
return nil
}
let reference = packageManager.packageReferenceWithString(packageRefString)!
return LRManifestLayer(manifest: info as! [String: AnyObject], requiredPackageReferences: [reference], errorSink: self)
}
let infoDictionaries = ArrayValue(manifest["info"]) { $0 as? [String: AnyObject] } ?? []
manifestLayers = infoDictionaries.map { LRManifestLayer(manifest: $0, errorSink: self) } + versionInfoLayers
let packageConfigurationManifests = ArrayValue(manifest["packages"]) { ArrayValue($0) { StringValue($0) } } ?? []
packageConfigurations = packageConfigurationManifests.map { packagesManifest in
return LRAssetPackageConfiguration(manifest: ["packages": packagesManifest], errorSink: self)
}
if packageConfigurations.isEmpty {
primaryVersionSpace = nil
} else {
// wow, that's quite a chain
primaryVersionSpace = packageConfigurations[0].packageReferences[0].type.versionSpace
}
}
public override var description: String {
return "\(kind) '\(identifier)'"
}
public func fakeChangeDestinationPathForSourceFile(file: ProjectFile) -> RelPath? {
guard kind == .Compiler else {
return nil
}
guard let fakeChangeExtension = fakeChangeExtension else {
return nil
}
guard !file.path.hasPathExtension(fakeChangeExtension) else {
return nil
}
guard let details = combinedIntrinsicInputPathSpec.includesWithDetails(file.path) else {
return nil
}
guard let suffix = details.matchedSuffix else {
return nil
}
let (path, found) = file.path.replacePathExtension(suffix, fakeChangeExtension)
if found {
return path
} else {
return nil
}
}
public func newRule(contextAction contextAction: LRContextAction, memento: JSONObject?) -> Rule {
return ruleType.init(contextAction: contextAction, memento: memento)
}
}
| 35.934524 | 148 | 0.621004 |
5d6c30f3534ebae6ea4ccd15ac4d812ef8810efa | 3,156 | //
// StubManager.swift
// PadelLessonLogTests
//
// Created by Yoshitaka Tanaka on 2022/01/08.
//
import Quick
@testable import PadelLessonLog
import Foundation
import CoreData
class StubManager {
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
var managedObjectContext: NSManagedObjectContext?
init() {
setUpStubCoreData()
}
func setUpStubCoreData() {
let storeCoordinator = appDelegate.persistentContainer.persistentStoreCoordinator
do {
try storeCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch let error as NSError {
print("\(error) \(error.userInfo)")
abort()
}
managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
guard let managedObjectContext = managedObjectContext else { return }
managedObjectContext.persistentStoreCoordinator = storeCoordinator
}
func createStubLessonData() -> Lesson {
let lessonData = NSEntityDescription.insertNewObject(forEntityName: CoreDataObjectType.lesson.rawValue, into: managedObjectContext!) as! Lesson
lessonData.id = UUID()
lessonData.timeStamp = Date()
lessonData.title = "TEST DATA"
lessonData.setValue(R.image.img_court(compatibleWith: .current)!.pngData(), forKey: "image")
lessonData.setValue(1, forKey: "imageOrientation")
let lessonStep = NSEntityDescription.insertNewObject(forEntityName: CoreDataObjectType.lessonStep.rawValue, into: managedObjectContext!) as! LessonStep
lessonStep.lessonID = UUID()
lessonStep.orderNum = Int16(0)
lessonStep.explication = "TEST DATA"
lessonData.addToSteps(lessonStep)
// saveContext()
return lessonData
}
func createStubDummmyLessonData() -> Lesson {
let lessonData = NSEntityDescription.insertNewObject(forEntityName: CoreDataObjectType.lesson.rawValue, into: managedObjectContext!) as! Lesson
lessonData.id = UUID()
lessonData.timeStamp = Date()
lessonData.title = "DUMMY DATA"
lessonData.setValue(R.image.img_court(compatibleWith: .current)!.pngData(), forKey: "image")
lessonData.setValue(2, forKey: "imageOrientation")
let lessonStep = NSEntityDescription.insertNewObject(forEntityName: CoreDataObjectType.lessonStep.rawValue, into: managedObjectContext!) as! LessonStep
lessonStep.lessonID = UUID()
lessonStep.orderNum = Int16(0)
lessonStep.explication = "DUMMY DATA"
lessonData.addToSteps(lessonStep)
return lessonData
}
func saveContext() {
guard let managedObjectContext = managedObjectContext else { return }
managedObjectContext.mergePolicy = NSOverwriteMergePolicy
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch let error {
print(error)
}
}
}
}
| 39.45 | 159 | 0.684728 |
62b09fcaea64bcbb7f0079df67058b54d1647f8a | 929 | //
// MustacheDemoOSXTests.swift
// MustacheDemoOSXTests
//
// Created by Gwendal Roué on 11/02/2015.
// Copyright (c) 2015 Gwendal Roué. All rights reserved.
//
import Cocoa
import XCTest
class MustacheDemoOSXTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.108108 | 111 | 0.625404 |
8fed5bc6eeddf05b11fe8de4b122b0c07b320796 | 8,717 | //
// AppManager.swift
// HitPay
//
// Created by nitin muthyala on 9/9/16.
// Copyright © 2016 Ezypayzy. All rights reserved.
//
import Foundation
import LocalAuthentication
import KeychainSwift
import Alamofire
import SwiftyJSON
import StoreKit
#if MAIN_APP
import Firebase
import FirebaseInstanceID
#endif
class AppManager
{
static func checkSighUpStatus() -> Bool {
let token = getFromKeychain(AppConstants.KEYCHIN_ACESS_TOKEN)
//let tokenAuthenti = getFromKeychain(AppConstants.KEYCHIN_AUTHENTICATION_TOKEN)
if let token = token, !token.isEmpty {
return true
}
if self.getString(AppConstants.PREF_USER_TOKEN) != nil {
return true
}
// if let tokenAuthenti = tokenAuthenti, !tokenAuthenti.isEmpty {
// return true
// }
return false
}
// Using UserDefault
static func getToken() -> String?{
return self.getString(AppConstants.PREF_USER_TOKEN)
}
static func setToKeychain(_ key:String,value:String){
let keychain = KeychainSwift()
keychain.accessGroup = AppConstants.APP_GROUP
keychain.set(value, forKey:key)
}
static func getFromKeychain(_ key:String) -> String?
{
let keychain = KeychainSwift()
keychain.accessGroup = AppConstants.APP_GROUP
return keychain.get(key)
}
static func removeAllKeychain() {
let keychain = KeychainSwift()
keychain.clear()
}
static func getString(_ key:String) -> String? {
guard let userDefault = UserDefaults.init(suiteName: AppConstants.APP_GROUP) else {
return nil
}
return userDefault.string(forKey: key)
}
static func setString(_ key:String,value:String?){
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.set(value, forKey: key)
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.synchronize()
}
static func deleteDefaultString(_ key:String) {
UserDefaults.standard.removeObject(forKey: key)
UserDefaults.standard.synchronize()
}
static func setBool(_ key:String,value:Bool){
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.set(value, forKey: key)
}
static func getBool(_ key:String)->Bool
{
if UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.object(forKey: key) == nil {
return false
}
return UserDefaults.init(suiteName:AppConstants.APP_GROUP)!.bool(forKey: key)
}
static func setInt(_ key:String,value:Int){
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.set(value, forKey: key)
}
static func getInt(_ key:String)->Int{
if UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.object(forKey: key) == nil {
return -1
}
return UserDefaults.init(suiteName:AppConstants.APP_GROUP)!.integer(forKey: key)
}
static func setDouble(_ key:String,value:Double){
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.set(value, forKey: key)
}
static func getDouble(_ key:String)->Double{
if UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.object(forKey: key) == nil {
return -1
}
return UserDefaults.init(suiteName:AppConstants.APP_GROUP)!.double(forKey: key)
}
static func setDictionary(_ key:String,value:Dictionary<String, Any>)
{
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.set(value, forKey: key)
}
static func getDictionary(_ key:String)->Dictionary<String, Any>?
{
if UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.object(forKey: key) == nil
{
return nil }
return UserDefaults.init(suiteName:AppConstants.APP_GROUP)!.object(forKey: key) as? Dictionary<String, Any>
}
static func deleteString(_ key:String){
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.removeObject(forKey: key)
UserDefaults.init(suiteName:AppConstants.APP_GROUP)?.synchronize()
let defaults = UserDefaults.standard
defaults.removeObject(forKey: key)
defaults.synchronize()
}
static func getDeviceTokenString() -> String
{
#if MAIN_APP
if let deviceToken = AppManager.getString(AppConstants.PREF_USER_DEVICE_TOKEN){
return deviceToken
}else{
// Try getting the token again
if let token = FIRInstanceID.instanceID().token(){
return token
}
}
return ""
#else
if let deviceToken = AppManager.getString(AppConstants.PREF_USER_DEVICE_TOKEN){
return deviceToken
}
return ""
#endif
}
static func requestRating()
{
if #available( iOS 10.3,*)
{
SKStoreReviewController.requestReview()
}
}
static func isIndia() -> Bool {
let baseUrl = DataStore.shared.baseUrl ?? AppConstants.BASE_URL
return baseUrl == AppConstants.BASE_URL_IN
}
static func isTouchIdAvailable() -> Bool{
let authenticationContext = LAContext()
var error:NSError?
guard authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
HitPayDebugPrint("no touch id ")
return false
}
if getInt(AppConstants.PREF_TOUCH_ID_OFF) == 1 {
HitPayDebugPrint("no touch off ")
return false
}
if getFromKeychain(AppConstants.KEYCHIN_PASSWORD) == nil {
HitPayDebugPrint("no password ")
return false
}
if getString(AppConstants.PREF_USER_TOKEN) == nil {
HitPayDebugPrint("no token ")
return false
}
if getString(AppConstants.KEYCHIN_USERNAME) == nil {
HitPayDebugPrint("no username ")
return false
}
return true
}
static func canShowLockSreen() -> Bool{
if getString(AppConstants.PREF_USER_TOKEN) == nil {
return false
}
if getString(AppConstants.KEYCHIN_USERNAME) == nil {
return false
}
return true
}
static func removeAllData()
{
if let defaults = UserDefaults.init(suiteName:AppConstants.APP_GROUP)
{
for key in defaults.dictionaryRepresentation().keys
{
if key != AppConstants.PREF_PROFILE_PIC || key != AppConstants.SERVER_VERSION_KEY
{
defaults.removeObject(forKey: key)
}
}
defaults.synchronize()
}
AppManager.deleteString(AppConstants.KEYCHIN_ACESS_TOKEN)
AppManager.deleteString(AppConstants.KEYCHIN_REFRESH_TOKEN)
AppManager.deleteString(AppConstants.PREF_USER_TOKEN)
AppManager.deleteString(AppConstants.PREF_PAYNOW_DATA)
AppManager.deleteString(AppConstants.PREF_USER_DEVICE_TOKEN)
AppManager.deleteString(AppConstants.PREF_USER_DEVICE_TOKEN)
AppManager.deleteDefaultString("userID")
// AppDelegate.clearUser()
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
AppManager.removeAllKeychain()
}
static func migrateDataToSharedContainer()
{
if let sharedDefaults = UserDefaults.init(suiteName:AppConstants.APP_GROUP)
{
for key in UserDefaults.standard.dictionaryRepresentation().keys
{
let object = UserDefaults.standard.object(forKey: key)
sharedDefaults.set(object, forKey: key)
UserDefaults.standard.removeObject(forKey: key)
}
sharedDefaults.synchronize()
UserDefaults.standard.synchronize()
}
let keychain = KeychainSwift()
if let password = keychain.get(AppConstants.KEYCHIN_PASSWORD)
{
self.setToKeychain(AppConstants.KEYCHIN_PASSWORD, value: password)
}
}
static func tutorialSeen()
{
setString(AppConstants.TUTORIAL_SEEN, value: "TUTORIAL_SEEN")
return
}
static func isMerchant() -> Bool
{
return AppManager.getBool(AppConstants.PREF_IS_MERCHANT_ACCOUNT)
}
}
| 30.911348 | 117 | 0.612137 |
dbc86bf3eea02c9ed55926edc820a3e2b3c39d7a | 693 | import Foundation
import RobinHood
protocol DataOperationFactoryProtocol {
func fetchData(from url: URL) -> BaseOperation<Data>
}
final class DataOperationFactory: DataOperationFactoryProtocol {
func fetchData(from url: URL) -> BaseOperation<Data> {
let requestFactory = BlockNetworkRequestFactory {
var request = URLRequest(url: url)
request.httpMethod = HttpMethod.get.rawValue
return request
}
let resultFactory = AnyNetworkResultFactory<Data> { data in
data
}
let operation = NetworkOperation(requestFactory: requestFactory, resultFactory: resultFactory)
return operation
}
}
| 27.72 | 102 | 0.685426 |
262ff23514b9d2794bdc579b678298ad3e16bee6 | 4,651 | //
// UserDefaults.swift
// SwiftCrystal
//
// Created by Jun Narumi on 2016/06/30.
// Copyright © 2016年 zenithgear. All rights reserved.
//
import UIKit
extension AppDelegate {
func registerDefaults() {
var defaults : [ String : AnyObject ] = [
AppDelegateDefaultsRadiiModeKey: RadiiType.Covalent.rawValue as AnyObject,
AppDelegateDefaultsRadiiSizeKey:1.0 as AnyObject,
LatticesDefaultsBondSize:0.25 as AnyObject,
AppDelegateDefaultsUsesOrthographic:true as AnyObject,
DocumentDefaultsLoadColorAndRadiiKey:true as AnyObject,
DocumentDefaultsLoadCameraKey:true as AnyObject,
DocumentDefaultsLoadBondExpansionKey:true as AnyObject,
LatticesDefaultsUsesBonding:true as AnyObject,
// LatticesDefaultsUsesGeomBondAtoms:false,
LatticesDefaultsInitialAnimationDurationKey:1.0 as AnyObject,
// AppDelegateDefaultsBondingModeKey: SwiftCrystal.BondingMode.ColoredCylindar.rawValue,
LatticesDefaultsInitialBondExpansionKey: SwiftCrystal.BondingRangeMode.UnitCell.rawValue as AnyObject
]
if UIScreen.main.scale == 1.0 {
defaults[LatticesDefaultsUsesBonding] = false as AnyObject?
}
let userDefaults = UserDefaults.standard
userDefaults.register(defaults: defaults)
}
func reflectSettingsBundle() {
let userDefaults = UserDefaults.standard
if let radiiFileName = userDefaults.string(forKey: AppDelegateDefaultsRadiiModeKey) {
SwiftCrystal.stdRadiiType = RadiiType( rawValue: radiiFileName ) ?? .Covalent
}
let radiiSize = userDefaults.double(forKey: AppDelegateDefaultsRadiiSizeKey)
SwiftCrystal.stdRadiiSize = RadiiSizeType(radiiSize)
let bondSize = userDefaults.double(forKey: LatticesDefaultsBondSize)
SwiftCrystal.stdBondSize = RadiiSizeType(bondSize)
let usesOrthographic = userDefaults.bool(forKey: AppDelegateDefaultsUsesOrthographic)
CameraInitial.stdUsesOrthographic = usesOrthographic
if let bondingRange = userDefaults.string( forKey: LatticesDefaultsInitialBondExpansionKey ) {
SwiftCrystal.DefaultBondingRangeMode = SwiftCrystal.BondingRangeMode( rawValue: bondingRange ) ?? .OneStep
}
// let usesGeomBondAtoms = userDefaults.boolForKey(LatticesDefaultsUsesGeomBondAtoms)
// SwiftCrystal.UsesGeomBondAtoms = usesGeomBondAtoms
let loadColorAndRadii = userDefaults.bool(forKey: DocumentDefaultsLoadColorAndRadiiKey)
Document.loadColorAndRadii = loadColorAndRadii
let loadCamera = userDefaults.bool(forKey: DocumentDefaultsLoadCameraKey)
Document.loadCamera = loadCamera
let loadBondExpansion = userDefaults.bool(forKey: DocumentDefaultsLoadBondExpansionKey)
Document.loadBondExpansion = loadBondExpansion
let usesBonding = userDefaults.bool(forKey: LatticesDefaultsUsesBonding)
SwiftCrystal.DefaultBondingMode = usesBonding ? .On : .Off
let initialAnimationDuration = userDefaults.double(forKey: LatticesDefaultsInitialAnimationDurationKey)
Document.initialAnimationDuration = initialAnimationDuration
}
}
let kMainStoryboardName = "Main"
let kSaveRecieveURLViewControllerIdentifier = "SaveRecieveURLViewController"
// Default Identifiers
let AppDelegateDefaultsRadiiModeKey = "RadiiModeKey"
let AppDelegateDefaultsRadiiSizeKey = "RadiiSizeKey"
let LatticesDefaultsBondSize = "BondSize"
let AppDelegateDefaultsUsesOrthographic = "UsesOrthographic"
let LatticesDefaultsUsesBonding = "UsesBonding"
//let LatticesDefaultsUsesGeomBondAtoms = "LatticesDefaultsUsesGeomBondAtoms"
let LatticesDefaultsInitialAnimationDurationKey = "InitialAnimationDurationKey"
let LatticesDefaultsInitialBondExpansionKey = "InitialBondExpansionKey"
let DocumentDefaultsLoadColorAndRadiiKey = "LoadColorAndRadiiKey"
let DocumentDefaultsLoadBondExpansionKey = "LoadBondExpansionKey"
let DocumentDefaultsLoadCameraKey = "LoadCameraKey"
//let AppDelegateSubscriptionTestKey = "AppDelegateSubscriptionTestKey"
// Notifications
extension AppDelegate {
// static let didFinishLoadDocument = Notification.Name(rawValue:"didFinishLoadDocument")
}
let AppDelegateDidFinishOpenURLNotification = "AppDelegateDidFinishOpenURLNotification"
let AppDelegateDidUpdateDocumentsNotification = "AppDelegateDidUpdateDocumentsNotification"
let latticesMenuWillAppear = Notification.Name(rawValue:"latticesMenuWillAppear")
let latticesMenuWillDisappear = Notification.Name(rawValue:"latticesMenuWillDisappear")
| 39.415254 | 118 | 0.769727 |
2f6e9a9c28c650b08192c45f9f582900c171baf9 | 3,431 | //
// AccessabilityIdentifier.swift
// TBG2
//
// Created by Kris Reid on 21/06/2020.
// Copyright © 2020 Kris Reid. All rights reserved.
//
import Foundation
enum AccessabilityIdentifier: String {
case
//Login
LoginEmail = "LoginEmail",
LoginPassword = "LoginPassword",
LoginButton = "LoginButton",
LoginSignupButton = "LoginSignupButton",
//Signup
SignupProfileButton = "SignupProfileButton",
SignupFullName = "SignupFullName",
SignupEmailAddress = "SignupEmailAddress",
SignupPassword = "SignupPassword",
SignupDOB = "SignupDOB",
SignupHouseNumber = "SignupHouseNumber",
SignupPostcode = "SignupPostcode",
SignupCreateTeamButton = "SignupCreateTeamButton",
SignupJoinTeamButton = "SignupJoinTeamButton",
//CreateTeam
CreateTeamCrestButton = "CreateTeamCrestButton",
CreateTeamName = "CreateTeamName",
CreateTeamPIN = "CreateTeamPIN",
CreateTeamPostcode = "CreateTeamPostcode",
CreateTeamSubmitButton = "CreateTeamSubmitButton",
//Join Team
JoinTeamId = "JoinTeamId",
joinTeamPIN = "joinTeamPIN",
joinTeamSubmitButton = "joinTeamSubmitButton",
//Share Team
ShareTeamName = "ShareTeamName",
ShareTeamPostcode = "ShareTeamPostcode",
ShareTeamPIN = "ShareTeamPIN",
ShareTeamID = "ShareTeamID",
//Change Team PIN
TeamPINTeamPIN = "TeamPINTeamPIN",
TeamPINDone = "TeamPINDone",
//Fixture
FixturesTable = "FixturesTable",
FixtureOpposition = "FixtureOpposition",
FixtureHomeAway = "FixtureHomeAway",
FixtureDateTime = "FixtureDateTime",
FixtureHomeTeamGoals = "FixtureHomeTeamGoals",
FixtureAwayTeamGoals = "FixtureAwayTeamGoals",
//Fixture Information (Detail)
FixtureDetailHomeTeamCrest = "FixtureDetailHomeTeamCrest",
FixtureDetailAwayTeamCrest = "FixtureDetailAwayTeamCrest",
FixtureDetailHomeTeamGoals = "FixtureDetailHomeTeamGoals",
FixtureDetailAwayTeamGoals = "FixtureDetailAwayTeamGoals",
FixtureDetailDate = "FixtureDetailDate",
FixtureDetailTime = "FixtureDetailTime",
FixtureDetailPostcode = "FixtureDetailPostcode",
FixtureDetailGoalIcon = "FixtureDetailGoalIcon",
FixtureDetailGoalCount = "FixtureDetailGoalCount",
FixtureDetailMotmIcon = "FixtureDetailMotmIcon",
FixtureDetailPlayerName = "FixtureDetailPlayerName",
//Create Fixture
CreateFixtureToggle = "CreateFixtureToggle",
CreateFixtureHomeOrAway = "CreateFixtureHomeOrAway",
CreateFixtureOpposition = "CreateFixtureOpposition",
CreateFixtureDate = "CreateFixtureDate",
CreateFixtureTime = "CreateFixtureTime",
CreateFixturePostcode = "CreateFixturePostcode",
CreateFixtureCreateGame = "CreateFixtureCreateGame",
//Player Details
PlayerDetailProfilePicture = "PlayerDetailProfilePicture",
PlayerDetailPlayerName = "PlayerDetailPlayerName",
PlayerDetailDateOfBirth = "PlayerDetailDateOfBirth",
PlayerDetailStatsTitle = "PlayerDetailStatsTitle",
PlayerDetailStatsGamesPlayedCount = "PlayerDetailStatsGamesPlayedCount",
PlayerDetailStatsGamesPlayedTitle = "PlayerDetailStatsGamesPlayedTitle",
PlayerDetailStatsGamesMOTMCount = "PlayerDetailStatsGamesMOTMCount",
PlayerDetailStatsGamesMOTMTitle = "PlayerDetailStatsGamesMOTMTitle",
PlayerDetailStatsGamesGoalsCount = "PlayerDetailStatsGamesGoalsCount",
PlayerDetailStatsGamesGoalsTitle = "PlayerDetailStatsGamesGoalsTitle"
}
| 40.364706 | 76 | 0.76246 |
72b9a2e68c7246b9e4ca42bbf4afae8933f30cde | 985 | //
// ArrayMapTests.swift
// ArrayMapTests
//
// Created by Valentin Knabel on 05.01.16.
// Copyright © 2016 Conclurer GmbH. All rights reserved.
//
import XCTest
@testable import ArrayMap
class ArrayMapTests: 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.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.621622 | 111 | 0.637563 |
38da58de111e45a4efb4527f4c6f1624b0f3a447 | 3,292 | //
// AppDelegate.swift
// twitter_final
//
// Created by Haena Kim on 7/22/16.
// Copyright © 2016 Haena Kim. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//get user info
if User.currentUser != nil{
print("There is a current user")
let storyboard = UIStoryboard( name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("TweetsNavigationController")
window?.rootViewController = vc
}
NSNotificationCenter.defaultCenter().addObserverForName(User.userDidLogOutNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) in
let storyboard = UIStoryboard( name: "Main", bundle: nil)
let vc = storyboard.instantiateInitialViewController()
self.window?.rootViewController = vc
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
print("go back to auth page")
print(url.description)
TwitterClient.sharedInstance.handleOpenUrl(url)
return true
}
}
| 41.15 | 285 | 0.686209 |
ff4372bba98621a092e18224f0e9a002ff76a53b | 1,671 | import XCTest
@testable import MetroKit
extension UserPreferenceKey {
static var testKey: UserPreferenceKey<String> {
UserPreferenceKey<String>(name: "SelectedAnimal", defaultValue: "Panda")
}
}
final class UserPreferencesTests: XCTestCase {
var userDefaults: UserDefaults!
override func setUp() {
super.setUp()
userDefaults = UserDefaults(suiteName: UUID().uuidString)
}
override func tearDown() {
super.tearDown()
userDefaults = nil
}
func testThatItReturnsDefaultValueWhenNeverSet() {
XCTAssertEqual(userDefaults.value(forKey: .testKey), "Panda")
}
func testThatItReturnsExistingValueWhenSet() {
userDefaults.set("Shark", forKey: "SelectedAnimal")
XCTAssertEqual(userDefaults.value(forKey: .testKey), "Shark")
}
func testThatItSetsValue() {
userDefaults.setValue("Brown Cow", forKey: .testKey)
XCTAssertEqual(userDefaults.string(forKey: "SelectedAnimal"), "Brown Cow")
}
func testThatItFallsBackToDefaultValue() {
// #1: Unknown value
do {
userDefaults.setValue("0_0_0", forKey: UserPreferenceKey<ModelVersion>.dataModelVersion.name)
XCTAssertEqual(userDefaults.value(forKey: .dataModelVersion), UserPreferenceKey<ModelVersion>.dataModelVersion.defaultValue)
}
// #2: Wrong type
do {
userDefaults.setValue(false, forKey: UserPreferenceKey<ModelVersion>.dataModelVersion.name)
XCTAssertEqual(userDefaults.value(forKey: .dataModelVersion), UserPreferenceKey<ModelVersion>.dataModelVersion.defaultValue)
}
}
}
| 32.764706 | 136 | 0.681029 |
710afbafeb6d03ca86479c217ec2c74291b462a1 | 45 | import ARHeadsetKit
extension Cube {
}
| 7.5 | 19 | 0.688889 |
08d6e9bcc3043df451c0385913cdaa04e2802bf6 | 9,581 | //
// PhotoAlbumVC.swift
// VirtualTouristMaster
//
// Created by Ahmad on 20/12/2019.
// Copyright © 2019 Ahmad. All rights reserved.
//
import UIKit
import MapKit
import SwiftyJSON
import CoreData
import SVProgressHUD
private let collectionCellIdentifier = "imageFlickerCell"
class PhotoAlbumVC: UIViewController, UICollectionViewDelegateFlowLayout{
var currentPage = 0
var photoData = [Photo]()
var selectedPin: Pin!
var itemsSelected = [IndexPath]()
var photosSelected = false
var initalLocation : CLLocation!
let regionRadius: CLLocationDistance = 1000
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//IBOutlets
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var flowLayout : UICollectionViewFlowLayout!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var newCollectionOutlet: UIButton!
// PhotoAlbumVC Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
let space:CGFloat = 3.0
let dimensionPortrait = (view.frame.size.width - (2 * space)) / 3.0
flowLayout.minimumInteritemSpacing = space
flowLayout.minimumLineSpacing = space
flowLayout.itemSize = CGSize(width: dimensionPortrait, height: dimensionPortrait)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
loadLocation()
fetchPhotos()
}
//IBOutlets
@IBAction func backButtonPressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func getNewCollection(_ sender: UIButton) {
if photosSelected{
//Delete Photos
removePhotos()
self.collectionView.reloadData()
photosSelected = false
newCollectionOutlet.setTitle("New Collection", for: .normal)
}
else {
//Add new Collection
newCollectionOutlet.isEnabled = false
for photo in photoData {
appDelegate.getContext().delete(photo)
}
photoData.removeAll()
saveItems()
currentPage += 1
getFlickrPhotosURL(page: currentPage)
}
}
func removePhotos() {
if itemsSelected.count > 0 {
for indexPath in itemsSelected {
let photo = photoData[indexPath.item]
appDelegate.getContext().delete(photo)
self.photoData.remove(at: indexPath.item)
self.collectionView.deleteItems(at: [indexPath as IndexPath])
//print("Photo at row \(indexPath.row) was deleted")
}
itemsSelected.removeAll()
saveItems()
}
}
//MARK:- Save the context
func saveItems(){
do{
try context.save()
} catch {
print("Error saving context \(error)")
}
}
// MARK: - Fetch Photos
func fetchPhotos(){
let fetchRequest:NSFetchRequest<Photo> = Photo.fetchRequest()
fetchRequest.sortDescriptors = []
fetchRequest.predicate = NSPredicate(format: "pin = %@", selectedPin!)
let context = appDelegate.getContext()
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("Unable to Perform Fetch Request")
print("\(fetchError), \(fetchError.localizedDescription)")
}
if let data = fetchedResultsController.fetchedObjects, data.count > 0 {
photoData = data
self.collectionView.reloadData()
} else {
getFlickrPhotosURL(page: currentPage)
}
}
// MARK: - Networking
func getFlickrPhotosURL(page: Int){
FlickerClient.getImagesFromFlickr(selectedPin, page, completion: getFlickerPhotosURLResponse(photosArray: error:))
}
func getFlickerPhotosURLResponse( photosArray: [Photo]?, error: Error?){
guard error == nil else {
raiseAlertView(withTitle: "Unable to get photos from Flickr", withMessage: error?.localizedDescription ?? "")
return
}
/* Add results to photoData and reload collectionView */
DispatchQueue.main.async {
if photosArray!.count > 0 {
self.photoData = photosArray!
//print("\(self.photoData.count) photos from Flickr fetched")
self.collectionView.reloadData()
}
else {
if self.currentPage == 0{
self.raiseAlertView(withTitle: "Can not get any photos", withMessage: "Can not get any photos, Please choice another location or try again")
} else {
self.currentPage = 0
self.getFlickrPhotosURL(page: self.currentPage)
}
}
self.newCollectionOutlet.isEnabled = true
}
}
}
// MARK:- CollectionView Data Source Methods
/***************************************************************/
extension PhotoAlbumVC: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellIdentifier, for: indexPath) as! FlickerImageCell
let photo = photoData[indexPath.row]
cell.flickerImage.image = UIImage(named: "placeholder")
cell.flickerImage.alpha = 1.0
SVProgressHUD.show()
if photo.imageData != nil {
DispatchQueue.main.async {
SVProgressHUD.dismiss()
cell.flickerImage.image = UIImage(data: photo.imageData! as Data)
}
}
else {
if let imageURL = URL(string: photo.urlString!){
FlickerClient.requestImagePhoto(url: imageURL) { (results, error) in
guard let imageData = results else {
self.raiseAlertView(withTitle: "Image data error", withMessage: error?.localizedDescription ?? "")
SVProgressHUD.dismiss()
return
}
DispatchQueue.main.async{
photo.imageData = imageData as Data?
self.saveItems()
SVProgressHUD.dismiss()
cell.flickerImage.image = UIImage(data: photo.imageData! as Data)
}
}
}
}
return cell
}
}
extension PhotoAlbumVC: UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! FlickerImageCell
let index = itemsSelected.firstIndex(of: indexPath)
if let index = index {
itemsSelected.remove(at: index)
cell.flickerImage.alpha = 1.0
} else {
itemsSelected.append(indexPath)
//print(itemsSelected)
cell.flickerImage.alpha = 0.25
}
if itemsSelected.count > 0 {
newCollectionOutlet.setTitle("Delete", for: .normal)
photosSelected = true
} else {
newCollectionOutlet.setTitle("New Collection", for: .normal)
photosSelected = false
}
}
}
// MARK:- MapView Delegate Methods
/***************************************************************/
extension PhotoAlbumVC: MKMapViewDelegate{
public func loadLocation () {
initalLocation = CLLocation(latitude: selectedPin.latitude, longitude: selectedPin.longitude)
centerMapOnLocation(location: initalLocation)
// The lat and long are used to create a CLLocationCoordinates2D instance.
let coordinate = CLLocationCoordinate2D(latitude: selectedPin.latitude, longitude: selectedPin.longitude)
// Here we create the annotation and set its coordiate, title, and subtitle properties
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
mapView.addAnnotation(annotation)
}
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegion(center: location.coordinate,
latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
self.mapView.setRegion(coordinateRegion, animated: true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.pinTintColor = .red
}
else {
pinView!.annotation = annotation
}
return pinView
}
}
| 36.291667 | 165 | 0.605574 |
71e8558f01ac8bc95acf188a36a2fc47893c5496 | 592 | //
// AppDelegate.swift
// KLNativeAddFlutter
//
// Created by WKL on 2021/3/31.
//
import UIKit
import Flutter
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var flutterEngine = FlutterEngine(name: "my flutter engine")
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
flutterEngine.run()
return true
}
}
| 19.096774 | 145 | 0.66723 |
f47bd0871d12361463914ffeb257472f4c84ea8a | 2,547 | //
// LocalizedStringTests.swift
// r2-shared-swiftTests
//
// Created by Mickaël Menu on 09.03.19.
//
// Copyright 2019 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import XCTest
@testable import R2Shared
class LocalizedStringTests: XCTestCase {
func testParseJSONString() {
XCTAssertEqual(
try? LocalizedString(json: "a string"),
.nonlocalized("a string")
)
}
func testParseJSONLocalizedStrings() {
XCTAssertEqual(
try? LocalizedString(json: ["en": "a string", "fr": "une chaîne"]),
.localized(["en": "a string", "fr": "une chaîne"])
)
}
func testParseInvalidJSON() {
XCTAssertThrowsError(try LocalizedString(json: ["a string", "une chaîne"]))
}
func testParseAllowsNil() {
XCTAssertNil(try LocalizedString(json: nil))
}
func testGetJSON() {
AssertJSONEqual(
LocalizedString.nonlocalized("a string").json,
"a string"
)
AssertJSONEqual(
LocalizedString.localized(["en": "a string", "fr": "une chaîne"]).json,
["en": "a string", "fr": "une chaîne"]
)
}
func testGetString() {
XCTAssertEqual(
LocalizedString.localized(["en": "hello", "fr": "bonjour"]).string,
"hello"
)
}
func testStringConversion() {
XCTAssertEqual(
String(describing: LocalizedString.localized(["en": "hello", "fr": "bonjour"])),
"hello"
)
}
func testGetStringByLanguageCode() {
XCTAssertEqual(
LocalizedString.localized(["en": "hello", "fr": "bonjour"]).string(forLanguageCode: "fr"),
"bonjour"
)
}
func testConvertFromLocalizedString() {
let string: LocalizedString = LocalizedString.localized(["en": "hello"]).localizedString
XCTAssertEqual(string, .localized(["en": "hello"]))
}
func testConvertFromStringLiteral() {
let string: LocalizedString = "hello".localizedString
XCTAssertEqual(string, .nonlocalized("hello"))
}
func testConvertFromDictionaryLiteral() {
let strings: LocalizedString = ["en": "hello", "fr": "bonjour"].localizedString
XCTAssertEqual(strings, .localized(["en": "hello", "fr": "bonjour"]))
}
}
| 29.275862 | 102 | 0.594425 |
23077f15579556998d41364f20fe5065225ef4dc | 199 | public extension Platform {
var prettyName: String {
switch self {
case .iOS: return "iOS"
case .macOS: return "macOS"
case .tvOS: return "tvOS"
}
}
}
| 19.9 | 35 | 0.532663 |
629f8d2a07bbc14cfd9b4e06dd0bbf61f5357b6c | 3,570 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPDotButton: SPButton {
var customSideSize: CGFloat = 26 {
didSet {
self.sizeToFit()
}
}
var dotColor: UIColor = UIColor.white {
didSet {
for dotView in self.dotsView {
dotView.backgroundColor = self.dotColor
}
}
}
override var isHighlighted: Bool{
didSet{
if isHighlighted{
UIView.animate(withDuration: 0.1, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1.0, options: [.curveEaseOut, .beginFromCurrentState], animations: {
for dotView in self.dotsView {
dotView.alpha = 0.35
}
}, completion: nil)
}else{
UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1.0, options: [.curveEaseOut, .beginFromCurrentState], animations: {
for dotView in self.dotsView {
dotView.alpha = 1
}
}, completion: nil)
}
}
}
private var dotsView: [UIView] = []
override func commonInit() {
super.commonInit()
self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
for _ in 0...2 {
let dotView = UIView()
dotView.isUserInteractionEnabled = false
dotView.backgroundColor = self.dotColor
self.dotsView.append(dotView)
self.addSubview(dotView)
}
}
override func sizeToFit() {
super.sizeToFit()
self.setWidth(self.customSideSize)
self.setHeight(self.customSideSize)
self.layoutSubviews()
}
override func layoutSubviews() {
super.layoutSubviews()
let space: CGFloat = 2
let sideSize: CGFloat = 4
let insest: CGFloat = (self.frame.width - (sideSize * 3) - (space * 2)) / 2
var currentXPosition: CGFloat = insest
for dotView in self.dotsView {
dotView.setWidth(sideSize)
dotView.setHeight(sideSize)
dotView.setYCenteringFromSuperview()
dotView.frame.origin.x = currentXPosition
dotView.round()
currentXPosition += (sideSize + space)
}
self.round()
}
}
| 35.346535 | 181 | 0.612605 |
2f334fb348a263217d00eea05fa5af88808267f4 | 12,226 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import AWSPluginsCore
import Combine
import Foundation
//Used for testing:
@available(iOS 13.0, *)
typealias ModelReconciliationQueueFactory = (
ModelSchema,
StorageEngineAdapter,
APICategoryGraphQLBehavior,
ReconcileAndSaveOperationQueue,
QueryPredicate?,
AuthCategoryBehavior?,
IncomingSubscriptionEventPublisher?
) -> ModelReconciliationQueue
/// A queue of reconciliation operations, merged from incoming subscription events and responses to locally-sourced
/// mutations for a single model type.
///
/// Although subscriptions are listened to and enqueued at initialization, you must call `start` on a
/// AWSModelReconciliationQueue to write events to the DataStore.
///
/// Internally, a AWSModelReconciliationQueue manages the `incomingSubscriptionEventQueue` to buffer incoming remote
/// events (e.g., subscriptions, mutation results), and is passed the reference of `ReconcileAndSaveOperationQueue`,
/// used to reconcile & save mutation sync events to local storage. A reference to the `ReconcileAndSaveOperationQueue`
/// is used here since some models have to be reconciled in dependency order and `ReconcileAndSaveOperationQueue` is responsible for managing the
/// ordering of these events.
/// These queues are required because each of these actions have different points in the sync lifecycle at which they
/// may be activated.
///
/// Flow:
/// - `AWSModelReconciliationQueue` init()
/// - `reconcileAndSaveQueue` queue for reconciliation and local save operations, passed in from initializer.
/// - `incomingSubscriptionEventQueue` created, but suspended
/// - `incomingEventsSink` listener set up for incoming remote events
/// - when `incomingEventsSink` listener receives an event, it adds an operation to `incomingSubscriptionEventQueue`
/// - Elsewhere in the system, the initial sync queries begin, and submit events via `enqueue`. That method creates a
/// `ReconcileAndLocalSaveOperation` for the event, and enqueues it on `reconcileAndSaveQueue`. `reconcileAndSaveQueue`
/// serially processes the events
/// - Once initial sync is done, the `ReconciliationQueue` is `start`ed, which activates the
/// `incomingSubscriptionEventQueue`.
/// - `incomingRemoteEventQueue` processes its operations, which are simply to call `enqueue` for each received remote
/// event.
@available(iOS 13.0, *)
final class AWSModelReconciliationQueue: ModelReconciliationQueue {
/// Exposes a publisher for incoming subscription events
private let incomingSubscriptionEvents: IncomingSubscriptionEventPublisher
private let modelSchema: ModelSchema
weak var storageAdapter: StorageEngineAdapter?
private let modelPredicate: QueryPredicate?
/// A buffer queue for incoming subsscription events, waiting for this ReconciliationQueue to be `start`ed. Once
/// the ReconciliationQueue is started, each event in the `incomingRemoveEventQueue` will be submitted to the
/// `reconcileAndSaveQueue`.
private let incomingSubscriptionEventQueue: OperationQueue
/// Applies incoming mutation or subscription events serially to local data store for this model type. This queue
/// is always active.
private let reconcileAndSaveQueue: ReconcileAndSaveOperationQueue
private var incomingEventsSink: AnyCancellable?
private var reconcileAndLocalSaveOperationSinks: AtomicValue<Set<AnyCancellable?>>
private let modelReconciliationQueueSubject: PassthroughSubject<ModelReconciliationQueueEvent, DataStoreError>
var publisher: AnyPublisher<ModelReconciliationQueueEvent, DataStoreError> {
return modelReconciliationQueueSubject.eraseToAnyPublisher()
}
init(modelSchema: ModelSchema,
storageAdapter: StorageEngineAdapter?,
api: APICategoryGraphQLBehavior,
reconcileAndSaveQueue: ReconcileAndSaveOperationQueue,
modelPredicate: QueryPredicate?,
auth: AuthCategoryBehavior?,
incomingSubscriptionEvents: IncomingSubscriptionEventPublisher? = nil) {
self.modelSchema = modelSchema
self.storageAdapter = storageAdapter
self.modelPredicate = modelPredicate
self.modelReconciliationQueueSubject = PassthroughSubject<ModelReconciliationQueueEvent, DataStoreError>()
self.reconcileAndSaveQueue = reconcileAndSaveQueue
self.incomingSubscriptionEventQueue = OperationQueue()
incomingSubscriptionEventQueue.name = "com.amazonaws.DataStore.\(modelSchema.name).remoteEvent"
incomingSubscriptionEventQueue.maxConcurrentOperationCount = 1
incomingSubscriptionEventQueue.underlyingQueue = DispatchQueue.global()
incomingSubscriptionEventQueue.isSuspended = true
let resolvedIncomingSubscriptionEvents = incomingSubscriptionEvents ??
AWSIncomingSubscriptionEventPublisher(modelSchema: modelSchema,
api: api,
modelPredicate: modelPredicate,
auth: auth)
self.incomingSubscriptionEvents = resolvedIncomingSubscriptionEvents
self.reconcileAndLocalSaveOperationSinks = AtomicValue(initialValue: Set<AnyCancellable?>())
self.incomingEventsSink = resolvedIncomingSubscriptionEvents
.publisher
.sink(receiveCompletion: { [weak self] completion in
self?.receiveCompletion(completion)
}, receiveValue: { [weak self] receiveValue in
self?.receive(receiveValue)
})
}
/// (Re)starts the incoming subscription event queue.
func start() {
incomingSubscriptionEventQueue.isSuspended = false
modelReconciliationQueueSubject.send(.started)
}
/// Pauses only the incoming subscription event queue. Events submitted via `enqueue` will still be processed
func pause() {
incomingSubscriptionEventQueue.isSuspended = true
modelReconciliationQueueSubject.send(.paused)
}
/// Cancels all outstanding operations on both the incoming subscription event queue and the reconcile queue, and
/// unsubscribes from the incoming events publisher. The queue may not be restarted after cancelling.
func cancel() {
incomingEventsSink?.cancel()
incomingEventsSink = nil
incomingSubscriptionEvents.cancel()
reconcileAndSaveQueue.cancelOperations(modelName: modelSchema.name)
incomingSubscriptionEventQueue.cancelAllOperations()
}
func enqueue(_ remoteModels: [MutationSync<AnyModel>]) {
guard let remoteModelName = remoteModels.first?.model.modelName else {
log.debug("\(#function) skipping reconciliation, no models to enqueue.")
return
}
let reconcileOp = ReconcileAndLocalSaveOperation(modelSchema: modelSchema,
remoteModels: remoteModels,
storageAdapter: storageAdapter)
var reconcileAndLocalSaveOperationSink: AnyCancellable?
reconcileAndLocalSaveOperationSink = reconcileOp.publisher.sink(receiveCompletion: { completion in
self.reconcileAndLocalSaveOperationSinks.with { $0.remove(reconcileAndLocalSaveOperationSink) }
if case .failure = completion {
self.modelReconciliationQueueSubject.send(completion: completion)
}
}, receiveValue: { value in
switch value {
case .mutationEventDropped(let modelName):
self.modelReconciliationQueueSubject.send(.mutationEventDropped(modelName: modelName))
case .mutationEvent(let event):
self.modelReconciliationQueueSubject.send(.mutationEvent(event))
}
})
reconcileAndLocalSaveOperationSinks.with { $0.insert(reconcileAndLocalSaveOperationSink) }
reconcileAndSaveQueue.addOperation(reconcileOp, modelName: remoteModelName)
}
private func receive(_ receive: IncomingSubscriptionEventPublisherEvent) {
switch receive {
case .mutationEvent(let remoteModel):
if let predicate = modelPredicate {
guard predicate.evaluate(target: remoteModel.model.instance) else {
return
}
}
incomingSubscriptionEventQueue.addOperation(CancelAwareBlockOperation {
self.enqueue([remoteModel])
})
case .connectionConnected:
modelReconciliationQueueSubject.send(.connected(modelName: modelSchema.name))
}
}
private func receiveCompletion(_ completion: Subscribers.Completion<DataStoreError>) {
switch completion {
case .finished:
log.info("receivedCompletion: finished")
modelReconciliationQueueSubject.send(completion: .finished)
case .failure(let dataStoreError):
if case let .api(error, _) = dataStoreError,
case let APIError.operationError(_, _, underlyingError) = error, isUnauthorizedError(underlyingError) {
modelReconciliationQueueSubject.send(.disconnected(modelName: modelSchema.name, reason: .unauthorized))
return
}
if case let .api(error, _) = dataStoreError,
case let APIError.operationError(_, _, underlyingError) = error, isOperationDisabledError(underlyingError) {
modelReconciliationQueueSubject.send(.disconnected(modelName: modelSchema.name, reason: .operationDisabled))
return
}
log.error("receiveCompletion: error: \(dataStoreError)")
modelReconciliationQueueSubject.send(completion: .failure(dataStoreError))
}
}
}
@available(iOS 13.0, *)
extension AWSModelReconciliationQueue: DefaultLogger { }
// MARK: Resettable
@available(iOS 13.0, *)
extension AWSModelReconciliationQueue: Resettable {
func reset(onComplete: () -> Void) {
let group = DispatchGroup()
incomingEventsSink?.cancel()
if let resettable = incomingSubscriptionEvents as? Resettable {
group.enter()
DispatchQueue.global().async {
resettable.reset { group.leave() }
}
}
group.enter()
DispatchQueue.global().async {
self.incomingSubscriptionEventQueue.cancelAllOperations()
self.incomingSubscriptionEventQueue.waitUntilAllOperationsAreFinished()
group.leave()
}
group.wait()
onComplete()
}
}
// MARK: Errors handling
@available(iOS 13.0, *)
extension AWSModelReconciliationQueue {
private typealias ResponseType = MutationSync<AnyModel>
private func graphqlErrors(from error: GraphQLResponseError<ResponseType>?) -> [GraphQLError]? {
if case let .error(errors) = error {
return errors
}
return nil
}
private func errorTypeValueFrom(graphQLError: GraphQLError) -> String? {
guard case let .string(errorTypeValue) = graphQLError.extensions?["errorType"] else {
return nil
}
return errorTypeValue
}
private func isUnauthorizedError(_ error: Error?) -> Bool {
if let responseError = error as? GraphQLResponseError<ResponseType>,
let graphQLError = graphqlErrors(from: responseError)?.first,
let errorTypeValue = errorTypeValueFrom(graphQLError: graphQLError),
case .unauthorized = AppSyncErrorType(errorTypeValue) {
return true
}
return false
}
private func isOperationDisabledError(_ error: Error?) -> Bool {
if let responseError = error as? GraphQLResponseError<ResponseType>,
let graphQLError = graphqlErrors(from: responseError)?.first,
let errorTypeValue = errorTypeValueFrom(graphQLError: graphQLError),
case .operationDisabled = AppSyncErrorType(errorTypeValue) {
return true
}
return false
}
}
| 44.620438 | 145 | 0.696794 |
9be789413561006648635dd120089dcf3715d540 | 2,585 | import Foundation
import TSCBasic
import TuistCore
import TuistCoreTesting
import XCTest
@testable import TuistCache
@testable import TuistSupportTesting
final class GraphContentHasherTests: TuistUnitTestCase {
private var subject: GraphContentHasher!
override func setUp() {
super.setUp()
subject = GraphContentHasher()
}
override func tearDown() {
subject = nil
super.tearDown()
}
func test_contentHashes_emptyGraph() throws {
// Given
let graph = Graph.test()
// When
let hashes = try subject.contentHashes(for: graph)
// Then
XCTAssertEqual(hashes, Dictionary())
}
func test_contentHashes_returnsOnlyFrameworks() throws {
// Given
let path: AbsolutePath = "/project"
let frameworkTarget = TargetNode.test(project: .test(path: path), target: .test(name: "FrameworkA", product: .framework, infoPlist: nil, entitlements: nil))
let secondFrameworkTarget = TargetNode.test(project: .test(path: path), target: .test(name: "FrameworkB", product: .framework, infoPlist: nil, entitlements: nil))
let appTarget = TargetNode.test(project: .test(path: path), target: .test(name: "App", product: .app, infoPlist: nil, entitlements: nil))
let dynamicLibraryTarget = TargetNode.test(project: .test(path: path), target: .test(name: "DynamicLibrary", product: .dynamicLibrary, infoPlist: nil, entitlements: nil))
let staticFrameworkTarget = TargetNode.test(project: .test(path: path), target: .test(name: "StaticFramework", product: .staticFramework, infoPlist: nil, entitlements: nil))
let graph = Graph.test(entryPath: path,
entryNodes: [],
projects: [],
cocoapods: [],
packages: [],
precompiled: [],
targets: [path: [frameworkTarget, secondFrameworkTarget, appTarget, dynamicLibraryTarget, staticFrameworkTarget]])
let expectedCachableTargets = [frameworkTarget, secondFrameworkTarget].sorted(by: { $0.target.name < $1.target.name })
// When
let hashes = try subject.contentHashes(for: graph)
let hashedTargets: [TargetNode] = hashes.keys.sorted { left, right -> Bool in
left.project.path.pathString < right.project.path.pathString
}.sorted(by: { $0.target.name < $1.target.name })
// Then
XCTAssertEqual(hashedTargets, expectedCachableTargets)
}
}
| 41.031746 | 181 | 0.636364 |
75b46ffbaccebbcef5651a693dca45954aa54e5c | 1,458 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
/// A simple struct that holds pagination information that can be applied queries.
public struct QueryPaginationInput {
/// The default page size.
public static let defaultLimit: UInt = 100
/// The page number. It starts at 0.
public let page: UInt
/// The number of results per page.
public let limit: UInt
}
extension QueryPaginationInput {
/// Creates a `QueryPaginationInput` in an expressive way, enabling a short
/// and developer friendly access to an instance of `QueryPaginationInput`.
///
/// - Parameters:
/// - page: the page number (starting at 0)
/// - limit: the page size (defaults to `QueryPaginationInput.defaultLimit`)
/// - Returns: a new instance of `QueryPaginationInput`
public static func page(_ page: UInt,
limit: UInt = QueryPaginationInput.defaultLimit) -> QueryPaginationInput {
return QueryPaginationInput(page: page, limit: limit)
}
/// Utility that created a `QueryPaginationInput` with `page` 0 and `limit` 1
public static var firstResult: QueryPaginationInput {
.page(0, limit: 1)
}
/// Utility that created a `QueryPaginationInput` with `page` 0 and the default `limit`
public static var firstPage: QueryPaginationInput {
.page(0)
}
}
| 29.755102 | 102 | 0.672154 |
91cc8d1d408a8507ac1f3ecc799a3210b70e5bb0 | 1,451 | import Foundation
import ShellInterface
public struct CreateBranch: CustomStringConvertible
{
public typealias Func = (_ name: String, _ context: TaskContext?) throws -> Void
private let vcs: String
private let params: [String]
private let shell: ExecuteCommand.Func
public var description: String
{
let components = [vcs] + params + ["<branchname>"]
return components.joined(separator: " ")
}
public init(vcs: String = "git",
params: [String] = ["branch"],
shell: @escaping ExecuteCommand.Func = ExecuteCommand().execute)
{
self.vcs = vcs
self.params = params
self.shell = shell
}
// MARK: -
public func execute(branch name: String, context: TaskContext? = TaskContext.current) throws
{
let params = self.params + [name]
let result = shell(vcs, params, context, true)
guard let terminationStatus = result.terminationStatus else {
throw TaskFailure.stillRunning(file: #file, line: #line)
}
guard terminationStatus == 0 else {
throw TaskFailure.nonzeroTerminationStatus(
file: #file,
line: #line,
terminationStatus: terminationStatus,
uncaughtSignal: result.terminatedDueUncaughtSignal
)
}
}
}
| 31.543478 | 96 | 0.574087 |
69c28ff07928e13c9254d99c7f56f0d7638da605 | 21,466 | //
// NaverMapController.swift
// naver_map_plugin
//
// Created by Maximilian on 2020/08/19.
//
import UIKit
import Flutter
import NMapsMap
protocol NaverMapOptionSink {
func setIndoorEnable(_ indoorEnable: Bool)
func setNightModeEnable(_ nightModeEnable: Bool)
func setLiteModeEnable(_ liteModeEnable: Bool)
func setMapType(_ typeIndex: Int)
func setBuildingHeight(_ buildingHeight: Float)
func setSymbolScale(_ symbolScale: CGFloat)
func setSymbolPerspectiveRatio(_ symbolPerspectiveRatio: CGFloat)
func setActiveLayers(_ activeLayers: Array<Any>)
func setContentPadding(_ paddingData: Array<CGFloat>)
func setMaxZoom(_ maxZoom: Double)
func setMinZoom(_ minZoom: Double)
func setRotationGestureEnable(_ rotationGestureEnable: Bool)
func setScrollGestureEnable(_ scrollGestureEnable: Bool)
func setTiltGestureEnable(_ tiltGestureEnable: Bool)
func setZoomGestureEnable(_ zoomGestureEnable: Bool)
func setLocationTrackingMode(_ locationTrackingMode: UInt)
func setLocationButtonEnable(_ locationButtonEnable: Bool)
}
class NaverMapController: NSObject, FlutterPlatformView, NaverMapOptionSink, NMFMapViewTouchDelegate, NMFMapViewCameraDelegate, NMFAuthManagerDelegate {
var mapView : NMFMapView?
var naverMap : NMFNaverMapView?
let viewId : Int64
var markersController: NaverMarkersController?
var pathController: NaverPathController?
var circleController: NaverCircleController?
var polygonController: NaverPolygonController?
var channel : FlutterMethodChannel?
var registrar : FlutterPluginRegistrar?
init(viewId: Int64, frame: CGRect, registrar: FlutterPluginRegistrar, argument: NSDictionary?) {
self.viewId = viewId
self.registrar = registrar
// need more http connections during getting map tile (default : 4)
URLSession.shared.configuration.httpMaximumConnectionsPerHost = 8
// property set
naverMap = NMFNaverMapView(frame: frame)
mapView = naverMap!.mapView
channel = FlutterMethodChannel(name: "naver_map_plugin_\(viewId)",
binaryMessenger: registrar.messenger())
super.init()
markersController = NaverMarkersController(naverMap: naverMap!,
registrar: registrar,
touchHandler: overlayTouchHandler(overlay:))
pathController = NaverPathController(naverMap: naverMap!,
registrar: registrar,
touchHandler: overlayTouchHandler(overlay:))
circleController = NaverCircleController(naverMap: naverMap!,
touchHandler: overlayTouchHandler(overlay:))
polygonController = NaverPolygonController(naverMap: naverMap!,
touchHandler: overlayTouchHandler(overlay:))
channel?.setMethodCallHandler(handle(call:result:))
// map view 설정
NMFAuthManager.shared().delegate = self as NMFAuthManagerDelegate // for debug
mapView!.touchDelegate = self
mapView!.addCameraDelegate(delegate: self)
if let arg = argument {
if let initialPositionData = arg["initialCameraPosition"] {
if initialPositionData is NSDictionary {
mapView!.moveCamera(NMFCameraUpdate(position: toCameraPosition(json: initialPositionData)))
}
}
if let options = arg["options"] as? NSDictionary {
interpretMapOption(option: options, sink: self)
}
if let markerData = arg["markers"] as? Array<Any> {
markersController?.add(jsonArray: markerData)
}
if let pathData = arg["paths"] as? Array<Any> {
pathController?.set(jsonArray: pathData)
}
if let circleData = arg["circles"] as? Array<Any> {
circleController?.add(jsonArray: circleData)
}
if let polygonData = arg["polygons"] as? Array<Any> {
polygonController?.add(jsonArray: polygonData)
}
}
// 제대로 동작하지 않는 컨트롤러 UI로 원인이 밝혀지기 전까진 강제 비활성화.
naverMap!.showZoomControls = false
naverMap!.showIndoorLevelPicker = false
}
func view() -> UIView {
return naverMap!
}
func handle(call: FlutterMethodCall, result:@escaping FlutterResult) {
switch call.method {
case "map#clearMapView":
mapView = nil
naverMap = nil
markersController = nil
polygonController = nil
pathController = nil
circleController = nil
registrar = nil
channel = nil
print("NaverMapController 인스턴스 속성, 메모리 해제");
break
case "map#waitForMap":
result(nil)
break
case "map#update":
if let arg = call.arguments as! NSDictionary?, let option = arg["options"] as? NSDictionary {
interpretMapOption(option: option, sink: self)
result(true)
} else {
result(false)
}
break
case "map#type":
if let arg = call.arguments as! NSDictionary?, let type = arg["mapType"] as? Int {
setMapType(type)
result(nil)
}
case "map#getVisibleRegion":
let bounds = mapView!.contentBounds
result(latlngBoundToJson(bound: bounds))
break
case "map#getPosition":
let position = mapView!.cameraPosition
result(cameraPositionToJson(position: position))
break
case "tracking#mode":
if let arg = call.arguments as! NSDictionary? {
setLocationTrackingMode(arg["locationTrackingMode"] as! UInt)
result(true)
} else {
result(false)
}
break
case "map#getSize" :
let width = CGFloat(mapView!.mapWidth)
let height = CGFloat(mapView!.mapHeight)
let resolution = UIScreen.main.nativeBounds.width / UIScreen.main.bounds.width
let data : Dictionary<String, Int> = [
"width" : Int(round(width * resolution)),
"height" : Int(round(height * resolution))
]
result(data)
break
case "meter#dp" :
let meterPerPx = mapView!.projection.metersPerPixel().advanced(by: 0.0)
let density = Double.init(UIScreen.main.scale)
result(meterPerPx*density)
break
case "meter#px":
let meterPerPx = mapView!.projection.metersPerPixel().advanced(by: 0.0)
result(meterPerPx)
break
case "camera#move" :
if let arg = call.arguments as? NSDictionary {
let update = toCameraUpdate(json: arg["cameraUpdate"]!)
let animationDuration = arg["animation"] as? Int
if animationDuration != nil {
update.animation = .easeOut
update.animationDuration = Double(animationDuration!) / 1000
}
mapView!.moveCamera(update, completion: { isCancelled in
result(nil)
})
} else {
result(nil)
}
break
case "map#capture" :
let dir = NSTemporaryDirectory()
let fileName = "\(NSUUID().uuidString).jpg"
if let tmpFileUrl = NSURL.fileURL(withPathComponents: [dir, fileName]) {
DispatchQueue.main.async {
self.naverMap!.takeSnapShot({ (image) in
if let data = image.jpegData(compressionQuality: 1.0) ?? image.pngData() {
do{
try data.write(to: tmpFileUrl)
self.channel?.invokeMethod("snapshot#done", arguments: ["path" : tmpFileUrl.path])
}catch {
self.channel?.invokeMethod("snapshot#done", arguments: ["path" : nil])
}
}else {
self.channel?.invokeMethod("snapshot#done", arguments: ["path" : nil])
}
})
}
}
result(nil)
break
case "map#padding":
if let arg = call.arguments as? NSDictionary {
if let top = arg["top"] as? CGFloat, let left = arg["left"] as? CGFloat,
let right = arg["right"] as? CGFloat, let bottom = arg["bottom"] as? CGFloat {
mapView!.contentInset = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
}
}
result(nil)
break
case "circleOverlay#update" :
if let arg = call.arguments as? NSDictionary {
if let dataToAdd = arg["circlesToAdd"] as? Array<Any> {
circleController?.add(jsonArray: dataToAdd)
}
if let dataToModify = arg["circlesToChange"] as? Array<Any> {
circleController?.modify(jsonArray: dataToModify)
}
if let dataToRemove = arg["circleIdsToRemove"] as? Array<Any>{
circleController?.remove(jsonArray: dataToRemove)
}
}
result(nil)
break
case "pathOverlay#update" :
if let arg = call.arguments as? NSDictionary {
if let dataToAdd = arg["pathToAddOrUpdate"] as? Array<Any> {
pathController?.set(jsonArray: dataToAdd)
}
if let dataToRemove = arg["pathIdsToRemove"] as? Array<Any>{
pathController?.remove(jsonArray: dataToRemove)
}
}
result(nil)
break
case "polygonOverlay#update" :
if let arg = call.arguments as? NSDictionary {
if let dataToAdd = arg["polygonToAdd"] as? Array<Any> {
polygonController?.add(jsonArray: dataToAdd)
}
if let dataToModify = arg["polygonToChange"] as? Array<Any> {
polygonController?.modify(jsonArray: dataToModify)
}
if let dataToRemove = arg["polygonToRemove"] as? Array<Any>{
polygonController?.remove(jsonArray: dataToRemove)
}
}
result(nil)
case "markers#update" :
if let arg = call.arguments as? NSDictionary {
if let dataToAdd = arg["markersToAdd"] as? Array<Any> {
markersController?.add(jsonArray: dataToAdd)
}
if let dataToModify = arg["markersToChange"] as? Array<Any> {
markersController?.modify(jsonArray: dataToModify)
}
if let dataToRemove = arg["markerIdsToRemove"] as? Array<Any>{
markersController?.remove(jsonArray: dataToRemove)
}
}
result(nil)
break
case "LO#set#position" :
if let arg = call.arguments as? NSDictionary, let data = arg["position"] {
let latLng = toLatLng(json: data)
mapView!.locationOverlay.location = latLng
}
result(nil)
break
case "LO#set#bearing" :
if let arg = call.arguments as? NSDictionary, let bearing = arg["bearing"] as? NSNumber {
mapView!.locationOverlay.heading = CGFloat(bearing.floatValue)
}
result(nil)
break
default:
print("지정되지 않은 메서드콜 함수명이 들어왔습니다.\n함수명 : \(call.method)")
}
}
// ==================== naver map camera delegate ==================
// onCameraChange
func mapView(_ mapView: NMFMapView, cameraDidChangeByReason reason: Int, animated: Bool) {
var r = 0;
switch reason {
case NMFMapChangedByGesture:
r = 1
break
case NMFMapChangedByControl:
r = 2
break
case NMFMapChangedByLocation:
r = 3
break;
default:
r = 0;
}
self.channel?.invokeMethod("camera#move",
arguments: ["position" : latlngToJson(latlng: mapView.cameraPosition.target),
"reason" : r,
"animated" : animated])
}
func mapViewCameraIdle(_ mapView: NMFMapView) {
self.channel?.invokeMethod("camera#idle" , arguments: nil)
}
// ========================== About Map Option ==============================
func interpretMapOption(option: NSDictionary, sink: NaverMapOptionSink){
if let indoorEnable = option["indoorEnable"] as? Bool {
sink.setIndoorEnable(indoorEnable)
}
if let nightModeEnable = option["nightModeEnable"] as? Bool {
sink.setNightModeEnable(nightModeEnable)
}
if let liteModeEnable = option["liteModeEnable"] as? Bool {
sink.setLiteModeEnable(liteModeEnable)
}
if let mapType = option["mapType"] as? Int {
sink.setMapType(mapType)
}
if let height = option["buildingHeight"] as? Float {
sink.setBuildingHeight(height)
}
if let scale = option["symbolScale"] as? CGFloat {
sink.setSymbolScale(scale)
}
if let ratio = option["symbolPerspectiveRatio"] as? CGFloat{
sink.setSymbolPerspectiveRatio(ratio)
}
if let layers = option["activeLayers"] as? Array<Any> {
sink.setActiveLayers(layers)
}
if let rotationGestureEnable = option["rotationGestureEnable"] as? Bool {
sink.setRotationGestureEnable(rotationGestureEnable)
}
if let scrollGestureEnable = option["scrollGestureEnable"] as? Bool {
sink.setScrollGestureEnable(scrollGestureEnable)
}
if let tiltGestureEnable = option["tiltGestureEnable"] as? Bool {
sink.setTiltGestureEnable(tiltGestureEnable)
}
if let zoomGestureEnable = option["zoomGestureEnable"] as? Bool{
sink.setZoomGestureEnable(zoomGestureEnable)
}
if let locationTrackingMode = option["locationTrackingMode"] as? UInt {
sink.setLocationTrackingMode(locationTrackingMode)
}
if let locationButtonEnable = option["locationButtonEnable"] as? Bool{
sink.setLocationButtonEnable(locationButtonEnable)
}
if let paddingData = option["contentPadding"] as? Array<CGFloat> {
sink.setContentPadding(paddingData)
}
if let maxZoom = option["maxZoom"] as? Double{
sink.setMaxZoom(maxZoom)
}
if let minZoom = option["minZoom"] as? Double{
sink.setMinZoom(minZoom)
}
}
// Naver touch Delegate method
func mapView(_ mapView: NMFMapView, didTapMap latlng: NMGLatLng, point: CGPoint) {
channel?.invokeMethod("map#onTap", arguments: ["position" : [latlng.lat, latlng.lng]])
}
func mapView(_ mapView: NMFMapView, didTap symbol: NMFSymbol) -> Bool {
channel?.invokeMethod("map#onSymbolClick",
arguments: ["position" : latlngToJson(latlng: symbol.position),
"caption" : symbol.caption!])
return false
}
// naver overlay touch handler
func overlayTouchHandler(overlay: NMFOverlay) -> Bool {
if let marker = overlay.userInfo["marker"] as? NMarkerController {
channel?.invokeMethod("marker#onTap", arguments: ["markerId" : marker.id,
"iconWidth" : pxFromPt(marker.marker.width),
"iconHeight" : pxFromPt(marker.marker.height)])
return markersController!.toggleInfoWindow(marker)
} else if let path = overlay.userInfo["path"] as? NPathController {
channel?.invokeMethod("path#onTap",
arguments: ["pathId" , path.id])
return true
} else if let circle = overlay.userInfo["circle"] as? NCircleController{
channel?.invokeMethod("circle#onTap",
arguments: ["overlayId" : circle.id])
return true
} else if let polygon = overlay.userInfo["polygon"] as? NPolygonController {
channel?.invokeMethod("polygon#onTap",
arguments: ["polygonOverlayId" : polygon.id])
return true
}
return false
}
// naver map option sink method
func setIndoorEnable(_ indoorEnable: Bool) {
mapView!.isIndoorMapEnabled = indoorEnable
}
func setNightModeEnable(_ nightModeEnable: Bool) {
mapView!.isNightModeEnabled = nightModeEnable
}
func setLiteModeEnable(_ liteModeEnable: Bool) {
mapView!.liteModeEnabled = liteModeEnable
}
func setMapType(_ typeIndex: Int) {
let type = NMFMapType(rawValue: typeIndex)!
mapView!.mapType = type
}
func setBuildingHeight(_ buildingHeight: Float) {
mapView!.buildingHeight = buildingHeight
}
func setSymbolScale(_ symbolScale: CGFloat) {
mapView!.symbolScale = symbolScale
}
func setSymbolPerspectiveRatio(_ symbolPerspectiveRatio: CGFloat) {
mapView!.symbolPerspectiveRatio = symbolPerspectiveRatio
}
func setActiveLayers(_ activeLayers: Array<Any>) {
mapView!.setLayerGroup(NMF_LAYER_GROUP_BUILDING, isEnabled: false)
mapView!.setLayerGroup(NMF_LAYER_GROUP_TRAFFIC, isEnabled: false)
mapView!.setLayerGroup(NMF_LAYER_GROUP_TRANSIT, isEnabled: false)
mapView!.setLayerGroup(NMF_LAYER_GROUP_BICYCLE, isEnabled: false)
mapView!.setLayerGroup(NMF_LAYER_GROUP_MOUNTAIN, isEnabled: false)
mapView!.setLayerGroup(NMF_LAYER_GROUP_CADASTRAL, isEnabled: false)
activeLayers.forEach { (any) in
let index = any as! Int
switch index {
case 0 :
mapView!.setLayerGroup(NMF_LAYER_GROUP_BUILDING, isEnabled: true)
break
case 1:
mapView!.setLayerGroup(NMF_LAYER_GROUP_TRAFFIC, isEnabled: true)
break
case 2:
mapView!.setLayerGroup(NMF_LAYER_GROUP_TRANSIT, isEnabled: true)
break
case 3:
mapView!.setLayerGroup(NMF_LAYER_GROUP_BICYCLE, isEnabled: true)
break
case 4:
mapView!.setLayerGroup(NMF_LAYER_GROUP_MOUNTAIN, isEnabled: true)
break
case 5:
mapView!.setLayerGroup(NMF_LAYER_GROUP_CADASTRAL, isEnabled: true)
break
default:
return
}
}
}
func setRotationGestureEnable(_ rotationGestureEnable: Bool) {
mapView!.isRotateGestureEnabled = rotationGestureEnable
}
func setScrollGestureEnable(_ scrollGestureEnable: Bool) {
mapView!.isScrollGestureEnabled = scrollGestureEnable
}
func setTiltGestureEnable(_ tiltGestureEnable: Bool) {
mapView!.isTiltGestureEnabled = tiltGestureEnable
}
func setZoomGestureEnable(_ zoomGestureEnable: Bool) {
mapView!.isZoomGestureEnabled = zoomGestureEnable
}
func setLocationTrackingMode(_ locationTrackingMode: UInt) {
mapView!.positionMode = NMFMyPositionMode(rawValue: locationTrackingMode)!
}
func setContentPadding(_ paddingData: Array<CGFloat>) {
mapView!.contentInset = UIEdgeInsets(top: paddingData[1], left: paddingData[0], bottom: paddingData[3], right: paddingData[2])
}
func setLocationButtonEnable(_ locationButtonEnable: Bool) {
naverMap!.showLocationButton = locationButtonEnable
}
func setMaxZoom(_ maxZoom: Double){
mapView!.maxZoomLevel = maxZoom
}
func setMinZoom(_ minZoom: Double){
mapView!.minZoomLevel = minZoom
}
// ===================== authManagerDelegate ========================
func authorized(_ state: NMFAuthState, error: Error?) {
switch state {
case .authorized:
print("네이버 지도 인증 완료")
break
case .authorizing:
print("네이버 지도 인증 진행중")
break
case .pending:
print("네이버 지도 인증 대기중")
break
case .unauthorized:
print("네이버 지도 인증 실패")
break
default:
break
}
if let e = error {
print("네이버 지도 인증 에러 발생 : \(e.localizedDescription)")
}
}
}
| 40.349624 | 152 | 0.564195 |
7a0802c248a85c63d42d2604f0d7921c45fac109 | 8,784 | // ----------------------------------------------------------------------------
//
// TransformOperatorsTests.SetOfBasicTypes.swift
//
// @author Natalia Mamunina <[email protected]>
// @copyright Copyright (c) 2018, Roxie Mobile Ltd. All rights reserved.
// @link https://www.roxiemobile.com/
//
// ----------------------------------------------------------------------------
@testable import SwiftCommonsData
import XCTest
// ----------------------------------------------------------------------------
// MARK: - Set of basic types
// ----------------------------------------------------------------------------
extension TransformOperatorsTests {
// MARK: - Tests
func testSetOfBasicTypesWithTransform_fromJSON() {
let map = Map(mappingType: .fromJSON, JSON: Constants.arrayOfIntegerBasicTypes)
let _set: Set<Int> = []
// Positive
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.array], StringToIntegerTransform.shared)
XCTAssertEqual(set.count, 1)
XCTAssertEqual(set.first, Int(Int32.max))
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.emptyArray], StringToIntegerTransform.shared)
XCTAssertEqual(set.count, 0)
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.noSuchKey], StringToIntegerTransform.shared, [Int(Int16.max)])
XCTAssertEqual(set.count, 1)
XCTAssertEqual(set.first, Int(Int16.max))
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.nilArray], StringToIntegerTransform.shared, [])
XCTAssertEqual(set.count, 0)
}
// Negative
assertThrowsException {
var set = _set
set <~ (map[JsonKeys.noSuchKey], StringToIntegerTransform.shared)
}
assertThrowsException {
var set = _set
set <~ (map[JsonKeys.invalidArray], StringToIntegerTransform.shared)
}
assertThrowsException {
var set = _set
set <~ (map[JsonKeys.invalidArray], StringToIntegerTransform.shared, [])
}
assertThrowsException {
var set = _set
set <~ (map[JsonKeys.nilArray], StringToIntegerTransform.shared)
}
}
func testSetOfBasicTypesWithTransform_toJSON() {
let map = Map(mappingType: .toJSON, JSON: [:])
let _set: Set<Int> = [Int(Int16.max), Int(Int32.max)]
let _emptySet: Set<Int> = []
// Positive
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.set], StringToIntegerTransform.shared)
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.set).value)
}
assertNoThrow {
var set = _emptySet
set <~ (map[JsonKeys.emptySet], StringToIntegerTransform.shared)
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.emptySet).value)
}
}
}
// ----------------------------------------------------------------------------
// MARK: - Optional set of basic types with Transform
// ----------------------------------------------------------------------------
extension TransformOperatorsTests {
// MARK: - Tests
func testOptionalSetOfBasicTypesWithTransform_fromJSON() {
let map = Map(mappingType: .fromJSON, JSON: Constants.arrayOfIntegerBasicTypes)
let _set: Set<Int>? = nil
// Positive
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.array], StringToIntegerTransform.shared)
XCTAssertEqual(set?.count ?? -1, 1)
XCTAssertEqual(set?.first, Int(Int32.max))
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.emptyArray], StringToIntegerTransform.shared)
XCTAssertEqual(set?.count ?? -1, 0)
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.noSuchKey], StringToIntegerTransform.shared)
XCTAssertNil(set)
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.noSuchKey], StringToIntegerTransform.shared, [Int(Int16.max)])
XCTAssertEqual(set?.count ?? -1, 1)
XCTAssertEqual(set?.first, Int(Int16.max))
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.nilArray], StringToIntegerTransform.shared)
XCTAssertNil(set)
}
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.nilArray], StringToIntegerTransform.shared, [])
XCTAssertEqual(set?.count ?? -1, 0)
}
// Negative
assertThrowsException {
var set = _set
set <~ (map[JsonKeys.invalidArray], StringToIntegerTransform.shared)
}
assertThrowsException {
var set = _set
set <~ (map[JsonKeys.invalidArray], StringToIntegerTransform.shared, [])
}
}
func testOptionalSetOfBasicTypesWithTransform_toJSON() {
let map = Map(mappingType: .toJSON, JSON: [:])
let _set: Set<Int>? = [Int(Int16.max), Int(Int32.max)]
let _emptySet: Set<Int>? = []
let _nilSet: Set<Int>? = nil
// Positive
assertNoThrow {
var set = _set
set <~ (map[JsonKeys.set], StringToIntegerTransform.shared)
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.set).value)
}
assertNoThrow {
var set = _emptySet
set <~ (map[JsonKeys.emptySet], StringToIntegerTransform.shared)
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.emptySet).value)
}
assertNoThrow {
var set = _nilSet
set <~ (map[JsonKeys.nilSet], StringToIntegerTransform.shared)
XCTAssertNil(map.fetch(valueFor: JsonKeys.nilSet).value)
}
}
}
// ----------------------------------------------------------------------------
// MARK: - Implicitly unwrapped optional set of basic types with Transform
// ----------------------------------------------------------------------------
extension TransformOperatorsTests {
// MARK: - Tests
func testImplicitlyUnwrappedOptionalSetOfBasicTypesWithTransform_fromJSON() {
let map = Map(mappingType: .fromJSON, JSON: Constants.arrayOfIntegerBasicTypes)
let _set: Set<Int>! = []
// Positive
assertNoThrow {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.array], StringToIntegerTransform.shared)
XCTAssertEqual(set.count, 1)
XCTAssertEqual(set.first, Int(Int32.max))
}
assertNoThrow {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.emptyArray], StringToIntegerTransform.shared)
XCTAssertEqual(set.count, 0)
}
assertNoThrow {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.noSuchKey], StringToIntegerTransform.shared)
XCTAssertNil(set)
}
assertNoThrow {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.noSuchKey], StringToIntegerTransform.shared, [Int(Int16.max)])
XCTAssertEqual(set.count, 1)
XCTAssertEqual(set.first, Int(Int16.max))
}
assertNoThrow {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.nilArray], StringToIntegerTransform.shared)
XCTAssertNil(set)
}
assertNoThrow {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.nilArray], StringToIntegerTransform.shared, [])
XCTAssertEqual(set.count, 0)
}
// Negative
assertThrowsException {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.invalidArray], StringToIntegerTransform.shared)
}
assertThrowsException {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.invalidArray], StringToIntegerTransform.shared, [])
}
}
func testImplicitlyUnwrappedOptionalSetOfBasicTypesWithTransform_toJSON() {
let map = Map(mappingType: .toJSON, JSON: [:])
let _set: Set<Int>! = [Int(Int16.max), Int(Int32.max)]
let _emptySet: Set<Int>! = []
// Positive
assertNoThrow {
var set: Set<Int>! = _set
set <~ (map[JsonKeys.set], StringToIntegerTransform.shared)
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.set).value)
}
assertNoThrow {
var set: Set<Int>! = _emptySet
set <~ (map[JsonKeys.emptySet], StringToIntegerTransform.shared)
XCTAssertNotNil(map.fetch(valueFor: JsonKeys.emptySet).value)
}
}
}
| 34.178988 | 95 | 0.540756 |
6944da8c7f9b4f0173af7ffc17144a760f3f545c | 3,767 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 726. Number of Atoms
// Given a chemical formula (given as a string), return the count of each atom.
// The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
// One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.
// Two formulas concatenated together to produce another formula. For example, H2O2He3Mg4 is also a formula.
// A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.
// Given a formula, return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
// Example 1:
// Input: formula = "H2O"
// Output: "H2O"
// Explanation: The count of elements are {'H': 2, 'O': 1}.
// Example 2:
// Input: formula = "Mg(OH)2"
// Output: "H2MgO2"
// Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
// Example 3:
// Input: formula = "K4(ON(SO3)2)2"
// Output: "K4N2O14S4"
// Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
// Example 4:
// Input: formula = "Be32"
// Output: "Be32"
// Constraints:
// 1 <= formula.length <= 1000
// formula consists of English letters, digits, '(', and ')'.
// formula is always valid.
func countOfAtoms(_ formula: String) -> String {
guard formula.count > 0 else { return formula }
let chars = Array(formula)
let res = helper(chars, 0)
let ret = res.0.sorted(by: {$0.key < $1.key})
var str = ""
for (k,v) in ret {
if v > 1 {
str += "\(k)\(v)"
} else {
str += "\(k)"
}
}
return str
}
func helper(_ chars: [Character], _ index: Int) -> ([String: Int], Int) {
var res = [String: Int]()
var stack = [[String: Int]]()
var i = index
while i < chars.count {
let c = chars[i]
if c == "(" {
stack.append(res)
res.removeAll()
i += 1
} else if c == ")" {
var right = i + 1
var val = 0
while right < chars.count && chars[right].isNumber {
val = val * 10 + Int(String(chars[right]))!
right += 1
}
if val == 0 { val = 1 }
for (k,v) in res { res[k] = v * val }
if !stack.isEmpty {
let tmp = stack.removeLast()
res.merge(tmp) { (v1, v2) -> Int in return v1 + v2 }
}
i = right
} else {
var right = i + 1
while right < chars.count && chars[right].isLetter && chars[right].isLowercase { right += 1 }
let atom = String(chars[i..<right])
i = right
var val = 0
while i < chars.count && chars[i].isNumber {
val = val * 10 + Int(String(chars[i]))!
i += 1
}
if val == 0 { val = 1 }
res[atom] = (res[atom] ?? 0) + val
}
}
return (res, i)
}
} | 36.931373 | 291 | 0.496416 |
21340742a4da6f32f7926b62799a6599a51b1a67 | 944 | //
// DoubleExtension.swift
// Fastcampus
//
// Created by 양중창 on 2020/07/14.
// Copyright © 2020 Kira. All rights reserved.
//
import Foundation
extension Double {
var toTimeString: String {
let interval = Int(self)
let oneMinute = 60
let oneHour = oneMinute * 60
let oneday = oneHour * 24
let days = interval / oneday
let daysToString = days != 0 ? "\(days)일 ": ""
let hours = (interval - (days * oneday)) / oneHour
let hoursToString = hours < 10 ? "0\(hours)": "\(hours)"
let minutes = (interval - (days * oneday) - (hours * oneHour)) / oneMinute
let minuteToString = minutes < 10 ? "0\(minutes)": "\(minutes)"
let sec = (interval - (days * oneday) - (hours * oneHour) - (minutes * oneMinute))
let secToString = sec < 10 ? "0\(sec)": "\(sec)"
let result = daysToString + hoursToString + ":" + minuteToString + ":" + secToString
return result
}
}
| 26.222222 | 88 | 0.59428 |
11346a9ff66cdd207cbe263b61658236dc7d5bca | 1,406 | //
// AnonymousObservable.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class AnonymousObservableSink<O: ObserverType> : Sink<O>, ObserverType {
typealias E = O.E
typealias Parent = AnonymousObservable<E>
// state
private var _isStopped: AtomicInt = 0
override init(observer: O) {
super.init(observer: observer)
}
func on(event: Event<E>) {
switch event {
case .Next:
if _isStopped == 1 {
return
}
forwardOn(event)
case .Error, .Completed:
if AtomicCompareAndSwap(0, 1, &_isStopped) {
forwardOn(event)
dispose()
}
}
}
func run(parent: Parent) -> Disposable {
return parent._subscribeHandler(AnyObserver(self))
}
}
class AnonymousObservable<Element> : Producer<Element> {
typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable
let _subscribeHandler: SubscribeHandler
init(_ subscribeHandler: SubscribeHandler) {
_subscribeHandler = subscribeHandler
}
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
let sink = AnonymousObservableSink(observer: observer)
sink.disposable = sink.run(self)
return sink
}
}
| 24.666667 | 89 | 0.613798 |
872bdeea95a106f3a029f900f01d7e8a1431f9eb | 2,155 | //
// ProfileAndMembershipTableViewCell.swift
// Simple Login
//
// Created by Thanh-Nhon Nguyen on 16/01/2020.
// Copyright © 2020 SimpleLogin. All rights reserved.
//
import UIKit
final class ProfileAndMembershipTableViewCell: UITableViewCell, RegisterableCell {
@IBOutlet private weak var avatarImageView: AvatarImageView!
@IBOutlet private weak var usernameLabel: UILabel!
@IBOutlet private weak var emailLabel: UILabel!
@IBOutlet private weak var modifyLabel: UILabel!
@IBOutlet private weak var membershipLabel: UILabel!
@IBOutlet private weak var upgradeLabel: UILabel!
var didTapModifyLabel: (() -> Void)?
var didTapUpgradeLabel: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
// let tapModify = UITapGestureRecognizer(target: self, action: #selector(modifyLabelTapped))
// modifyLabel.isUserInteractionEnabled = true
// modifyLabel.addGestureRecognizer(tapModify)
modifyLabel.isHidden = true
let tapUpgrade = UITapGestureRecognizer(target: self, action: #selector(upgradeLabelTapped))
upgradeLabel.isUserInteractionEnabled = true
upgradeLabel.addGestureRecognizer(tapUpgrade)
}
@objc private func modifyLabelTapped() {
didTapModifyLabel?()
}
@objc private func upgradeLabelTapped() {
didTapUpgradeLabel?()
}
func bind(with userInfo: UserInfo) {
usernameLabel.text = userInfo.name
emailLabel.text = userInfo.email
if userInfo.inTrial {
membershipLabel.text = "Premium trial membership"
membershipLabel.textColor = .systemBlue
upgradeLabel.isHidden = false
} else if userInfo.isPremium {
membershipLabel.text = "Premium membership"
membershipLabel.textColor = SLColor.premiumColor
upgradeLabel.isHidden = true
} else {
membershipLabel.text = "Free membership"
membershipLabel.textColor = SLColor.titleColor
upgradeLabel.isHidden = false
}
}
}
| 34.206349 | 100 | 0.668677 |
0af5e69d71c8b63a19d4ae8e0b3edd7695eb23d2 | 18,097 | //
// MessagePresenter.swift
// SwiftMessages
//
// Created by Timothy Moose on 7/30/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
protocol PresenterDelegate: AnimationDelegate {
func hide(presenter: Presenter)
}
//弹出框的类
class Presenter: NSObject {
//弹出的上下文
enum PresentationContext {
//类型
case viewController(_: Weak<UIViewController>)
case view(_: Weak<UIView>)
func viewControllerValue() -> UIViewController? {
switch self {
case .viewController(let weak):
return weak.value
case .view:
return nil
}
}
func viewValue() -> UIView? {
switch self {
case .viewController(let weak):
return weak.value?.view
case .view(let weak):
return weak.value
}
}
}
var config: SwiftMessages.Config
//显示的view
let view: UIView
weak var delegate: PresenterDelegate?
let maskingView = MaskingView()
var presentationContext = PresentationContext.viewController(Weak<UIViewController>(value: nil))
//
let animator: Animator
init(config: SwiftMessages.Config, view: UIView, delegate: PresenterDelegate) {
self.config = config
self.view = view
self.delegate = delegate
self.animator = Presenter.animator(forPresentationStyle: config.presentationStyle, delegate: delegate)
if let identifiable = view as? Identifiable {
id = identifiable.id
} else {
var mutableView = view
//指针地址作为id
id = withUnsafePointer(to: &mutableView) { "\($0)" }
}
super.init()
}
//动画:返回值是一个协议
private static func animator(forPresentationStyle style: SwiftMessages.PresentationStyle, delegate: AnimationDelegate) -> Animator {
switch style {
case .top:
return TopBottomAnimation(style: .top, delegate: delegate)
case .bottom:
return TopBottomAnimation(style: .bottom, delegate: delegate)
case .center:
return PhysicsAnimation(delegate: delegate)
case .custom(let animator):
animator.delegate = delegate
return animator
}
}
var id: String
var pauseDuration: TimeInterval? {
let duration: TimeInterval?
switch self.config.duration {
case .automatic:
duration = 2
case .seconds(let seconds):
duration = seconds
case .forever, .indefinite:
duration = nil
}
return duration
}
//记录时间
var showDate: CFTimeInterval?
private var interactivelyHidden = false;
//延迟时间
var delayShow: TimeInterval? {
if case .indefinite(let opts) = config.duration { return opts.delay }
return nil
}
/// Returns the required delay for hiding based on time shown
var delayHide: TimeInterval? {
if interactivelyHidden { return 0 }
if case .indefinite(let opts) = config.duration, let showDate = showDate {
let timeIntervalShown = CACurrentMediaTime() - showDate
return max(0, opts.minimum - timeIntervalShown)
}
return nil
}
/*
MARK: - Showing and hiding
*/
//显示
func show(completion: @escaping AnimationCompletion) throws {
try presentationContext = getPresentationContext()
install()
//将要显示
self.config.eventListeners.forEach { $0(.willShow) }
showAnimation() { completed in
completion(completed)
if completed {
if self.config.dimMode.modal {
self.showAccessibilityFocus()
} else {
self.showAccessibilityAnnouncement()
}
self.config.eventListeners.forEach { $0(.didShow) }
}
}
}
//动画显示
private func showAnimation(completion: @escaping AnimationCompletion) {
//动画设置maskingView的背景色
func dim(_ color: UIColor) {
self.maskingView.backgroundColor = UIColor.clear
UIView.animate(withDuration: 0.2, animations: {
self.maskingView.backgroundColor = color
})
}
//动画设置模糊背景
func blur(style: UIBlurEffect.Style, alpha: CGFloat) {
let blurView = UIVisualEffectView(effect: nil)
blurView.alpha = alpha
maskingView.backgroundView = blurView
UIView.animate(withDuration: 0.3) {
blurView.effect = UIBlurEffect(style: style)
}
}
let context = animationContext()
animator.show(context: context) { (completed) in
completion(completed)
}
switch config.dimMode {
case .none:
break
case .gray:
dim(UIColor(white: 0, alpha: 0.3))
case .color(let color, _):
dim(color)
case .blur(let style, let alpha, _):
blur(style: style, alpha: alpha)
}
}
private func showAccessibilityAnnouncement() {
guard let accessibleMessage = view as? AccessibleMessage,
let message = accessibleMessage.accessibilityMessage else { return }
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: message)
}
private func showAccessibilityFocus() {
guard let accessibleMessage = view as? AccessibleMessage,
let focus = accessibleMessage.accessibilityElement ?? accessibleMessage.additonalAccessibilityElements?.first else { return }
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: focus)
}
//隐藏
var isHiding = false
func hide(animated: Bool, completion: @escaping AnimationCompletion) {
isHiding = true
self.config.eventListeners.forEach { $0(.willHide) }
let context = animationContext()
let action = {
if let viewController = self.presentationContext.viewControllerValue() as? WindowViewController {
viewController.uninstall()
}
self.maskingView.removeFromSuperview()
completion(true)
self.config.eventListeners.forEach { $0(.didHide) }
}
guard animated else {
action()
return
}
animator.hide(context: context) { (completed) in
action()
}
func undim() {
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
self.maskingView.backgroundColor = UIColor.clear
}, completion: nil)
}
func unblur() {
guard let view = maskingView.backgroundView as? UIVisualEffectView else { return }
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
view.effect = nil
}, completion: nil)
}
switch config.dimMode {
case .none:
break
case .gray:
undim()
case .color:
undim()
case .blur:
unblur()
}
}
private func animationContext() -> AnimationContext {
return AnimationContext(messageView: view, containerView: maskingView, safeZoneConflicts: safeZoneConflicts(), interactiveHide: config.interactiveHide)
}
private func safeZoneConflicts() -> SafeZoneConflicts {
guard let window = maskingView.window else { return [] }
let windowLevel: UIWindow.Level = {
if let vc = presentationContext.viewControllerValue() as? WindowViewController {
return vc.windowLevel
}
return UIWindow.Level.normal
}()
// TODO `underNavigationBar` and `underTabBar` should look up the presentation context's hierarchy
// TODO for cases where both should be true (probably not an issue for typical height messages, though).
let underNavigationBar: Bool = {
if let vc = presentationContext.viewControllerValue() as? UINavigationController { return vc.sm_isVisible(view: vc.navigationBar) }
return false
}()
let underTabBar: Bool = {
if let vc = presentationContext.viewControllerValue() as? UITabBarController { return vc.sm_isVisible(view: vc.tabBar) }
return false
}()
if #available(iOS 11, *) {
if windowLevel > UIWindow.Level.normal {
// TODO seeing `maskingView.safeAreaInsets.top` value of 20 on
// iPhone 8 with status bar window level. This seems like an iOS bug since
// the message view's window is above the status bar. Applying a special rule
// to allow the animator to revove this amount from the layout margins if needed.
// This may need to be reworked if any future device has a legitimate 20pt top safe area,
// such as with a potentially smaller notch.
if maskingView.safeAreaInsets.top == 20 {
return [.overStatusBar]
} else {
var conflicts: SafeZoneConflicts = []
if maskingView.safeAreaInsets.top > 0 {
conflicts.formUnion(.sensorNotch)
}
if maskingView.safeAreaInsets.bottom > 0 {
conflicts.formUnion(.homeIndicator)
}
return conflicts
}
}
var conflicts: SafeZoneConflicts = []
if !underNavigationBar {
conflicts.formUnion(.sensorNotch)
}
if !underTabBar {
conflicts.formUnion(.homeIndicator)
}
return conflicts
} else {
#if SWIFTMESSAGES_APP_EXTENSIONS
return []
#else
if UIApplication.shared.isStatusBarHidden { return [] }
if (windowLevel > UIWindow.Level.normal) || underNavigationBar { return [] }
let statusBarFrame = UIApplication.shared.statusBarFrame
let statusBarWindowFrame = window.convert(statusBarFrame, from: nil)
let statusBarViewFrame = maskingView.convert(statusBarWindowFrame, from: nil)
return statusBarViewFrame.intersects(maskingView.bounds) ? SafeZoneConflicts.statusBar : []
#endif
}
}
private func getPresentationContext() throws -> PresentationContext {
func newWindowViewController(_ windowLevel: UIWindow.Level) -> UIViewController {
let viewController = WindowViewController.newInstance(windowLevel: windowLevel, config: config)
return viewController
}
switch config.presentationContext {
case .automatic:
#if SWIFTMESSAGES_APP_EXTENSIONS
throw SwiftMessagesError.noRootViewController
#else
if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
let viewController = rootViewController.sm_selectPresentationContextTopDown(config)
return .viewController(Weak(value: viewController))
} else {
throw SwiftMessagesError.noRootViewController
}
#endif
case .window(let level):
let viewController = newWindowViewController(level)
return .viewController(Weak(value: viewController))
case .viewController(let viewController):
let viewController = viewController.sm_selectPresentationContextBottomUp(config)
return .viewController(Weak(value: viewController))
case .view(let view):
return .view(Weak(value: view))
}
}
/*
MARK: - Installation
*/
func install() {
func topLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint {
if case .top = config.presentationStyle, let nav = viewController as? UINavigationController, nav.sm_isVisible(view: nav.navigationBar) {
return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: nav.navigationBar, attribute: .bottom, multiplier: 1.00, constant: 0.0)
}
return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1.00, constant: 0.0)
}
func bottomLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint {
if case .bottom = config.presentationStyle, let tab = viewController as? UITabBarController, tab.sm_isVisible(view: tab.tabBar) {
return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: tab.tabBar, attribute: .top, multiplier: 1.00, constant: 0.0)
}
return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1.00, constant: 0.0)
}
func installMaskingView(containerView: UIView) {
maskingView.translatesAutoresizingMaskIntoConstraints = false
if let nav = presentationContext.viewControllerValue() as? UINavigationController {
containerView.insertSubview(maskingView, belowSubview: nav.navigationBar)
} else if let tab = presentationContext.viewControllerValue() as? UITabBarController {
containerView.insertSubview(maskingView, belowSubview: tab.tabBar)
} else {
containerView.addSubview(maskingView)
}
maskingView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
maskingView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
topLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue()).isActive = true
bottomLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue()).isActive = true
if let keyboardTrackingView = config.keyboardTrackingView {
maskingView.install(keyboardTrackingView: keyboardTrackingView)
}
// Update the container view's layout in order to know the masking view's frame
containerView.layoutIfNeeded()
}
func installInteractive() {
guard config.dimMode.modal else { return }
if config.dimMode.interactive {
maskingView.tappedHander = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.interactivelyHidden = true
strongSelf.delegate?.hide(presenter: strongSelf)
}
} else {
// There's no action to take, but the presence of
// a tap handler prevents interaction with underlying views.
maskingView.tappedHander = { }
}
}
func installAccessibility() {
var elements: [NSObject] = []
if let accessibleMessage = view as? AccessibleMessage {
if let message = accessibleMessage.accessibilityMessage {
let element = accessibleMessage.accessibilityElement ?? view
element.isAccessibilityElement = true
if element.accessibilityLabel == nil {
element.accessibilityLabel = message
}
elements.append(element)
}
if let additional = accessibleMessage.additonalAccessibilityElements {
elements += additional
}
} else {
elements += [view]
}
if config.dimMode.interactive {
let dismissView = UIView(frame: maskingView.bounds)
dismissView.translatesAutoresizingMaskIntoConstraints = true
dismissView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
maskingView.addSubview(dismissView)
maskingView.sendSubviewToBack(dismissView)
dismissView.isUserInteractionEnabled = false
dismissView.isAccessibilityElement = true
dismissView.accessibilityLabel = config.dimModeAccessibilityLabel
dismissView.accessibilityTraits = UIAccessibilityTraits.button
elements.append(dismissView)
}
if config.dimMode.modal {
maskingView.accessibilityViewIsModal = true
}
maskingView.accessibleElements = elements
}
//容器View
guard let containerView = presentationContext.viewValue() else { return }
if let windowViewController = presentationContext.viewControllerValue() as? WindowViewController {
if #available(iOS 13, *) {
let scene = UIApplication.shared.keyWindow?.windowScene
windowViewController.install(becomeKey: becomeKeyWindow, scene: scene)
} else {
windowViewController.install(becomeKey: becomeKeyWindow)
}
}
installMaskingView(containerView: containerView)
installInteractive()
installAccessibility()
}
private var becomeKeyWindow: Bool {
//可选值的等于
if config.becomeKeyWindow == .some(true) { return true }
switch config.dimMode {
case .gray, .color, .blur:
// Should become key window in modal presentation style
// for proper VoiceOver handling.
return true
case .none:
return false
}
}
}
| 40.851016 | 169 | 0.606454 |
6aa6563ac86c2d0cd981a39ad24f6597a52416cd | 747 | import XCTest
import BlueIntent
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.758621 | 111 | 0.601071 |
e941189f9129f9c86142d3790785a878ce448dca | 5,146 | //
// ItemRowView.swift
// ACHNBrowserUI
//
// Created by Thomas Ricouard on 08/04/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import Backend
import UI
struct ItemRowView: View {
@EnvironmentObject private var collection: UserCollection
enum DisplayMode {
case compact, large, largeNoButton
}
let displayMode: DisplayMode
let item: Item
@State private var displayedVariant: Variant?
private var imageSize: CGFloat {
switch displayMode {
case .compact:
return 25
case .large, .largeNoButton:
return 100
}
}
private var itemInfo: some View {
Group {
Text(item.localizedName.capitalized)
.style(appStyle: .rowTitle)
Text(LocalizedStringKey(item.obtainedFrom ?? item.obtainedFromNew?.first ?? "unknown source"))
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(.acSecondaryText)
}
}
private var itemSubInfo: some View {
HStack {
if (item.isCritter && item.formattedTimes() != nil) {
HStack(spacing: 4) {
Image(systemName: "clock")
.resizable()
.frame(width: 12, height: 12)
.foregroundColor(.acSecondaryText)
Text(item.formattedTimes()!)
.foregroundColor(.acSecondaryText)
.fontWeight(.semibold)
.font(.caption)
}
}
if item.buy != nil {
ItemBellsView(mode: .buy, price: item.buy!)
}
if item.sell != nil {
ItemBellsView(mode: .buy, price: item.sell!)
}
Spacer()
}
}
private var itemVariants: some View {
Group {
if item.variations != nil {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 2) {
item.variations.map { variations in
ForEach(variations) { variant in
ItemImage(path: variant.content.image,
size: 25)
.cornerRadius(4)
.background(Rectangle()
.cornerRadius(4)
.foregroundColor(self.displayedVariant == variant ? Color.gray : Color.clear))
.onTapGesture {
FeedbackGenerator.shared.triggerSelection()
self.displayedVariant = variant
}
}
}
}.frame(height: 30)
}
}
}
}
var body: some View {
HStack(spacing: 8) {
if displayMode != .largeNoButton {
LikeButtonView(item: item,
variant: displayedVariant).environmentObject(collection)
}
if item.finalImage == nil && displayedVariant == nil {
Image(item.appCategory.iconName())
.resizable()
.frame(width: imageSize, height: imageSize)
} else {
ItemImage(path: displayedVariant?.content.image ?? item.finalImage,
size: imageSize)
}
VStack(alignment: .leading, spacing: 2) {
itemInfo
if displayMode != .compact {
itemSubInfo
.padding(.top, 4)
itemVariants
}
}
Spacer()
}
}
}
struct ItemRowView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
VStack {
List {
ItemRowView(displayMode: .large, item: static_item)
.environmentObject(UserCollection.shared)
ItemRowView(displayMode: .compact, item: static_item)
.environmentObject(UserCollection.shared)
ItemRowView(displayMode: .large, item: static_item)
.environmentObject(UserCollection.shared)
}
List {
ItemRowView(displayMode: .large, item: static_item)
.environmentObject(UserCollection.shared)
ItemRowView(displayMode: .compact, item: static_item)
.environmentObject(UserCollection.shared)
ItemRowView(displayMode: .large, item: static_item)
.environmentObject(UserCollection.shared)
}
.environment(\.colorScheme, .dark)
}
}
}
}
| 34.306667 | 118 | 0.46405 |
9cb7184552e698818944b5a892972bd652aec281 | 2,646 | //
// HomeViewController.swift
// Unsplash
//
// Created by LMinh on 4/22/20.
// Copyright © 2020 LMinh. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
// MARK: - Properties
var viewModel: HomeViewModel = HomeViewModel()
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var downloadButton: UIButton!
@IBOutlet weak var collectionView: PhotoCollectionView!
var refreshControl: UIRefreshControl!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// UI Stuff
setupUI()
updateUI()
// Reload photos
viewModel.loadPhotos()
}
// MARK: - UI Stuff
func setupUI() {
// Navigation Bar
navigationController?.navigationBar.isHidden = true
// Collection View
collectionView.photoDelegate = self
// Pull to refresh
refreshControl = UIRefreshControl(frame: .zero)
refreshControl.addTarget(self, action: #selector(refreshControlValueChanged), for: .valueChanged)
collectionView.backgroundView = refreshControl
}
func updateUI() {
viewModel.collectionDatasource.bind { [weak self] (photosCollection, progressStatus) in
DispatchQueue.main.async {
self?.collectionView.progressStatus = progressStatus
self?.collectionView.photosCollection = photosCollection
self?.collectionView.reloadData()
if !progressStatus.isLoading {
self?.refreshControl.endRefreshing()
}
}
}
}
// MARK: - Events
@IBAction func downloadButtonTapped(_ sender: Any) {
let viewController = CollectionViewController.instanceFromStoryboard
navigationController?.pushViewController(viewController, animated: true)
}
@objc func refreshControlValueChanged(_ sender: Any) {
viewModel.refreshPhotos()
}
}
// MARK: - Photo Collection View
extension HomeViewController: PhotoCollectionViewDelegate {
func photoCollectionViewDidSelectPhoto(_ photo: Photo, cell: PhotoCell, indexPath: IndexPath) {
let viewController = PhotoViewController.instanceFromStoryboard
viewController.viewModel = PhotoViewModel(photo: photo)
present(viewController, animated: true, completion: nil)
}
func photoCollectionViewNeedLoadMore() {
viewModel.loadMorePhotos()
}
}
| 29.076923 | 105 | 0.647014 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.