repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
lvogelzang/Blocky
Blocky/Levels/Level31.swift
1
877
// // Level31.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level31: Level { let levelNumber = 31 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
1af39aa6d7297e740a4e789a597ccf6e
24.794118
89
0.573546
2.649547
false
false
false
false
multinerd/Mia
Mia/Libraries/DeviceKit/Device.swift
1
2893
import SystemConfiguration.CaptiveNetwork // MARK: - *** Device *** public struct Device { public struct Accessories { } public struct Carrier { } public struct Disk { } public struct Firmware { } public struct Processors { } public struct Screen { } public struct Sensors { } public struct Settings { } } // MARK: - *** Battery *** extension Device { public struct Battery { /// Determines whether the low power mode is currently enabled @available(iOS 9.0, *) public static var isLowPowerModeEnabled: Bool { return ProcessInfo().isLowPowerModeEnabled } /// The battery's current level public static var level: Int { UIDevice.current.isBatteryMonitoringEnabled = true let batteryLevel = Int(UIDevice.current.batteryLevel * 100) UIDevice.current.isBatteryMonitoringEnabled = false return batteryLevel } /// The battery's current public static var state: UIDeviceBatteryState { UIDevice.current.isBatteryMonitoringEnabled = true let batteryState = UIDevice.current.batteryState UIDevice.current.isBatteryMonitoringEnabled = false return batteryState } } } // MARK: - *** Network *** extension Device { public struct Network { private static var connection: Reachability.Connection { return Reachability()!.connection } /// Determines whether the device is connected to the WiFi network public static var isConnected: Bool { return connection != .none } /// Determines whether the device is connected to the WiFi network public static var isConnectedViaWiFi: Bool { return connection == .wifi } /// Determines whether the device is connected to the cellular network public static var isConnectedViaCellular: Bool { return connection == .cellular } /// Get the name of the network the device is currently connected to. Does not work on Simulator. public static var ssidName: String { guard isConnectedViaWiFi, let interfaces = CNCopySupportedInterfaces(), let interfacesArray = interfaces as? [String], interfacesArray.count > 0, let unsafeInterfaceData = CNCopyCurrentNetworkInfo(interfacesArray[0] as CFString), let interfaceData = unsafeInterfaceData as? [String: Any], let ssid = interfaceData["SSID"] as? String else { return "" } return ssid } } } // MARK: - *** Screen *** extension Device { public struct Screens { } }
mit
3bdcf353ced1c87a2a8513415da3f252
23.310924
105
0.59281
5.694882
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Transport/HTTP/HTTPTransport.swift
1
2111
// // HTTPTransport.swift // // // Created by Vladislav Fitc on 19/02/2020. // import Foundation /** The transport layer is responsible of the serialization/deserialization and the retry strategy. */ class HTTPTransport: Transport { var applicationID: ApplicationID { return credentials.applicationID } var apiKey: APIKey { return credentials.apiKey } let requestBuilder: HTTPRequestBuilder let operationLauncher: OperationLauncher let credentials: Credentials init(requestBuilder: HTTPRequestBuilder, operationLauncher: OperationLauncher, credentials: Credentials) { self.requestBuilder = requestBuilder self.operationLauncher = operationLauncher self.credentials = credentials } convenience init(requester: HTTPRequester, configuration: Configuration, retryStrategy: RetryStrategy, credentials: Credentials, operationLauncher: OperationLauncher) { let requestBuilder = HTTPRequestBuilder(requester: requester, retryStrategy: retryStrategy, configuration: configuration, credentials: credentials) self.init(requestBuilder: requestBuilder, operationLauncher: operationLauncher, credentials: credentials) } func execute<Command: AlgoliaCommand, Response: Decodable, Output>(_ command: Command, transform: @escaping (Response) -> Output, completion: @escaping (Result<Output, Swift.Error>) -> Void) -> Operation & TransportTask { let request = requestBuilder.build(for: command, transform: transform, with: completion) return operationLauncher.launch(request) } func execute<Command: AlgoliaCommand, Response: Decodable, Output>(_ command: Command, transform: @escaping (Response) -> Output) throws -> Output { let request = requestBuilder.build(for: command, transform: transform, responseType: Output.self) return try operationLauncher.launchSync(request) } @discardableResult func launch<O: Operation>(_ operation: O) -> O { return operationLauncher.launch(operation) } func launch<O: OperationWithResult>(_ operation: O) throws -> O.ResultValue { return try operationLauncher.launchSync(operation) } }
mit
86fd1351054086caf1c6484e4bc94da3
36.696429
223
0.765988
5.02619
false
true
false
false
EclipseSoundscapes/EclipseSoundscapes
EclipseSoundscapes/Features/RumbleMap/RumbleCardView.swift
1
15971
// // RumbleCardView.swift // EclipseSoundscapes // // Created by Arlindo Goncalves on 7/5/17. // // Copyright © 2017 Arlindo Goncalves. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see [http://www.gnu.org/licenses/]. // // For Contact email: [email protected] // import Material import RxSwift import RxCocoa class RumbleCardView: UIView { private struct Constants { static let animationDuration: TimeInterval = 0.5 static let imageHeightRatio: CGFloat = 3 / 4 static let arrowButtonHeight: CGFloat = 40 static let arrowButtonWidth: CGFloat = 40 static let closeButtonHeight: CGFloat = 35 static let closeButtonWidth: CGFloat = 35 static let gradientPadding: CGFloat = 20 static let maxWordCount: Int = 50 } private let trashBag = DisposeBag() private let card = View() private let descriptionCard = View() private let backgroundView = View() private let imageView = UIImageView() private let contentView = UIView() private let titleLabel = UILabel() private let summaryLabel = UILabel() private let descriptionTextView = UITextView() private let descriptionTitleLabel = UILabel() private let leftArrowButton = IconButton(image: #imageLiteral(resourceName: "Left_Arrow").withRenderingMode(.alwaysTemplate), tintColor: SoundscapesColor.eclipseOrange) private let rightArrowButton = IconButton(image: #imageLiteral(resourceName: "Right_Arrow").withRenderingMode(.alwaysTemplate), tintColor: SoundscapesColor.eclipseOrange) private let readMoreButton = UIButton(type: .system) private let rumbleButton = UIButton(type: .system) override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { backgroundColor = .clear setupImageView() setupArrowButtons() setupReadMoreButton() setupRumbleButton() setupTitleLabel() setupSummaryLabel() setupDescriptionTextView() setupBackgroundView() setupDescriptionCard() setupCard() setupContentView() setupCardComponents() setupContentViewComponents() setupDescriptionCardComponents() } private func setupImageView() { imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.image = #imageLiteral(resourceName: "frontier") imageView.clipsToBounds = true } private func setupArrowButtons() { leftArrowButton.translatesAutoresizingMaskIntoConstraints = false leftArrowButton.accessibilityLabel = localizedString(key: "Previous") leftArrowButton.accessibilityHint = localizedString(key: "RumbleCardLeftArrowHint") rightArrowButton.translatesAutoresizingMaskIntoConstraints = false rightArrowButton.accessibilityLabel = localizedString(key: "Next") rightArrowButton.accessibilityHint = localizedString(key: "RumbleCardRightArrowHint") } private func setupRumbleButton() { rumbleButton.translatesAutoresizingMaskIntoConstraints = false rumbleButton.setTitle(localizedString(key: "RumbleCardOpenButtonTitle"), for: .normal) rumbleButton.setTitleColor(SoundscapesColor.eclipseOrange, for: .normal) rumbleButton.titleLabel?.font = UIFont.getDefautlFont(.bold, size: 22) rumbleButton.addSqueeze() } private func setupTitleLabel() { titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = UIFont.getDefautlFont(.extraBold, size: 25) titleLabel.textAlignment = .center titleLabel.textColor = .white titleLabel.adjustsFontSizeToFitWidth = true titleLabel.accessibilityTraits = .header } private func setupSummaryLabel() { summaryLabel.translatesAutoresizingMaskIntoConstraints = false summaryLabel.font = UIFont.getDefautlFont(.meduium, size: 15) summaryLabel.numberOfLines = 0 summaryLabel.accessibilityHint = localizedString(key: "RumbleCardSummaryLabelHint") } private func setupDescriptionTextView() { descriptionTextView.isEditable = false descriptionTextView.translatesAutoresizingMaskIntoConstraints = false descriptionTextView.font = UIFont.getDefautlFont(.meduium, size: 15) descriptionTextView.accessibilityTraits = .staticText } private func setupReadMoreButton() { readMoreButton.translatesAutoresizingMaskIntoConstraints = false readMoreButton.setTitle(localizedString(key: "RumbleCardReadMoreButtonTitle"), for: .normal) readMoreButton.setTitleColor(.black, for: .normal) readMoreButton.titleLabel?.font = UIFont.getDefautlFont(.meduium, size: 22) readMoreButton.addSqueeze() readMoreButton.accessibilityHint = localizedString(key: "RumbleCardReadMoreButtonHint") readMoreButton.addTarget(self, action: #selector(openRumbleMapDescription), for: .touchUpInside) } private func setupCard() { card.translatesAutoresizingMaskIntoConstraints = false card.cornerRadiusPreset = .cornerRadius3 card.backgroundColor = .white card.clipsToBounds = true addSubview(card) card.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor) card.accessibilityElements = [titleLabel, leftArrowButton, rightArrowButton, rumbleButton, contentView] } private func setupDescriptionCard() { descriptionCard.translatesAutoresizingMaskIntoConstraints = false descriptionCard.cornerRadiusPreset = .cornerRadius3 descriptionCard.backgroundColor = .white descriptionCard.clipsToBounds = true descriptionCard.isHidden = true addSubview(descriptionCard) descriptionCard.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor) } func setupContentView() { contentView.isAccessibilityElement = false contentView.accessibilityElements = [summaryLabel, readMoreButton] } func setupBackgroundView() { backgroundView.translatesAutoresizingMaskIntoConstraints = false backgroundView.cornerRadiusPreset = .cornerRadius3 backgroundView.depthPreset = .depth5 backgroundView.shadowColor = SoundscapesColor.eclipseOrange backgroundView.backgroundColor = SoundscapesColor.lead addSubview(backgroundView) backgroundView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor) } private func setupCardComponents() { let topGradientView = GradientView() topGradientView.translatesAutoresizingMaskIntoConstraints = false topGradientView.setDirection(to: .topToBottom) let bottomGradeientView = GradientView() bottomGradeientView.translatesAutoresizingMaskIntoConstraints = false bottomGradeientView.setDirection(to: .bottomToTop) card.addSubviews(imageView, topGradientView, bottomGradeientView, titleLabel, leftArrowButton, rightArrowButton, rumbleButton, contentView) contentView.anchor(nil, left: card.leftAnchor, bottom: card.bottomAnchor, right: card.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) imageView.heightAnchor.constraint(equalTo: card.heightAnchor, multiplier: Constants.imageHeightRatio).isActive = true imageView.anchor(card.topAnchor, left: card.leftAnchor, bottom: contentView.topAnchor, right: card.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) leftArrowButton.topAnchor.constraint(equalTo: imageView.topAnchor, constant: 16).isActive = true leftArrowButton.leftAnchor.constraint(equalTo: imageView.leftAnchor, constant: 8).isActive = true leftArrowButton.setSize(Constants.arrowButtonWidth, height: Constants.arrowButtonHeight) rightArrowButton.topAnchor.constraint(equalTo: imageView.topAnchor, constant: 16).isActive = true rightArrowButton.rightAnchor.constraint(equalTo: imageView.rightAnchor, constant: -8).isActive = true rightArrowButton.setSize(Constants.arrowButtonWidth, height: Constants.arrowButtonHeight) titleLabel.centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true titleLabel.topAnchor.constraint(equalTo: imageView.topAnchor, constant: 16).isActive = true titleLabel.leftAnchor.constraint(equalTo: leftArrowButton.rightAnchor, constant: 8).isActive = true titleLabel.rightAnchor.constraint(equalTo: rightArrowButton.leftAnchor, constant: -8).isActive = true rumbleButton.anchor(left: imageView.leftAnchor, bottom: imageView.bottomAnchor, right: imageView.rightAnchor, leftConstant: 0, bottomConstant: 4, rightConstant: 0) topGradientView.anchor(imageView.topAnchor, left: imageView.leftAnchor, bottom: titleLabel.bottomAnchor, right: imageView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: -Constants.gradientPadding, rightConstant: 0, widthConstant: 0, heightConstant: 0) bottomGradeientView.anchor(rumbleButton.topAnchor, left: imageView.leftAnchor, bottom: imageView.bottomAnchor, right: imageView.rightAnchor, topConstant: -Constants.gradientPadding, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) } private func setupDescriptionCardComponents() { descriptionTitleLabel.translatesAutoresizingMaskIntoConstraints = false descriptionTitleLabel.font = UIFont.getDefautlFont(.extraBold, size: 22) descriptionTitleLabel.textAlignment = .center descriptionTitleLabel.adjustsFontSizeToFitWidth = true descriptionTitleLabel.accessibilityTraits = UIAccessibilityTraits.header let closeButton = UIButton(type: .system) closeButton.translatesAutoresizingMaskIntoConstraints = false closeButton.setImage(#imageLiteral(resourceName: "close"), for: .normal) closeButton.tintColor = SoundscapesColor.eclipseOrange closeButton.addSqueeze() closeButton.addTarget(self, action: #selector(closeRumbleMapDescription), for: .touchUpInside) descriptionCard.addSubviews(descriptionTitleLabel, descriptionTextView, closeButton) descriptionTitleLabel.anchor(descriptionCard.topAnchor, left: descriptionCard.leftAnchor, bottom: descriptionTextView.topAnchor, right: closeButton.leftAnchor, topConstant: 8, leftConstant: Constants.closeButtonWidth + 8 + 2, bottomConstant: 2, rightConstant: 2) closeButton.anchor(descriptionCard.topAnchor, right: descriptionCard.rightAnchor, topConstant: 8, rightConstant: 8) closeButton.setSize(Constants.closeButtonWidth, height: Constants.closeButtonHeight) descriptionTextView.anchor(closeButton.bottomAnchor, left: descriptionCard.leftAnchor, bottom: descriptionCard.bottomAnchor, right: descriptionCard.rightAnchor, topConstant: 4, leftConstant: 8, bottomConstant: 0, rightConstant: 8) } private func setupContentViewComponents() { contentView.addSubviews(summaryLabel, readMoreButton) summaryLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true summaryLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16).isActive = true summaryLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16).isActive = true summaryLabel.setContentCompressionResistancePriority(.defaultLow, for: .vertical) readMoreButton.anchor(summaryLabel.bottomAnchor, left: contentView.leftAnchor, bottom: contentView.bottomAnchor, right: contentView.rightAnchor, topConstant: 4, leftConstant: 0, bottomConstant: 4, rightConstant: 0, widthConstant: 0, heightConstant: 0) readMoreButton.setContentCompressionResistancePriority(.required, for: .vertical) } func bind(to rumbleMapViewModel: RumbleMapViewModel) { rumbleMapViewModel.currentRumbleEvent.asDriver() .drive(onNext: { [unowned self] rumbleEvent in guard let rumbleEvent = rumbleEvent else { return } self.updateView(with: rumbleEvent) }).disposed(by: trashBag) leftArrowButton.rx.tap .subscribe(onNext: { rumbleMapViewModel.setPreviousRumbleEvent() }).disposed(by: trashBag) rightArrowButton.rx.tap .subscribe(onNext: { rumbleMapViewModel.setNextRumbleEvent() }).disposed(by: trashBag) rumbleButton.rx.tap .subscribe(onNext: { rumbleMapViewModel.openRumbleMap() }).disposed(by: trashBag) } @objc private func openRumbleMapDescription() { let transitionOptions: UIView.AnimationOptions = [.transitionFlipFromLeft, .showHideTransitionViews] flipCards(fromView: card, toView: descriptionCard, with: transitionOptions) } @objc private func closeRumbleMapDescription() { let transitionOptions: UIView.AnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews] flipCards(fromView: descriptionCard, toView: card, with: transitionOptions) } private func flipCards(fromView: UIView, toView: UIView, with transitionOptions: UIView.AnimationOptions) { UIView.transition(from: fromView, to: toView, duration: Constants.animationDuration, options: transitionOptions) } private func updateView(with event: RumbleEvent) { updateImage(to: event.image) updateTitle(to: event.name) updateSummary(to: event.info) } private func updateImage(to image: UIImage?) { UIView.transition(with: imageView, duration: Constants.animationDuration, options: UIView.AnimationOptions.transitionCrossDissolve, animations: { self.imageView.image = image }, completion: nil) } private func updateTitle(to title: String?) { descriptionTitleLabel.text = title UIView.transition(with: titleLabel, duration: Constants.animationDuration, options: UIView.AnimationOptions.transitionCrossDissolve, animations: { self.titleLabel.text = title }, completion: nil) } private func updateSummary(to summary: String?) { descriptionTextView.text = summary let updatedSummary: String? = summary? .replacingOccurrences(of: "\n", with: " ") .replacingOccurrences(of: "\r", with: " ") .replacingOccurrences(of: " ", with: " ") .split(separator: " ")[0...Constants.maxWordCount] .joined(separator: " ") UIView.transition(with: summaryLabel, duration: Constants.animationDuration, options: UIView.AnimationOptions.transitionCrossDissolve, animations: { self.summaryLabel.text = "\(updatedSummary ?? "")..." }, completion: nil) } }
gpl-3.0
501548d4bdd5fb8a04f2b6b1ffe2135d
46.814371
280
0.717971
5.275851
false
false
false
false
xiaohu557/TinyPlayer
Sources/Classes/PlayerCore/TinyVideoProjectionView.swift
2
2964
// // TinyVideoProjectionView.swift // Leanr // // Created by Kevin Chen on 29/11/2016. // Copyright © 2016 Magic Internet. All rights reserved. // import Foundation import AVFoundation import UIKit /** A view which is connected to an instance of TinyVideoPlayer that can draw video content directly onto it. The default backing layer(CALayer) of TinyVideoProjectionView is set to a AVPlayerLayer. You should always create the TinyVideoPlayer instance first, before you can create its projection view. This ensures that the video object gets initialized and handled properly before it gets propergated to the view. - Note: Every TinyVideoPlayer can be connected to arbitrary number of TinyVideoProjectionViews. The correct initial sequence: TinyVideoPlayer -> generateVideoProjectionView() -> TinyVideoProjectionView. */ public class TinyVideoProjectionView: UIView { internal weak var player: AVPlayer? { get { return playerLayer.player } set { playerLayer.player = newValue } } internal var playerLayer: AVPlayerLayer { return layer as! AVPlayerLayer } /** A read-only unique identify for a single video projection view instance, that is generated while the instance is created. */ private(set) public var hashId: String override public class var layerClass: AnyClass { return AVPlayerLayer.self } /** Set fillMode to determine how you want the video content to be rendered within the playerView. */ public var fillMode: TinyPlayerContentFillMode { didSet { switch fillMode { case .resizeFill: playerLayer.videoGravity = AVLayerVideoGravityResize case .resizeAspect: playerLayer.videoGravity = AVLayerVideoGravityResizeAspect case .resizeAspectFill: playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill } } } override init(frame: CGRect) { fillMode = .resizeAspectFill hashId = UUID().uuidString super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fillMode = .resizeAspectFill hashId = UUID().uuidString super.init(coder: aDecoder) } } /** There are three predefined fill modes for displaying video content: - resizeFill: Stretch the video content to fill the playerView's bounds. - resizeAspect: Maintain the video's aspect ratio and fit it within the playerView's bounds. - resizeAspect: Maintain the video's aspect ratio while expanding the content to fill the playerView's bounds. */ public enum TinyPlayerContentFillMode { case resizeFill case resizeAspect case resizeAspectFill }
mit
5ad37b8adff764edc98280cb8a81c7cb
28.336634
116
0.656429
5.456722
false
false
false
false
apple/swift-async-algorithms
Sources/AsyncAlgorithms/AsyncBufferSequence.swift
1
10423
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// actor AsyncBufferState<Input: Sendable, Output: Sendable> { enum TerminationState: Sendable, CustomStringConvertible { case running case baseFailure(Error) // An error from the base sequence has occurred. We need to process any buffered items before throwing the error. We can rely on it not emitting any more items. case baseTermination case terminal var description: String { switch self { case .running: return "running" case .baseFailure: return "base failure" case .baseTermination: return "base termination" case .terminal: return "terminal" } } } var pending = [UnsafeContinuation<Result<Output?, Error>, Never>]() var terminationState = TerminationState.running init() { } func drain<Buffer: AsyncBuffer>(buffer: Buffer) async where Buffer.Input == Input, Buffer.Output == Output { guard pending.count > 0 else { return } do { if let value = try await buffer.pop() { pending.removeFirst().resume(returning: .success(value)) } else { switch terminationState { case .running: // There's no value to report, because it was probably grabbed by next() before we could grab it. The pending continuation was either resumed by next() directly, or will be by a future enqueued value or base termination/failure. break case .baseFailure(let error): // Now that there are no more items in the buffer, we can finally report the base sequence's error and enter terminal state. pending.removeFirst().resume(returning: .failure(error)) self.terminate() case .terminal, .baseTermination: self.terminate() } } } catch { // Errors thrown by the buffer immediately terminate the sequence. pending.removeFirst().resume(returning: .failure(error)) self.terminate() } } func enqueue<Buffer: AsyncBuffer>(_ item: Input, buffer: Buffer) async where Buffer.Input == Input, Buffer.Output == Output { await buffer.push(item) await drain(buffer: buffer) } func fail<Buffer: AsyncBuffer>(_ error: Error, buffer: Buffer) async where Buffer.Input == Input, Buffer.Output == Output { terminationState = .baseFailure(error) await drain(buffer: buffer) } func finish<Buffer: AsyncBuffer>(buffer: Buffer) async where Buffer.Input == Input, Buffer.Output == Output { if case .running = terminationState { terminationState = .baseTermination } await drain(buffer: buffer) } func terminate() { terminationState = .terminal let oldPending = pending pending = [] for continuation in oldPending { continuation.resume(returning: .success(nil)) } } func next<Buffer: AsyncBuffer>(buffer: Buffer) async throws -> Buffer.Output? where Buffer.Input == Input, Buffer.Output == Output { if case .terminal = terminationState { return nil } do { while let value = try await buffer.pop() { if let continuation = pending.first { pending.removeFirst() continuation.resume(returning: .success(value)) } else { return value } } } catch { // Errors thrown by the buffer immediately terminate the sequence. self.terminate() throw error } switch terminationState { case .running: break case .baseFailure(let error): self.terminate() throw error case .baseTermination, .terminal: self.terminate() return nil } let result: Result<Output?, Error> = await withUnsafeContinuation { continuation in pending.append(continuation) } return try result._rethrowGet() } } /// An asynchronous buffer storage actor protocol used for buffering /// elements to an `AsyncBufferSequence`. @rethrows public protocol AsyncBuffer: Actor { associatedtype Input: Sendable associatedtype Output: Sendable /// Push an element to enqueue to the buffer func push(_ element: Input) async /// Pop an element from the buffer. /// /// Implementors of `pop()` may throw. In cases where types /// throw from this function, that throwing behavior contributes to /// the rethrowing characteristics of `AsyncBufferSequence`. func pop() async throws -> Output? } /// A buffer that limits pushed items by a certain count. public actor AsyncLimitBuffer<Element: Sendable>: AsyncBuffer { /// A policy for buffering elements to an `AsyncLimitBuffer` public enum Policy: Sendable { /// A policy for no bounding limit of pushed elements. case unbounded /// A policy for limiting to a specific number of oldest values. case bufferingOldest(Int) /// A policy for limiting to a specific number of newest values. case bufferingNewest(Int) } var buffer = [Element]() let policy: Policy init(policy: Policy) { // limits should always be greater than 0 items switch policy { case .bufferingNewest(let limit): precondition(limit > 0) case .bufferingOldest(let limit): precondition(limit > 0) default: break } self.policy = policy } /// Push an element to enqueue to the buffer. public func push(_ element: Element) async { switch policy { case .unbounded: buffer.append(element) case .bufferingOldest(let limit): if buffer.count < limit { buffer.append(element) } case .bufferingNewest(let limit): if buffer.count < limit { // there is space available buffer.append(element) } else { // no space is available and this should make some room buffer.removeFirst() buffer.append(element) } } } /// Pop an element from the buffer. public func pop() async -> Element? { guard buffer.count > 0 else { return nil } return buffer.removeFirst() } } extension AsyncSequence where Element: Sendable, Self: Sendable { /// Creates an asynchronous sequence that buffers elements using a buffer created from a supplied closure. /// /// Use the `buffer(_:)` method to account for `AsyncSequence` types that may produce elements faster /// than they are iterated. The `createBuffer` closure returns a backing buffer for storing elements and dealing with /// behavioral characteristics of the `buffer(_:)` algorithm. /// /// - Parameter createBuffer: A closure that constructs a new `AsyncBuffer` actor to store buffered values. /// - Returns: An asynchronous sequence that buffers elements using the specified `AsyncBuffer`. public func buffer<Buffer: AsyncBuffer>(_ createBuffer: @Sendable @escaping () -> Buffer) -> AsyncBufferSequence<Self, Buffer> where Buffer.Input == Element { AsyncBufferSequence(self, createBuffer: createBuffer) } /// Creates an asynchronous sequence that buffers elements using a specific policy to limit the number of /// elements that are buffered. /// /// - Parameter policy: A limiting policy behavior on the buffering behavior of the `AsyncBufferSequence` /// - Returns: An asynchronous sequence that buffers elements up to a given limit. public func buffer(policy limit: AsyncLimitBuffer<Element>.Policy) -> AsyncBufferSequence<Self, AsyncLimitBuffer<Element>> { buffer { AsyncLimitBuffer(policy: limit) } } } /// An `AsyncSequence` that buffers elements utilizing an `AsyncBuffer`. public struct AsyncBufferSequence<Base: AsyncSequence & Sendable, Buffer: AsyncBuffer> where Base.Element == Buffer.Input { let base: Base let createBuffer: @Sendable () -> Buffer init(_ base: Base, createBuffer: @Sendable @escaping () -> Buffer) { self.base = base self.createBuffer = createBuffer } } extension AsyncBufferSequence: Sendable where Base: Sendable { } extension AsyncBufferSequence: AsyncSequence { public typealias Element = Buffer.Output /// The iterator for a `AsyncBufferSequence` instance. public struct Iterator: AsyncIteratorProtocol { struct Active { var task: Task<Void, Never>? let buffer: Buffer let state: AsyncBufferState<Buffer.Input, Buffer.Output> init(_ base: Base, buffer: Buffer, state: AsyncBufferState<Buffer.Input, Buffer.Output>) { self.buffer = buffer self.state = state task = Task { var iter = base.makeAsyncIterator() do { while let item = try await iter.next() { await state.enqueue(item, buffer: buffer) } await state.finish(buffer: buffer) } catch { await state.fail(error, buffer: buffer) } } } func next() async rethrows -> Element? { let result: Result<Element?, Error> = await withTaskCancellationHandler { do { let value = try await state.next(buffer: buffer) return .success(value) } catch { task?.cancel() return .failure(error) } } onCancel: { task?.cancel() } return try result._rethrowGet() } } enum State { case idle(Base, @Sendable () -> Buffer) case active(Active) } var state: State init(_ base: Base, createBuffer: @Sendable @escaping () -> Buffer) { state = .idle(base, createBuffer) } public mutating func next() async rethrows -> Element? { switch state { case .idle(let base, let createBuffer): let bufferState = AsyncBufferState<Base.Element, Buffer.Output>() let buffer = Active(base, buffer: createBuffer(), state: bufferState) state = .active(buffer) return try await buffer.next() case .active(let buffer): return try await buffer.next() } } } public func makeAsyncIterator() -> Iterator { Iterator(base, createBuffer: createBuffer) } }
apache-2.0
44a6f563202c528af3923e5997370e80
32.840909
240
0.646263
4.663535
false
false
false
false
michael-r-may/CatsAndDogs-Swift-Server
Sources/dates.swift
1
810
// // Created by Developer on 2017/03/26. // // import Foundation public extension TimeZone { static var Polish = TimeZone(identifier: "Europe/Warsaw") static var California = TimeZone(identifier: "US/Pacific") } public extension Locale { static var Polish = Locale(identifier: "pl_PL") static var US = Locale(identifier: "en_US") } public class RFC3339DateFormatter: DateFormatter { static var RFC3339DateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" init(locale: Locale, timezone: TimeZone) { super.init() self.locale = locale self.dateFormat = RFC3339DateFormatter.RFC3339DateFormat self.timeZone = timezone } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
a99eaa334cec33c8fbb272ff79352a6e
24.3125
64
0.667901
4.029851
false
false
false
false
AppLozic/Applozic-iOS-SDK
sample-with-framework/Applozic/Applozic/ALSearchViewModel.swift
1
2211
// // ALSearchViewModel.swift // Applozic // // Created by Sunil on 02/07/20. // Copyright © 2020 applozic Inc. All rights reserved. // import Foundation @objc public class ALSearchViewModel: NSObject { @objc public override init() { } static let forCellReuseIdentifier = "ContactCell" var messageList = [ALMessage]() @objc public func numberOfSections() -> Int { return 1 } @objc public func numberOfRowsInSection() -> Int { return messageList.count } @objc public func clear() { messageList.removeAll() } @objc public func messageAtIndexPath(indexPath: IndexPath) -> ALMessage? { guard indexPath.row < messageList.count && messageList.count > 1 else { return nil } return messageList[indexPath.row] as ALMessage } @objc public func searchMessage(with key: String, _ completion: @escaping ((_ result: Bool) -> Void)) { searchMessages(with: key) { messages, error in guard let messages = messages, messages.count > 0, error == nil else { print("Error \(String(describing: error)) while searching messages") completion(false) return } // Sort _ = messages .sorted(by: { Int(truncating: $0.createdAtTime) > Int(truncating: $1.createdAtTime) }).filter { ($0.groupId != nil || $0.to != nil) }.map { self.messageList.append($0) } completion(true) } } func searchMessages( with key: String, _ completion: @escaping (_ message: [ALMessage]?, _ error: Any?) -> Void ) { let service = ALMessageClientService() let request = ALSearchRequest() request.searchText = key service.searchMessage(with: request) { messages, error in guard let messages = messages as? [ALMessage] else { completion(nil, error) return } completion(messages, error) } } }
bsd-3-clause
869d737bb3c7f2965d42d36ca47783c9
28.466667
89
0.538914
4.762931
false
false
false
false
amandafer/ecommerce
ecommerce/View/ImageView.swift
1
657
// // ImageView.swift // ecommerce // // Created by Amanda Fernandes on 17/04/2017. // Copyright © 2017 Amanda Fernandes. All rights reserved. // import UIKit @IBDesignable class ImageView: UIImageView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = true } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.cgColor } } }
mit
12707829b3de47abb3d86dfdeb75b8f9
19.5
59
0.58689
4.823529
false
false
false
false
FelixII/FlatButton
FlatButton/FlatButton.swift
1
12996
// // FlatButton.swift // Disk Sensei // // Created by Oskar Groth on 02/08/16. // Copyright © 2016 Cindori. All rights reserved. // import Cocoa import QuartzCore internal extension CALayer { internal func animate(color: CGColor, keyPath: String, duration: Double) { if value(forKey: keyPath) as! CGColor? != color { let animation = CABasicAnimation(keyPath: keyPath) animation.toValue = color animation.fromValue = value(forKey: keyPath) animation.duration = duration animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards add(animation, forKey: keyPath) setValue(color, forKey: keyPath) } } } //unused for now internal extension NSColor { internal func tintedColor() -> NSColor { var h = CGFloat(), s = CGFloat(), b = CGFloat(), a = CGFloat() let rgbColor = usingColorSpaceName(NSCalibratedRGBColorSpace) rgbColor?.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return NSColor(hue: h, saturation: s, brightness: b == 0 ? 0.2 : b * 0.8, alpha: a) } } open class FlatButton: NSButton, CALayerDelegate { internal var containerLayer = CALayer() internal var iconLayer = CAShapeLayer() internal var alternateIconLayer = CAShapeLayer() internal var titleLayer = CATextLayer() internal var mouseDown = Bool() @IBInspectable public var momentary: Bool = true { didSet { animateColor(state == NSOnState) } } @IBInspectable public var onAnimationDuration: Double = 0 @IBInspectable public var offAnimationDuration: Double = 0.1 @IBInspectable public var glowRadius: CGFloat = 0 { didSet { containerLayer.shadowRadius = glowRadius animateColor(state == NSOnState) } } @IBInspectable public var glowOpacity: Float = 0 { didSet { containerLayer.shadowOpacity = glowOpacity animateColor(state == NSOnState) } } @IBInspectable public var cornerRadius: CGFloat = 4 { didSet { layer?.cornerRadius = cornerRadius } } @IBInspectable public var borderWidth: CGFloat = 1 { didSet { layer?.borderWidth = borderWidth } } @IBInspectable public var borderColor: NSColor = NSColor.darkGray { didSet { animateColor(state == NSOnState) } } @IBInspectable public var activeBorderColor: NSColor = NSColor.white { didSet { animateColor(state == NSOnState) } } @IBInspectable public var buttonColor: NSColor = NSColor.darkGray { didSet { animateColor(state == NSOnState) } } @IBInspectable public var activeButtonColor: NSColor = NSColor.white { didSet { animateColor(state == NSOnState) } } @IBInspectable public var iconColor: NSColor = NSColor.gray { didSet { animateColor(state == NSOnState) } } @IBInspectable public var activeIconColor: NSColor = NSColor.black { didSet { animateColor(state == NSOnState) } } @IBInspectable public var textColor: NSColor = NSColor.gray { didSet { animateColor(state == NSOnState) } } @IBInspectable public var activeTextColor: NSColor = NSColor.gray { didSet { animateColor(state == NSOnState) } } override open var title: String { didSet { setupTitle() } } override open var font: NSFont? { didSet { setupTitle() } } override open var frame: NSRect { didSet { positionTitleAndImage() } } override open var image: NSImage? { didSet { setupImage() } } override open var alternateImage: NSImage? { didSet { setupImage() } } override open var isEnabled: Bool { didSet { alphaValue = isEnabled ? 1 : 0.5 } } // MARK: Setup & Initialization required public init?(coder: NSCoder) { super.init(coder: coder) setup() } override init(frame: NSRect) { super.init(frame: frame) setup() } internal func setup() { wantsLayer = true layer?.masksToBounds = false containerLayer.masksToBounds = false layer?.cornerRadius = 4 layer?.borderWidth = 1 layer?.delegate = self //containerLayer.backgroundColor = NSColor.blue.withAlphaComponent(0.1).cgColor //titleLayer.backgroundColor = NSColor.red.withAlphaComponent(0.2).cgColor titleLayer.delegate = self iconLayer.delegate = self alternateIconLayer.delegate = self iconLayer.masksToBounds = true alternateIconLayer.masksToBounds = true containerLayer.shadowOffset = NSSize.zero containerLayer.shadowColor = NSColor.clear.cgColor containerLayer.frame = NSMakeRect(0, 0, bounds.width, bounds.height) containerLayer.addSublayer(iconLayer) containerLayer.addSublayer(alternateIconLayer) containerLayer.addSublayer(titleLayer) layer?.addSublayer(containerLayer) setupTitle() setupImage() } internal func setupTitle() { guard let font = font else { return } titleLayer.string = title titleLayer.font = font titleLayer.fontSize = font.pointSize positionTitleAndImage() } func positionTitleAndImage() { let attributes = [NSFontAttributeName: font as Any] let titleSize = title.size(withAttributes: attributes) var titleRect = NSMakeRect(0, 0, titleSize.width, titleSize.height) var imageRect = iconLayer.frame let hSpacing = round((bounds.width-(imageRect.width+titleSize.width))/3) let vSpacing = round((bounds.height-(imageRect.height+titleSize.height))/3) switch imagePosition { case .imageAbove: titleRect.origin.y = bounds.height-titleRect.height - 2 titleRect.origin.x = round((bounds.width - titleSize.width)/2) imageRect.origin.y = vSpacing imageRect.origin.x = round((bounds.width - imageRect.width)/2) break case .imageBelow: titleRect.origin.y = 2 titleRect.origin.x = round((bounds.width - titleSize.width)/2) imageRect.origin.y = bounds.height-vSpacing-imageRect.height imageRect.origin.x = round((bounds.width - imageRect.width)/2) break case .imageLeft: titleRect.origin.y = round((bounds.height - titleSize.height)/2) titleRect.origin.x = bounds.width - titleSize.width - 2 imageRect.origin.y = round((bounds.height - imageRect.height)/2) imageRect.origin.x = hSpacing break case .imageRight: titleRect.origin.y = round((bounds.height - titleSize.height)/2) titleRect.origin.x = 2 imageRect.origin.y = round((bounds.height - imageRect.height)/2) imageRect.origin.x = bounds.width - imageRect.width - hSpacing break default: titleRect.origin.y = round((bounds.height - titleSize.height)/2) titleRect.origin.x = round((bounds.width - titleSize.width)/2) } iconLayer.frame = imageRect alternateIconLayer.frame = imageRect titleLayer.frame = titleRect } internal func setupImage() { guard let image = image else { return } let maskLayer = CALayer() let imageSize = image.size var imageRect:CGRect = NSMakeRect(0, 0, imageSize.width, imageSize.height) let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil) maskLayer.contents = imageRef iconLayer.frame = imageRect maskLayer.frame = imageRect iconLayer.mask = maskLayer //maskLayer.backgroundColor = NSColor.green.withAlphaComponent(0.5).cgColor if let alternateImage = alternateImage { let altMaskLayer = CALayer() //altMaskLayer.backgroundColor = NSColor.green.withAlphaComponent(0.5).cgColor let altImageSize = alternateImage.size var altImageRect:CGRect = NSMakeRect(0, 0, altImageSize.width, altImageSize.height) let altImageRef = alternateImage.cgImage(forProposedRect: &altImageRect, context: nil, hints: nil) altMaskLayer.contents = altImageRef alternateIconLayer.frame = altImageRect altMaskLayer.frame = altImageRect alternateIconLayer.mask = altMaskLayer alternateIconLayer.frame = altImageRect } positionTitleAndImage() } override open func awakeFromNib() { super.awakeFromNib() let trackingArea = NSTrackingArea(rect: bounds, options: [.activeAlways, .inVisibleRect, .mouseEnteredAndExited], owner: self, userInfo: nil) addTrackingArea(trackingArea) } // MARK: Animations internal func removeAnimations() { layer?.removeAllAnimations() if layer?.sublayers != nil { for subLayer in (layer?.sublayers)! { subLayer.removeAllAnimations() } } } public func animateColor(_ isOn: Bool) { removeAnimations() let duration = isOn ? onAnimationDuration : offAnimationDuration let bgColor = isOn ? activeButtonColor : buttonColor let titleColor = isOn ? activeTextColor : textColor let imageColor = isOn ? activeIconColor : iconColor let borderColor = isOn ? activeBorderColor : self.borderColor layer?.animate(color: bgColor.cgColor, keyPath: "backgroundColor", duration: duration) layer?.animate(color: borderColor.cgColor, keyPath: "borderColor", duration: duration) /* I started seeing high (~5%) background CPU usage in apps using FlatButton, and was able to track it down to background CATextLayer animation calls happening constantly, originating from the call below. It could be a CATextLayer bug. For now I'm going with setting the color instantly as it fixes this issue. */ //titleLayer.animate(color: titleColor.cgColor, keyPath: "foregroundColor", duration: duration) titleLayer.foregroundColor = titleColor.cgColor if alternateImage == nil { iconLayer.animate(color: imageColor.cgColor, keyPath: "backgroundColor", duration: duration) } else { iconLayer.animate(color: isOn ? NSColor.clear.cgColor : iconColor.cgColor, keyPath: "backgroundColor", duration: duration) alternateIconLayer.animate(color: isOn ? activeIconColor.cgColor : NSColor.clear.cgColor, keyPath: "backgroundColor", duration: duration) } // Shadows if glowRadius > 0, glowOpacity > 0 { containerLayer.animate(color: isOn ? activeIconColor.cgColor : NSColor.clear.cgColor, keyPath: "shadowColor", duration: duration) } } // MARK: Interaction public func setOn(_ isOn: Bool) { let nextState = isOn ? NSOnState : NSOffState if nextState != state { state = nextState animateColor(state == NSOnState) } } override open func hitTest(_ point: NSPoint) -> NSView? { return isEnabled ? super.hitTest(point) : nil } override open func mouseDown(with event: NSEvent) { if isEnabled { mouseDown = true setOn(state == NSOnState ? false : true) } } override open func mouseEntered(with event: NSEvent) { if mouseDown { setOn(state == NSOnState ? false : true) } } override open func mouseExited(with event: NSEvent) { if mouseDown { setOn(state == NSOnState ? false : true) mouseDown = false } } override open func mouseUp(with event: NSEvent) { if mouseDown { mouseDown = false if momentary { setOn(state == NSOnState ? false : true) } _ = target?.perform(action, with: self) } } // MARK: Drawing override open func layer(_ layer: CALayer, shouldInheritContentsScale newScale: CGFloat, from window: NSWindow) -> Bool { return true } override open func draw(_ dirtyRect: NSRect) { } override open func layout() { super.layout() positionTitleAndImage() } override open func updateLayer() { super.updateLayer() } }
mit
783768a7ae688080327caf9f6e2cce7f
33.56117
149
0.607926
5.046602
false
false
false
false
Midhun-MP/Past
Past/Past.swift
1
11210
/** MIT License Copyright (c) 2016 Midhun MP Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation // MARK: Extension extension NSDate { @objc public enum PastOptions : Int { case Seconds case Minutes case Hours case Days case Weeks case Months case Years static let AllValues = [Seconds, Minutes, Hours, Days, Weeks, Months, Years] } } // MARK: Utility Methods extension NSDate { /// Checks whether the passed NSDate is today or not /// - returns: Indicates the status of operation public func isToday() -> Bool { var isToday = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let components = calendar.components([.Day, .Month, .Year], fromDate: self) let todayComponents = calendar.components([.Day, .Month, .Year], fromDate: today) if (components.day == todayComponents.day && components.month == todayComponents.month && components.year == todayComponents.year) { isToday = true } return isToday } /// Checks whether the passed NSDate is yesterday or not /// - returns: Indicates the status of operation public func isYesterday() -> Bool { var isYesterday = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let yesterday = calendar.dateByAddingUnit(.Day, value: -1, toDate: today, options: [])! let components = calendar.components([.Day, .Month, .Year], fromDate: self) let yestdComponents = calendar.components([.Day, .Month, .Year], fromDate: yesterday) if (components.day == yestdComponents.day && components.month == yestdComponents.month && components.year == yestdComponents.year) { isYesterday = true } return isYesterday } /// Checks whether the passed NSDate is within this week or not /// - returns: Indicates the status of operation public func isThisWeek() -> Bool { var isThisWeek = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let components = calendar.components([.WeekOfYear, .Year], fromDate: self) let todayComponents = calendar.components([.WeekOfYear, .Year], fromDate: today) if (components.weekOfYear == todayComponents.weekOfYear && components.year == todayComponents.year) { isThisWeek = true } return isThisWeek } /// Checks whether the passed NSDate is within the last week or not /// - returns: Indicates the status of operation public func isLastWeek() -> Bool { var isLastWeek = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let lastWeekDay = calendar.dateByAddingUnit(.WeekOfYear, value: -1, toDate: today, options: [])! let components = calendar.components([.WeekOfYear, .Year], fromDate: self) let lastWeekComponents = calendar.components([.WeekOfYear, .Year], fromDate: lastWeekDay) if (components.weekOfYear == lastWeekComponents.weekOfYear && components.year == lastWeekComponents.year) { isLastWeek = true } return isLastWeek } /// Checks whether the passed NSDate is within this month or not /// - returns: Indicates the status of operation public func isThisMonth() -> Bool { var isThisMonth = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let components = calendar.components([.Month, .Year], fromDate: self) let todayComponents = calendar.components([.Month, .Year], fromDate: today) if (components.month == todayComponents.month && components.year == todayComponents.year) { isThisMonth = true } return isThisMonth } /// Checks whether the passed NSDate is within the last month or not /// - returns: Indicates the status of operation public func isLastMonth() -> Bool { var isLastMonth = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let lastMonth = calendar.dateByAddingUnit(.Month, value: -1, toDate: today, options: [])! let components = calendar.components([.Month, .Year], fromDate: self) let lastMonthComponents = calendar.components([.Month, .Year], fromDate: lastMonth) if (components.month == lastMonthComponents.month && components.year == lastMonthComponents.year) { isLastMonth = true } return isLastMonth } /// Checks whether the passed NSDate is within this year or not /// - returns: Indicates the status of operation public func isThisYear() -> Bool { var isThisYear = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let components = calendar.components([.Year], fromDate: self) let todayComponents = calendar.components([.Year], fromDate: today) if (components.year == todayComponents.year) { isThisYear = true } return isThisYear } /// Checks whether the passed NSDate is within the last year or not /// - returns: Indicates the status of operation public func isLastYear() -> Bool { var isLastYear = false let calendar = NSCalendar.currentCalendar() let today = NSDate() let lastYear = calendar.dateByAddingUnit(.Year, value: -1, toDate: today, options: [])! let components = calendar.components([.Year], fromDate: self) let lastYearComponents = calendar.components([.Year], fromDate: lastYear) if (components.year == lastYearComponents.year) { isLastYear = true } return isLastYear } /// Returns the moment difference between current time and the passed object's date /// - parameter option: PastOptions enum value /// - returns: String representation of the moment public func getMoment(inTermsOf option : PastOptions) -> String { var moment = "" switch option { case .Seconds: moment = getStringRepresentation(getElapsedSeconds(), option: option) case .Minutes: moment = getStringRepresentation(getElapsedMinutes(), option: option) case .Hours: moment = getStringRepresentation(getElapsedHours(), option: option) case .Days: moment = getStringRepresentation(getElapsedDays(), option: option) case .Weeks: moment = getStringRepresentation(getElapsedWeeks(), option: option) case .Months: moment = getStringRepresentation(getElapsedMonths(), option: option) case .Years: moment = getStringRepresentation(getElapsedYears(), option: option) } return moment } // Returns the elapsed seconds public func getElapsedSeconds() -> Int { let seconds = NSCalendar.currentCalendar().components(.Second, fromDate: self, toDate: NSDate(), options: []).second return seconds } // Returns the elapsed minutes public func getElapsedMinutes() -> Int { let minutes = NSCalendar.currentCalendar().components(.Minute, fromDate: self, toDate: NSDate(), options: []).minute return minutes } // Returns the elapsed hours public func getElapsedHours() -> Int { let hours = NSCalendar.currentCalendar().components(.Hour, fromDate: self, toDate: NSDate(), options: []).hour return hours } // Returns the elapsed days public func getElapsedDays() -> Int { let days = NSCalendar.currentCalendar().components(.Day, fromDate: self, toDate: NSDate(), options: []).day return days } // Returns the elapsed weeks public func getElapsedWeeks() -> Int { let week = NSCalendar.currentCalendar().components(.WeekOfYear, fromDate: self, toDate: NSDate(), options: []).weekOfYear return week } // Returns the elapsed months public func getElapsedMonths() -> Int { let month = NSCalendar.currentCalendar().components(.Month, fromDate: self, toDate: NSDate(), options: []).month return month } // Returns the elapsed years public func getElapsedYears() -> Int { let minutes = NSCalendar.currentCalendar().components(.Year, fromDate: self, toDate: NSDate(), options: []).year return minutes } } // MARK: Private Methods extension NSDate { // Returns the string representation of moment private func getStringRepresentation(time : Int, option : PastOptions) -> String { var momentAsString = "Now" switch option { case .Seconds: momentAsString = time > 0 ? "\(time) seconds ago" : "After \(abs(time)) seconds" case .Minutes: momentAsString = time > 0 ? "\(time) minutes ago" : "After \(abs(time)) minutes" case .Hours: momentAsString = time > 0 ? "\(time) hours ago" : "After \(abs(time)) hours" case .Days: momentAsString = time > 0 ? "\(time) days ago" : "After \(abs(time)) days" case .Weeks: momentAsString = time > 0 ? "\(time) weeks ago" : "After \(abs(time)) weeks" case .Months: momentAsString = time > 0 ? "\(time) months ago" : "After \(abs(time)) months" case .Years: momentAsString = time > 0 ? "\(time) years ago" : "After \(abs(time)) years" } momentAsString = time == 0 ? "Now" : momentAsString return momentAsString } }
mit
109ebb94573ac4cd5b2b0f8d94d5d555
37.129252
138
0.612756
5.026906
false
false
false
false
Antidote-for-Tox/Antidote
Antidote/iPadFriendsButton.swift
1
3014
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit private struct Constants { static let BadgeHorizontalOffset = 5.0 static let BadgeMinimumWidth = 22.0 static let BadgeHeight: CGFloat = 18.0 static let BadgeRightOffset = -10.0 } class iPadFriendsButton: UIView { var didTapHandler: (() -> Void)? var badgeText: String? { didSet { badgeLabel.text = badgeText badgeContainer.isHidden = (badgeText == nil) } } fileprivate var badgeContainer: UIView! fileprivate var badgeLabel: UILabel! fileprivate var button: UIButton! init(theme: Theme) { super.init(frame: CGRect.zero) createViews(theme) installConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension iPadFriendsButton { @objc func buttonPressed() { didTapHandler?() } } private extension iPadFriendsButton { func createViews(_ theme: Theme) { badgeContainer = UIView() badgeContainer.backgroundColor = theme.colorForType(.TabBadgeBackground) badgeContainer.layer.masksToBounds = true badgeContainer.layer.cornerRadius = Constants.BadgeHeight / 2 addSubview(badgeContainer) badgeLabel = UILabel() badgeLabel.textColor = theme.colorForType(.TabBadgeText) badgeLabel.textAlignment = .center badgeLabel.backgroundColor = .clear badgeLabel.font = UIFont.antidoteFontWithSize(14.0, weight: .light) badgeContainer.addSubview(badgeLabel) button = UIButton(type: .system) button.contentHorizontalAlignment = .left button.contentEdgeInsets.left = 20.0 button.titleEdgeInsets.left = 20.0 button.titleLabel?.font = UIFont.systemFont(ofSize: 18.0) button.setTitle(String(localized: "contacts_title"), for: UIControlState()) button.setImage(UIImage(named: "tab-bar-friends"), for: UIControlState()) button.addTarget(self, action: #selector(iPadFriendsButton.buttonPressed), for: .touchUpInside) addSubview(button) } func installConstraints() { badgeContainer.snp.makeConstraints { $0.trailing.equalTo(self).offset(Constants.BadgeRightOffset) $0.centerY.equalTo(self) $0.width.greaterThanOrEqualTo(Constants.BadgeMinimumWidth) $0.height.equalTo(Constants.BadgeHeight) } badgeLabel.snp.makeConstraints { $0.leading.equalTo(badgeContainer).offset(Constants.BadgeHorizontalOffset) $0.trailing.equalTo(badgeContainer).offset(-Constants.BadgeHorizontalOffset) $0.centerY.equalTo(badgeContainer) } button.snp.makeConstraints { $0.edges.equalTo(self) } } }
mpl-2.0
638994b8eb650bffdef5ec1ededc340a
32.120879
103
0.668215
4.636923
false
false
false
false
lukevanin/SwiftPromise
SwiftPromise/CancellationToken.swift
1
1102
// // CancellationToken.swift // SwiftPromise // // Created by Luke Van In on 2016/07/05. // Copyright © 2016 Luke Van In. All rights reserved. // import Foundation public class CancellationToken { public typealias Handler = (Void) -> Void public var cancelled: Bool { return _cancelled } private let lockQueue = DispatchQueue( label: "SwiftPromise.CancellationToken.lockQueue", attributes: .serial ) private let eventQueue = DispatchQueue( label: "SwiftPromise.CancellationToken.eventQueue", attributes: .serial ) private var _cancelled = false public init() { eventQueue.suspend() } public func cancel() { lockQueue.sync() { [weak self] in guard let `self` = self else { return } guard !self.cancelled else { return } self._cancelled = true self.eventQueue.resume() } } public func onCancel(handler: Handler) { eventQueue.async(execute: handler) } }
mit
015da777b9393191c9e4183608386a84
19.388889
59
0.579473
4.766234
false
false
false
false
daxiangfei/RTSwiftUtils
RTSwiftUtils/Core/PathHelper.swift
1
1608
// // PathHelper.swift // XiaoZhuGeJinFu // // Created by rongteng on 16/6/22. // Copyright © 2016年 rongteng. All rights reserved. // import Foundation public class PathHelper { ///给对应盘下 创建文件夹 public class func createSubDirectoryPathIn(_ directory:FileManager.SearchPathDirectory,name:String) -> String? { let paths = NSSearchPathForDirectoriesInDomains(directory, .userDomainMask, true) let mainPath = paths[0] let subPath = mainPath + ("/"+name) guard self.createPathIfNecessary(mainPath) else { return nil } guard self.createPathIfNecessary(subPath) else { return nil } return subPath } ///获取对应盘下 文件夹的路径 public class func achieveSubDirectoryPathIn(_ directory:FileManager.SearchPathDirectory,name:String) -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let mainPath = paths[0] let subPath = mainPath + ("/"+name) return subPath } //创建路径 如果不存在 public class func createPathIfNecessary(_ path:String) -> Bool { var succeeded = true let fileManager = FileManager.default if !fileManager.fileExists(atPath: path) { do { try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) } catch { succeeded = false } } return succeeded } }
mit
b3af6fe3e3e713d85587d66a2617ed05
19.302632
116
0.61698
4.821875
false
false
false
false
sschiau/swift
test/Constraints/closures.swift
1
31335
// RUN: %target-typecheck-verify-swift func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {} var intArray : [Int] _ = myMap(intArray, { String($0) }) _ = myMap(intArray, { x -> String in String(x) } ) // Closures with too few parameters. func foo(_ x: (Int, Int) -> Int) {} foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} foo({ [intArray] in $0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} struct X {} func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {} func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {} var strings : [String] _ = mySort(strings, { x, y in x < y }) // Closures with inout arguments. func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U { var t2 = t return f(&t2) } struct X2 { func g() -> Float { return 0 } } _ = f0(X2(), {$0.g()}) // Closures with inout arguments and '__shared' conversions. func inoutToSharedConversions() { func fooOW<T, U>(_ f : (__owned T) -> U) {} fooOW({ (x : Int) in return Int(5) }) // defaut-to-'__owned' allowed fooOW({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__owned' allowed fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__owned Int) -> Int'}} func fooIO<T, U>(_ f : (inout T) -> U) {} fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(inout Int) -> Int'}} fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout Int) -> Int'}} fooIO({ (x : __owned Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__owned Int) -> Int' to expected argument type '(inout Int) -> Int'}} func fooSH<T, U>(_ f : (__shared T) -> U) {} fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed fooSH({ (x : __owned Int) in return Int(5) }) // '__owned'-to-'__shared' allowed fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared Int) -> Int'}} fooSH({ (x : Int) in return Int(5) }) // default-to-'__shared' allowed } // Autoclosure func f1(f: @autoclosure () -> Int) { } func f2() -> Int { } f1(f: f2) // expected-error{{add () to forward @autoclosure parameter}}{{9-9=()}} f1(f: 5) // Ternary in closure var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"} // <rdar://problem/15367882> func foo() { not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}} } // <rdar://problem/15536725> struct X3<T> { init(_: (T) -> ()) {} } func testX3(_ x: Int) { var x = x _ = X3({ x = $0 }) _ = x } // <rdar://problem/13811882> func test13811882() { var _ : (Int) -> (Int, Int) = {($0, $0)} var x = 1 var _ : (Int) -> (Int, Int) = {($0, x)} x = 2 } // <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement // <https://bugs.swift.org/browse/SR-3671> func r21544303() { var inSubcall = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false // This is a problem, but isn't clear what was intended. var somethingElse = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false var v2 : Bool = false v2 = inSubcall { // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } } // <https://bugs.swift.org/browse/SR-3671> func SR3671() { let n = 42 func consume(_ x: Int) {} { consume($0) }(42) ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; // This is technically a valid call, so nothing goes wrong until (42) { $0(3) } { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; { $0(3) } { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; // Equivalent but more obviously unintended. { $0(3) } // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ({ $0(3) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ; // Also a valid call (!!) { $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}} consume(111) } // <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure func r22162441(_ lines: [String]) { _ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} _ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} } func testMap() { let a = 42 [1,a].map { $0 + 1.0 } // expected-error {{cannot convert value of type 'Int' to expected element type 'Double'}} } // <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier [].reduce { $0 + $1 } // expected-error {{cannot invoke 'reduce' with an argument list of type '(@escaping (_, _) -> _)'}} // <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments var _: () -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }} var _: (Int) -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}} var _: (Int) -> Int = { 0 } // expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }} var _: (Int, Int) -> Int = {0} // expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {$0+$1} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}} var _: (Int) -> Int = {a,b in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}} var _: (Int) -> Int = {a,b,c in 0} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {a, b in a+b} // <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument func r15998821() { func take_closure(_ x : (inout Int) -> ()) { } func test1() { take_closure { (a : inout Int) in a = 42 } } func test2() { take_closure { a in a = 42 } } func withPtr(_ body: (inout Int) -> Int) {} func f() { withPtr { p in return p } } let g = { x in x = 3 } take_closure(g) } // <rdar://problem/22602657> better diagnostics for closures w/o "in" clause var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} // Crash when re-typechecking bodies of non-single expression closures struct CC {} func callCC<U>(_ f: (CC) -> U) -> () {} func typeCheckMultiStmtClosureCrash() { callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }} _ = $0 return 1 } } // SR-832 - both these should be ok func someFunc(_ foo: ((String) -> String)?, bar: @escaping (String) -> String) { let _: (String) -> String = foo != nil ? foo! : bar let _: (String) -> String = foo ?? bar } func verify_NotAC_to_AC_failure(_ arg: () -> ()) { func takesAC(_ arg: @autoclosure () -> ()) {} takesAC(arg) // expected-error {{add () to forward @autoclosure parameter}} {{14-14=()}} } // SR-1069 - Error diagnostic refers to wrong argument class SR1069_W<T> { func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {} } class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() } struct S<T> { let cs: [SR1069_C<T>] = [] func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable { let wrappedMethod = { (object: AnyObject, value: T) in } // expected-error @+3 {{value of optional type 'Object?' must be unwrapped to a value of type 'Object'}} // expected-note @+2{{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note @+1{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) } } } // Similar to SR1069 but with multiple generic arguments func simplified1069() { class C {} struct S { func genericallyNonOptional<T: AnyObject>(_ a: T, _ b: T, _ c: T) { } func f(_ a: C?, _ b: C?, _ c: C) { genericallyNonOptional(a, b, c) // expected-error 2{{value of optional type 'C?' must be unwrapped to a value of type 'C'}} // expected-note @-1 2{{coalesce}} // expected-note @-2 2{{force-unwrap}} } } } // Make sure we cannot infer an () argument from an empty parameter list. func acceptNothingToInt (_: () -> Int) {} func testAcceptNothingToInt(ac1: @autoclosure () -> Int) { acceptNothingToInt({ac1($0)}) // expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} } // <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference) struct Thing { init?() {} } // This throws a compiler error let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> Thing }} // Commenting out this makes it compile _ = thing return thing } // <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches func r21675896(file : String) { let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }} if true { return "foo" } else { return file } }().pathExtension } // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(_ t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? func uintFunc() -> UInt {} func takeVoidVoidFn(_ a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(_ x: String) {} // expected-note {{candidate expects value of type 'String' at position #0}} func f19997471(_ x: Int) {} // expected-note {{candidate expects value of type 'Int' at position #0}} func someGeneric19997471<T>(_ x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{no exact matches in call to global function 'f19997471'}} } } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } [0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }} _ in let r = (1,2).0 return r } // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) throws -> [(String, String)]' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(_ callback: ([String]) -> ()) { } func rdar20868864(_ s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} {{17-17=UInt8(}} {{25-25=)}} } } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(_ value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }} print("a") return "hi" } } // In the example below, SR-2505 started preferring C_SR_2505.test(_:) over // test(it:). Prior to Swift 5.1, we emulated the old behavior. However, // that behavior is inconsistent with the typical approach of preferring // overloads from the concrete type over one from a protocol, so we removed // the hack. protocol SR_2505_Initable { init() } struct SR_2505_II : SR_2505_Initable {} protocol P_SR_2505 { associatedtype T: SR_2505_Initable } extension P_SR_2505 { func test(it o: (T) -> Bool) -> Bool { return o(T.self()) } } class C_SR_2505 : P_SR_2505 { typealias T = SR_2505_II func test(_ o: Any) -> Bool { return false } func call(_ c: C_SR_2505) -> Bool { // Note: the diagnostic about capturing 'self', indicates that we have // selected test(_) rather than test(it:) return c.test { o in test(o) } // expected-error{{call to method 'test' in closure requires explicit 'self.' to make capture semantics explicit}} } } let _ = C_SR_2505().call(C_SR_2505()) // <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic extension Collection { func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index { return startIndex } } func fn_r28909024(n: Int) { return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}} _ in true } } // SR-2994: Unexpected ambiguous expression in closure with generics struct S_2994 { var dataOffset: Int } class C_2994<R> { init(arg: (R) -> Void) {} } func f_2994(arg: String) {} func g_2994(arg: Int) -> Double { return 2 } C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}} let _ = { $0[$1] }(1, 1) // expected-error {{value of type 'Int' has no subscripts}} let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}} let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}} // https://bugs.swift.org/browse/SR-403 // The () -> T => () -> () implicit conversion was kicking in anywhere // inside a closure result, not just at the top-level. let mismatchInClosureResultType : (String) -> ((Int) -> Void) = { (String) -> ((Int) -> Void) in return { } // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} } // SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS func sr3520_1<T>(_ g: (inout T) -> Int) {} sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} // This test makes sure that having closure with inout argument doesn't crash with member lookup struct S_3520 { var number1: Int } func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} // expected-note {{in call to function 'sr3520_set_via_closure'}} sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{generic parameter 'S' could not be inferred}} // SR-3073: UnresolvedDotExpr in single expression closure struct SR3073Lense<Whole, Part> { let set: (inout Whole, Part) -> () } struct SR3073 { var number1: Int func lenses() { let _: SR3073Lense<SR3073, Int> = SR3073Lense( set: { $0.number1 = $1 } // ok ) } } // SR-3479: Segmentation fault and other error for closure with inout parameter func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {} func sr3497() { let _ = sr3497_unfold((0, 0)) { s in 0 } // ok } // SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs let _: ((Any?) -> Void) = { (arg: Any!) in } // This example was rejected in 3.0 as well, but accepting it is correct. let _: ((Int?) -> Void) = { (arg: Int!) in } // rdar://30429709 - We should not attempt an implicit conversion from // () -> T to () -> Optional<()>. func returnsArray() -> [Int] { return [] } returnsArray().compactMap { $0 }.compactMap { } // expected-warning@-1 {{expression of type 'Int' is unused}} // expected-warning@-2 {{result of call to 'compactMap' is unused}} // rdar://problem/30271695 _ = ["hi"].compactMap { $0.isEmpty ? nil : $0 } // rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected func r32432145(_ a: () -> ()) {} r32432145 { _ in let _ = 42 } // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}} r32432145 { _ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}} print("answer is 42") } r32432145 { _,_ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}} print("answer is 42") } // rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller [1, 2].first { $0.foo = 3 } // expected-error@-1 {{value of type 'Int' has no member 'foo'}} // expected-error@-2 {{cannot convert value of type '()' to closure result type 'Bool'}} // rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem protocol A_SR_5030 { associatedtype Value func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U> } struct B_SR_5030<T> : A_SR_5030 { typealias Value = T func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() } } func sr5030_exFalso<T>() -> T { fatalError() } extension A_SR_5030 { func foo() -> B_SR_5030<Int> { let tt : B_SR_5030<Int> = sr5030_exFalso() return tt.map { x in (idx: x) } // expected-error@-1 {{cannot convert value of type '(idx: Int)' to closure result type 'Int'}} } } // rdar://problem/33296619 let u = rdar33296619().element //expected-error {{use of unresolved identifier 'rdar33296619'}} [1].forEach { _ in _ = "\(u)" _ = 1 + "hi" // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } class SR5666 { var property: String? } func testSR5666(cs: [SR5666?]) -> [String?] { return cs.map({ c in let a = c.propertyWithTypo ?? "default" // expected-error@-1 {{value of type 'SR5666?' has no member 'propertyWithTypo'}} let b = "\(a)" return b }) } // Ensure that we still do the appropriate pointer conversion here. _ = "".withCString { UnsafeMutableRawPointer(mutating: $0) } // rdar://problem/34077439 - Crash when pre-checking bails out and // leaves us with unfolded SequenceExprs inside closure body. _ = { (offset) -> T in // expected-error {{use of undeclared type 'T'}} return offset ? 0 : 0 } struct SR5202<T> { func map<R>(fn: (T) -> R) {} } SR5202<()>().map{ return 0 } SR5202<()>().map{ _ in return 0 } SR5202<Void>().map{ return 0 } SR5202<Void>().map{ _ in return 0 } func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) { var x = item update(&x) } var sr3250_arg = 42 sr3520_2(sr3250_arg) { $0 += 3 } // ok // SR-1976/SR-3073: Inference of inout func sr1976<T>(_ closure: (inout T) -> Void) {} sr1976({ $0 += 2 }) // ok // rdar://problem/33429010 struct I_33429010 : IteratorProtocol { func next() -> Int? { fatalError() } } extension Sequence { public func rdar33429010<Result>(into initialResult: Result, _ nextPartialResult: (_ partialResult: inout Result, Iterator.Element) throws -> () ) rethrows -> Result { return initialResult } } extension Int { public mutating func rdar33429010_incr(_ inc: Int) { self += inc } } func rdar33429010_2() { let iter = I_33429010() var acc: Int = 0 // expected-warning {{}} let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0 + $1 }) // expected-warning@-1 {{result of operator '+' is unused}} let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0.rdar33429010_incr($1) }) } class P_33429010 { var name: String = "foo" } class C_33429010 : P_33429010 { } func rdar33429010_3() { let arr = [C_33429010()] let _ = arr.map({ ($0.name, $0 as P_33429010) }) // Ok } func rdar36054961() { func bar(dict: [String: (inout String, Range<String.Index>, String) -> Void]) {} bar(dict: ["abc": { str, range, _ in str.replaceSubrange(range, with: str[range].reversed()) }]) } protocol P_37790062 { associatedtype T var elt: T { get } } func rdar37790062() { struct S<T> { init(_ a: () -> T, _ b: () -> T) {} } class C1 : P_37790062 { typealias T = Int var elt: T { return 42 } } class C2 : P_37790062 { typealias T = (String, Int, Void) var elt: T { return ("question", 42, ()) } } func foo() -> Int { return 42 } func bar() -> Void {} func baz() -> (String, Int) { return ("question", 42) } func bzz<T>(_ a: T) -> T { return a } func faz<T: P_37790062>(_ a: T) -> T.T { return a.elt } _ = S({ foo() }, { bar() }) // expected-warning {{result of call to 'foo()' is unused}} _ = S({ baz() }, { bar() }) // expected-warning {{result of call to 'baz()' is unused}} _ = S({ bzz(("question", 42)) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ bzz(String.self) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ bzz(((), (()))) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ bzz(C1()) }, { bar() }) // expected-warning {{result of call to 'bzz' is unused}} _ = S({ faz(C2()) }, { bar() }) // expected-warning {{result of call to 'faz' is unused}} } // <rdar://problem/39489003> typealias KeyedItem<K, T> = (key: K, value: T) // expected-note {{'T' declared as parameter to type 'KeyedItem'}} protocol Node { associatedtype T associatedtype E associatedtype K var item: E {get set} var children: [(key: K, value: T)] {get set} } extension Node { func getChild(for key:K)->(key: K, value: T) { return children.first(where: { (item:KeyedItem) -> Bool in return item.key == key // expected-error@-1 {{generic parameter 'T' could not be inferred}} })! } } // Make sure we don't allow this anymore func takesTwo(_: (Int, Int) -> ()) {} func takesTwoInOut(_: (Int, inout Int) -> ()) {} takesTwo { _ in } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} takesTwoInOut { _ in } // expected-error {{contextual closure type '(Int, inout Int) -> ()' expects 2 arguments, but 1 was used in closure body}} // <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information func f20371273() { let x: [Int] = [1, 2, 3, 4] let y: UInt = 4 _ = x.filter { ($0 + y) > 42 } // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} } // rdar://problem/42337247 func overloaded(_ handler: () -> Int) {} // expected-note {{found this candidate}} func overloaded(_ handler: () -> Void) {} // expected-note {{found this candidate}} overloaded { } // empty body => inferred as returning () overloaded { print("hi") } // single-expression closure => typechecked with body overloaded { print("hi"); print("bye") } // multiple expression closure without explicit returns; can default to any return type // expected-error@-1 {{ambiguous use of 'overloaded'}} func not_overloaded(_ handler: () -> Int) {} not_overloaded { } // empty body // expected-error@-1 {{cannot convert value of type '() -> ()' to expected argument type '() -> Int'}} not_overloaded { print("hi") } // single-expression closure // expected-error@-1 {{cannot convert value of type '()' to closure result type 'Int'}} // no error in -typecheck, but dataflow diagnostics will complain about missing return not_overloaded { print("hi"); print("bye") } // multiple expression closure func apply(_ fn: (Int) throws -> Int) rethrows -> Int { return try fn(0) } enum E : Error { case E } func test() -> Int? { return try? apply({ _ in throw E.E }) } var fn: () -> [Int] = {} // expected-error@-1 {{cannot convert value of type '() -> ()' to specified type '() -> [Int]'}} fn = {} // expected-error@-1 {{cannot assign value of type '() -> ()' to type '() -> [Int]'}} func test<Instances : Collection>( _ instances: Instances, _ fn: (Instances.Index, Instances.Index) -> Bool ) { fatalError() } test([1]) { _, _ in fatalError(); () } // rdar://problem/40537960 - Misleading diagnostic when using closure with wrong type protocol P_40537960 {} func rdar_40537960() { struct S { var v: String } struct L : P_40537960 { init(_: String) {} } struct R<T : P_40537960> { init(_: P_40537960) {} } struct A<T: Collection, P: P_40537960> { // expected-note {{'P' declared as parameter to type 'A'}} typealias Data = T.Element init(_: T, fn: (Data) -> R<P>) {} } var arr: [S] = [] _ = A(arr, fn: { L($0.v) }) // expected-error {{cannot convert value of type 'L' to closure result type 'R<Any>'}} // expected-error@-1 {{generic parameter 'P' could not be inferred}} // expected-note@-2 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<[S], <#P: P_40537960#>>}} } // rdar://problem/45659733 func rdar_45659733() { func foo<T : BinaryInteger>(_: AnyHashable, _: T) {} func bar(_ a: Int, _ b: Int) { _ = (a ..< b).map { i in foo(i, i) } // Ok } struct S<V> { func map<T>( get: @escaping (V) -> T, set: @escaping (inout V, T) -> Void ) -> S<T> { fatalError() } subscript<T>( keyPath: WritableKeyPath<V, T?>, default defaultValue: T ) -> S<T> { return map( get: { $0[keyPath: keyPath] ?? defaultValue }, set: { $0[keyPath: keyPath] = $1 } ) // Ok, make sure that we deduce result to be S<T> } } } func rdar45771997() { struct S { mutating func foo() {} } let _: Int = { (s: inout S) in s.foo() } // expected-error@-1 {{cannot convert value of type '(inout S) -> ()' to specified type 'Int'}} } struct rdar30347997 { func withUnsafeMutableBufferPointer(body : (inout Int) -> ()) {} func foo() { withUnsafeMutableBufferPointer { // expected-error {{cannot convert value of type '(Int) -> ()' to expected argument type '(inout Int) -> ()'}} (b : Int) in } } } struct rdar43866352<Options> { func foo() { let callback: (inout Options) -> Void callback = { (options: Options) in } // expected-error {{cannot assign value of type '(inout Options) -> ()' to type '(inout _) -> Void'}} } } extension Hashable { var self_: Self { return self } } do { struct S< C : Collection, I : Hashable, R : Numeric > { init(_ arr: C, id: KeyPath<C.Element, I>, content: @escaping (C.Element) -> R) {} } func foo(_ arr: [Int]) { _ = S(arr, id: \.self_) { // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{30-30=_ in }} return 42 } } } // Don't allow result type of a closure to end up as a noescape type // The funny error is because we infer the type of badResult as () -> () // via the 'T -> U => T -> ()' implicit conversion. let badResult = { (fn: () -> ()) in fn } // expected-error@-1 {{expression resolves to an unused function}}
apache-2.0
55e822a38d2b6a5240434a5732ace174
33.54796
254
0.62435
3.354925
false
false
false
false
jopamer/swift
test/SILGen/errors.swift
1
49229
// RUN: %target-swift-emit-silgen -parse-stdlib -enable-sil-ownership -Xllvm -sil-print-debuginfo -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s // TODO: Turn back on ownership verification. I turned off the verification on // this file since it shows an ownership error that does not affect // codegen. Specifically when we destroy the temporary array we use for the // variadic tuple, we try to borrow the temporary array when we pass it to the // destroy function. This makes the ownership verifier think that the owned // value we are trying to destroy is not cleaned up. But once ownership is // stripped out, the destroy array function still does what it needs to do. The // actual fix for this would require a bunch of surgery in SILGenApply around // how function types are computed and preserving non-canonical function types // through SILGenApply. This is something that can be done after +0 is turned // on. import Swift class Cat {} enum HomeworkError : Error { case TooHard case TooMuch case CatAteIt(Cat) } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // CHECK: sil hidden @$S6errors10make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK: [[T0:%.*]] = function_ref @$S6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: return [[T2]] : $Cat func make_a_cat() throws -> Cat { return Cat() } // CHECK: sil hidden @$S6errors15dont_make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[BOX]] func dont_make_a_cat() throws -> Cat { throw HomeworkError.TooHard } // CHECK: sil hidden @$S6errors11dont_return{{.*}}F : $@convention(thin) <T> (@in_guaranteed T) -> (@out T, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NOT: destroy_addr %1 : $*T // CHECK-NEXT: throw [[BOX]] func dont_return<T>(_ argument: T) throws -> T { throw HomeworkError.TooMuch } // CHECK: sil hidden @$S6errors16all_together_nowyAA3CatCSbF : $@convention(thin) (Bool) -> @owned Cat { // CHECK: bb0(%0 : @trivial $Bool): // CHECK: [[RET_TEMP:%.*]] = alloc_stack $Cat // Branch on the flag. // CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]] // In the true case, call make_a_cat(). // CHECK: [[FLAG_TRUE]]: // CHECK: [[MAC_FN:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]] // CHECK: [[MAC_NORMAL]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat) // In the false case, call dont_make_a_cat(). // CHECK: [[FLAG_FALSE]]: // CHECK: [[DMAC_FN:%.*]] = function_ref @$S6errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]] // CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat) // Merge point for the ternary operator. Call dont_return with the result. // CHECK: [[TERNARY_CONT]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]] // CHECK: [[DR_FN:%.*]] = function_ref @$S6errors11dont_return{{.*}} : // CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]] // CHECK: [[DR_NORMAL]]({{%.*}} : @trivial $()): // CHECK-NEXT: destroy_addr [[ARG_TEMP]] // CHECK-NEXT: dealloc_stack [[ARG_TEMP]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat) // Return block. // CHECK: [[RETURN]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: return [[T0]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error // CHECK-NEXT: [[COPIED_BORROWED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]] // CHECK-NEXT: store [[COPIED_BORROWED_ERROR]] to [init] [[SRC_TEMP]] // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0_ORIG:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[T0_ORIG]] // CHECK-NEXT: switch_enum [[T0_COPY]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH]]([[T0:%.*]] : @owned $Cat): // CHECK-NEXT: debug_value // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: destroy_value [[T0_ORIG]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]] // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]([[CATCHALL_ERROR:%.*]] : @owned $HomeworkError): // CHECK-NEXT: destroy_value [[CATCHALL_ERROR]] // CHECK-NEXT: destroy_value [[T0_ORIG]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch all. // CHECK: [[CATCHALL]]: // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK: [[T0:%.*]] = function_ref @$S6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]] // CHECK-NEXT: destroy_value [[ERROR]] : $Error // CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat) // Landing pad. // CHECK: [[MAC_ERROR]]([[T0:%.*]] : @owned $Error): // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DMAC_ERROR]]([[T0:%.*]] : @owned $Error): // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DR_ERROR]]([[T0:%.*]] : @owned $Error): // CHECK-NEXT: destroy_addr [[CAT:%.*]] : // CHECK-NEXT: dealloc_stack [[CAT]] // CHECK-NEXT: dealloc_stack // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) func all_together_now(_ flag: Bool) -> Cat { do { return try dont_return(flag ? make_a_cat() : dont_make_a_cat()) } catch HomeworkError.CatAteIt(let cat) { return cat } catch _ { return Cat() } } // Catch in non-throwing context. // CHECK-LABEL: sil hidden @$S6errors11catch_a_catAA3CatCyF : $@convention(thin) () -> @owned Cat // CHECK-NEXT: bb0: // CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type // CHECK: [[F:%.*]] = function_ref @$S6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]]) // CHECK-NEXT: return [[V]] : $Cat func catch_a_cat() -> Cat { do { return Cat() } catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} } // Initializers. class HasThrowingInit { var field: Int init(value: Int) throws { field = value } } // CHECK-LABEL: sil hidden @$S6errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error) // CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit // CHECK: [[T0:%.*]] = function_ref @$S6errors15HasThrowingInit{{.*}}c : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2 // CHECK: bb1([[SELF:%.*]] : @owned $HasThrowingInit): // CHECK-NEXT: return [[SELF]] // CHECK: bb2([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[ERROR]] // CHECK-LABEL: sil hidden @$S6errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) { // CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[BORROWED_T0]] : $HasThrowingInit // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int // CHECK-NEXT: assign %0 to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit enum ColorError : Error { case Red, Green, Blue } //CHECK-LABEL: sil hidden @$S6errors6IThrows5Int32VyKF //CHECK: builtin "willThrow" //CHECK-NEXT: throw func IThrow() throws -> Int32 { throw ColorError.Red return 0 // expected-warning {{will never be executed}} } // Make sure that we are not emitting calls to 'willThrow' on rethrow sites. //CHECK-LABEL: sil hidden @$S6errors12DoesNotThrows5Int32VyKF //CHECK-NOT: builtin "willThrow" //CHECK: return func DoesNotThrow() throws -> Int32 { _ = try IThrow() return 2 } // rdar://20782111 protocol Doomed { func check() throws } // CHECK-LABEL: sil private [transparent] [thunk] @$S6errors12DoomedStructVAA0B0A2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed DoomedStruct) -> @error Error // CHECK: [[SELF:%.*]] = load [trivial] %0 : $*DoomedStruct // CHECK: [[T0:%.*]] = function_ref @$S6errors12DoomedStructV5checkyyKF : $@convention(method) (DoomedStruct) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : @trivial $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : @owned $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: throw [[T0]] : $Error struct DoomedStruct : Doomed { func check() throws {} } // CHECK-LABEL: sil private [transparent] [thunk] @$S6errors11DoomedClassCAA0B0A2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed DoomedClass) -> @error Error { // CHECK: [[BORROWED_SELF:%.*]] = load_borrow %0 // CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> (), $@convention(method) (@guaranteed DoomedClass) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[BORROWED_SELF]]) // CHECK: bb1([[T0:%.*]] : @trivial $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: end_borrow [[BORROWED_SELF]] from %0 // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : @owned $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: end_borrow [[BORROWED_SELF]] from %0 // CHECK: throw [[T0]] : $Error class DoomedClass : Doomed { func check() throws {} } // CHECK-LABEL: sil private [transparent] [thunk] @$S6errors11HappyStructVAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed HappyStruct) -> @error Error // CHECK: [[T0:%.*]] = function_ref @$S6errors11HappyStructV5checkyyF : $@convention(method) (HappyStruct) -> () // CHECK: [[T1:%.*]] = apply [[T0]](%1) // CHECK: [[T1:%.*]] = tuple () // CHECK: return [[T1]] : $() struct HappyStruct : Doomed { func check() {} } // CHECK-LABEL: sil private [transparent] [thunk] @$S6errors10HappyClassCAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed HappyClass) -> @error Error // CHECK: [[SELF:%.*]] = load_borrow %0 : $*HappyClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> (), $@convention(method) (@guaranteed HappyClass) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: end_borrow [[SELF]] from %0 // CHECK: return [[T1]] : $() class HappyClass : Doomed { func check() {} } func create<T>(_ fn: () throws -> T) throws -> T { return try fn() } func testThunk(_ fn: () throws -> Int) throws -> Int { return try create(fn) } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSis5Error_pIgdzo_SisAA_pIegrzo_TR : $@convention(thin) (@noescape @callee_guaranteed () -> (Int, @error Error)) -> (@out Int, @error Error) // CHECK: bb0(%0 : @trivial $*Int, %1 : @trivial $@noescape @callee_guaranteed () -> (Int, @error Error)): // CHECK: try_apply %1() // CHECK: bb1([[T0:%.*]] : @trivial $Int): // CHECK: store [[T0]] to [trivial] %0 : $*Int // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] // CHECK: bb2([[T0:%.*]] : @owned $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: throw [[T0]] : $Error func createInt(_ fn: () -> Int) throws {} func testForceTry(_ fn: () -> Int) { try! createInt(fn) } // CHECK-LABEL: sil hidden @$S6errors12testForceTryyySiyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> () // CHECK: bb0([[ARG:%.*]] : @trivial $@noescape @callee_guaranteed () -> Int): // CHECK: [[FUNC:%.*]] = function_ref @$S6errors9createIntyySiyXEKF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> @error Error // CHECK: try_apply [[FUNC]]([[ARG]]) // CHECK: return // CHECK: builtin "unexpectedError" // CHECK: unreachable func testForceTryMultiple() { _ = try! (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @$S6errors20testForceTryMultipleyyF // CHECK-NEXT: bb0: // CHECK: [[FN_1:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : @owned $Cat) // CHECK: [[FN_2:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : @owned $Cat) // CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error) // CHECK-NEXT: unreachable // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$S6errors20testForceTryMultipleyyF' // Make sure we balance scopes correctly inside a switch. // <rdar://problem/20923654> enum CatFood { case Canned case Dry } // Something we can switch on that throws. func preferredFood() throws -> CatFood { return CatFood.Canned } func feedCat() throws -> Int { switch try preferredFood() { case .Canned: return 0 case .Dry: return 1 } } // CHECK-LABEL: sil hidden @$S6errors7feedCatSiyKF : $@convention(thin) () -> (Int, @error Error) // CHECK: debug_value undef : $Error, var, name "$error", argno 1 // CHECK: %1 = function_ref @$S6errors13preferredFoodAA03CatC0OyKF : $@convention(thin) () -> (CatFood, @error Error) // CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5 // CHECK: bb1([[VAL:%.*]] : @trivial $CatFood): // CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3 // CHECK: bb5([[ERROR:%.*]] : @owned $Error) // CHECK: throw [[ERROR]] : $Error // Throwing statements inside cases. func getHungryCat(_ food: CatFood) throws -> Cat { switch food { case .Canned: return try make_a_cat() case .Dry: return try dont_make_a_cat() } } // errors.getHungryCat throws (errors.CatFood) -> errors.Cat // CHECK-LABEL: sil hidden @$S6errors12getHungryCatyAA0D0CAA0D4FoodOKF : $@convention(thin) (CatFood) -> (@owned Cat, @error Error) // CHECK: bb0(%0 : @trivial $CatFood): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3 // CHECK: bb1: // CHECK: [[FN:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @$S6errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7 // CHECK: bb6([[ERROR:%.*]] : @owned $Error): // CHECK: br bb8([[ERROR:%.*]] : $Error) // CHECK: bb7([[ERROR:%.*]] : @owned $Error): // CHECK: br bb8([[ERROR]] : $Error) // CHECK: bb8([[ERROR:%.*]] : @owned $Error): // CHECK: throw [[ERROR]] : $Error func take_many_cats(_ cats: Cat...) throws {} func test_variadic(_ cat: Cat) throws { try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @$S6errors13test_variadicyyAA3CatCKF : $@convention(thin) (@guaranteed Cat) -> @error Error { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Cat): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4 // CHECK: [[T0:%.*]] = function_ref @$Ss27_allocateUninitializedArray{{.*}}F // CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]]) // CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]] // CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 0 // CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]] // CHECK: [[T2:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 1 // CHECK: end_borrow [[BORROWED_T1]] from [[T1]] // CHECK: destroy_value [[T1]] // CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat // Element 0. // CHECK: [[T0:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]] // CHECK: [[NORM_0]]([[CAT0:%.*]] : @owned $Cat): // CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]] // Element 1. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1 // CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]] // Element 2. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2 // CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]] // CHECK: [[NORM_2]]([[CAT2:%.*]] : @owned $Cat): // CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]] // Element 3. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3 // CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]] // CHECK: [[NORM_3]]([[CAT3:%.*]] : @owned $Cat): // CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]] // Complete the call and return. // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[TAKE_FN:%.*]] = function_ref @$S6errors14take_many_catsyyAA3CatCd_tKF : $@convention(thin) (@guaranteed Array<Cat>) -> @error Error // CHECK-NEXT: try_apply [[TAKE_FN]]([[BORROWED_ARRAY]]) : $@convention(thin) (@guaranteed Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]] // CHECK: [[NORM_CALL]]([[T0:%.*]] : @trivial $()): // CHECK-NEXT: end_borrow [[BORROWED_ARRAY]] from [[ARRAY]] // CHECK-NEXT: destroy_value [[ARRAY]] // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return // Failure from element 0. // CHECK: [[ERR_0]]([[ERROR:%.*]] : @owned $Error): // CHECK-NOT: end_borrow // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$Ss29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error) // Failure from element 2. // CHECK: [[ERR_2]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$Ss29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from element 3. // CHECK: [[ERR_3]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_addr [[ELT2]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @$Ss29_deallocateUninitializedArray{{.*}}F // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from call. // CHECK: [[ERR_CALL]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: end_borrow // CHECK-NEXT: destroy_value [[ARRAY]] // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Rethrow. // CHECK: [[RETHROW]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$S6errors13test_variadicyyAA3CatCKF' // rdar://20861374 // Clear out the self box before delegating. class BaseThrowingInit : HasThrowingInit { var subField: Int init(value: Int, subField: Int) throws { self.subField = subField try super.init(value: value) } } // CHECK: sil hidden @$S6errors16BaseThrowingInit{{.*}}c : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error) // CHECK: [[BOX:%.*]] = alloc_box ${ var BaseThrowingInit } // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]] // CHECK: [[PB:%.*]] = project_box [[MARKED_BOX]] // Initialize subField. // CHECK: [[T0:%.*]] = load_borrow [[PB]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int // CHECK-NEXT: assign %1 to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: end_borrow [[T0]] from [[PB]] // Super delegation. // CHECK-NEXT: [[T0:%.*]] = load [take] [[PB]] // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit // CHECK: [[T3:%[0-9]+]] = function_ref @$S6errors15HasThrowingInitC5valueACSi_tKcfc : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: apply [[T3]](%0, [[T2]]) // Cleanups for writebacks. protocol Supportable { mutating func support() throws } protocol Buildable { associatedtype Structure : Supportable var firstStructure: Structure { get set } subscript(name: String) -> Structure { get set } } func supportFirstStructure<B: Buildable>(_ b: inout B) throws { try b.firstStructure.support() } // CHECK-LABEL: sil hidden @$S6errors21supportFirstStructure{{.*}}F : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error { // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: [[T5:%.*]] = begin_access [modify] [unsafe] [[T4]] : $*B.Structure // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$S6errors21supportFirstStructure{{.*}}F' func supportStructure<B: Buildable>(_ b: inout B, name: String) throws { try b[name].support() } // CHECK-LABEL: sil hidden @$S6errors16supportStructure_4nameyxz_SStKAA9BuildableRzlF : $@convention(thin) <B where B : Buildable> (@inout B, @guaranteed String) -> @error Error { // CHECK: bb0({{.*}}, [[INDEX:%.*]] : @guaranteed $String): // CHECK: [[INDEX_COPY:%.*]] = copy_value [[INDEX]] : $String // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[BORROWED_INDEX_COPY:%.*]] = begin_borrow [[INDEX_COPY]] // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BORROWED_INDEX_COPY]], [[BASE:%[0-9]*]]) // CHECK: end_borrow [[BORROWED_INDEX_COPY]] from [[INDEX_COPY]] // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: [[T5:%.*]] = begin_access [modify] [unsafe] [[T4]] : $*B.Structure // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T5]]) : $@convention(witness_method: Supportable) <τ_0_0 where τ_0_0 : Supportable> (@inout τ_0_0) -> @error Error, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] : ${{.*}}, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]( // CHECK: apply // // CHECK: [[NONE_BB]]: // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: destroy_value [[INDEX_COPY]] : $String // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: destroy_value [[INDEX_COPY]] : $String // CHECK: throw [[ERROR]] // CHECK: } // end sil function '$S6errors16supportStructure{{.*}}F' struct Pylon { var name: String mutating func support() throws {} } struct Bridge { var mainPylon : Pylon subscript(name: String) -> Pylon { get { return mainPylon } set {} } } func supportStructure(_ b: inout Bridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @$S6errors16supportStructure_4nameyAA6BridgeVz_SStKF : $@convention(thin) (@inout Bridge, @guaranteed String) -> @error Error { // CHECK: bb0([[ARG1:%.*]] : @trivial $*Bridge, [[ARG2:%.*]] : @guaranteed $String): // CHECK: [[INDEX_COPY_1:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*Bridge // CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon // CHECK-NEXT: [[BASE:%.*]] = load_borrow [[WRITE]] : $*Bridge // CHECK-NEXT: [[BORROWED_INDEX_COPY_1:%.*]] = begin_borrow [[INDEX_COPY_1]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @$S6errors6BridgeVyAA5PylonVSScig : // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[BORROWED_INDEX_COPY_1]], [[BASE]]) // CHECK-NEXT: end_borrow [[BORROWED_INDEX_COPY_1]] // CHECK-NEXT: store [[T0]] to [init] [[TEMP]] // CHECK-NEXT: end_borrow [[BASE]] from [[WRITE]] // CHECK: [[SUPPORT:%.*]] = function_ref @$S6errors5PylonV7supportyyKF // CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$S6errors6BridgeVyAA5PylonVSScis : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[WRITE]]) // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: destroy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // We end up with ugly redundancy here because we don't want to // consume things during cleanup emission. It's questionable. // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$S6errors6BridgeVyAA5PylonVSScis : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[WRITE]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: dealloc_stack [[TEMP]] // ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY // CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: destroy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$S6errors16supportStructure_4nameyAA6BridgeVz_SStKF' struct OwnedBridge { var owner : AnyObject subscript(name: String) -> Pylon { addressWithOwner { return (someValidPointer(), owner) } mutableAddressWithOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout OwnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @$S6errors16supportStructure_4nameyAA11OwnedBridgeVz_SStKF : // CHECK: bb0([[ARG1:%.*]] : @trivial $*OwnedBridge, [[ARG2:%.*]] : @guaranteed $String): // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*OwnedBridge // CHECK: [[BORROWED_ARG2_COPY:%.*]] = begin_borrow [[ARG2_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @$S6errors11OwnedBridgeVyAA5PylonVSSciaO : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[BORROWED_ARG2_COPY]], [[WRITE]]) // CHECK-NEXT: end_borrow [[BORROWED_ARG2_COPY]] // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0 // CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1 // CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T5]] : $*Pylon // CHECK: [[SUPPORT:%.*]] = function_ref @$S6errors5PylonV7supportyyKF // CHECK-NEXT: try_apply [[SUPPORT]]([[ACCESS]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: end_access [[ACCESS]] : $*Pylon // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: destroy_value [[OWNER]] : $AnyObject // CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: end_access [[ACCESS]] : $*Pylon // CHECK-NEXT: destroy_value [[OWNER]] : $AnyObject // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$S6errors16supportStructure_4nameyAA11OwnedBridgeVz_SStKF' struct PinnedBridge { var owner : Builtin.NativeObject subscript(name: String) -> Pylon { addressWithPinnedNativeOwner { return (someValidPointer(), owner) } mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout PinnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @$S6errors16supportStructure_4nameyAA12PinnedBridgeVz_SStKF : // CHECK: bb0([[ARG1:%.*]] : @trivial $*PinnedBridge, [[ARG2:%.*]] : @guaranteed $String): // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*PinnedBridge // CHECK-NEXT: [[BORROWED_ARG2_COPY:%.*]] = begin_borrow [[ARG2_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @$S6errors12PinnedBridgeVyAA5PylonVSSciaP : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[BORROWED_ARG2_COPY]], [[WRITE]]) // CHECK-NEXT: end_borrow [[BORROWED_ARG2_COPY]] // CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0 // CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1 // CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T5]] : $*Pylon // CHECK: [[SUPPORT:%.*]] = function_ref @$S6errors5PylonV7supportyyKF // CHECK-NEXT: try_apply [[SUPPORT]]([[ACCESS]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: end_access [[ACCESS]] : $*Pylon // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: end_access [[ACCESS]] : $*Pylon // CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]] // CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[OWNER]] // CHECK-NEXT: end_access [[WRITE]] // CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '$S6errors16supportStructure_4nameyAA12PinnedBridgeVz_SStKF' // ! peepholes its argument with getSemanticsProvidingExpr(). // Test that that doesn't look through try!. // rdar://21515402 func testForcePeephole(_ f: () throws -> Int?) -> Int { let x = (try! f())! return x } // CHECK-LABEL: sil hidden @$S6errors15testOptionalTryyyF // CHECK-NEXT: bb0: // CHECK: [[FN:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : @owned $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>) // CHECK: [[DONE]]([[RESULT:%.+]] : @owned $Optional<Cat>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>) // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$S6errors15testOptionalTryyyF' func testOptionalTry() { _ = try? make_a_cat() } func sudo_make_a_cat() {} // CHECK-LABEL: sil hidden @{{.*}}testOptionalTryThatNeverThrows func testOptionalTryThatNeverThrows() { guard let _ = try? sudo_make_a_cat() else { // expected-warning{{no calls to throwing}} return } } // CHECK-LABEL: sil hidden @$S6errors18testOptionalTryVaryyF // CHECK-NEXT: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<Cat> } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : @owned $Cat) // CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<Cat> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$S6errors18testOptionalTryVaryyF' func testOptionalTryVar() { var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @$S6errors26testOptionalTryAddressOnly{{.*}}F // CHECK: bb0(%0 : @trivial $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @$S6errors11dont_return{{.*}}F // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], %0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : @trivial $()): // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NOT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$S6errors26testOptionalTryAddressOnlyyyxlF' func testOptionalTryAddressOnly<T>(_ obj: T) { _ = try? dont_return(obj) } // CHECK-LABEL: sil hidden @$S6errors29testOptionalTryAddressOnlyVar{{.*}}F // CHECK: bb0(%0 : @trivial $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @$S6errors11dont_return{{.*}}F // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], %0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : @trivial $()): // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NOT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$S6errors29testOptionalTryAddressOnlyVaryyxlF' func testOptionalTryAddressOnlyVar<T>(_ obj: T) { var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @$S6errors23testOptionalTryMultipleyyF // CHECK: bb0: // CHECK: [[FN_1:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : @owned $Cat) // CHECK: [[FN_2:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : @owned $Cat) // CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>) // CHECK: [[DONE]]([[RESULT:%.+]] : @owned $Optional<(Cat, Cat)>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>) // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : @owned $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '$S6errors23testOptionalTryMultipleyyF' func testOptionalTryMultiple() { _ = try? (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @$S6errors25testOptionalTryNeverFailsyyF // CHECK: bb0: // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '$S6errors25testOptionalTryNeverFailsyyF' func testOptionalTryNeverFails() { _ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @$S6errors28testOptionalTryNeverFailsVaryyF // CHECK: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<()> } // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<()> } // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '$S6errors28testOptionalTryNeverFailsVaryyF' func testOptionalTryNeverFailsVar() { var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}} } // CHECK-LABEL: sil hidden @$S6errors36testOptionalTryNeverFailsAddressOnly{{.*}}F // CHECK: bb0(%0 : @trivial $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NOT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '$S6errors36testOptionalTryNeverFailsAddressOnlyyyxlF' func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) { _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @$S6errors39testOptionalTryNeverFailsAddressOnlyVar{{.*}}F // CHECK: bb0(%0 : @trivial $*T): // CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '$S6errors13OtherErrorSubCACycfC' func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) { var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } class SomeErrorClass : Error { } // CHECK-LABEL: sil_vtable SomeErrorClass // CHECK-NEXT: #SomeErrorClass.init!initializer.1: {{.*}} : @$S6errors14SomeErrorClassCACycfc // CHECK-NEXT: #SomeErrorClass.deinit!deallocator.1: @$S6errors14SomeErrorClassCfD // CHECK-NEXT: } class OtherErrorSub : OtherError { } // CHECK-LABEL: sil_vtable OtherErrorSub { // CHECK-NEXT: #OtherError.init!initializer.1: {{.*}} : @$S6errors13OtherErrorSubCACycfc [override] // OtherErrorSub.init() // CHECK-NEXT: #OtherErrorSub.deinit!deallocator.1: @$S6errors13OtherErrorSubCfD // OtherErrorSub.__deallocating_deinit // CHECK-NEXT:}
apache-2.0
66250b874f30ce5a1c595a996ea5d4b0
49.419057
234
0.610234
3.198297
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Metadata/Tests/MetadataKitTests/MetadataServiceTests.swift
1
10617
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine @testable import MetadataDataKit @testable import MetadataKit import NetworkKit import TestKit import ToolKit import XCTest // swiftlint:disable line_length final class MetadataServiceTests: XCTestCase { var cancellables: Set<AnyCancellable>! private var subject: MetadataServiceAPI! override func setUpWithError() throws { try super.setUpWithError() cancellables = [] } override func tearDownWithError() throws { subject = nil cancellables = nil try super.tearDownWithError() } func test_initialize() throws { let environment = TestEnvironment() let initializedExpecation = expectation( description: "Metadata was successfully initialized" ) let fetchCalledWithCorrectAddressExpectation = expectation( description: "Fetch was called with the correct address" ) let expectedAddress = "12TMDMri1VSjbBw8WJvHmFpvpxzTJe7EhU" let fetch: FetchMetadataEntry = { address in XCTAssertEqual(address, expectedAddress) fetchCalledWithCorrectAddressExpectation.fulfill() return .just(MetadataPayload.rootMetadataPayload) } let put: PutMetadataEntry = { _, _ in XCTFail("Put should not be called") return .just(()) } let expectedState = environment.metadataState subject = MetadataService( initialize: provideInitialize( fetch: fetch, put: put ), initializeAndRecoverCredentials: provideInitializeAndRecoverCredentials( fetch: fetch ), fetchEntry: provideFetchEntry(fetch: fetch), saveEntry: provideSave(fetch: fetch, put: put) ) subject .initialize( credentials: environment.credentials, masterKey: environment.masterKey, payloadIsDoubleEncrypted: false ) .sink(receiveCompletion: { completion in switch completion { case .failure(let error): XCTFail(error.localizedDescription) case .finished: break } }, receiveValue: { [initializedExpecation] metadataState in XCTAssertEqual(metadataState, expectedState) initializedExpecation.fulfill() }) .store(in: &cancellables) wait( for: [ initializedExpecation, fetchCalledWithCorrectAddressExpectation ], timeout: 10.0 ) } func test_initialize_with_wrong_root_private_key_fixes_the_error() { let environment = TestEnvironment() let initializedExpecation = expectation( description: "Metadata was successfully initialized" ) let fetchCalledWithCorrectAddressExpectation = expectation( description: "Fetch was called with the correct address" ) // this is because before we `PUT` an entry we re fetch the entry fetchCalledWithCorrectAddressExpectation.expectedFulfillmentCount = 2 let expectedAddress = "12TMDMri1VSjbBw8WJvHmFpvpxzTJe7EhU" // given a wrong metadata payload let fetch: FetchMetadataEntry = { address in XCTAssertEqual(address, expectedAddress) fetchCalledWithCorrectAddressExpectation.fulfill() return .just(MetadataPayload.erroreousRootMetadataPayload) } let putCalledWithCorrectAddressExpectation = expectation( description: "Put was called with the correct address" ) let expectedRootXpriv = "xprv9uvPCc4bEjZEaAAxnva4d9gnUGPssAVsT8DfnGuLVdtD9TeQfFtfySYD7P1cBAUZSNXnT52zxxmpx4rs2pzCJxu64gpwzUdu33HEzzjbHty" let put: PutMetadataEntry = { address, body in XCTAssertEqual(address, expectedAddress) putCalledWithCorrectAddressExpectation.fulfill() let decryptedJSON = decryptMetadata( metadata: environment.secondPasswordNode.metadataNode, payload: body.payload ).success ?? "" let decoded = decryptedJSON .decodeJSON( to: RemoteMetadataNodesResponse.self ) .success! XCTAssertEqual(decoded.metadata!, expectedRootXpriv) return .just(()) } let expectedState = environment.metadataState subject = MetadataService( initialize: provideInitialize( fetch: fetch, put: put ), initializeAndRecoverCredentials: provideInitializeAndRecoverCredentials( fetch: fetch ), fetchEntry: provideFetchEntry(fetch: fetch), saveEntry: provideSave(fetch: fetch, put: put) ) subject .initialize( credentials: environment.credentials, masterKey: environment.masterKey, payloadIsDoubleEncrypted: false ) .sink(receiveCompletion: { completion in switch completion { case .failure(let error): XCTFail(error.localizedDescription) case .finished: break } }, receiveValue: { [initializedExpecation] metadataState in XCTAssertEqual(metadataState, expectedState) initializedExpecation.fulfill() }) .store(in: &cancellables) wait( for: [ initializedExpecation, putCalledWithCorrectAddressExpectation, fetchCalledWithCorrectAddressExpectation ], timeout: 10.0 ) } func test_initialize_and_recover_credentials() throws { let environment = TestEnvironment() let initializedAndRecoveredSuccessfullyExpecation = expectation( description: "Metadata was successfully initialized and the credentials recovered" ) let fetchCalledWithCorrectAddressExpectation = expectation( description: "Fetch was called with the correct address" ) let mnemonic = environment.mnemonic.mnemonicString let expectedAddress = "1EfF3b4GusL5YkKji9HxqAhDBRRvEFSZiP" let fetch: FetchMetadataEntry = { address in XCTAssertEqual(address, expectedAddress) fetchCalledWithCorrectAddressExpectation.fulfill() return .just(MetadataPayload.credentialsMetadataEntryPayload) } let put: PutMetadataEntry = { _, _ in XCTFail("Put should not be called") return .just(()) } let expectedMetadataState = environment.metadataState let expectedCredentials = environment.credentials let expectedRecoveryContext = RecoveryContext( metadataState: expectedMetadataState, credentials: expectedCredentials ) subject = MetadataService( initialize: provideInitialize( fetch: fetch, put: put ), initializeAndRecoverCredentials: provideInitializeAndRecoverCredentials( fetch: fetch ), fetchEntry: provideFetchEntry(fetch: fetch), saveEntry: provideSave(fetch: fetch, put: put) ) subject .initializeAndRecoverCredentials(from: mnemonic) .sink(receiveCompletion: { completion in switch completion { case .failure(let error): XCTFail(error.localizedDescription) case .finished: break } }, receiveValue: { [initializedAndRecoveredSuccessfullyExpecation] recoveryContext in XCTAssertEqual(recoveryContext, expectedRecoveryContext) initializedAndRecoveredSuccessfullyExpecation.fulfill() }) .store(in: &cancellables) wait( for: [ initializedAndRecoveredSuccessfullyExpecation, fetchCalledWithCorrectAddressExpectation ], timeout: 10.0 ) } func test_fetch() throws { let successfullyFetchedExpectation = expectation( description: "The entry was successfully fetched" ) let fetchCalledWithCorrectAddressExpectation = expectation( description: "Fetch was called with the correct address" ) let expectedAddress = "129GLwNB2EbNRrGMuNSRh9PM83xU2Mpn81" let fetch: FetchMetadataEntry = { address in XCTAssertEqual(address, expectedAddress) fetchCalledWithCorrectAddressExpectation.fulfill() return .just(MetadataPayload.ethereumMetadataEntryPayload) } let put: PutMetadataEntry = { _, _ in XCTFail("Put should not be called") return .just(()) } let environment = TestEnvironment() let metadataState = environment.metadataState let expectedEntryPayload = EthereumEntryPayload.entry subject = MetadataService( initialize: provideInitialize( fetch: fetch, put: put ), initializeAndRecoverCredentials: provideInitializeAndRecoverCredentials( fetch: fetch ), fetchEntry: provideFetchEntry(fetch: fetch), saveEntry: provideSave(fetch: fetch, put: put) ) subject .fetchEntry(with: metadataState) .sink(receiveCompletion: { completion in switch completion { case .failure(let error): XCTFail(error.localizedDescription) case .finished: break } }, receiveValue: { [successfullyFetchedExpectation] (entry: EthereumEntryPayload) in XCTAssertEqual(entry, expectedEntryPayload) successfullyFetchedExpectation.fulfill() }) .store(in: &cancellables) wait( for: [ fetchCalledWithCorrectAddressExpectation, successfullyFetchedExpectation ], timeout: 10.0 ) } }
lgpl-3.0
bbe7125bd209c771824079586413b7f5
32.071651
145
0.59627
5.53782
false
false
false
false
wolfposd/Caffeed
FeedbackBeaconContext/FeedbackBeaconContext/FeedbackSheet/View/ListCell.swift
1
1615
// // ListModuleCell.swift // DynamicFeedbackSheets // // Created by Jan Hennings on 09/06/14. // Copyright (c) 2014 Jan Hennings. All rights reserved. // import UIKit class ListCell: ModuleCell { // MARK: Properties @IBOutlet var descriptionLabel: UILabel! @IBOutlet var listControl: UISegmentedControl! override var module: FeedbackSheetModule? { willSet { listControl.removeAllSegments() descriptionLabel.text = nil if let list = newValue as? ListModule { descriptionLabel.text = list.text for (index, segmentTitle) in enumerate(list.elements) { listControl.insertSegmentWithTitle(segmentTitle, atIndex: index, animated: true) } } } } // FIXME: Testing, current Bug in Xcode (Ambiguous use of module) override func setModule(module: FeedbackSheetModule) { self.module = module } // MARK: IBActions @IBAction func selectSegment(sender: UISegmentedControl) { if let list = module as? ListModule { list.responseData = list.elements[sender.selectedSegmentIndex] delegate?.moduleCell(self, didGetResponse: list.responseData, forID: list.ID) } } // MARK: Actions override func reloadWithResponseData(responseData: AnyObject) { for index in 0..<listControl.numberOfSegments { if responseData as? String == listControl.titleForSegmentAtIndex(index) { listControl.selectedSegmentIndex = index } } } }
gpl-3.0
cfff800aa7c1794652cf81df7aff9c76
27.839286
96
0.626625
4.835329
false
false
false
false
Jnosh/swift
test/Generics/function_defs.swift
8
10869
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Type-check function definitions //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Basic type checking //===----------------------------------------------------------------------===// protocol EqualComparable { func isEqual(_ other: Self) -> Bool } func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool { var b1 = t1.isEqual(t2) if b1 { return true } return t1.isEqual(u) // expected-error {{cannot invoke 'isEqual' with an argument list of type '(U)'}} expected-note {{expected an argument list of type '(T)'}} } protocol MethodLessComparable { func isLess(_ other: Self) -> Bool } func min<T : MethodLessComparable>(_ x: T, y: T) -> T { if (y.isLess(x)) { return y } return x } //===----------------------------------------------------------------------===// // Interaction with existential types //===----------------------------------------------------------------------===// func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) { var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} eqComp = u if t1.isEqual(eqComp) {} // expected-error{{cannot invoke 'isEqual' with an argument list of type '(EqualComparable)'}} // expected-note @-1 {{expected an argument list of type '(T)'}} if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}} } protocol OtherEqualComparable { func isEqual(_ other: Self) -> Bool } func otherExistential<T : EqualComparable>(_ t1: T) { var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}} otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp2 _ = t1 as EqualComparable & OtherEqualComparable // expected-error{{'T' is not convertible to 'EqualComparable & OtherEqualComparable'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} } protocol Runcible { func runce<A>(_ x: A) func spoon(_ x: Self) } func testRuncible(_ x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}} x.runce(5) } //===----------------------------------------------------------------------===// // Overloading //===----------------------------------------------------------------------===// protocol Overload { associatedtype A associatedtype B func getA() -> A func getB() -> B func f1(_: A) -> A func f1(_: B) -> B func f2(_: Int) -> A // expected-note{{found this candidate}} func f2(_: Int) -> B // expected-note{{found this candidate}} func f3(_: Int) -> Int // expected-note {{found this candidate}} func f3(_: Float) -> Float // expected-note {{found this candidate}} func f3(_: Self) -> Self // expected-note {{found this candidate}} var prop : Self { get } } func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl, other: OtherOvl) { var a = ovl.getA() var b = ovl.getB() // Overloading based on arguments _ = ovl.f1(a) a = ovl.f1(a) _ = ovl.f1(b) b = ovl.f1(b) // Overloading based on return type a = ovl.f2(17) b = ovl.f2(17) ovl.f2(17) // expected-error{{ambiguous use of 'f2'}} // Check associated types from different objects/different types. a = ovl2.f2(17) a = ovl2.f1(a) other.f1(a) // expected-error{{cannot invoke 'f1' with an argument list of type '(Ovl.A)'}} // expected-note @-1 {{overloads for 'f1' exist with these partially matching parameter lists: (Self.A), (Self.B)}} // Overloading based on context var f3i : (Int) -> Int = ovl.f3 var f3f : (Float) -> Float = ovl.f3 var f3ovl_1 : (Ovl) -> Ovl = ovl.f3 var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3 var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}} var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3 var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3 var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3 var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3 var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3 } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol Subscriptable { associatedtype Index associatedtype Value func getIndex() -> Index func getValue() -> Value subscript (index : Index) -> Value { get set } } protocol IntSubscriptable { associatedtype ElementType func getElement() -> ElementType subscript (index : Int) -> ElementType { get } } func subscripting<T : Subscriptable & IntSubscriptable>(_ t: T) { var index = t.getIndex() var value = t.getValue() var element = t.getElement() value = t[index] t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}} element = t[17] t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}} // Suggests the Int form because we prefer concrete matches to generic matches in diagnosis. t[value] = 17 // expected-error{{cannot convert value of type 'T.Value' to expected argument type 'Int'}} } //===----------------------------------------------------------------------===// // Static functions //===----------------------------------------------------------------------===// protocol StaticEq { static func isEqual(_ x: Self, y: Self) -> Bool } func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) { if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}} if T.isEqual(t, y: t) { return } if U.isEqual(u, y: u) { return } T.isEqual(t, y: u) // expected-error{{cannot invoke 'isEqual' with an argument list of type '(T, y: U)'}} expected-note {{expected an argument list of type '(T, y: T)'}} } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Ordered { static func <(lhs: Self, rhs: Self) -> Bool } func testOrdered<T : Ordered>(_ x: T, y: Int) { if y < 100 || 500 < y { return } if x < x { return } } //===----------------------------------------------------------------------===// // Requires clauses //===----------------------------------------------------------------------===// func conformanceViaRequires<T>(_ t1: T, t2: T) -> Bool where T : EqualComparable, T : MethodLessComparable { let b1 = t1.isEqual(t2) if b1 || t1.isLess(t2) { return true } } protocol GeneratesAnElement { associatedtype Element : EqualComparable func makeIterator() -> Element } protocol AcceptsAnElement { associatedtype Element : MethodLessComparable func accept(_ e : Element) } func impliedSameType<T : GeneratesAnElement>(_ t: T) where T : AcceptsAnElement { t.accept(t.makeIterator()) let e = t.makeIterator(), e2 = t.makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } protocol GeneratesAssoc1 { associatedtype Assoc1 : EqualComparable func get() -> Assoc1 } protocol GeneratesAssoc2 { associatedtype Assoc2 : MethodLessComparable func get() -> Assoc2 } func simpleSameType<T : GeneratesAssoc1, U : GeneratesAssoc2> (_ t: T, u: U) -> Bool where T.Assoc1 == U.Assoc2 { return t.get().isEqual(u.get()) || u.get().isLess(t.get()) } protocol GeneratesMetaAssoc1 { associatedtype MetaAssoc1 : GeneratesAnElement func get() -> MetaAssoc1 } protocol GeneratesMetaAssoc2 { associatedtype MetaAssoc2 : AcceptsAnElement func get() -> MetaAssoc2 } func recursiveSameType <T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1> (_ t: T, u: U, v: V) where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2 { t.get().accept(t.get().makeIterator()) let e = t.get().makeIterator(), e2 = t.get().makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } // <rdar://problem/13985164> protocol P1 { associatedtype Element } protocol P2 { associatedtype AssocP1 : P1 func getAssocP1() -> AssocP1 } func beginsWith2<E0: P1, E1: P1>(_ e0: E0, _ e1: E1) -> Bool where E0.Element == E1.Element, E0.Element : EqualComparable { } func beginsWith3<S0: P2, S1: P2>(_ seq1: S0, _ seq2: S1) -> Bool where S0.AssocP1.Element == S1.AssocP1.Element, S1.AssocP1.Element : EqualComparable { return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1()) } // FIXME: Test same-type constraints that try to equate things we // don't want to equate, e.g., T == U. //===----------------------------------------------------------------------===// // Bogus requirements //===----------------------------------------------------------------------===// func nonTypeReq<T>(_: T) where T : Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func badProtocolReq<T>(_: T) where T : Int {} // expected-error{{type 'T' constrained to non-protocol type 'Int'}} func nonTypeSameType<T>(_: T) where T == Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func nonTypeSameType2<T>(_: T) where Wibble == T {} // expected-error{{use of undeclared type 'Wibble'}} func sameTypeEq<T>(_: T) where T = T {} // expected-error{{use '==' for same-type requirements rather than '='}} {{34-35===}} // expected-warning@-1{{redundant same-type constraint 'T' == 'T'}} func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of 'T'}} func badSameType<T, U : GeneratesAnElement, V>(_ : T, _ : U) where T == U.Element, U.Element == V {} // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
apache-2.0
7449254068aaab9ad22a13902acd005f
35.351171
375
0.576594
3.985699
false
false
false
false
MadAppGang/MAGPagedScrollView
MAGPagedScrollViewDemo/MAGPagedScrollViewDemo/ViewController.swift
1
2290
// // ViewController.swift // MAGPagedScrollViewDemo // // Created by Ievgen Rudenko on 21/08/15. // Copyright (c) 2015 MadAppGang. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var scrollView: PagedScrollView! var colors = [ UIColor.redColor(), UIColor.blueColor(), UIColor.greenColor(), UIColor.magentaColor() ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //alternate way to add subviews // createView(0) // createView(1) // createView(2) // createView(3) scrollView.addSubviews([ createView(0), createView(1), createView(2), createView(3) ]) } @IBAction func goToLast(sender: AnyObject) { self.scrollView.goToPage(3, animated: true) } func createView(color: Int) -> UIView { let view = UIView(frame: CGRectMake(0, 0, 100, 100)) view.backgroundColor = colors[color] view.layer.cornerRadius = 10.0 return view } func createAndAddView(color: Int) { let width = CGRectGetWidth(scrollView.frame) let height = CGRectGetHeight(scrollView.frame) let x = CGFloat(scrollView.subviews.count) * width let view = UIView(frame: CGRectMake(x, 0, width, height)) view.backgroundColor = colors[color] view.layer.cornerRadius = 10.0 scrollView.addSubview(view) scrollView.contentSize = CGSizeMake(x+width, height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func segmentedViewChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 1: scrollView.transition = .Slide case 2: scrollView.transition = .Dive case 3: scrollView.transition = .Roll case 4: scrollView.transition = .Cards default: scrollView.transition = .None } } }
mit
a22c142598aaacf5cd69189656f43256
26.590361
80
0.614847
4.64503
false
false
false
false
psharanda/adocgen
adocgen/SourceKittenOutputParser.swift
1
3113
// // Copyright © 2016 Pavel Sharanda. All rights reserved. // import Foundation import SwiftyJSON /* SAMPLE JSON { "\/Users\/psharanda\/Work\/adocgen\/adocgen\/CellModel.swift":{ "key.substructure":[ { "key.kind":"source.lang.swift.decl.class", "key.doc.comment":"Simplest type of cell. Has optional title and icon. Corresponds to cell of .Default style.", "key.name":"DefaultCellModel", "key.inheritedtypes":[ { "key.name":"CellModel" } ], "key.substructure":[ { "key.kind":"source.lang.swift.decl.var.instance", "key.doc.comment":"The name of a book, chapter, poem, essay, picture, statue, piece of music, play, film, etc", "key.typename":"String?", "key.name":"title" } ] } ] } } */ struct SKField { let comment: String? let typename: String? let name: String? static func makeFromDict(_ dict: [String: JSON]) -> SKField { return SKField(comment: dict["key.doc.comment"]?.string, typename: dict["key.typename"]?.string, name: dict["key.name"]?.string) } } struct SKType { let comment: String? let name: String? let inheritedTypes: [String] let fields: [SKField] static func makeFromDict(_ dict: [String: JSON]) -> SKType { var inheritedTypes = [String]() if let a = dict["key.inheritedtypes"]?.array { for d in a { if let t = d["key.name"].string { inheritedTypes.append(t) } } } var fields = [SKField]() if let a = dict["key.substructure"]?.array { for d in a { if let dd = d.dictionary, dd["key.kind"] == "source.lang.swift.decl.var.instance" { fields.append(SKField.makeFromDict(dd)) } } } return SKType(comment: dict["key.doc.comment"]?.string, name: dict["key.name"]?.string, inheritedTypes: inheritedTypes, fields: fields) } } func parseSourceKittenOutput(_ jsonPath: String) throws -> [SKType] { var types = [SKType]() if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath)) { let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) let json = JSON(jsonObject) if let (_,jsonDict) = json.dictionary?.first, let structure = jsonDict["key.substructure"].array { for substr in structure { if let substrDict = substr.dictionary { if substrDict["key.kind"] == "source.lang.swift.decl.class" { types.append(SKType.makeFromDict(substrDict)) } } } } } return types }
mit
705bb3fbb4d2cc304eb0a8b7fa56dde2
29.213592
143
0.507712
4.48415
false
false
false
false
Derek-Chiu/Mr-Ride-iOS
Mr-Ride-iOS/Mr-Ride-iOS/CellTableViewCell.swift
1
1007
// // CellTableViewCell.swift // Mr-Ride-iOS // // Created by Derek on 5/25/16. // Copyright © 2016 AppWorks School Derek. All rights reserved. // import UIKit class CellTableViewCell: UITableViewCell { @IBOutlet weak var dot: UIView! @IBOutlet weak var label: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code dot.layer.cornerRadius = dot.frame.size.width / 2 dot.clipsToBounds = true dot.hidden = true label.textColor = UIColor.whiteColor() label.font = UIFont.mrTextStyle7Font(24) label.textColor = UIColor.mrWhite50Color() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { dot.hidden = false label.textColor = UIColor.whiteColor() } else { dot.hidden = true label.textColor = UIColor.mrWhite50Color() } } }
mit
a0959407158b76bccd247ba598e3b679
24.794872
64
0.619284
4.354978
false
false
false
false
bhyzy/Ripped
Ripped/Ripped/UI/DayViewModel.swift
1
2398
// // File.swift // Ripped // // Created by Bartlomiej Hyzy on 2/7/17. // Copyright © 2017 Bartlomiej Hyzy. All rights reserved. // import Foundation class DayViewModel: TableViewModel { // MARK: - Properties private var day: Day // MARK: - Definitions typealias ExerciseResultsViewSetup = (title: String, results: [String], comment: String?) typealias ExerciseCellSetup = (name: String, goal: String, todayResults: ExerciseResultsViewSetup, lastResults: ExerciseResultsViewSetup?) // MARK: - Initialization init(day: Day) { self.day = day super.init() } // MARK: - Overriden override var title: String? { return day.fullName } override var numberOfRows: Int { return day.exercises.count } // MARK: - Internal func exerciseCellSetup(forRow row: Int) -> ExerciseCellSetup { let exercise = self.exercise(atRow: row) let todayResults = ExerciseResultsViewSetup(title: NSLocalizedString("Today", comment: ""), results: results(forExercise: exercise), comment: exercise.comment) var lastResults: ExerciseResultsViewSetup? if let lastExercise = exercise.previousOccurence { lastResults = ExerciseResultsViewSetup(title: NSLocalizedString("Last Time", comment: ""), results: results(forExercise: lastExercise), comment: lastExercise.comment) } return ExerciseCellSetup(name: exercise.name, goal: exercise.goal, todayResults: todayResults, lastResults: lastResults) } // MARK: - Private private func exercise(atRow row: Int) -> Exercise { return day.exercises[row] } private func results(forExercise exercise: Exercise) -> [String] { return exercise.sets.map { "\(Int($0.weight)) x \($0.numberOfRepetitions)" } } }
mit
1595a53ca3e56808f78ac9558c66cd33
30.539474
102
0.511055
5.485126
false
false
false
false
anlaital/Swan
Swan/Swan/StringExtensions.swift
1
3598
// // StringExtensions.swift // Swan // // Created by Antti Laitala on 22/05/15. // // import Foundation public extension String { /// Returns the uppercase representation of this string taking into account the current app locale. var upcase: String { return uppercased(with: Locale.appLocale()) } /// Returns the downcase representation of this string taking into account the current app locale. var downcase: String { return lowercased(with: Locale.appLocale()) } /// Returns a string object containing the characters of the `String` that lie within a given range. subscript(subRange: Range<Int>) -> String { let start = index(startIndex, offsetBy: subRange.lowerBound) let end = index(startIndex, offsetBy: subRange.upperBound) return String(self[start..<end]) } /// Returns a string object containing the characters of the `String` that lie within a given range. subscript(subRange: NSRange) -> String { let start = index(startIndex, offsetBy: subRange.lowerBound) let end = index(startIndex, offsetBy: subRange.upperBound) return String(self[start..<end]) } /// Remove the indicated `subRange` of characters. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`self.count`). /// - Returns: String that was removed mutating func removeRange(_ subRange: Range<Int>) -> String { let removed = self[subRange] removeSubrange(index(startIndex, offsetBy: subRange.lowerBound)..<index(startIndex, offsetBy: subRange.upperBound)) return removed } } // MARK: Regex public extension String { func match(_ pattern: String) throws -> [String] { let regexp = try createRegexWithPattern(pattern) let matches = regexp.matches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, count)) var results = [String]() for match in matches { results.append(self[match.range]) } return results } func gsub(_ pattern: String, replacement: String) throws -> String { let regexp = try createRegexWithPattern(pattern) return regexp.stringByReplacingMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, count), withTemplate: replacement) } func gsub(_ pattern: String, replacementClosure: (String) -> (String)) throws -> String { let regexp = try createRegexWithPattern(pattern) let matches = regexp.matches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSMakeRange(0, count)) var result = "" var idx = 0 for match in matches { let replacement = replacementClosure(self[match.range]) // Insert unmodified content. result += self[idx..<match.range.location] // Replace modified content. result += replacement idx = match.range.location + match.range.length } result += self[idx..<count] return result } static fileprivate var regexpCache = [String: NSRegularExpression]() fileprivate func createRegexWithPattern(_ pattern: String) throws -> NSRegularExpression { var regexp: NSRegularExpression? = String.regexpCache[pattern] if regexp == nil { regexp = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options()) String.regexpCache[pattern] = regexp } return regexp! } }
mit
64df1a43c964d740e22e4a3bdf47030d
35.714286
161
0.651751
4.823056
false
false
false
false
ello/ello-ios
Sources/Controllers/ArtistInvites/Cells/ArtistInviteSubmissionsButtonCell.swift
1
1634
//// /// ArtistInviteSubmissionsButtonCell.swift // import SnapKit class ArtistInviteSubmissionsButtonCell: CollectionViewCell { static let reuseIdentifier = "ArtistInviteSubmissionsButtonCell" struct Size { static let height: CGFloat = 70 static let buttonMargins = UIEdgeInsets(top: 0, left: 15, bottom: 30, right: 15) } private let submissionsButton = StyledButton(style: .artistInviteSubmissions) override func style() { submissionsButton.titleEdgeInsets.top = 4 } override func bindActions() { submissionsButton.addTarget( self, action: #selector(tappedSubmissionsButton), for: .touchUpInside ) } override func setText() { submissionsButton.title = InterfaceString.ArtistInvites.SeeSubmissions } override func arrange() { contentView.addSubview(submissionsButton) submissionsButton.snp.makeConstraints { make in make.edges.equalTo(contentView).inset(Size.buttonMargins) } } } extension ArtistInviteSubmissionsButtonCell { @objc func tappedSubmissionsButton() { let responder: ArtistInviteResponder? = findResponder() responder?.tappedArtistInviteSubmissionsButton() } } extension StyledButton.Style { static let artistInviteSubmissions = StyledButton.Style( backgroundColor: .white, highlightedBackgroundColor: .greenD1, titleColor: .greenD1, highlightedTitleColor: .white, borderColor: .greenD1, highlightedBorderColor: .white, cornerRadius: .rounded ) }
mit
8bd7e890e32c248250c95b9f954313df
25.786885
88
0.679927
4.981707
false
false
false
false
DuckDeck/ViewChaos
Sources/Tool.swift
1
7281
// // Tool.swift // ViewChaosDemo // // Created by Stan Hu on 2019/1/16. // Copyright © 2019 Qfq. All rights reserved. // import UIKit extension Float{ func format(_ f:String)->String{ return String(format:"%\(f)",self) } } extension Double{ func format(_ f:String)->String{ return String(format:"%\(f)",self) } } extension CGFloat{ func format(_ f:String)->String{ return String(format:"%\(f)",self) } } private var NSObject_Name = 0 extension NSObject{ @objc var chaosName:String?{ get{ return objc_getAssociatedObject(self, &NSObject_Name) as? String } set{ objc_setAssociatedObject(self, &NSObject_Name, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } } } private var UIWindow_Feature = "UIWindow_Feature" extension UIWindow{ @objc var chaosFeature:Int{ get{ let v = objc_getAssociatedObject(self, &UIWindow_Feature) if let str = v as? String{ if let n = Int(str) { return n } } return 0 // return objc_getAssociatedObject(self, &UIWindow_Feature) as! Int } set{ objc_setAssociatedObject(self, &UIWindow_Feature, "\(newValue)", objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) //Issue1, 要添加不同的类型的属性,就要设置正确的objc_AssociationPolicy,如果是Class,就要用OBJC_ASSOCIATION_RETAIN_NONATOMIC,Int要用OBJC_ASSOCIATION_ASSIGN,String要用OBJC_ASSOCIATION_COPY_NONATOMIC //不然后可能会造成数据丢失或者其他异常 //注意objc_AssociationPolicy类型一定要正确,不然可能会从内存里丢失 //Issue 12: 在最新的Swift3里面,好像不能保存Int到AssociatedObject里面,反正每次都取不出来。我换成STRING 就OK了 } } } private var UIView_Level = "UIView_Level" extension UIView{ @objc var viewLevel:Int{ get{ let v = objc_getAssociatedObject(self, &UIView_Level) if let str = v as? String{ if let n = Int(str) { return n } } return 0 } set{ objc_setAssociatedObject(self, &UIView_Level, "\(newValue)", objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } } } extension UIDevice{ var modelName:String{ var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce(""){identifier,element in guard let value = element.value as? Int8,value != 0 else{ return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { // iPod case "iPod1,1": return "iPod touch" case "iPod2,1": return "iPod touch 2" case "iPod3,1": return "iPod touch 3" case "iPod4,1": return "iPod touch 4" case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPod9,1": return "iPod Touch 7" // iPhone case "iPhone1,1": return "iPhone" case "iPhone1,2": return "iPhone 3G" case "iPhone2,1": return "iPhone 3GS" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,6": return "iPhone XS MAX" case "iPhone11,8": return "iPhone XR" case "iPhone12,1": return "iPhone 11" case "iPhone12,3": return "iPhone 11 Pro" case "iPhone12,5": return "iPhone 11 Pro max" // iPad case "iPad1,1": return "iPad" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch)" case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) 2" case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" case "iPad7,5", "iPad7,6": return "iPad 6" // AppleTV case "AppleTV5,3": return "Apple TV" // Other case "i386", "x86_64": return "Simulator" default: return identifier } } } extension UIDevice{ public static var isNotchScreen:Bool{ if UIDevice.current.userInterfaceIdiom == .pad{ return false } let size = UIScreen.main.bounds.size let notchValue: Int = Int(size.width/size.height * 100) if 216 == notchValue || 46 == notchValue { return true } return false } }
mit
9a4f1d7936b52df77b2c98b052fbb05b
39.022599
178
0.480661
4.116212
false
false
false
false
austinzheng/swift-compiler-crashes
fixed/25966-llvm-densemap-swift-normalprotocolconformance.swift
7
1293
// 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 S<a struct B Void{ var a: A : A protocol c : A } class var e : a { protocol a : a { struct B<String in }struct B<T where k : A func a func a=e protocol P { func f<h = object { protocol c B a Foundation } protocol a { class A? = compose(" } { class A : a class d class B<String, C>(" class d>() typealias e : a: a :d protocol P { struct A class A { struct B func a { class A<T.e func a { } struct b<d } } class B protocol a { var " case c, let end = compose(" } in } case c typealias e : A extension g:BooleanType{ class A {} extension NSFileManager { return E.c{ enum b { } typealias e = compose()enum C { {struct A var d { { func a :BooleanType{ let b{struct B<T:C>() let h : A { case c } protocol P { } struct c { } { protocol A { } } return E.e func a { } atic var d { class B<T where T? {{ protocol a { class B< { } class A { enum S<b{ class A { } }} } Void{{ if struct c, func c{ enum S<h : a typealias e : A { class d} struct b: a {enum b = F>() { } } ( " func a { class A : A func a:BooleanType{ var f = compose(n: Dictionary<String, C>()) struct b: A protocol A { class A { static let f = e } let end = [
mit
2bd13e4b89f7cba9fa399e9e707a1f1e
10.862385
87
0.635731
2.612121
false
false
false
false
mozilla-mobile/focus
XCUITest/SearchSuggestionsTest.swift
1
6398
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCTest class SearchSuggestionsPromptTest: BaseTestCase { override func setUp() { super.setUp() dismissFirstRunUI() } override func tearDown() { app.terminate() super.tearDown() } func checkToggle(isOn: Bool) { let targetValue = isOn ? "1" : "0" XCTAssertEqual(app.tables.switches["BlockerToggle.enableSearchSuggestions"].value as! String, targetValue) } func checkSuggestions() { // Check search cells are displayed correctly let firstSuggestion = app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 0) waitforExistence(element: firstSuggestion) waitforExistence(element: app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 1)) waitforExistence(element: app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 2)) waitforExistence(element: app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 3)) let predicate = NSPredicate(format: "label BEGINSWITH 'g'") let predicateQuery = app.buttons.matching(predicate) // Confirm that we have at least four suggestions starting with "g" XCTAssert(predicateQuery.count >= 4) // Check tapping on first suggestion leads to correct page firstSuggestion.tap() waitForValueContains(element: app.textFields["URLBar.urlText"], value: "g") } func typeInURLBar(text: String) { app.textFields["Search or enter address"].tap() app.textFields["Search or enter address"].typeText(text) } func checkToggleStartsOff() { waitforHittable(element: app.buttons["Settings"]) app.buttons["Settings"].tap() checkToggle(isOn: false) } func testEnableThroughPrompt() { // Check search suggestions toggle is initially OFF checkToggleStartsOff() // Activate prompt by typing in URL bar app.buttons["SettingsViewController.doneButton"].tap() typeInURLBar(text: "g") // Prompt should display waitforExistence(element: app.otherElements["SearchSuggestionsPromptView"]) // Press enable app.buttons["SearchSuggestionsPromptView.enableButton"].tap() // Ensure prompt disappears waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"]) // Adding a delay in case of slow network sleep(4) // Ensure search suggestions are shown checkSuggestions() // Check search suggestions toggle is ON waitforHittable(element: app.buttons["HomeView.settingsButton"]) app.buttons["HomeView.settingsButton"].tap() checkToggle(isOn: true) } func testDisableThroughPrompt() { // Check search suggestions toggle is initially OFF checkToggleStartsOff() // Activate prompt by typing in URL bar app.buttons["SettingsViewController.doneButton"].tap() typeInURLBar(text: "g") // Prompt should display waitforExistence(element: app.otherElements["SearchSuggestionsPromptView"]) // Press disable app.buttons["SearchSuggestionsPromptView.disableButton"].tap() // Ensure prompt disappears waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"]) // Ensure only one search cell is shown let suggestion = app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 0) waitforExistence(element: suggestion) XCTAssert("Search for g" == suggestion.label || "g" == suggestion.label) // Check tapping on suggestion leads to correct page suggestion.tap() waitForValueContains(element: app.textFields["URLBar.urlText"], value: "g") // Check search suggestions toggle is OFF waitforHittable(element: app.buttons["HomeView.settingsButton"]) app.buttons["HomeView.settingsButton"].tap() checkToggle(isOn: false) } func testEnableThroughToggle() { // Check search suggestions toggle is initially OFF checkToggleStartsOff() // Turn toggle ON app.tables.switches["BlockerToggle.enableSearchSuggestions"].tap() // Prompt should not display app.buttons["SettingsViewController.doneButton"].tap() typeInURLBar(text: "g") // Adding a delay in case of slow network sleep(4) waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"]) // Ensure search suggestions are shown checkSuggestions() } func testEnableThenDisable() { // Check search suggestions toggle is initially OFF checkToggleStartsOff() // Activate prompt by typing in URL bar app.buttons["SettingsViewController.doneButton"].tap() typeInURLBar(text: "g") // Prompt should display waitforExistence(element: app.otherElements["SearchSuggestionsPromptView"]) // Press enable app.buttons["SearchSuggestionsPromptView.enableButton"].tap() // Adding a delay in case of slow network sleep(4) // Ensure prompt disappears waitforNoExistence(element: app.otherElements["SearchSuggestionsPromptView"]) // Ensure search suggestions are shown checkSuggestions() // Disable through settings waitforHittable(element: app.buttons["HomeView.settingsButton"]) app.buttons["HomeView.settingsButton"].tap() app.tables.switches["BlockerToggle.enableSearchSuggestions"].tap() checkToggle(isOn: false) // Ensure only one search cell is shown app.buttons["SettingsViewController.doneButton"].tap() let urlBarTextField = app.textFields["URLBar.urlText"] urlBarTextField.tap() urlBarTextField.typeText("g") let suggestion = app.buttons.matching(identifier: "OverlayView.searchButton").element(boundBy: 0) waitforExistence(element: suggestion) XCTAssert("Search for g" == suggestion.label || "g" == suggestion.label) } }
mpl-2.0
792459a1f68ec1b7de94cdeb580b80c6
35.982659
115
0.670991
5.138956
false
false
false
false
controlgroup/coffee-bot
CoffeeBar/CoffeeBar/AppDelegate.swift
1
6395
// // AppDelegate.swift // CoffeeBar // // Created by Tim Mattison on 7/24/15. // Copyright (c) 2015 controlgroup. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let configPlistName = "Config" let apiEndpointConfigKeyName = "API endpoint" let refreshIntervalInSeconds = 15.0 let coffeeProcessor = CoffeeProcessor() let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2) var refreshTimer:NSTimer? var endpointUrl:String? var coffeeCupImage:NSImage? var noCarafeImage:NSImage? var coffeeCupImages = [NSImage]() var statusBarItem: NSStatusItem = NSStatusItem() var menu: NSMenu = NSMenu() var toolTip: NSMenuItem = NSMenuItem() func applicationDidFinishLaunching(aNotification: NSNotification) { loadButtonIcons() createMenu() populateEndpointUrl() createRefreshTimer() } private func loadButtonIcons() { coffeeCupImage = NSImage(named: "StatusBarButtonImage")! noCarafeImage = NSImage(named: "NoCarafe") coffeeCupImages.append(coffeeCupImage!) coffeeCupImages.append(NSImage(named: "1Cup")!) coffeeCupImages.append(NSImage(named: "2Cups")!) coffeeCupImages.append(NSImage(named: "3Cups")!) coffeeCupImages.append(NSImage(named: "4Cups")!) coffeeCupImages.append(NSImage(named: "5Cups")!) coffeeCupImages.append(NSImage(named: "6Cups")!) coffeeCupImages.append(NSImage(named: "7Cups")!) coffeeCupImages.append(NSImage(named: "8Cups")!) coffeeCupImages.append(NSImage(named: "9Cups")!) coffeeCupImages.append(NSImage(named: "10Cups")!) updateButtonImage(coffeeCupImage) } private func updateButtonImage(input: NSImage!) { dispatch_async(dispatch_get_main_queue()) { if let button = self.statusItem.button { button.image = input } } } private func createMenu() { let menu = NSMenu() toolTip.title = "Checking with the bot..." toolTip.keyEquivalent = "" menu.addItem(toolTip) menu.addItem(NSMenuItem(title: "Quit CoffeeBar", action: Selector("terminate:"), keyEquivalent: "q")) statusItem.menu = menu } private func populateEndpointUrl() { if let path = NSBundle.mainBundle().pathForResource(configPlistName, ofType: "plist") { if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> { // TODO: Check if this is "CHANGEME" and remind the user to change it endpointUrl = dict[apiEndpointConfigKeyName] as? String } } } private func createRefreshTimer() { refreshTimer = NSTimer(timeInterval: refreshIntervalInSeconds, target: self, selector: "refreshTimerFired", userInfo: nil, repeats: true) if refreshTimer != nil { NSRunLoop.currentRunLoop().addTimer(refreshTimer!, forMode: NSRunLoopCommonModes) } } func refreshTimerFired() { let result: AnyObject? = coffeeProcessor.pollCoffeeUrl(endpointUrl) if result == nil { // TODO: Eventually let the user know that the coffee status is invalid return } let carafePresent = coffeeProcessor.carafePresent(result!) if carafePresent == false { updateButtonImage(noCarafeImage) toolTip.title = "\(getTime()): No carafe present" return } if let cupsRemaining = coffeeProcessor.cupsRemaining(result!) { let clampedCupsRemaining = max(0, min(10, cupsRemaining)) let lastBrewed = coffeeProcessor.lastBrewed(result!) updateButtonImage(coffeeCupImages[clampedCupsRemaining]) if(clampedCupsRemaining == 1) { toolTip.title = "\(getTime()): 1 cup remaining, \(getBrewedTime(lastBrewed))" } else { toolTip.title = "\(getTime()): \(clampedCupsRemaining) cups remaining, \(getBrewedTime(lastBrewed))" } } } private func getTime() -> String { let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date) let ampm = (components.hour >= 12) ? "PM" : "AM" let hourNumber = (components.hour > 12) ? components.hour - 12 : components.hour let hour = String(format: "%02d", hourNumber) let minutes = String(format: "%02d", components.minute) return "\(hour):\(minutes) \(ampm)" } private func getBrewedTime(brewedTime: Int?) -> String { if (brewedTime == nil) { return "no brew time available" } if brewedTime < 0 { return "not sure when it was brewed" } let date = NSDate().timeIntervalSince1970 let epoch = Int(round(date) * 1000) var difference = epoch - brewedTime! let days = difference / 86400000 difference = difference % 86400000 let hours = difference / 3600000 difference = difference % 3600000 let minutes = difference / 60000 if (days == 0) && (hours == 0) && (minutes == 0) { return "just brewed" } var result = "brewed " var separator = "" if days > 0 { result += "\(separator)\(days) day" if days != 1 { result += "s" } separator = ", " } if hours > 0 { result += "\(separator)\(hours) hour" if hours != 1 { result += "s" } separator = ", " } if minutes > 0 { result += "\(separator)\(minutes) minute" if minutes != 1 { result += "s" } separator = ", " } result += " ago" return result } }
apache-2.0
f151be0c7e49bd3b7d770b7e0c9bdccd
31.30303
145
0.563409
4.83006
false
false
false
false
kzin/swift-testing
swift-testing/swift-testing/User.swift
1
851
// // User.swift // swift-testing // // Created by Rodrigo Cavalcante on 03/03/17. // Copyright © 2017 Rodrigo Cavalcante. All rights reserved. // import Foundation protocol JsonObjectParseable { init?(json: JsonObject) } struct User: JsonObjectParseable{ let username: String let email: String let age: Int let access: Access init?(json: JsonObject) { guard let username = json["username"] as? String else { return nil } guard let email = json["email"] as? String else { return nil } guard let age = json["age"] as? Int else { return nil } self.username = username self.age = age self.email = email self.access = Access(json: json["access"] as? JsonObject) } }
mit
89a3ef6a22dcff215fa6c67c19063e98
20.25
65
0.563529
4.10628
false
false
false
false
ra1028/FloatingActionSheetController
FloatingActionSheetController-Demo/FloatingActionSheetController-Demo/TableViewCell.swift
1
866
// // TableViewCell.swift // FloatingActionSheetController-Demo // // Created by Ryo Aoyama on 10/28/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit final class TableViewCell: UITableViewCell { // MARK: Public var title: String? { get { return titleLabel.text } set { titleLabel.text = newValue } } override func awakeFromNib() { super.awakeFromNib() contentView.backgroundColor = UIColor(red:0.14, green:0.16, blue:0.2, alpha:1) let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = UIColor(red:0.11, green:0.12, blue:0.15, alpha:1) self.selectedBackgroundView = selectedBackgroundView } // MARK: Private @IBOutlet fileprivate weak var titleLabel: UILabel! }
mit
2e21a3dce6cd90fe7e09992394e47d03
23.714286
98
0.625434
4.481865
false
false
false
false
1170197998/Swift-DEMO
CountDown/CountDown/ViewController.swift
1
4071
// // ViewController.swift // CountDown // // Created by ShaoFeng on 2017/2/20. // Copyright © 2017年 ShaoFeng. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var day: UILabel! @IBOutlet weak var hour: UILabel! @IBOutlet weak var minute: UILabel! @IBOutlet weak var second: UILabel! var timer: DispatchSourceTimer? override func viewDidLoad() { super.viewDidLoad() datePicker.minimumDate = Date() datePicker.locale = Locale(identifier: "zh_CH") datePicker.addTarget(self, action: #selector(dateChange), for: .valueChanged) } @objc fileprivate func dateChange()->() { //datePicker选择完毕 } @IBAction func calculateTime(_ sender: Any) { print(datePicker.date) timer = nil //截止日期 let endDate = datePicker.date //开始日期 let startDate = Date() //时间间隔 let timeInterval:TimeInterval = endDate.timeIntervalSince(startDate) if timer == nil { //剩余时间 var timeout = timeInterval if timeout != 0 { //创建全局队列 let queue = DispatchQueue.global() //在全局队列下创建一个时间源 timer = DispatchSource.makeTimerSource(flags: [], queue: queue) //设定循环的间隔是一秒,并且立即开始 timer?.schedule(wallDeadline: DispatchWallTime.now(), repeating: .seconds(1)) //时间源出发事件 timer?.setEventHandler(handler: { //必须是当前日期往后的日期,在datePicker上也做了限制 if timeout <= 0 { self.timer?.cancel() self.timer = nil DispatchQueue.main.async(execute: { self.day.text = "00" self.hour.text = "00" self.minute.text = "00" self.second.text = "00" }) } else { //计算剩余时间 let days = Int(timeout) / (3600 * 24) if days == 0 { self.day.text = "" } let hours = (Int(timeout) - Int(days) * 24 * 3600) / 3600 let minutes = (Int(timeout) - Int(days) * 24 * 3600 - Int(hours) * 3600) / 60 let seconds = Int(timeout) - Int(days) * 24 * 3600 - Int(hours) * 3600 - Int(minutes) * 60 //主队列中刷新UI DispatchQueue.main.async(execute: { if days == 0 { self.day.text = "0" } else { self.day.text = "\(days)" } if hours < 10 { self.hour.text = "0" + "\(hours)" } else { self.hour.text = "\(hours)" } if minutes < 10 { self.minute.text = "0" + "\(minutes)" } else { self.minute.text = "\(minutes)" } if seconds < 10 { self.second.text = "0" + "\(seconds)" } else { self.second.text = "\(seconds)" } }) timeout -= 1 } }) //启动时间源 timer?.resume() } } } }
apache-2.0
31a1b19c24c3d47aa40d0799e0323e96
35.186916
114
0.399535
5.318681
false
false
false
false
4np/UitzendingGemist
UitzendingGemist/EpisodeCollectionViewCell.swift
1
2917
// // EpisodeCollectionViewCell.swift // UitzendingGemist // // Created by Jeroen Wesbeek on 19/07/16. // Copyright © 2016 Jeroen Wesbeek. All rights reserved. // import Foundation import UIKit import NPOKit import CocoaLumberjack class EpisodeCollectionViewCell: UICollectionViewCell { @IBOutlet weak fileprivate var episodeImageView: UIImageView! @IBOutlet weak var episodeNameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! weak var episodeRequest: NPORequest? weak var programRequest: NPORequest? // MARK: Lifecycle override func prepareForReuse() { super.prepareForReuse() self.episodeImageView.image = nil self.episodeNameLabel.text = nil self.dateLabel.text = nil } // MARK: Focus engine override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { self.episodeImageView.adjustsImageWhenAncestorFocused = self.isFocused } // MARK: Configuration func configure(withEpisode episode: NPOEpisode, andProgram program: NPOProgram?) { self.episodeNameLabel.text = episode.getDisplayName() self.dateLabel.text = episode.broadcastedDisplayValue // Somehow in tvOS 10 / Xcode 8 / Swift 3 the frame will initially be 1000x1000 // causing the images to look compressed so hardcode the dimensions for now... // TODO: check if this is solved in later releases... //let size = self.episodeImageView.frame.size let size = CGSize(width: 375, height: 211) // get image self.episodeRequest = episode.getImage(ofSize: size) { [weak self] image, _, request in guard let image = image else { // fallback to program self?.fetchImage(byProgram: program) return } guard request == self?.episodeRequest else { // this is the result of another cell, ignore it return } self?.episodeImageView.image = image } } fileprivate func fetchImage(byProgram program: NPOProgram?) { // Somehow in tvOS 10 / Xcode 8 / Swift 3 the frame will initially be 1000x1000 // causing the images to look compressed so hardcode the dimensions for now... // TODO: check if this is solved in later releases... //let size = self.episodeImageView.frame.size let size = CGSize(width: 375, height: 211) self.programRequest = program?.getImage(ofSize: size) { [weak self] image, _, request in guard request == self?.programRequest else { // this is the result of another cell, ignore it return } self?.episodeImageView.image = image } } }
apache-2.0
ea4cdee877b9632d7265a46adbea2646
34.13253
115
0.625857
5.10683
false
false
false
false
airbnb/lottie-ios
Example/iOS/ViewControllers/AnimationPreviewViewController.swift
2
8100
// Created by Cal Stephens on 12/10/21. // Copyright © 2021 Airbnb Inc. All rights reserved. import Lottie import UIKit class AnimationPreviewViewController: UIViewController { // MARK: Lifecycle init(_ animationName: String) { self.animationName = animationName super.init(nibName: nil, bundle: nil) title = animationName.components(separatedBy: "/").last! animationView.loopMode = .autoReverse configureSettingsMenu() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Internal override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) displayLink?.invalidate() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground if let animation = LottieAnimation.named(animationName) { animationView.animation = animation } else { DotLottieFile.named(animationName) { [animationView] result in guard case Result.success(let lottie) = result else { return } animationView.loadAnimation(from: lottie) } } animationView.contentMode = .scaleAspectFit view.addSubview(animationView) slider.translatesAutoresizingMaskIntoConstraints = false slider.minimumValue = 0 slider.maximumValue = 1 slider.value = 0 view.addSubview(slider) animationView.backgroundBehavior = .pauseAndRestore animationView.translatesAutoresizingMaskIntoConstraints = false engineLabel.font = .preferredFont(forTextStyle: .footnote) engineLabel.textColor = .secondaryLabel engineLabel.translatesAutoresizingMaskIntoConstraints = false engineLabel.setContentCompressionResistancePriority(.required, for: .vertical) view.addSubview(engineLabel) NSLayoutConstraint.activate([ animationView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), animationView.leadingAnchor.constraint(equalTo: view.leadingAnchor), animationView.bottomAnchor.constraint(equalTo: engineLabel.topAnchor, constant: -8), animationView.trailingAnchor.constraint(equalTo: view.trailingAnchor), engineLabel.trailingAnchor.constraint(equalTo: slider.trailingAnchor), engineLabel.bottomAnchor.constraint(equalTo: slider.topAnchor), ]) /// Slider slider.heightAnchor.constraint(equalToConstant: 40).isActive = true slider.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true slider.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true slider.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -12).isActive = true slider.addTarget(self, action: #selector(updateAnimation(sender:)), for: .valueChanged) /// Create a display link to make slider track with animation progress. displayLink = CADisplayLink(target: self, selector: #selector(animationCallback)) displayLink?.add( to: .current, forMode: RunLoop.Mode.default) } @objc func updateAnimation(sender: UISlider) { animationView.currentProgress = CGFloat(sender.value) } @objc func animationCallback() { if animationView.isAnimationPlaying { slider.value = Float(animationView.realtimeAnimationProgress) } engineLabel.text = [ animationView.currentRenderingEngine?.description, animationView.isAnimationPlaying ? "Playing" : "Paused", ].compactMap { $0 }.joined(separator: " · ") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateAnimation() } // MARK: Private private let animationName: String private let animationView = LottieAnimationView() private let slider = UISlider() private let engineLabel = UILabel() private var displayLink: CADisplayLink? private var loopMode = LottieLoopMode.autoReverse private var speed: CGFloat = 1 private var fromProgress: AnimationProgressTime = 0 private var toProgress: AnimationProgressTime = 1 private func configureSettingsMenu() { navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Settings", image: UIImage(systemName: "repeat.circle")!, primaryAction: nil, menu: UIMenu(children: [ UIMenu( title: "Loop Mode...", children: [ UIAction( title: "Autoreverse", state: loopMode == .autoReverse ? .on : .off, handler: { [unowned self] _ in loopMode = .autoReverse updateAnimation() }), UIAction( title: "Loop", state: loopMode == .loop ? .on : .off, handler: { [unowned self] _ in loopMode = .loop updateAnimation() }), UIAction( title: "Play Once", state: loopMode == .playOnce ? .on : .off, handler: { [unowned self] _ in loopMode = .playOnce updateAnimation() }), ]), UIMenu( title: "Speed", children: [ UIAction( title: "-100%", state: speed == -1 ? .on : .off, handler: { [unowned self] _ in speed = -1 updateAnimation() }), UIAction( title: "-50%", state: speed == -0.5 ? .on : .off, handler: { [unowned self] _ in speed = -0.5 updateAnimation() }), UIAction( title: "50%", state: speed == 0.5 ? .on : .off, handler: { [unowned self] _ in speed = 0.5 updateAnimation() }), UIAction( title: "100%", state: speed == 1 ? .on : .off, handler: { [unowned self] _ in speed = 1 updateAnimation() }), ]), UIMenu( title: "From Progress...", children: [ UIAction( title: "0%", state: fromProgress == 0 ? .on : .off, handler: { [unowned self] _ in fromProgress = 0 updateAnimation() }), UIAction( title: "25%", state: fromProgress == 0.25 ? .on : .off, handler: { [unowned self] _ in fromProgress = 0.25 updateAnimation() }), UIAction( title: "50%", state: fromProgress == 0.5 ? .on : .off, handler: { [unowned self] _ in fromProgress = 0.5 updateAnimation() }), ]), UIMenu( title: "To Progress...", children: [ UIAction( title: "0%", state: toProgress == 0 ? .on : .off, handler: { [unowned self] _ in toProgress = 0 updateAnimation() }), UIAction( title: "50%", state: toProgress == 0.5 ? .on : .off, handler: { [unowned self] _ in toProgress = 0.5 updateAnimation() }), UIAction( title: "75%", state: toProgress == 0.75 ? .on : .off, handler: { [unowned self] _ in toProgress = 0.75 updateAnimation() }), UIAction( title: "100%", state: toProgress == 1 ? .on : .off, handler: { [unowned self] _ in toProgress = 1 updateAnimation() }), ]), ])) } private func updateAnimation() { animationView.play(fromProgress: fromProgress, toProgress: toProgress, loopMode: loopMode) animationView.animationSpeed = speed configureSettingsMenu() } }
apache-2.0
8f4c55e84d738f376b834b2c07cc6e09
31.134921
112
0.569894
5.067584
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Core/_Extensions/_Foundation/Int+Utils.swift
1
1389
// // Int+Utils.swift // APExtensions // // Created by Anton Plebanovich on 2/5/19. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import Foundation // ******************************* MARK: - Is public extension Int { /// Returns whether number is even var isEven: Bool { self % 2 == 0 } /// Returns whether number is odd var isOdd: Bool { self % 2 == 1 } /// Returns `true` if value end on 1. var isSingular: Bool { self % 10 == 1 } } // ******************************* MARK: - As public extension Int { /// Returns `self` as `UInt` var asUInt: UInt? { UInt(exactly: self) } /// Returns `self` as `CGFloat` var asCGFloat: CGFloat { .init(self) } /// Returns `self` as `Double` var asDouble: Double { .init(self) } /// Returns `self` as `Float` var asFloat: Float { .init(self) } /// Returns `self` as `String` var asString: String { .init(self) } /// Returns `self` as HEX `String` in a format like `0xAABB11` var asHexString: String { .init(format:"0x%02X", self) } /// Returns `self` as `TimeInterval` var asTimeInterval: TimeInterval { .init(self) } } // ******************************* MARK: - Other public extension Int { /// Makes `self` negative to the current value. var negative: Int { -self } }
mit
382fd9134a1c49073c7258aac5be4b39
22.525424
66
0.537464
3.80274
false
false
false
false
kaideyi/KDYSample
ImagePicker/ImagePicker/ViewController.swift
1
1275
// // ViewController.swift // ImagePicker // // Created by mac on 17/3/28. // Copyright © 2017年 mac. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "ImagePicker" self.view.backgroundColor = .white let photoBtn = UIButton() photoBtn.setTitle("选择图片", for: .normal) photoBtn.setTitleColor(.red, for: .normal) self.view.addSubview(photoBtn) photoBtn.addTarget(self, action: #selector(ViewController.selectPhotos), for: .touchUpInside) photoBtn.snp.makeConstraints { (make) in make.center.equalTo(self.view) make.size.equalTo(CGSize(width: 150, height: 40)) } } func selectPhotos() { let albumController = KYAlbumPickerController() let navigation = KYNavigationController(rootViewController: albumController) self.present(navigation, animated: true, completion: nil) albumController.selectDoneClosure = { array in for phAsset in array as! [KYAsset] { print("phAsset = \(phAsset), count = \(array.count)") } } } }
mit
ffb0dee4a424c53625fd60e26b9ce920
27.727273
101
0.60443
4.514286
false
false
false
false
zisko/swift
test/SILGen/collection_subtype_downcast.swift
1
2141
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s struct S { var x, y: Int } // CHECK-LABEL: sil hidden @$S27collection_subtype_downcast06array_C00D0SayAA1SVGSgSayypG_tF : // CHECK: bb0([[ARG:%.*]] : @owned $Array<Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @$Ss21_arrayConditionalCastySayq_GSgSayxGr0_lF // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Any, S>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func array_downcast(array: [Any]) -> [S]? { return array as? [S] } extension S : Hashable { var hashValue : Int { return x + y } } func ==(lhs: S, rhs: S) -> Bool { return true } // FIXME: This entrypoint name should not be bridging-specific // CHECK-LABEL: sil hidden @$S27collection_subtype_downcast05dict_C00D0s10DictionaryVyAA1SVSiGSgAEyAGypG_tF : // CHECK: bb0([[ARG:%.*]] : @owned $Dictionary<S, Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @$Ss30_dictionaryDownCastConditionalys10DictionaryVyq0_q1_GSgACyxq_Gs8HashableRzsAGR0_r2_lF // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<S, Any, S, Int>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>> // CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func dict_downcast(dict: [S: Any]) -> [S: Int]? { return dict as? [S: Int] } // It's not actually possible to test this for Sets independent of // the bridging rules.
apache-2.0
b7e8708bc10c8550f1441c804066e707
45.23913
244
0.639868
2.878214
false
false
false
false
alblue/swift
test/SILGen/generic_literals.swift
1
4116
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s // CHECK-LABEL: sil hidden @$s16generic_literals0A14IntegerLiteral1xyx_ts013ExpressibleBycD0RzlF : $@convention(thin) <T where T : ExpressibleByIntegerLiteral> (@in_guaranteed T) -> () { func genericIntegerLiteral<T : ExpressibleByIntegerLiteral>(x: T) { var x = x // CHECK: [[ADDR:%.*]] = alloc_stack $T // CHECK: [[TMETA:%.*]] = metatype $@thick T.Type // CHECK: [[LITVAR:%.*]] = alloc_stack $T.IntegerLiteralType // CHECK: [[LITMETA:%.*]] = metatype $@thick T.IntegerLiteralType.Type // CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.IntLiteral, 17 // CHECK: [[BUILTINCONV:%.*]] = witness_method $T.IntegerLiteralType, #_ExpressibleByBuiltinIntegerLiteral.init!allocator.1 // CHECK: [[LIT:%.*]] = apply [[BUILTINCONV]]<T.IntegerLiteralType>([[LITVAR]], [[INTLIT]], [[LITMETA]]) : $@convention(witness_method: _ExpressibleByBuiltinIntegerLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinIntegerLiteral> (Builtin.IntLiteral, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[TCONV:%.*]] = witness_method $T, #ExpressibleByIntegerLiteral.init!allocator.1 // CHECK: apply [[TCONV]]<T>([[ADDR]], [[LITVAR]], [[TMETA]]) : $@convention(witness_method: ExpressibleByIntegerLiteral) <τ_0_0 where τ_0_0 : ExpressibleByIntegerLiteral> (@in τ_0_0.IntegerLiteralType, @thick τ_0_0.Type) -> @out τ_0_0 x = 17 } // CHECK-LABEL: sil hidden @$s16generic_literals0A15FloatingLiteral1xyx_ts018ExpressibleByFloatD0RzlF : $@convention(thin) <T where T : ExpressibleByFloatLiteral> (@in_guaranteed T) -> () { func genericFloatingLiteral<T : ExpressibleByFloatLiteral>(x: T) { var x = x // CHECK: [[TVAL:%.*]] = alloc_stack $T // CHECK: [[TMETA:%.*]] = metatype $@thick T.Type // CHECK: [[FLT_VAL:%.*]] = alloc_stack $T.FloatLiteralType // CHECK: [[TFLT_META:%.*]] = metatype $@thick T.FloatLiteralType.Type // CHECK: [[LIT_VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4004000000000000|0x4000A000000000000000}} // CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.FloatLiteralType, #_ExpressibleByBuiltinFloatLiteral.init!allocator.1 // CHECK: apply [[BUILTIN_CONV]]<T.FloatLiteralType>([[FLT_VAL]], [[LIT_VALUE]], [[TFLT_META]]) : $@convention(witness_method: _ExpressibleByBuiltinFloatLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinFloatLiteral> (Builtin.FPIEEE{{64|80}}, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByFloatLiteral.init!allocator.1 // CHECK: apply [[CONV]]<T>([[TVAL]], [[FLT_VAL]], [[TMETA]]) : $@convention(witness_method: ExpressibleByFloatLiteral) <τ_0_0 where τ_0_0 : ExpressibleByFloatLiteral> (@in τ_0_0.FloatLiteralType, @thick τ_0_0.Type) -> @out τ_0_0 x = 2.5 } // CHECK-LABEL: sil hidden @$s16generic_literals0A13StringLiteral1xyx_ts013ExpressibleBycD0RzlF : $@convention(thin) <T where T : ExpressibleByStringLiteral> (@in_guaranteed T) -> () { func genericStringLiteral<T : ExpressibleByStringLiteral>(x: T) { var x = x // CHECK: [[LIT_VALUE:%.*]] = string_literal utf8 "hello" // CHECK: [[TSTR_META:%.*]] = metatype $@thick T.StringLiteralType.Type // CHECK: [[STR_VAL:%.*]] = alloc_stack $T.StringLiteralType // CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.StringLiteralType, #_ExpressibleByBuiltinStringLiteral.init!allocator.1 // CHECK: apply [[BUILTIN_CONV]]<T.StringLiteralType>([[STR_VAL]], [[LIT_VALUE]], {{.*}}, [[TSTR_META]]) : $@convention(witness_method: _ExpressibleByBuiltinStringLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinStringLiteral> (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[TMETA:%.*]] = metatype $@thick T.Type // CHECK: [[TVAL:%.*]] = alloc_stack $T // CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByStringLiteral.init!allocator.1 // CHECK: apply [[CONV]]<T>([[TVAL]], [[STR_VAL]], [[TMETA]]) : $@convention(witness_method: ExpressibleByStringLiteral) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@in τ_0_0.StringLiteralType, @thick τ_0_0.Type) -> @out τ_0_0 x = "hello" }
apache-2.0
14856cac550957d5e38a18fa335967cf
80.78
312
0.683297
3.564952
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV1/Models/EnrichmentOptions.swift
1
3701
/** * (C) Copyright IBM Corp. 2018, 2022. * * 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 /** Options that are specific to a particular enrichment. The `elements` enrichment type is deprecated. Use the [Create a project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the Discovery v2 API to create a `content_intelligence` project type instead. */ public struct EnrichmentOptions: Codable, Equatable { /** ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. */ public enum Language: String { case ar = "ar" case en = "en" case fr = "fr" case de = "de" case it = "it" case pt = "pt" case ru = "ru" case es = "es" case sv = "sv" } /** Object containing Natural Language Understanding features to be used. */ public var features: NluEnrichmentFeatures? /** ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. */ public var language: String? /** The element extraction model to use, which can be `contract` only. The `elements` enrichment is deprecated. */ public var model: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case features = "features" case language = "language" case model = "model" } /** Initialize a `EnrichmentOptions` with member variables. - parameter features: Object containing Natural Language Understanding features to be used. - parameter language: ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - parameter model: The element extraction model to use, which can be `contract` only. The `elements` enrichment is deprecated. - returns: An initialized `EnrichmentOptions`. */ public init( features: NluEnrichmentFeatures? = nil, language: String? = nil, model: String? = nil ) { self.features = features self.language = language self.model = model } }
apache-2.0
675e98e4b46bd8e8a95728a9a1a809ac
38.37234
119
0.661983
4.167793
false
false
false
false
jasnig/DouYuTVMutate
DouYuTVMutate/DouYuTV/Main/Lib/PPTView/PPTView.swift
1
11854
// // PageView.swift // PPT // // Created by jasnig on 16/4/2. // Copyright © 2016年 ZeroJ. All rights reserved. // // github: https://github.com/jasnig // 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles import UIKit class PPTImageView: UIView { lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.textColor = UIColor.whiteColor() titleLabel.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3) titleLabel.font = UIFont.systemFontOfSize(14.0) return titleLabel }() lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .ScaleAspectFill /// 剪去多余的部分 imageView.clipsToBounds = true imageView.userInteractionEnabled = true return imageView }() convenience init() { self.init(frame: CGRectZero) } override init(frame: CGRect) { super.init(frame: frame) addSubview(imageView) addSubview(titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView.frame = bounds titleLabel.frame = CGRect(x: 0, y: bounds.height - 28.0, width: bounds.width, height: 28.0) } } public class PPTView: UIView { // 滚动方向 public enum Direction { /// 当前的图片向左移 case Left /// 当前的图片向右移 case Right } // PageControl位置 public enum PageControlPosition { case TopCenter case BottomLeft case BottomRight case BottomCenter } public typealias PageDidClickAction = (clickedIndex: Int) -> Void public typealias SetupImageAndTitle = (titleLabel: UILabel, imageView: UIImageView, index: Int) -> Void public typealias ImagesCount = () -> Int //MARK:- 可供外部修改的属性 // pageControl的位置 默认为底部中间 public var pageControlPosition: PageControlPosition = .BottomCenter // 点击响应 public var pageDidClick:PageDidClickAction? // 设置图片和标题, 同时可以设置相关的控件的属性 public var setupImageAndTitle: SetupImageAndTitle? // 滚动间隔 public var timerInterval = 3.0 /// 图片总数, 需要在初始化的时候指定* var imagesCount: ImagesCount! /// 总页数 private var pageCount: Int { return self.imagesCount() } /// 其他page的颜色 public var pageIndicatorTintColor = UIColor.whiteColor() { willSet { pageControl.pageIndicatorTintColor = newValue } } /// 当前page的颜色 public var currentPageIndicatorTintColor = UIColor.whiteColor() { willSet { pageControl.currentPageIndicatorTintColor = newValue } } /// 是否自动滚动, 默认为自动滚动 public var autoScroll = true { willSet { if !newValue { stopTimer() } } } //MARK:- 私有属性 private var scrollDirection: Direction = .Left private var currentIndex = -1 private var leftIndex = -1 private var rightIndex = 1 /// 计时器 private var timer: NSTimer? private lazy var scrollView: UIScrollView = { [weak self] in let scroll = UIScrollView(frame: CGRectZero) if let strongSelf = self { scroll.delegate = strongSelf } scroll.bounces = false scroll.showsVerticalScrollIndicator = false scroll.showsHorizontalScrollIndicator = false scroll.pagingEnabled = true return scroll }() private lazy var pageControl: UIPageControl = { let pageC = UIPageControl() pageC.currentPage = 0 pageC.hidesForSinglePage = true pageC.userInteractionEnabled = false return pageC }() lazy var currentPPTImageView: PPTImageView = { let imageView = PPTImageView() return imageView }() lazy var rightPPTImageView = PPTImageView() lazy var leftPPTImageView = PPTImageView() // MARK: - 可链式调用 public class func PPTViewWithImagesCount(imagesCount: ImagesCount) -> PPTView { return PPTView(imagesCount: imagesCount) } public func setupImageAndTitle(setupImageAndTitle: SetupImageAndTitle) -> Self { self.setupImageAndTitle = setupImageAndTitle return self } public func setupPageDidClickAction(pageDidClick: PageDidClickAction?) -> Self { self.pageDidClick = pageDidClick return self } //MARK:- 初始化 // 遍历构造器, 不监控点击事件的时候可以使用 public convenience init(imagesCount: ImagesCount, setupImageAndTitle: SetupImageAndTitle) { self.init(imagesCount: imagesCount, setupImageAndTitle: setupImageAndTitle, pageDidClick: nil) } private init(imagesCount: ImagesCount) { self.imagesCount = imagesCount super.init(frame: CGRectZero) initialization() } public init(imagesCount: ImagesCount, setupImageAndTitle: SetupImageAndTitle, pageDidClick: PageDidClickAction?) { // 这个Closure 处理点击 self.pageDidClick = pageDidClick // 这个Closure获取图片 相当于UITableView的cellForRow...方法 self.setupImageAndTitle = setupImageAndTitle // 相当于UITableView的numberOfRows...方法 self.imagesCount = imagesCount super.init(frame: CGRectZero) // 这里面添加了各个控件, 和设置了初始的图片和title initialization() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } //MARK:- 初始设置和内部函数 private func initialization() { let tapGuesture = UITapGestureRecognizer(target: self, action: #selector(self.imageTapdAction)) tapGuesture.numberOfTapsRequired = 1 currentPPTImageView.addGestureRecognizer(tapGuesture) setupPageControl() addSubview(scrollView) addSubview(pageControl) scrollView.addSubview(currentPPTImageView) scrollView.addSubview(leftPPTImageView) scrollView.addSubview(rightPPTImageView) // 添加初始化图片 loadImages() /// startTimer() } private func setupPageControl() { pageControl.numberOfPages = pageCount pageControl.sizeForNumberOfPages(pageCount) } public func reloadData() { currentIndex = -1 setupPageControl() loadImages() startTimer() } override public func layoutSubviews() { super.layoutSubviews() scrollView.frame = bounds let pageHeight:CGFloat = 28.0 let width = bounds.size.width let height = bounds.size.height switch pageControlPosition { case .BottomLeft: pageControl.frame = CGRect(x: 0, y: height - pageHeight, width: width / 2, height: pageHeight) case .BottomCenter: pageControl.frame = CGRect(x: 0, y: height - pageHeight, width: width, height: pageHeight) case .BottomRight: pageControl.frame = CGRect(x: width / 2, y: height - pageHeight, width: width / 2, height: pageHeight) case .TopCenter: pageControl.frame = CGRect(x: 0, y: 0, width: width, height: pageHeight) } currentPPTImageView.frame = CGRect(x: width, y: 0, width: width, height: height) leftPPTImageView.frame = CGRect(x: 0, y: 0, width: width, height: height) rightPPTImageView.frame = CGRect(x: width * 2, y: 0, width: width, height: height) scrollView.contentOffset = CGPoint(x: width, y: 0) scrollView.contentSize = CGSize(width: 3 * width, height: 0) } /// 开启倒计时 private func startTimer() { if timer == nil { timer = NSTimer(timeInterval: timerInterval, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) } } /// 停止倒计时 private func stopTimer() { if timer != nil { timer?.invalidate() timer = nil } } /// 计时器响应方法 func timerAction() { // 更新位置, 更换图片 UIView.animateWithDuration(3.0, animations: { self.scrollView.setContentOffset(CGPoint(x: self.bounds.size.width * 2, y: 0), animated: true) }, completion: nil) } func imageTapdAction() { pageDidClick?(clickedIndex:currentIndex) } deinit { // debugPrint("\(self.debugDescription) --- 销毁") stopTimer() } /// 当父view将释放的时候需要 释放掉timer以释放当前view override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if newSuperview == nil { stopTimer() } } } extension PPTView: UIScrollViewDelegate { // 手指触摸到时 public func scrollViewWillBeginDragging(scrollView: UIScrollView) { if autoScroll { stopTimer() } } // 松开手指时 public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if autoScroll { scrollDirection = .Left startTimer() } } /// 代码设置scrollview的contentOffSet滚动完成后调用 public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { // 重新加载图片 scrollDirection = .Left loadImages() } /// scrollview的滚动是由拖拽触发的时候,在它将要停止时调用 public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // 1/2屏 if fabs(scrollView.contentOffset.x - scrollView.bounds.size.width) > scrollView.bounds.size.width / 2 { scrollDirection = scrollView.contentOffset.x > bounds.size.width ? .Left : .Right // 重新加载图片 loadImages() } } private func loadImages() { if pageCount == 0 { return } // 根据滚动方向不同设置将要显示的图片下标 switch scrollDirection { case .Left: currentIndex = (currentIndex + 1) % pageCount case .Right: currentIndex = (currentIndex - 1 + pageCount) % pageCount } leftIndex = (currentIndex - 1 + pageCount) % pageCount rightIndex = (currentIndex + 1) % pageCount setupImageAndTitle?(titleLabel: currentPPTImageView.titleLabel, imageView: currentPPTImageView.imageView, index: currentIndex) setupImageAndTitle?(titleLabel: rightPPTImageView.titleLabel, imageView: rightPPTImageView.imageView, index: rightIndex) setupImageAndTitle?(titleLabel: leftPPTImageView.titleLabel, imageView: leftPPTImageView.imageView, index: leftIndex) pageControl.currentPage = currentIndex // 将currentImageView显示在屏幕上 scrollView.contentOffset = CGPoint(x: bounds.size.width, y: 0) } }
mit
76563ccd08f69a808c496190a511c204
27.855297
139
0.611534
4.817515
false
false
false
false
mshhmzh/firefox-ios
Storage/SuggestedSites.swift
3
1627
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCGLogger import UIKit import Shared private let log = XCGLogger.defaultInstance() public class SuggestedSite: Site { public let wordmark: Favicon public let backgroundColor: UIColor override public var tileURL: NSURL { return NSURL(string: url) ?? NSURL(string: "about:blank")! } let trackingId: Int init(data: SuggestedSiteData) { self.backgroundColor = UIColor(colorString: data.bgColor) self.trackingId = data.trackingId self.wordmark = Favicon(url: data.imageUrl, date: NSDate(), type: .Icon) super.init(url: data.url, title: data.title, bookmarked: nil) self.icon = Favicon(url: data.faviconUrl, date: NSDate(), type: .Icon) } } public let SuggestedSites: SuggestedSitesCursor = SuggestedSitesCursor() public class SuggestedSitesCursor: ArrayCursor<SuggestedSite> { private init() { let locale = NSLocale.currentLocale() let sites = DefaultSuggestedSites.sites[locale.localeIdentifier] ?? DefaultSuggestedSites.sites["default"]! as Array<SuggestedSiteData> let tiles = sites.map({data in SuggestedSite(data: data)}) super.init(data: tiles, status: .Success, statusMessage: "Loaded") } } public struct SuggestedSiteData { var url: String var bgColor: String var imageUrl: String var faviconUrl: String var trackingId: Int var title: String }
mpl-2.0
6e44d9ee94bf523b9e013be14604d25a
32.895833
87
0.692071
4.236979
false
false
false
false
huyphamthanh8290/HPUIViewExtensions
Pod/Classes/Helpers/Utils.swift
1
1383
// // Utils.swift // Pods // // Created by Huy Pham on 11/2/15. // // import UIKit class Utils { // MARK: Image Utils class func roundCorners(view: UIView, corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath view.layer.mask = mask // Reset corner radius to make Bezier Path to work view.layer.cornerRadius = 0 } class func imageWithSolidColor(color: UIColor, size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } // MARK: Image Utils class func localizeWithDefinedMode(text: String?) -> String? { guard let text = text else { return nil } switch HPUIViewExtensions.shared.localizationMode { case .ByKey, .ByContent: return NSLocalizedString(text, comment: "") default: return text } } }
mit
264a1f41913dc6d439db3a06981670b1
26.117647
137
0.600145
4.785467
false
false
false
false
daviejaneway/OrbitFrontend
Sources/ValueRule.swift
1
20663
// // ValueRule.swift // OrbitCompilerUtils // // Created by Davie Janeway on 21/02/2018. // import Foundation import OrbitCompilerUtils public class IntegerLiteralRule : ParseRule { public let name = "Orb.Core.Grammar.Literal.Integer" public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return [.LParen, .Int].contains(token.type) } public func parse(context: ParseContext) throws -> AbstractExpression { let valueToken = try context.expectAny(types: [.Int, .LParen], consumes: true) if valueToken.type == .LParen { // e.g. (123) let iParser = IntegerLiteralRule() let expr = try iParser.parse(context: context) _ = try context.expect(type: .RParen) return expr } guard let value = Int(valueToken.value) else { throw OrbitError.expectedNumericLiteral(token: valueToken) } return IntLiteralExpression(value: value, startToken: valueToken) } } public class RealLiteralRule : ParseRule { public let name = "Orb.Core.Grammar.Literal.Real" public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return [.LParen, .Real].contains(token.type) } public func parse(context: ParseContext) throws -> AbstractExpression { let realToken = try context.expectAny(types: [.Real, .LParen], consumes: true) if realToken.type == .LParen { // e.g. (123.1) let rParser = RealLiteralRule() let expr = try rParser.parse(context: context) _ = try context.expect(type: .RParen) return expr } guard let real = Double(realToken.value) else { throw OrbitError.expectedNumericLiteral(token: realToken) } return RealLiteralExpression(value: real, startToken: realToken) } } public class ListLiteralRule : ParseRule { public let name = "Orb.Core.Grammar.Literal.List" public func trigger(tokens: [Token]) throws -> Bool { return false } public func parse(context: ParseContext) throws -> AbstractExpression { let startToken = try context.expectAny(types: [.LBracket], consumes: true) let delimitedRule = DelimitedRule(delimiter: .Comma, elementRule: ExpressionRule()) guard let delim = try delimitedRule.parse(context: context) as? DelimitedExpression else { throw OrbitError(message: "FATAL Weird list literal") } _ = try context.expect(type: .RBracket) return ListLiteralExpression(value: delim.expressions, startToken: startToken) } } //private class PathLiteralRule : ParseRule { // public let name = "Orb.Core.Grammar.Literal.Path" // // func trigger(tokens: [Token]) throws -> Bool { // return true // } // // func parse(context: ParseContext) throws -> AbstractExpression { // guard let component // } //} // //public class URLLiteralRule : ParseRule { // public let name = "Orb.Core.Grammar.Literal.URL" // // public func trigger(tokens: [Token]) throws -> Bool { // return true // } // // public func parse(context: ParseContext) throws -> AbstractExpression { // let scheme = try IdentifierRule().parse(context: context) as! IdentifierExpression // // let separator: (Token) -> Bool = { token in return token.value == "/" } // // _ = try context.expect(type: .Colon) // _ = try context.expect(type: .Operator, overrideError: nil, requirements: separator) // _ = try context.expect(type: .Operator, overrideError: nil, requirements: separator) // // // } //} public class InstanceCallRule : ParseRule { public let name = "Orb.Core.Grammar.InstanceCall" public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return token.type == .Identifier } public func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.peek() if start.type == .LParen { _ = try context.consume() let expr = try parse(context: context) _ = try context.expect(type: .RParen) return expr } let receiver = try IdentifierRule().parse(context: context) as! IdentifierExpression _ = try context.expect(type: .Dot) let fname = try IdentifierRule().parse(context: context) as! IdentifierExpression _ = try context.expect(type: .LParen) if try context.peek().type == .RParen { _ = try context.expect(type: .RParen) return InstanceCallExpression(receiver: receiver, methodName: fname, args: [], startToken: start) } let arguments = try DelimitedRule(delimiter: .Comma, elementRule: ExpressionRule()).parse(context: context) as! DelimitedExpression _ = try context.expect(type: .RParen) return InstanceCallExpression(receiver: receiver, methodName: fname, args: arguments.expressions as! [RValueExpression], startToken: start) } } public class ConstructorCallRule : ParseRule { public let name = "Orb.Core.Grammar.ConstructorCall" public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return token.type == .TypeIdentifier } public func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.peek() if start.type == .LParen { _ = try context.consume() let expr = try parse(context: context) _ = try context.expect(type: .RParen) return expr } let receiverRule = TypeIdentifierRule() let receiver = try receiverRule.parse(context: context) as! TypeIdentifierExpression let _ = try context.expect(type: .LParen) let next = try context.peek() if next.type == .RParen { let _ = try context.expect(type: .RParen) return ConstructorCallExpression(receiver: receiver, args: [], startToken: start) } let rule = DelimitedRule(delimiter: .Comma, elementRule: ExpressionRule()) let args = try rule.parse(context: context) as! DelimitedExpression let _ = try context.expect(type: .RParen) return ConstructorCallExpression(receiver: receiver, args: args.expressions as! [RValueExpression], startToken: start) } } public class StaticCallRule : ParseRule { public let name = "Orb.Core.Grammar.StaticCall" public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return token.type == .TypeIdentifier } public func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.peek() if start.type == .LParen { _ = try context.consume() let expr = try parse(context: context) _ = try context.expect(type: .RParen) return expr } let rec = try TypeIdentifierRule().parse(context: context) as! TypeIdentifierExpression _ = try context.expect(type: .Dot) let fname = try IdentifierRule().parse(context: context) as! IdentifierExpression // TODO: Generics _ = try context.expect(type: .LParen) if try context.peek().type == .RParen { _ = try context.expect(type: .RParen) return StaticCallExpression(receiver: rec, methodName: fname, args: [], startToken: start) } let arguments = try DelimitedRule(delimiter: .Comma, elementRule: ExpressionRule()).parse(context: context) as! DelimitedExpression _ = try context.expect(type: .RParen) return StaticCallExpression(receiver: rec, methodName: fname, args: arguments.expressions as! [RValueExpression], startToken: start) } } public class BlockExpression : AbstractExpression, RewritableExpression { private(set) public var body: [AbstractExpression & Statement] public let returnStatement: ReturnStatement? init(body: [AbstractExpression & Statement], returnStatement: ReturnStatement?, startToken: Token) { self.body = body self.returnStatement = returnStatement super.init(startToken: startToken) } public func rewriteChildExpression(childExpressionHash: Int, input: AbstractExpression) throws { let indices = self.body.enumerated().filter { $0.element.hashValue == childExpressionHash }.map { $0.offset} guard indices.count > 0 else { throw OrbitError(message: "FATAL Multiple nodes match hash: \(childExpressionHash)") } guard indices.count == 1 else { throw OrbitError(message: "FATAL No Nodes match hash: \(childExpressionHash)") } let idx = indices[0] self.body[idx] = (input as! (AbstractExpression & Statement)) } } public class BlockRule : ParseRule { public let name = "Orb.Core.Grammar.Block" public func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return token.type == .LBrace } public func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.expect(type: .LBrace) var body = [Statement]() var ret: ReturnStatement? = nil var next = try context.peek() while next.type != .RBrace { guard let statement = try context.attemptAny(of: [StatementRule(), ReturnRule()], propagateError: true) else { throw OrbitError.unexpectedToken(token: next) } next = try context.peek() if statement is ReturnStatement { if next.type != .RBrace { // Code after return statement is redundant throw OrbitError.codeAfterReturn(token: next) } ret = (statement as! ReturnStatement) } else { body.append(statement as! Statement) } } _ = try context.expect(type: .RBrace) return BlockExpression(body: body as! [AbstractExpression & Statement], returnStatement: ret, startToken: start) } } class UnaryRule : ParseRule { let name = "Orb.Core.Grammar.Prefix" func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return [.LParen, .Operator].contains(token.type) } func parse(context: ParseContext) throws -> AbstractExpression { let opToken = try context.peek() if opToken.type == .LParen { _ = try context.consume() let unaryExpression = try parse(context: context) _ = try context.expect(type: .RParen) return unaryExpression } if opToken.type == .Operator { _ = try context.consume() let op = try Operator.lookup(operatorWithSymbol: opToken.value, inPosition: .Prefix, token: opToken) return UnaryExpression(value: try parse(context: context), op: op, startToken: opToken) } let valueExpression = try PrimaryRule().parse(context: context) // Not a unary expression, just a value return valueExpression } } class InfixRule : ParseRule { let name = "Orb.Core.Grammar.Infix" let left: AbstractExpression init(left: AbstractExpression) { self.left = left } func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return [.LParen, .Identifier, .Int, .Real, .Operator].contains(token.type) } func parse(context: ParseContext) throws -> AbstractExpression { let opToken = try context.expect(type: .Operator) let op = try Operator.lookup(operatorWithSymbol: opToken.value, inPosition: .Infix, token: opToken) let right = try ExpressionRule().parse(context: context) if let lexpr = left as? BinaryExpression, !lexpr.parenthesised { let opRelationship = lexpr.op.relationships[op] ?? .Equal if opRelationship == .Greater { let nRight = BinaryExpression(left: lexpr.right, right: right, op: op, startToken: right.startToken) return BinaryExpression(left: lexpr.left, right: nRight, op: lexpr.op, startToken: lexpr.startToken) } } else if let rexpr = right as? BinaryExpression, !rexpr.parenthesised { let opRelationship = rexpr.op.relationships[op] ?? .Equal if opRelationship == .Lesser { // Precedence is wrong, rewrite the expr let nLeft = BinaryExpression(left: self.left, right: rexpr.left, op: op, startToken: self.left.startToken) return BinaryExpression(left: nLeft, right: rexpr.right, op: rexpr.op, startToken: rexpr.startToken) } } return BinaryExpression(left: self.left, right: right, op: op, startToken: opToken) } } class AnnotationParameterRule : ParseRule { let name = "Orb.Core.Grammar.AnnotationParameter" func trigger(tokens: [Token]) throws -> Bool { return true } func parse(context: ParseContext) throws -> AbstractExpression { guard let result = try context.attemptAny(of: [ // The order matters! MethodRule(), SignatureRule(), ExpressionRule() ]) else { throw OrbitError(message: "Expected value expression") } return result } } class ExpressionRule : ParseRule { let name = "Orb.Core.Grammar.Expression" func trigger(tokens: [Token]) throws -> Bool { return true } func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.peek() let left: AbstractExpression if start.type == .LParen { _ = try context.consume() left = try parse(context: context) if left is BinaryExpression { (left as! BinaryExpression).parenthesised = true } _ = try context.expect(type: .RParen) } else { left = try UnaryRule().parse(context: context) } guard context.hasMore() else { return left } let next = try context.peek() guard next.type == .Operator else { return left } return try InfixRule(left: left).parse(context: context) } } class PrimaryRule : ParseRule { let name = "Orb.Core.Grammar.Primary" func trigger(tokens: [Token]) throws -> Bool { return true } func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.peek() if start.type == .LParen { _ = try context.consume() let expr = try parse(context: context) _ = try context.expect(type: .RParen) return expr } guard let result = try context.attemptAny(of: [ // The order matters! ListLiteralRule(), BlockRule(), AnnotationRule(), ConstructorCallRule(), InstanceCallRule(), StaticCallRule(), RealLiteralRule(), IntegerLiteralRule(), IdentifierRule(), TypeIdentifierRule(), UnaryRule() ]) else { throw OrbitError(message: "Expected value expression") } return result } } class ReturnRule : ParseRule { let name = "Orb.Core.Grammar.Return" func trigger(tokens: [Token]) throws -> Bool { guard let token = tokens.first else { throw OrbitError.ranOutOfTokens() } return token.type == .Keyword && Keywords.return.matches(token: token) } func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.expect(type: .Keyword) guard Keywords.return.matches(token: start) else { throw OrbitError.unexpectedToken(token: start) } let value = try ExpressionRule().parse(context: context) return ReturnStatement(value: value, startToken: start) } } class AssignmentRule : ParseRule { let name = "Orb.Core.Grammar.Assignment" func trigger(tokens: [Token]) throws -> Bool { return true } func parse(context: ParseContext) throws -> AbstractExpression { guard let lhs = try context.attemptAny(of: [PairRule(), IdentifierRule()]) else { throw OrbitError(message: "Expected Pair or Identifier on left-hand side of assignment") } let identifier: IdentifierExpression let type: TypeIdentifierExpression? if let pair = lhs as? PairExpression { identifier = pair.name type = pair.type } else { identifier = lhs as! IdentifierExpression type = nil } _ = try context.expect(type: .Assignment) let rhs = try ExpressionRule().parse(context: context) return AssignmentStatement(name: identifier, type: type, value: rhs, startToken: identifier.startToken) } } class StatementRule : ParseRule { let name = "Orb.Core.Grammar.Statement" func trigger(tokens: [Token]) throws -> Bool { return true } func parse(context: ParseContext) throws -> AbstractExpression { guard let result = try context.attemptAny(of: [ // The order matters! AssignmentRule(), AnnotationRule(), DeferRule(), InstanceCallRule(), StaticCallRule(), ReturnRule() ]) else { throw OrbitError(message: "Expected value expression") } return result } } class DelimitedExpression : AbstractExpression { let expressions: [AbstractExpression] init(expressions: [AbstractExpression], startToken: Token) { self.expressions = expressions super.init(startToken: startToken) } } class DelimitedRule : ParseRule { let name = "Orb.Core.Grammar.Delimited" let delimiter: TokenType let elementRule: ParseRule init(delimiter: TokenType, elementRule: ParseRule) { self.delimiter = delimiter self.elementRule = elementRule } func trigger(tokens: [Token]) throws -> Bool { return true } func parse(context: ParseContext) throws -> AbstractExpression { var expressions = [AbstractExpression]() let start = try context.peek() let first = try self.elementRule.parse(context: context) expressions.append(first) if context.hasMore() { var next = try context.peek() while next.type == self.delimiter { _ = try context.consume() let expr = try self.elementRule.parse(context: context) expressions.append(expr) if context.hasMore() { next = try context.peek() } else { break } } } return DelimitedExpression(expressions: expressions, startToken: start) } }
mit
9a4f2252ee6f1a0af98e616c32f531fc
32.435275
147
0.58462
4.626735
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Model/Contact+Extensions.swift
2
7962
// // Contact+Extensions.swift // Neocom // // Created by Artem Shimanski on 2/13/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import Foundation import EVEAPI import CoreData import Combine import Alamofire import Expressible extension Contact { private struct PartialResult { var contacts: [Int64: Contact] var missingIDs: Set<Int64> } struct SearchOptions: OptionSet { let rawValue: Int static let universe = SearchOptions(rawValue: 1 << 0) static let mailingLists = SearchOptions(rawValue: 1 << 1) static let all: SearchOptions = [.universe, .mailingLists] } static func contacts(with contactIDs: Set<Int64>, esi: ESI, characterID: Int64?, options: SearchOptions, managedObjectContext: NSManagedObjectContext) -> AnyPublisher<[Int64: Contact], Never> { var missing = contactIDs let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) backgroundContext.parent = managedObjectContext guard !missing.isEmpty else {return Just([:]).eraseToAnyPublisher()} func localContact(_ missingIDs: Set<Int64>) -> Future<PartialResult, Never> { Future { promise in backgroundContext.perform { let result = (try? Dictionary(backgroundContext.from(Contact.self) .filter((/\Contact.contactID).in(missing)) .fetch() .map{($0.contactID, $0)}) {a, _ in a}) ?? [:] promise(.success(PartialResult(contacts: result, missingIDs: missingIDs.subtracting(result.keys)))) } } } func mailingLists(_ result: PartialResult) -> AnyPublisher<PartialResult, Never> { guard let characterID = characterID, !result.missingIDs.isEmpty, options.contains(.mailingLists) else {return Just(result).eraseToAnyPublisher()} return esi.characters.characterID(Int(characterID)).mail().lists().get().receive(on: backgroundContext).map { mailingLists -> PartialResult in let ids = mailingLists.value.map{$0.mailingListID} guard !ids.isEmpty else {return result} let existing = (try? backgroundContext.from(Contact.self).filter((/\Contact.contactID).in(ids)).fetch()) ?? [] let existingIDs = Set(existing.map{$0.contactID}) let new = mailingLists.value.filter{!existingIDs.contains(Int64($0.mailingListID))}.map { mailingList -> Contact in let contact = Contact(context: backgroundContext) contact.contactID = Int64(mailingList.mailingListID) contact.category = ESI.RecipientType.mailingList.rawValue contact.name = mailingList.name return contact } let contacts = (existing + new).filter{result.missingIDs.contains($0.contactID)} let missing = result.missingIDs.subtracting(contacts.map{$0.contactID}) let mergedContacts = result.contacts.merging(contacts.map{($0.contactID, $0)}) {a, _ in a} return PartialResult(contacts: mergedContacts, missingIDs: missing) }.replaceError(with: result) .eraseToAnyPublisher() } func universeNames(_ result: PartialResult) -> AnyPublisher<PartialResult, Never> { guard !result.missingIDs.isEmpty, options.contains(.universe) else {return Just(result).eraseToAnyPublisher()} return esi.universe.names().post(ids: result.missingIDs.compactMap{Int(exactly: $0)}).receive(on: backgroundContext).map { names ->PartialResult in let contacts = names.value.map { name -> Contact in let contact = Contact(context: backgroundContext) contact.contactID = Int64(name.id) contact.category = name.category.rawValue contact.name = name.name return contact } let missing = result.missingIDs.subtracting(contacts.map{$0.contactID}) let mergedContacts = result.contacts.merging(contacts.map{($0.contactID, $0)}) {a, _ in a} return PartialResult(contacts: mergedContacts, missingIDs: missing) }.replaceError(with: result) .eraseToAnyPublisher() } return localContact(missing) .flatMap { mailingLists($0) } .flatMap { universeNames($0) } .receive(on: backgroundContext) .map { result -> [Int64: NSManagedObjectID] in var contacts = result.contacts while true { do { try backgroundContext.save() break } catch { guard let error = error as? CocoaError, error.errorCode == CocoaError.managedObjectConstraintMerge.rawValue else {break} guard let conflicts = error.errorUserInfo[NSPersistentStoreSaveConflictsErrorKey] as? [NSConstraintConflict], !conflicts.isEmpty else {break} let pairs = conflicts.filter{$0.databaseObject is Contact}.map { conflict in (conflict.databaseObject as! Contact, Set(conflict.conflictingObjects.compactMap{$0 as? Contact})) }.filter{!$0.1.isEmpty} if !pairs.isEmpty { for (object, objects) in pairs { contacts.filter{objects.contains($0.value)}.forEach { contacts[$0.key] = object } objects.forEach { $0.managedObjectContext?.delete($0) } } } else { break } } } return contacts.mapValues{$0.objectID} }.receive(on: managedObjectContext) .map { $0.compactMapValues{try? managedObjectContext.existingObject(with: $0) as? Contact} }.eraseToAnyPublisher() } static func searchContacts(containing string: String, esi: ESI, options: SearchOptions, managedObjectContext: NSManagedObjectContext) -> AnyPublisher<[Contact], Never> { let s = string.trimmingCharacters(in: .whitespacesAndNewlines) guard !s.isEmpty else {return Just([]).eraseToAnyPublisher()} let contacts = try? managedObjectContext.from(Contact.self).filter((/\Contact.name).caseInsensitive.contains(s)) .fetch() let searchResults: AnyPublisher<[Contact], Never> if s.count < 3 { searchResults = Empty().eraseToAnyPublisher() } else { searchResults = esi.search.get(categories: [.character, .corporation, .alliance], search: s).map {$0.value}.map { Set([$0.character, $0.corporation, $0.alliance].compactMap{$0}.joined().map{Int64($0)}) }.flatMap { ids in Contact.contacts(with: ids, esi: esi, characterID: nil, options: [.universe], managedObjectContext: managedObjectContext) .map{Array($0.values)} .setFailureType(to: AFError.self) } .catch{_ in Empty()} .eraseToAnyPublisher() } if contacts?.isEmpty == false { return Just(contacts ?? []).merge(with: searchResults).eraseToAnyPublisher() } else { return searchResults } } }
lgpl-2.1
b531ad0a86ee15abdc1e0c4e36266198
48.141975
197
0.564879
5.240948
false
false
false
false
slavapestov/swift
stdlib/public/core/Reflection.swift
1
15943
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Customizes the result of `_reflect(x)`, where `x` is a conforming /// type. public protocol _Reflectable { // The runtime has inappropriate knowledge of this protocol and how its // witness tables are laid out. Changing this protocol requires a // corresponding change to Reflection.cpp. /// Returns a mirror that reflects `self`. @warn_unused_result func _getMirror() -> _MirrorType } /// A unique identifier for a class instance or metatype. This can be used by /// reflection clients to recognize cycles in the object graph. /// /// In Swift, only class instances and metatypes have unique identities. There /// is no notion of identity for structs, enums, functions, or tuples. public struct ObjectIdentifier : Hashable, Comparable { let value: Builtin.RawPointer /// Convert to a `UInt` that captures the full value of `self`. /// /// Axiom: `a.uintValue == b.uintValue` iff `a == b`. public var uintValue: UInt { return UInt(Builtin.ptrtoint_Word(value)) } // FIXME: Better hashing algorithm /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`. /// /// - Note: The hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { return Int(Builtin.ptrtoint_Word(value)) } /// Construct an instance that uniquely identifies the class instance `x`. public init(_ x: AnyObject) { self.value = Builtin.bridgeToRawPointer(x) } /// Construct an instance that uniquely identifies the metatype `x`. public init(_ x: Any.Type) { self.value = unsafeBitCast(x, Builtin.RawPointer.self) } } @warn_unused_result public func <(lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool { return lhs.uintValue < rhs.uintValue } @warn_unused_result public func ==(x: ObjectIdentifier, y: ObjectIdentifier) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(x.value, y.value)) } /// How children of this value should be presented in the IDE. public enum _MirrorDisposition { /// As a struct. case Struct /// As a class. case Class /// As an enum. case Enum /// As a tuple. case Tuple /// As a miscellaneous aggregate with a fixed set of children. case Aggregate /// As a container that is accessed by index. case IndexContainer /// As a container that is accessed by key. case KeyContainer /// As a container that represents membership of its values. case MembershipContainer /// As a miscellaneous container with a variable number of children. case Container /// An Optional which can have either zero or one children. case Optional /// An Objective-C object imported in Swift. case ObjCObject } /// The type returned by `_reflect(x)`; supplies an API for runtime /// reflection on `x`. public protocol _MirrorType { /// The instance being reflected. var value: Any { get } /// Identical to `value.dynamicType`. var valueType: Any.Type { get } /// A unique identifier for `value` if it is a class instance; `nil` /// otherwise. var objectIdentifier: ObjectIdentifier? { get } /// The count of `value`'s logical children. var count: Int { get } /// Get a name and mirror for the `i`th logical child. subscript(i: Int) -> (String, _MirrorType) { get } /// A string description of `value`. var summary: String { get } /// A rich representation of `value` for an IDE, or `nil` if none is supplied. var quickLookObject: PlaygroundQuickLook? { get } /// How `value` should be presented in an IDE. var disposition: _MirrorDisposition { get } } /// An entry point that can be called from C++ code to get the summary string /// for an arbitrary object. The memory pointed to by "out" is initialized with /// the summary string. @warn_unused_result @_silgen_name("swift_getSummary") public // COMPILER_INTRINSIC func _getSummary<T>(out: UnsafeMutablePointer<String>, x: T) { out.initialize(String(reflecting: x)) } /// Produce a mirror for any value. If the value's type conforms to /// `_Reflectable`, invoke its `_getMirror()` method; otherwise, fall back /// to an implementation in the runtime that structurally reflects values /// of any type. @warn_unused_result @_silgen_name("swift_reflectAny") public func _reflect<T>(x: T) -> _MirrorType /// Dump an object's contents using its mirror to the specified output stream. public func dump<T, TargetStream : OutputStreamType>( x: T, inout _ targetStream: TargetStream, name: String? = nil, indent: Int = 0, maxDepth: Int = .max, maxItems: Int = .max ) -> T { var maxItemCounter = maxItems var visitedItems = [ObjectIdentifier : Int]() targetStream._lock() defer { targetStream._unlock() } _dumpObject_unlocked( x, name, indent, maxDepth, &maxItemCounter, &visitedItems, &targetStream) return x } /// Dump an object's contents using its mirror to standard output. public func dump<T>(x: T, name: String? = nil, indent: Int = 0, maxDepth: Int = .max, maxItems: Int = .max) -> T { var stdoutStream = _Stdout() return dump( x, &stdoutStream, name: name, indent: indent, maxDepth: maxDepth, maxItems: maxItems) } /// Dump an object's contents. User code should use dump(). internal func _dumpObject_unlocked<TargetStream : OutputStreamType>( object: Any, _ name: String?, _ indent: Int, _ maxDepth: Int, inout _ maxItemCounter: Int, inout _ visitedItems: [ObjectIdentifier : Int], inout _ targetStream: TargetStream ) { guard maxItemCounter > 0 else { return } maxItemCounter -= 1 for _ in 0..<indent { targetStream.write(" ") } let mirror = Mirror(reflecting: object) let count = mirror.children.count let bullet = count == 0 ? "-" : maxDepth <= 0 ? "▹" : "▿" targetStream.write(bullet) targetStream.write(" ") if let nam = name { targetStream.write(nam) targetStream.write(": ") } // This takes the place of the old mirror API's 'summary' property _dumpPrint_unlocked(object, mirror, &targetStream) let id: ObjectIdentifier? if let classInstance = object as? AnyObject where object.dynamicType is AnyObject.Type { // Object is a class (but not an ObjC-bridged struct) id = ObjectIdentifier(classInstance) } else if let metatypeInstance = object as? Any.Type { // Object is a metatype id = ObjectIdentifier(metatypeInstance) } else { id = nil } if let theId = id { if let previous = visitedItems[theId] { targetStream.write(" #") _print_unlocked(previous, &targetStream) targetStream.write("\n") return } let identifier = visitedItems.count visitedItems[theId] = identifier targetStream.write(" #") _print_unlocked(identifier, &targetStream) } targetStream.write("\n") guard maxDepth > 0 else { return } if let superclassMirror = mirror.superclassMirror() { _dumpSuperclass_unlocked(superclassMirror, indent + 2, maxDepth - 1, &maxItemCounter, &visitedItems, &targetStream) } var currentIndex = mirror.children.startIndex for i in 0..<count { if maxItemCounter <= 0 { for _ in 0..<(indent+4) { _print_unlocked(" ", &targetStream) } let remainder = count - i targetStream.write("(") _print_unlocked(remainder, &targetStream) if i > 0 { targetStream.write(" more") } if remainder == 1 { targetStream.write(" child)\n") } else { targetStream.write(" children)\n") } return } let (name, child) = mirror.children[currentIndex] currentIndex = currentIndex.successor() _dumpObject_unlocked(child, name, indent + 2, maxDepth - 1, &maxItemCounter, &visitedItems, &targetStream) } } /// Dump information about an object's superclass, given a mirror reflecting /// that superclass. internal func _dumpSuperclass_unlocked<TargetStream : OutputStreamType>( mirror: Mirror, _ indent: Int, _ maxDepth: Int, inout _ maxItemCounter: Int, inout _ visitedItems: [ObjectIdentifier : Int], inout _ targetStream: TargetStream ) { guard maxItemCounter > 0 else { return } maxItemCounter -= 1 for _ in 0..<indent { targetStream.write(" ") } let count = mirror.children.count let bullet = count == 0 ? "-" : maxDepth <= 0 ? "▹" : "▿" targetStream.write(bullet) targetStream.write(" super: ") _debugPrint_unlocked(mirror.subjectType, &targetStream) targetStream.write("\n") guard maxDepth > 0 else { return } if let superclassMirror = mirror.superclassMirror() { _dumpSuperclass_unlocked(superclassMirror, indent + 2, maxDepth - 1, &maxItemCounter, &visitedItems, &targetStream) } var currentIndex = mirror.children.startIndex for i in 0..<count { if maxItemCounter <= 0 { for _ in 0..<(indent+4) { targetStream.write(" ") } let remainder = count - i targetStream.write("(") _print_unlocked(remainder, &targetStream) if i > 0 { targetStream.write(" more") } if remainder == 1 { targetStream.write(" child)\n") } else { targetStream.write(" children)\n") } return } let (name, child) = mirror.children[currentIndex] currentIndex = currentIndex.successor() _dumpObject_unlocked(child, name, indent + 2, maxDepth - 1, &maxItemCounter, &visitedItems, &targetStream) } } // -- Implementation details for the runtime's _MirrorType implementation @_silgen_name("swift_MagicMirrorData_summary") func _swift_MagicMirrorData_summaryImpl( metadata: Any.Type, _ result: UnsafeMutablePointer<String> ) public struct _MagicMirrorData { let owner: Builtin.NativeObject let ptr: Builtin.RawPointer let metadata: Any.Type var value: Any { @_silgen_name("swift_MagicMirrorData_value")get } var valueType: Any.Type { @_silgen_name("swift_MagicMirrorData_valueType")get } public var objcValue: Any { @_silgen_name("swift_MagicMirrorData_objcValue")get } public var objcValueType: Any.Type { @_silgen_name("swift_MagicMirrorData_objcValueType")get } var summary: String { let (_, result) = _withUninitializedString { _swift_MagicMirrorData_summaryImpl(self.metadata, $0) } return result } public func _loadValue<T>() -> T { return Builtin.load(ptr) as T } } struct _OpaqueMirror : _MirrorType { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { return 0 } subscript(i: Int) -> (String, _MirrorType) { _preconditionFailure("no children") } var summary: String { return data.summary } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .Aggregate } } internal struct _TupleMirror : _MirrorType { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { @_silgen_name("swift_TupleMirror_count")get } subscript(i: Int) -> (String, _MirrorType) { @_silgen_name("swift_TupleMirror_subscript")get } var summary: String { return "(\(count) elements)" } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .Tuple } } struct _StructMirror : _MirrorType { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { @_silgen_name("swift_StructMirror_count")get } subscript(i: Int) -> (String, _MirrorType) { @_silgen_name("swift_StructMirror_subscript")get } var summary: String { return _typeName(valueType) } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .Struct } } struct _EnumMirror : _MirrorType { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { @_silgen_name("swift_EnumMirror_count")get } var caseName: UnsafePointer<CChar> { @_silgen_name("swift_EnumMirror_caseName")get } subscript(i: Int) -> (String, _MirrorType) { @_silgen_name("swift_EnumMirror_subscript")get } var summary: String { let maybeCaseName = String.fromCString(self.caseName) let typeName = _typeName(valueType) if let caseName = maybeCaseName { return typeName + "." + caseName } return typeName } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .Enum } } @warn_unused_result @_silgen_name("swift_ClassMirror_count") func _getClassCount(_: _MagicMirrorData) -> Int @warn_unused_result @_silgen_name("swift_ClassMirror_subscript") func _getClassChild(_: Int, _: _MagicMirrorData) -> (String, _MirrorType) #if _runtime(_ObjC) @warn_unused_result @_silgen_name("swift_ClassMirror_quickLookObject") public func _getClassPlaygroundQuickLook( data: _MagicMirrorData ) -> PlaygroundQuickLook? #endif struct _ClassMirror : _MirrorType { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return data._loadValue() as ObjectIdentifier } var count: Int { return _getClassCount(data) } subscript(i: Int) -> (String, _MirrorType) { return _getClassChild(i, data) } var summary: String { return _typeName(valueType) } var quickLookObject: PlaygroundQuickLook? { #if _runtime(_ObjC) return _getClassPlaygroundQuickLook(data) #else return nil #endif } var disposition: _MirrorDisposition { return .Class } } struct _ClassSuperMirror : _MirrorType { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } // Suppress the value identifier for super mirrors. var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { return _getClassCount(data) } subscript(i: Int) -> (String, _MirrorType) { return _getClassChild(i, data) } var summary: String { return _typeName(data.metadata) } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .Class } } struct _MetatypeMirror : _MirrorType { let data: _MagicMirrorData var value: Any { return data.value } var valueType: Any.Type { return data.valueType } var objectIdentifier: ObjectIdentifier? { return data._loadValue() as ObjectIdentifier } var count: Int { return 0 } subscript(i: Int) -> (String, _MirrorType) { _preconditionFailure("no children") } var summary: String { return _typeName(data._loadValue() as Any.Type) } var quickLookObject: PlaygroundQuickLook? { return nil } // Special disposition for types? var disposition: _MirrorDisposition { return .Aggregate } } @available(*, unavailable, message="call the 'Mirror(reflecting:)' initializer") public func reflect<T>(x: T) -> _MirrorType { fatalError("unavailable function can't be called") }
apache-2.0
366da0b395f3570e9fdfdb05eb0d0edd
29.703276
119
0.676624
4.173651
false
false
false
false
elationfoundation/Reporta-iOS
IWMF/TableViewCell/ContactLst/NewDetailTableViewCell.swift
1
3001
// // NewDetailTableViewCell.swift // CustomIOS7AlertView // // // // import UIKit class NewDetailTableViewCell: UITableViewCell { @IBOutlet weak var ivUpperLine: UIImageView! @IBOutlet weak var ivUpperCutLine: UIImageView! @IBOutlet weak var ivBelowLine: UIImageView! @IBOutlet weak var lblDetail: UILabel! @IBOutlet weak var ivRight: UIImageView! typealias level = Level! var levelString : NSString = "" var isSelectedValue : Bool = false var type : Int = 0 var identity : String = "" func intialize(){ self.lblDetail.font = Utility.setFont() if isSelectedValue && type == 1 { ivRight.hidden = false } else { ivRight.hidden = true } if type == 3 { self.lblDetail.font = Utility.setDetailFont() } if type == 4 { self.lblDetail.font = Utility.setDetailFont() } if type == 5 { self.lblDetail.textColor = UIColor.blackColor() } else { } if isSelectedValue && type == 3 { ivRight.hidden = false } if isSelectedValue && type == 4 { ivRight.hidden = false } if self.identity == "UpdatedUsername" { let Contact = UIImage(named: "Contact") ivRight.image = Contact ivRight.hidden = false } else if self.identity == "Password" { let Password = UIImage(named: "Password") ivRight.image = Password ivRight.hidden = false }else if self.identity == "ProfessionalDetails"{ let EditDetails = UIImage(named: "EditDetails") ivRight.image = EditDetails ivRight.hidden = false }else if self.identity == "SignOut"{ let SignOut = UIImage(named: "SignOut") ivRight.image = SignOut ivRight.hidden = false } if levelString == Level.Single.rawValue{ ivUpperCutLine.hidden = true ivUpperLine.hidden = false ivBelowLine.hidden = false }else if levelString == Level.Top.rawValue{ ivUpperCutLine.hidden = true ivUpperLine.hidden = false ivBelowLine.hidden = true }else if levelString == Level.Middle.rawValue{ ivUpperCutLine.hidden = false ivUpperLine.hidden = true ivBelowLine.hidden = true } else { ivUpperCutLine.hidden = false ivUpperLine.hidden = true ivBelowLine.hidden = false } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
gpl-3.0
604b36340a0dede673ba87787891cda5
25.324561
61
0.53149
4.8016
false
false
false
false
CosmicMind/Motion
Sources/MotionAnimation.swift
3
11950
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * 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 public class MotionAnimation { /// A reference to the callback that applies the MotionAnimationState. internal let apply: (inout MotionAnimationState) -> Void /** An initializer that accepts a given callback. - Parameter applyFunction: A given callback. */ init(applyFunction: @escaping (inout MotionAnimationState) -> Void) { apply = applyFunction } } public extension MotionAnimation { /** Animates a view's current background color to the given color. - Parameter color: A UIColor. - Returns: A MotionAnimation. */ static func background(color: UIColor) -> MotionAnimation { return MotionAnimation { $0.backgroundColor = color.cgColor } } /** Animates a view's current border color to the given color. - Parameter color: A UIColor. - Returns: A MotionAnimation. */ static func border(color: UIColor) -> MotionAnimation { return MotionAnimation { $0.borderColor = color.cgColor } } /** Animates a view's current border width to the given width. - Parameter width: A CGFloat. - Returns: A MotionAnimation. */ static func border(width: CGFloat) -> MotionAnimation { return MotionAnimation { $0.borderWidth = width } } /** Animates a view's current corner radius to the given radius. - Parameter radius: A CGFloat. - Returns: A MotionAnimation. */ static func corner(radius: CGFloat) -> MotionAnimation { return MotionAnimation { $0.cornerRadius = radius } } /** Animates a view's current transform (perspective, scale, rotate) to the given one. - Parameter _ transform: A CATransform3D. - Returns: A MotionAnimation. */ static func transform(_ transform: CATransform3D) -> MotionAnimation { return MotionAnimation { $0.transform = transform } } /** Animates a view's current rotation to the given x, y, and z values. - Parameter x: A CGFloat. - Parameter y: A CGFloat. - Parameter z: A CGFloat. - Returns: A MotionAnimation. */ static func rotate(x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> MotionAnimation { return MotionAnimation { var t = $0.transform ?? CATransform3DIdentity t = CATransform3DRotate(t, CGFloat(Double.pi) * x / 180, 1, 0, 0) t = CATransform3DRotate(t, CGFloat(Double.pi) * y / 180, 0, 1, 0) $0.transform = CATransform3DRotate(t, CGFloat(Double.pi) * z / 180, 0, 0, 1) } } /** Animates a view's current rotation to the given point. - Parameter _ point: A CGPoint. - Parameter z: A CGFloat. - Returns: A MotionAnimation. */ static func rotate(_ point: CGPoint, z: CGFloat = 0) -> MotionAnimation { return .rotate(x: point.x, y: point.y, z: z) } /** Rotate 2d. - Parameter _ z: A CGFloat. - Returns: A MotionAnimation. */ static func rotate(_ z: CGFloat) -> MotionAnimation { return .rotate(z: z) } /** Animates a view's current spin to the given x, y, and z values. - Parameter x: A CGFloat. - Parameter y: A CGFloat. - Parameter z: A CGFloat. - Returns: A MotionAnimation. */ static func spin(x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> MotionAnimation { return MotionAnimation { $0.spin = (x, y, z) } } /** Animates a view's current spin to the given point. - Parameter _ point: A CGPoint. - Parameter z: A CGFloat. - Returns: A MotionAnimation. */ static func spin(_ point: CGPoint, z: CGFloat = 0) -> MotionAnimation { return .spin(x: point.x, y: point.y, z: z) } /** Spin 2d. - Parameter _ z: A CGFloat. - Returns: A MotionAnimation. */ static func spin(_ z: CGFloat) -> MotionAnimation { return .spin(z: z) } /** Animates the view's current scale to the given x, y, and z scale values. - Parameter x: A CGFloat. - Parameter y: A CGFloat. - Parameter z: A CGFloat. - Returns: A MotionAnimation. */ static func scale(x: CGFloat = 1, y: CGFloat = 1, z: CGFloat = 1) -> MotionAnimation { return MotionAnimation { $0.transform = CATransform3DScale($0.transform ?? CATransform3DIdentity, x, y, z) } } /** Animates the view's current x & y scale to the given scale value. - Parameter _ xy: A CGFloat. - Returns: A MotionAnimation. */ static func scale(_ xy: CGFloat) -> MotionAnimation { return .scale(x: xy, y: xy) } /** Animates a view equal to the distance given by the x, y, and z values. - Parameter x: A CGFloat. - Parameter y: A CGFloat. - Parameter z: A CGFloat. - Returns: A MotionAnimation. */ static func translate(x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> MotionAnimation { return MotionAnimation { $0.transform = CATransform3DTranslate($0.transform ?? CATransform3DIdentity, x, y, z) } } /** Animates a view equal to the distance given by a point and z value. - Parameter _ point: A CGPoint. - Parameter z: A CGFloat. - Returns: A MotionAnimation. */ static func translate(_ point: CGPoint, z: CGFloat = 0) -> MotionAnimation { return .translate(x: point.x, y: point.y, z: z) } /** Animates a view's current position to the given point. - Parameter _ point: A CGPoint. - Returns: A MotionAnimation. */ static func position(_ point: CGPoint) -> MotionAnimation { return MotionAnimation { $0.position = point } } /** Animates a view's current position to the given x and y values. - Parameter x: A CGloat. - Parameter y: A CGloat. - Returns: A MotionAnimation. */ static func position(x: CGFloat, y: CGFloat) -> MotionAnimation { return .position(CGPoint(x: x, y: y)) } /// Fades the view in during an animation. static var fadeIn = MotionAnimation.fade(1) /// Fades the view out during an animation. static var fadeOut = MotionAnimation.fade(0) /** Animates a view's current opacity to the given one. - Parameter _ opacity: A Double. - Returns: A MotionAnimation. */ static func fade(_ opacity: Double) -> MotionAnimation { return MotionAnimation { $0.opacity = opacity } } /** Animates a view's current zPosition to the given position. - Parameter _ position: An Int. - Returns: A MotionAnimation. */ static func zPosition(_ position: CGFloat) -> MotionAnimation { return MotionAnimation { $0.zPosition = position } } /** Animates a view's current size to the given one. - Parameter _ size: A CGSize. - Returns: A MotionAnimation. */ static func size(_ size: CGSize) -> MotionAnimation { return MotionAnimation { $0.size = size } } /** Animates the view's current size to the given width and height. - Parameter width: A CGFloat. - Parameter height: A CGFloat. - Returns: A MotionAnimation. */ static func size(width: CGFloat, height: CGFloat) -> MotionAnimation { return .size(CGSize(width: width, height: height)) } /** Animates a view's current shadow path to the given one. - Parameter path: A CGPath. - Returns: A MotionAnimation. */ static func shadow(path: CGPath) -> MotionAnimation { return MotionAnimation { $0.shadowPath = path } } /** Animates a view's current shadow color to the given one. - Parameter color: A UIColor. - Returns: A MotionAnimation. */ static func shadow(color: UIColor) -> MotionAnimation { return MotionAnimation { $0.shadowColor = color.cgColor } } /** Animates a view's current shadow offset to the given one. - Parameter offset: A CGSize. - Returns: A MotionAnimation. */ static func shadow(offset: CGSize) -> MotionAnimation { return MotionAnimation { $0.shadowOffset = offset } } /** Animates a view's current shadow opacity to the given one. - Parameter opacity: A Float. - Returns: A MotionAnimation. */ static func shadow(opacity: Float) -> MotionAnimation { return MotionAnimation { $0.shadowOpacity = opacity } } /** Animates a view's current shadow radius to the given one. - Parameter radius: A CGFloat. - Returns: A MotionAnimation. */ static func shadow(radius: CGFloat) -> MotionAnimation { return MotionAnimation { $0.shadowRadius = radius } } /** Animates the views shadow offset, opacity, and radius. - Parameter offset: A CGSize. - Parameter opacity: A Float. - Parameter radius: A CGFloat. */ static func depth(offset: CGSize, opacity: Float, radius: CGFloat) -> MotionAnimation { return MotionAnimation { $0.shadowOffset = offset $0.shadowOpacity = opacity $0.shadowRadius = radius } } /** Animates the views shadow offset, opacity, and radius. - Parameter _ depth: A tuple (CGSize, FLoat, CGFloat). */ static func depth(_ depth: (CGSize, Float, CGFloat)) -> MotionAnimation { return .depth(offset: depth.0, opacity: depth.1, radius: depth.2) } /** Available in iOS 9+, animates a view using the spring API, given a stiffness and damping. - Parameter stiffness: A CGFlloat. - Parameter damping: A CGFloat. - Returns: A MotionAnimation. */ @available(iOS 9, *) static func spring(stiffness: CGFloat, damping: CGFloat) -> MotionAnimation { return MotionAnimation { $0.spring = (stiffness, damping) } } /** The duration of the view's animation. If a duration of 0 is used, the value will be converted to 0.01, to give a close to zero value. - Parameter _ duration: A TimeInterval. - Returns: A MotionAnimation. */ static func duration(_ duration: TimeInterval) -> MotionAnimation { return MotionAnimation { $0.duration = duration } } /** Delays the animation of a given view. - Parameter _ time: TimeInterval. - Returns: A MotionAnimation. */ static func delay(_ time: TimeInterval) -> MotionAnimation { return MotionAnimation { $0.delay = time } } /** Sets the view's timing function for the animation. - Parameter _ timingFunction: A CAMediaTimingFunction. - Returns: A MotionAnimation. */ static func timingFunction(_ timingFunction: CAMediaTimingFunction) -> MotionAnimation { return MotionAnimation { $0.timingFunction = timingFunction } } /** Creates a completion block handler that is executed once the animation is done. - Parameter _ execute: A callback to execute once completed. */ static func completion(_ execute: @escaping () -> Void) -> MotionAnimation { return MotionAnimation { $0.completion = execute } } }
mit
50f10f2a179ea29d8fe234c3bec1760b
27.384798
92
0.653808
4.218143
false
false
false
false
studyYF/YueShiJia
YueShiJia/YueShiJia/Classes/Category/Size.swift
2
1238
// // Size.swift // Suyuan-swift // // Created by YangFan on 16/12/16. // Copyright © 2016年 YangFan. All rights reserved. // import Foundation import UIKit extension UIView { ///控件的宽 var yfWidth : CGFloat { set { frame.size.width = yfWidth } get { return frame.size.width } } ///控件的高 var yfHeight : CGFloat { set { frame.size.height = yfHeight } get { return frame.size.height } } ///控件的x var yfX : CGFloat { set { frame.origin.x = yfX } get { return frame.origin.x } } ///控件的y var yfY : CGFloat { set { frame.origin.y = yfY } get { return frame.origin.y } } ///控件的centerX var yfCenterX : CGFloat { set { center.x = yfCenterX } get { return center.x } } ///控件的centerY var yfCenterY : CGFloat { set { center.y = yfCenterY } get { return center.y } } }
apache-2.0
143907cb34cddb3a2e895eed01146dd8
15.369863
51
0.421757
4.092466
false
false
false
false
kstaring/swift
test/decl/func/trailing_closures.swift
10
858
// RUN: %target-parse-verify-swift // Warn about non-trailing closures followed by parameters with // default arguments. func f1(_ f: () -> (), bar: Int = 10) { } // expected-warning{{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} func f2(_ f: (() -> ())!, bar: Int = 10, wibble: Int = 17) { } // expected-warning{{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} func f3(_ f: (() -> ())?, bar: Int = 10) { } // expected-warning{{closure parameter prior to parameters with default arguments will not be treated as a trailing closure}} // An extra set of parentheses suppresses the warning. func g1(_ f: (() -> ()), bar: Int = 10) { } // no-warning // Stop at the first closure. func g2(_ f: () -> (), g: (() -> ())? = nil) { } // no-warning
apache-2.0
3380e8506e70be2c3b8279e87d795242
65
188
0.656177
3.830357
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/Dispatcher.swift
1
2961
// // Dispatcher.swift // MrGreen // // Created by Benzi on 01/09/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // // https://raw.githubusercontent.com/aleclarson/swift-dispatcher/master/Dispatcher.swift import Foundation let gcd = Dispatcher() class Dispatcher { /// dispatch_get_main_queue() let main = DispatchQueue("main") /// DISPATCH_QUEUE_PRIORITY_DEFAULT let global = DispatchQueue("global") /// DISPATCH_QUEUE_PRIORITY_BACKGROUND let background = DispatchQueue("background") /// DISPATCH_QUEUE_PRIORITY_LOW let low = DispatchQueue("low") /// DISPATCH_QUEUE_PRIORITY_HIGH let high = DispatchQueue("high") /// DISPATCH_QUEUE_SERIAL func serial (id: String) -> DispatchQueue { let queue = DispatchQueue(id) queue.q = dispatch_queue_create(id, DISPATCH_QUEUE_SERIAL) return queue } /// DISPATCH_QUEUE_CONCURRENT func concurrent (id: String) -> DispatchQueue { let queue = DispatchQueue(id) queue.q = dispatch_queue_create(id, DISPATCH_QUEUE_CONCURRENT) return queue } private init () { main.q = dispatch_get_main_queue() global.q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) background.q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) high.q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) low.q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0) } } private var queueIDs = [String:Void]() class DispatchQueue { private init (_ id: String) { if queueIDs[id] != nil { fatalError("The 'id' provided is already in use!") } queueIDs[id] = () self.id = id } let id: String func async (block: dispatch_block_t) { dispatch_async(q, block) } // func async (block: () -> ()) { // async { block() } // } func sync (block: dispatch_block_t) { dispatch_sync(q, block) } // func sync (block: () -> ()) { // sync { block() } // } /// A lower level of abstraction private(set) var q: dispatch_queue_t! } class DispatchGroup { private(set) var count = 0 convenience init(_ count: Int) { self.init() self += count } /// dispatch_group_notify() func onFinish (block: () -> ()) { dispatch_group_notify(g, gcd.global.q, block) } /// Lower level of abstraction private(set) var g = dispatch_group_create() } /// dispatch_group_enter() func += (lhs: DispatchGroup, rhs: Int) { lhs.count += rhs for _ in 0..<rhs { dispatch_group_enter(lhs.g) } } /// dispatch_group_leave() func -= (lhs: DispatchGroup, rhs: Int) { let count = rhs > lhs.count ? lhs.count : rhs lhs.count -= count for _ in 0..<count { dispatch_group_leave(lhs.g) } }
isc
3053a0ba4cf08f0de3ed0afb35f6452c
23.278689
88
0.591017
3.767176
false
false
false
false
yoonapps/QPXExpressWrapper
QPXExpressWrapper/Classes/SearchResults.swift
1
847
// // SearchData.swift // Flights // // Created by Kyle Yoon on 2/14/16. // Copyright © 2016 Kyle Yoon. All rights reserved. // import Foundation import Gloss public struct SearchResults: Decodable { public static let dateFormatter = DateFormatter() public let kind: String public let trips: Trips? // Only setable within this class fileprivate(set) public var isRoundTrip: Bool = true public init?(json: JSON) { guard let kind: String = "kind" <~~ json else { return nil } self.kind = kind self.trips = "trips" <~~ json } } extension DateFormatter { func decodedDate(for dateString: String) -> Date? { self.dateFormat = "yyyy-MM-dd'T'HH:mmZZZZZ" //"2016-02-19T17:35-08:00" return self.date(from: dateString) } }
mit
7f7430248c9f35034dd719f00d4babe4
21.263158
78
0.609929
3.810811
false
true
false
false
turingcorp/gattaca
UnitTests/Model/Gif/Abstract/TMGifStorer.swift
1
2572
import XCTest @testable import gattaca class TMGifStorer:XCTestCase { private let kIdentifier:String = "lorem ipsum" private let kWaitExpectation:TimeInterval = 4 //MARK: private private func deleteAll( coreData:Database, completion:@escaping(() -> ())) { coreData.fetch { [weak self] (items:[DGif]) in self?.recursiveDelete( coreData:coreData, items:items, completion:completion) } } private func recursiveDelete( coreData:Database, items:[DGif], completion:@escaping(() -> ())) { var items:[DGif] = items guard let item:DGif = items.popLast() else { completion() return } coreData.delete(data:item) { [weak self] in self?.recursiveDelete( coreData:coreData, items:items, completion:completion) } } //MARK: internal func testStoreItems() { let bundle:Bundle = Bundle(for:TMGifStorer.self) guard let coreData:Database = Database(bundle:bundle) else { return } var items:[DGif]? let storeExpectation:XCTestExpectation = expectation( description:"store item expectation") let identifier:String = kIdentifier let giphyItem:MGiphyItem = MGiphyItem( identifier:identifier) let gif:MGif = MGif() deleteAll(coreData:coreData) { gif.storeItems( coreData:coreData, items:[giphyItem]) { coreData.fetch { (fetchedItems:[DGif]) in items = fetchedItems storeExpectation.fulfill() } } } waitForExpectations(timeout:kWaitExpectation) { (error:Error?) in XCTAssertNotNil( items, "failed storing items") XCTAssertEqual( items?.count, 1, "amount stored don't match") XCTAssertEqual( items?.first?.identifier, identifier, "identifier doesn't match") } } }
mit
c8ac371dfddb380b48303f0e2db76e98
22.59633
61
0.458398
5.715556
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/AsyncAwaitSupport/AsyncClientTests.swift
1
13534
/* * Copyright 2022, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if compiler(>=5.6) import EchoImplementation import EchoModel import GRPC import NIOCore import NIOPosix import XCTest @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) final class AsyncClientCancellationTests: GRPCTestCase { private var server: Server! private var group: EventLoopGroup! private var pool: GRPCChannel! override func setUp() { super.setUp() self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) } override func tearDown() async throws { if self.pool != nil { try self.pool.close().wait() self.pool = nil } if self.server != nil { try self.server.close().wait() self.server = nil } try self.group.syncShutdownGracefully() self.group = nil try await super.tearDown() } private func startServer(service: CallHandlerProvider) throws { precondition(self.server == nil) self.server = try Server.insecure(group: self.group) .withServiceProviders([service]) .withLogger(self.serverLogger) .bind(host: "127.0.0.1", port: 0) .wait() } private func startServerAndClient(service: CallHandlerProvider) throws -> Echo_EchoAsyncClient { try self.startServer(service: service) return try self.makeClient(port: self.server.channel.localAddress!.port!) } private func makeClient( port: Int, configure: (inout GRPCChannelPool.Configuration) -> Void = { _ in } ) throws -> Echo_EchoAsyncClient { precondition(self.pool == nil) self.pool = try GRPCChannelPool.with( target: .host("127.0.0.1", port: port), transportSecurity: .plaintext, eventLoopGroup: self.group ) { $0.backgroundActivityLogger = self.clientLogger configure(&$0) } return Echo_EchoAsyncClient(channel: self.pool) } func testCancelUnaryFailsResponse() async throws { // We don't want the RPC to complete before we cancel it so use the never resolving service. let echo = try self.startServerAndClient(service: NeverResolvingEchoProvider()) let get = echo.makeGetCall(.with { $0.text = "foo bar baz" }) get.cancel() do { _ = try await get.response XCTFail("Expected to throw a status with code .cancelled") } catch let status as GRPCStatus { XCTAssertEqual(status.code, .cancelled) } catch { XCTFail("Expected to throw a status with code .cancelled") } // Status should be 'cancelled'. let status = await get.status XCTAssertEqual(status.code, .cancelled) } func testCancelFailsUnaryResponseForWrappedCall() async throws { // We don't want the RPC to complete before we cancel it so use the never resolving service. let echo = try self.startServerAndClient(service: NeverResolvingEchoProvider()) let task = Task { try await echo.get(.with { $0.text = "I'll be cancelled" }) } task.cancel() do { _ = try await task.value XCTFail("Expected to throw a status with code .cancelled") } catch let status as GRPCStatus { XCTAssertEqual(status.code, .cancelled) } catch { XCTFail("Expected to throw a status with code .cancelled") } } func testCancelServerStreamingClosesResponseStream() async throws { // We don't want the RPC to complete before we cancel it so use the never resolving service. let echo = try self.startServerAndClient(service: NeverResolvingEchoProvider()) let expand = echo.makeExpandCall(.with { $0.text = "foo bar baz" }) expand.cancel() var responseStream = expand.responseStream.makeAsyncIterator() do { _ = try await responseStream.next() XCTFail("Expected to throw a status with code .cancelled") } catch let status as GRPCStatus { XCTAssertEqual(status.code, .cancelled) } catch { XCTFail("Expected to throw a status with code .cancelled") } // Status should be 'cancelled'. let status = await expand.status XCTAssertEqual(status.code, .cancelled) } func testCancelServerStreamingClosesResponseStreamForWrappedCall() async throws { // We don't want the RPC to complete before we cancel it so use the never resolving service. let echo = try self.startServerAndClient(service: NeverResolvingEchoProvider()) let task = Task { let responseStream = echo.expand(.with { $0.text = "foo bar baz" }) var responseIterator = responseStream.makeAsyncIterator() do { _ = try await responseIterator.next() XCTFail("Expected to throw a status with code .cancelled") } catch let status as GRPCStatus { XCTAssertEqual(status.code, .cancelled) } catch { XCTFail("Expected to throw a status with code .cancelled") } } task.cancel() await task.value } func testCancelClientStreamingClosesRequestStreamAndFailsResponse() async throws { let echo = try self.startServerAndClient(service: EchoProvider()) let collect = echo.makeCollectCall() // Make sure the stream is up before we cancel it. try await collect.requestStream.send(.with { $0.text = "foo" }) collect.cancel() // Cancellation is async so loop until we error. while true { do { try await collect.requestStream.send(.with { $0.text = "foo" }) try await Task.sleep(nanoseconds: 1000) } catch { break } } // There should be no response. await XCTAssertThrowsError(try await collect.response) // Status should be 'cancelled'. let status = await collect.status XCTAssertEqual(status.code, .cancelled) } func testCancelClientStreamingClosesRequestStreamAndFailsResponseForWrappedCall() async throws { let echo = try self.startServerAndClient(service: NeverResolvingEchoProvider()) let requests = (0 ..< 10).map { i in Echo_EchoRequest.with { $0.text = String(i) } } let task = Task { do { let _ = try await echo.collect(requests) XCTFail("Expected to throw a status with code .cancelled") } catch let status as GRPCStatus { XCTAssertEqual(status.code, .cancelled) } catch { XCTFail("Expected to throw a status with code .cancelled") } } task.cancel() await task.value } func testClientStreamingClosesRequestStreamOnEnd() async throws { let echo = try self.startServerAndClient(service: EchoProvider()) let collect = echo.makeCollectCall() // Send and close. try await collect.requestStream.send(.with { $0.text = "foo" }) collect.requestStream.finish() // Await the response and status. _ = try await collect.response let status = await collect.status XCTAssert(status.isOk) // Sending should fail. await XCTAssertThrowsError( try await collect.requestStream.send(.with { $0.text = "should throw" }) ) } func testCancelBidiStreamingClosesRequestStreamAndResponseStream() async throws { let echo = try self.startServerAndClient(service: EchoProvider()) let update = echo.makeUpdateCall() // Make sure the stream is up before we cancel it. try await update.requestStream.send(.with { $0.text = "foo" }) // Wait for the response. var responseStream = update.responseStream.makeAsyncIterator() _ = try await responseStream.next() update.cancel() // Cancellation is async so loop until we error. while true { do { try await update.requestStream.send(.with { $0.text = "foo" }) try await Task.sleep(nanoseconds: 1000) } catch { break } } // Status should be 'cancelled'. let status = await update.status XCTAssertEqual(status.code, .cancelled) } func testCancelBidiStreamingClosesRequestStreamAndResponseStreamForWrappedCall() async throws { let echo = try self.startServerAndClient(service: EchoProvider()) let requests = (0 ..< 10).map { i in Echo_EchoRequest.with { $0.text = String(i) } } let task = Task { let responseStream = echo.update(requests) var responseIterator = responseStream.makeAsyncIterator() do { _ = try await responseIterator.next() XCTFail("Expected to throw a status with code .cancelled") } catch let status as GRPCStatus { XCTAssertEqual(status.code, .cancelled) } catch { XCTFail("Expected to throw a status with code .cancelled") } } task.cancel() await task.value } func testBidiStreamingClosesRequestStreamOnEnd() async throws { let echo = try self.startServerAndClient(service: EchoProvider()) let update = echo.makeUpdateCall() // Send and close. try await update.requestStream.send(.with { $0.text = "foo" }) update.requestStream.finish() // Await the response and status. let responseCount = try await update.responseStream.count() XCTAssertEqual(responseCount, 1) let status = await update.status XCTAssert(status.isOk) // Sending should fail. await XCTAssertThrowsError( try await update.requestStream.send(.with { $0.text = "should throw" }) ) } private enum RequestStreamingRPC { typealias Request = Echo_EchoRequest typealias Response = Echo_EchoResponse case clientStreaming(GRPCAsyncClientStreamingCall<Request, Response>) case bidirectionalStreaming(GRPCAsyncBidirectionalStreamingCall<Request, Response>) func sendRequest(_ text: String) async throws { switch self { case let .clientStreaming(call): try await call.requestStream.send(.with { $0.text = text }) case let .bidirectionalStreaming(call): try await call.requestStream.send(.with { $0.text = text }) } } func cancel() { switch self { case let .clientStreaming(call): call.cancel() case let .bidirectionalStreaming(call): call.cancel() } } } private func testSendingRequestsSuspendsWhileStreamIsNotReady( makeRPC: @escaping () -> RequestStreamingRPC ) async throws { // The strategy for this test is to race two different tasks. The first will attempt to send a // message on a request stream on a connection which will never establish. The second will sleep // for a little while. Each task returns a `SendOrTimedOut` event. If the message is sent then // the test definitely failed; it should not be possible to send a message on a stream which is // not open. If the time out happens first then it probably did not fail. enum SentOrTimedOut: Equatable, Sendable { case messageSent case timedOut } await withThrowingTaskGroup(of: SentOrTimedOut.self) { group in group.addTask { let rpc = makeRPC() return try await withTaskCancellationHandler { // This should suspend until we cancel it: we're never going to start a server so it // should never succeed. try await rpc.sendRequest("I should suspend") return .messageSent } onCancel: { rpc.cancel() } } group.addTask { // Wait for 100ms. try await Task.sleep(nanoseconds: 100_000_000) return .timedOut } do { let event = try await group.next() // If this isn't timed out then the message was sent before the stream was ready. XCTAssertEqual(event, .timedOut) } catch { XCTFail("Unexpected error \(error)") } // Cancel the other task. group.cancelAll() } } func testClientStreamingSuspendsWritesUntilStreamIsUp() async throws { // Make a client for a server which isn't up yet. It will continually fail to establish a // connection. let echo = try self.makeClient(port: 0) try await self.testSendingRequestsSuspendsWhileStreamIsNotReady { return .clientStreaming(echo.makeCollectCall()) } } func testBidirectionalStreamingSuspendsWritesUntilStreamIsUp() async throws { // Make a client for a server which isn't up yet. It will continually fail to establish a // connection. let echo = try self.makeClient(port: 0) try await self.testSendingRequestsSuspendsWhileStreamIsNotReady { return .bidirectionalStreaming(echo.makeUpdateCall()) } } func testConnectionFailureCancelsRequestStreamWithError() async throws { let echo = try self.makeClient(port: 0) { // Configure a short wait time; we will not start a server so fail quickly. $0.connectionPool.maxWaitTime = .milliseconds(10) } let update = echo.makeUpdateCall() await XCTAssertThrowsError(try await update.requestStream.send(.init())) { error in XCTAssertFalse(error is CancellationError) } let collect = echo.makeCollectCall() await XCTAssertThrowsError(try await collect.requestStream.send(.init())) { error in XCTAssertFalse(error is CancellationError) } } } #endif // compiler(>=5.6)
apache-2.0
1cf99a2535270b48959e8ae2b215ee98
31.22381
100
0.677922
4.382772
false
false
false
false
YR/Cachyr
Tests/CachyrTests/DataCacheAccessTests.swift
1
7825
/** * Cachyr * * Copyright (c) 2018 NRK. Licensed under the MIT license, as follows: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import XCTest @testable import Cachyr class DataCacheAccessTests: XCTestCase { var cache: DataCache<String>! let expectationWaitTime: TimeInterval = 5 override func setUp() { super.setUp() cache = DataCache<String>() } override func tearDown() { super.tearDown() cache.removeAll() } func testContainsAccess() { let foo = "bar" let key = "foo" cache.removeAll() cache.setValue(foo, forKey: key) XCTAssertTrue(cache.contains(key: key, access: [.memory])) XCTAssertTrue(cache.contains(key: key, access: [.disk])) cache.removeAll() cache.setValue(foo, forKey: key, access: [.memory]) XCTAssertTrue(cache.contains(key: key, access: [.memory])) XCTAssertFalse(cache.contains(key: key, access: [.disk])) cache.removeAll() cache.setValue(foo, forKey: key, access: [.disk]) XCTAssertFalse(cache.contains(key: key, access: [.memory])) XCTAssertTrue(cache.contains(key: key, access: [.disk])) cache.removeAll() } func testValueAccess() { let foo = "bar" let key = "foo" cache.removeAll() cache.setValue(foo, forKey: key) let value = cache.value(forKey: key) XCTAssertNotNil(value) cache.removeAll() cache.setValue(foo, forKey: key, access: [.memory]) var memoryValue = cache.value(forKey: key, access: [.memory]) XCTAssertNotNil(memoryValue) var diskValue = cache.value(forKey: key, access: [.disk]) XCTAssertNil(diskValue) cache.removeAll() cache.setValue(foo, forKey: key, access: [.disk]) memoryValue = cache.value(forKey: key, access: [.memory]) XCTAssertNil(memoryValue) diskValue = cache.value(forKey: key, access: [.disk]) XCTAssertNotNil(diskValue) cache.removeAll() } func testRemoveValueAccess() { let foo = "bar" let key = "foo" cache.removeAll() cache.setValue(foo, forKey: key) cache.removeValue(forKey: key, access: [.memory]) XCTAssertFalse(cache.contains(key: key, access: [.memory])) XCTAssertTrue(cache.contains(key: key, access: [.disk])) cache.removeAll() cache.setValue(foo, forKey: key) cache.removeValue(forKey: key, access: [.disk]) XCTAssertTrue(cache.contains(key: key, access: [.memory])) XCTAssertFalse(cache.contains(key: key, access: [.disk])) cache.removeAll() } func testRemoveAllAccess() { let foo = "bar" let bar = "wat" let fooKey = "foo" let barKey = "bar" cache.removeAll() cache.setValue(foo, forKey: fooKey) cache.setValue(bar, forKey: barKey) XCTAssertTrue(cache.contains(key: fooKey, access: [.memory])) XCTAssertTrue(cache.contains(key: barKey, access: [.memory])) XCTAssertTrue(cache.contains(key: fooKey, access: [.disk])) XCTAssertTrue(cache.contains(key: barKey, access: [.disk])) cache.removeAll(access: [.memory]) XCTAssertFalse(cache.contains(key: fooKey, access: [.memory])) XCTAssertFalse(cache.contains(key: barKey, access: [.memory])) XCTAssertTrue(cache.contains(key: fooKey, access: [.disk])) XCTAssertTrue(cache.contains(key: barKey, access: [.disk])) cache.removeAll(access: [.disk]) XCTAssertFalse(cache.contains(key: fooKey, access: [.memory])) XCTAssertFalse(cache.contains(key: barKey, access: [.memory])) XCTAssertFalse(cache.contains(key: fooKey, access: [.disk])) XCTAssertFalse(cache.contains(key: barKey, access: [.disk])) cache.removeAll() } func testRemoveExpiredAccess() { let foo = "bar" let key = "foo" cache.removeAll() cache.setValue(foo, forKey: key) cache.setExpirationDate(Date.distantPast, forKey: key) cache.removeExpired(access: [.memory]) XCTAssertFalse(cache.contains(key: key, access: [.memory])) XCTAssertTrue(cache.contains(key: key, access: [.disk])) cache.removeExpired(access: [.disk]) XCTAssertFalse(cache.contains(key: key, access: [.memory])) XCTAssertFalse(cache.contains(key: key, access: [.disk])) cache.removeAll() } func testRemoveOlderThanAccess() { let foo = "bar" let key = "foo" let maxExpire = Date(timeIntervalSinceNow: 10) let expires = Date(timeIntervalSinceNow: 1) cache.removeAll() cache.setValue(foo, forKey: key, expires: expires) cache.removeItems(olderThan: maxExpire, access: [.memory]) XCTAssertFalse(cache.contains(key: key, access: [.memory])) XCTAssertTrue(cache.contains(key: key, access: [.disk])) cache.removeItems(olderThan: maxExpire, access: [.disk]) XCTAssertFalse(cache.contains(key: key, access: [.memory])) XCTAssertFalse(cache.contains(key: key, access: [.disk])) cache.removeAll() } func testExpirationAccess() { let foo = "bar" let key = "foo" let expires = Date(timeIntervalSinceNow: 10) cache.removeAll() cache.setValue(foo, forKey: key) XCTAssertNil(cache.expirationDate(forKey: key, access: [.memory])) XCTAssertNil(cache.expirationDate(forKey: key, access: [.disk])) cache.setExpirationDate(expires, forKey: key, access: [.memory]) XCTAssertNotNil(cache.expirationDate(forKey: key, access: [.memory])) XCTAssertNil(cache.expirationDate(forKey: key, access: [.disk])) cache.setExpirationDate(nil, forKey: key, access: [.memory]) cache.setExpirationDate(expires, forKey: key, access: [.disk]) XCTAssertNil(cache.expirationDate(forKey: key, access: [.memory])) XCTAssertNotNil(cache.expirationDate(forKey: key, access: [.disk])) cache.removeAll() } } #if os(Linux) extension DataCacheTests { static var allTests : [(String, (DataCacheTests) -> () throws -> Void)] { return [ ("testContainsAccess", testContainsAccess), ("testValueAccess", testValueAccess), ("testRemoveValueAccess", testRemoveValueAccess), ("testRemoveAllAccess", testRemoveAllAccess), ("testRemoveExpiredAccess", testRemoveExpiredAccess), ("testRemoveOlderThanAccess", testRemoveOlderThanAccess), ("testExpirationAccess", testExpirationAccess) ] } } #endif
mit
67baba81a38bddce41a44e6ae7355025
33.170306
82
0.636294
4.369068
false
true
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/PaymentMethodsViewController.swift
1
4203
// // PaymentMethodsViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 9/1/15. // Copyright (c) 2015 com.mercadopago. All rights reserved. // import UIKit public class PaymentMethodsViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { var publicKey : String? @IBOutlet weak private var tableView : UITableView! var loadingView : UILoadingView! var items : [PaymentMethod]! var supportedPaymentTypes: [String]! var bundle : NSBundle? = MercadoPago.getBundle() var callback : ((paymentMethod : PaymentMethod) -> Void)? init(merchantPublicKey: String, supportedPaymentTypes: [String], callback:(paymentMethod: PaymentMethod) -> Void) { super.init(nibName: "PaymentMethodsViewController", bundle: bundle) self.publicKey = merchantPublicKey self.supportedPaymentTypes = supportedPaymentTypes self.callback = callback } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init() { super.init(nibName: nil, bundle: nil) } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override public func viewDidAppear(animated: Bool) { self.tableView.reloadData() } override public func viewDidLoad() { super.viewDidLoad() self.title = "Medio de pago".localized self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás".localized, style: UIBarButtonItemStyle.Plain, target: nil, action: nil) self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized) self.view.addSubview(self.loadingView) let mercadoPago : MercadoPago = MercadoPago(publicKey: self.publicKey!) mercadoPago.getPaymentMethods({(paymentMethods: [PaymentMethod]?) -> Void in self.items = [PaymentMethod]() if paymentMethods != nil { var pms : [PaymentMethod] = [PaymentMethod]() if self.supportedPaymentTypes != nil { for pm in paymentMethods! { for supported in self.supportedPaymentTypes! { if supported == pm.paymentTypeId { pms.append(pm) } } } } self.items = pms } self.tableView.reloadData() self.loadingView.removeFromSuperview() }, failure: { (error: NSError?) -> Void in MercadoPago.showAlertViewWithError(error, nav: self.navigationController) }) let paymentMethodNib = UINib(nibName: "PaymentMethodTableViewCell", bundle: self.bundle) self.tableView.registerNib(paymentMethodNib, forCellReuseIdentifier: "paymentMethodCell") self.tableView.delegate = self self.tableView.dataSource = self } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items == nil ? 0 : items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let pmcell : PaymentMethodTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("paymentMethodCell") as! PaymentMethodTableViewCell let paymentMethod : PaymentMethod = items[indexPath.row] pmcell.setLabel(paymentMethod.name) pmcell.setImageWithName("icoTc_" + paymentMethod._id) return pmcell } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.callback!(paymentMethod: self.items![indexPath.row]) } }
mit
6566f54b553893fc4109ac9a0e8b33e8
38.650943
150
0.631366
5.617647
false
false
false
false
u10int/Kinetic
Pod/Classes/Tweenable.swift
1
9735
// // Tweenable.swift // Pods // // Created by Nicholas Shipes on 2/5/17. // // import UIKit public protocol Tweenable: class { func apply(_ prop: Property) func currentProperty(for prop: Property) -> Property? } extension Tweenable { public func tween() -> Tween { return Tween(target: self) } } extension Array where Element: Tweenable { public func tween() -> Timeline { return Kinetic.animateAll(self) } } public protocol KeyPathTweenable : Tweenable {} extension Tweenable where Self: KeyPathTweenable { public func apply(_ prop: Property) { if let keyPath = prop as? KeyPath, let target = self as? NSObject, target.responds(to:Selector(keyPath.key)) { target.setValue(prop.value.toInterpolatable(), forKey: keyPath.key) } } public func currentProperty(for prop: Property) -> Property? { if prop is KeyPath { if let target = self as? NSObject, let value = target.value(forKey: prop.key) as? Interpolatable { return KeyPath(prop.key, value) } } return nil } } extension UIView : Tweenable { public func apply(_ prop: Property) { if let transform = prop as? Transform { transform.applyTo(self) } else if let value = prop.value.toInterpolatable() as? CGFloat { if prop is X { frame.origin.x = value } else if prop is Y { frame.origin.y = value } else if prop is Alpha { alpha = value } else if let pathProp = prop as? Path { center = pathProp.path.interpolate(value) } } else if let value = prop.value.toInterpolatable() as? CGPoint { if prop is Position { frame.origin = value } else if prop is Center { center = value } else if prop is Shift { frame.origin.x += value.x frame.origin.y += value.y } } else if let value = prop.value.toInterpolatable() as? CGSize { if prop is Size { frame.size = value } } else if let value = prop.value.toInterpolatable() as? UIColor { if prop is BackgroundColor { backgroundColor = value } } } public func currentProperty(for prop: Property) -> Property? { var vectorValue: Property? if prop is X || prop is Y { if prop is X { vectorValue = X(frame.origin.x) } else { vectorValue = Y(frame.origin.y) } } else if prop is Position { vectorValue = Position(frame.origin) } else if prop is Center { vectorValue = Center(center) } else if prop is Shift { vectorValue = Shift(CGPoint.zero) } else if prop is Size { vectorValue = Size(frame.size) } else if prop is Alpha { vectorValue = Alpha(alpha) } else if prop is BackgroundColor { if let color = backgroundColor { vectorValue = BackgroundColor(color) } else { vectorValue = BackgroundColor(UIColor.clear) } } else if prop is Scale { vectorValue = layer.transform.scale() } else if prop is Rotation { vectorValue = layer.transform.rotation() } else if prop is Translation { vectorValue = layer.transform.translation() } else if prop is Path { var start = prop start.value = CGFloat(0.0).vectorize() vectorValue = start } return vectorValue } } extension CALayer : Tweenable { public func apply(_ prop: Property) { // since CALayer has implicit animations when changing its properties, wrap updates in a CATransaction where animations are disabled CATransaction.begin() CATransaction.setDisableActions(true) if let transform = prop as? Transform { transform.applyTo(self) } else if let value = prop.value.toInterpolatable() as? CGFloat { if prop is X { frame.origin.x = value } else if prop is Y { frame.origin.y = value } else if prop is Alpha { opacity = Float(value) } else if prop is BorderWidth { borderWidth = value } else if prop is CornerRadius { cornerRadius = value } else if prop is StrokeStart, let shapeLayer = self as? CAShapeLayer { shapeLayer.strokeStart = value } else if prop is StrokeEnd, let shapeLayer = self as? CAShapeLayer { shapeLayer.strokeEnd = value } else if let pathProp = prop as? Path { position = pathProp.path.interpolate(value) } } else if let value = prop.value.toInterpolatable() as? CGPoint { if prop is Position { frame.origin = value } else if prop is Center { position = value } else if prop is Shift { frame.origin.x += value.x frame.origin.y += value.y } } else if let value = prop.value.toInterpolatable() as? CGSize { if prop is Size { frame.size = value } } else if let value = prop.value.toInterpolatable() as? UIColor { if prop is BackgroundColor { backgroundColor = value.cgColor } else if prop is BorderColor { borderColor = value.cgColor } else if prop is FillColor, let shapeLayer = self as? CAShapeLayer { shapeLayer.fillColor = value.cgColor } else if prop is StrokeColor, let shapeLayer = self as? CAShapeLayer { shapeLayer.strokeColor = value.cgColor } } CATransaction.commit() } public func currentProperty(for prop: Property) -> Property? { var vectorValue: Property? if prop is X || prop is Y { if prop is X { vectorValue = X(frame.origin.x) } else { vectorValue = Y(frame.origin.y) } } else if prop is Position { vectorValue = Position(frame.origin) } else if prop is Center { vectorValue = Center(position) } else if prop is Shift { vectorValue = Shift(CGPoint.zero) } else if prop is Size { vectorValue = Size(frame.size) } else if prop is Alpha { vectorValue = Alpha(CGFloat(opacity)) } else if prop is BackgroundColor { if let color = backgroundColor { vectorValue = BackgroundColor(UIColor(cgColor: color)) } else { vectorValue = BackgroundColor(UIColor.clear) } } else if prop is BorderColor { if let color = borderColor { vectorValue = BorderColor(UIColor(cgColor: color)) } else { vectorValue = BorderColor(UIColor.clear) } } else if prop is FillColor, let shapeLayer = self as? CAShapeLayer { if let color = shapeLayer.fillColor { vectorValue = FillColor(UIColor(cgColor: color)) } else { vectorValue = FillColor(UIColor.clear) } } else if prop is StrokeColor, let shapeLayer = self as? CAShapeLayer { if let color = shapeLayer.strokeColor { vectorValue = StrokeColor(UIColor(cgColor: color)) } else { vectorValue = StrokeColor(UIColor.clear) } } else if prop is StrokeStart, let shapeLayer = self as? CAShapeLayer { vectorValue = StrokeStart(shapeLayer.strokeStart) } else if prop is StrokeEnd, let shapeLayer = self as? CAShapeLayer { vectorValue = StrokeEnd(shapeLayer.strokeEnd) } else if prop is Scale { vectorValue = transform.scale() } else if prop is Rotation { vectorValue = transform.rotation() } else if prop is Translation { vectorValue = transform.translation() } else if prop is Path { var start = prop start.value = CGFloat(0.0).vectorize() vectorValue = start } return vectorValue } } public protocol ViewType { var anchorPoint: CGPoint { get set } var perspective: CGFloat { get set } var antialiasing: Bool { get set } var transform3d: CATransform3D { get set } } extension UIView : ViewType {} extension ViewType where Self: UIView { public var anchorPoint: CGPoint { get { return layer.anchorPoint } set { // adjust the layer's anchorPoint without moving the view // re: https://www.hackingwithswift.com/example-code/calayer/how-to-change-a-views-anchor-point-without-moving-it var newPoint = CGPoint(x: bounds.size.width * newValue.x, y: bounds.size.height * newValue.y) var oldPoint = CGPoint(x: bounds.size.width * layer.anchorPoint.x, y: bounds.size.height * layer.anchorPoint.y); newPoint = newPoint.applying(transform) oldPoint = oldPoint.applying(transform) var position = layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y layer.position = position layer.anchorPoint = newValue } } public var perspective: CGFloat { get { if let superlayer = layer.superlayer { return superlayer.sublayerTransform.m34 } return 0 } set { if let superlayer = layer.superlayer { superlayer.sublayerTransform.m34 = newValue } } } public var antialiasing: Bool { get { return layer.allowsEdgeAntialiasing } set { layer.allowsEdgeAntialiasing = newValue } } public var transform3d: CATransform3D { get { return layer.transform } set { layer.transform = newValue } } } extension CALayer : ViewType {} extension ViewType where Self: CALayer { public var perspective: CGFloat { get { if let superlayer = superlayer { return superlayer.sublayerTransform.m34 } return 0 } set { if let superlayer = superlayer { superlayer.sublayerTransform.m34 = newValue } } } public var antialiasing: Bool { get { return allowsEdgeAntialiasing } set { allowsEdgeAntialiasing = newValue } } public var transform3d: CATransform3D { get { return transform } set { transform = newValue } } } public class TransformContainerView: UIView { public init(view: UIView) { super.init(frame: .zero) self.translatesAutoresizingMaskIntoConstraints = false view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) NSLayoutConstraint.activate([view.topAnchor.constraint(equalTo: self.topAnchor), self.bottomAnchor.constraint(equalTo: view.bottomAnchor), self.leftAnchor.constraint(equalTo: view.leftAnchor), self.rightAnchor.constraint(equalTo: view.rightAnchor)]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0ca36107c05c5da85d1bef687a633c37
25.744505
134
0.683513
3.543866
false
false
false
false
full-of-fire/YJWeibo
YJWeibo/YJWeibo/Classes/Main/Controllers/YJQRCardViewController.swift
1
4271
// // YJQRCardViewController.swift // YJWeibo // // Created by pan on 16/8/22. // Copyright © 2016年 yj. All rights reserved. // import UIKit import SnapKit class YJQRCardViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "我的名片" //添加二维码图片 view.addSubview(QRCardImageView) //生成二维码Image let qrCodeImage = crateQRCodeImage("大杰哥") //显示 QRCardImageView.image = qrCodeImage } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) QRCardImageView.snp_makeConstraints(closure: { (make) in make.size.equalTo(CGSizeMake(200, 200)) make.center.equalTo(self.view) }) } //MARK:生成二维image private func crateQRCodeImage(QRString:String)->UIImage { //1.创建滤镜 let filter = CIFilter(name: "CIQRCodeGenerator") // 设置默认属性 filter?.setDefaults() //设置需要生成二维码的数据 filter?.setValue(QRString.dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage") //从滤镜中取出生成好的图片 let ciImage = filter?.outputImage //将模糊的生成高清的 let bgImage = createNonInterpolatedUIImageFormCIImage(ciImage!, size: 200) //创建一个头像 let iconImage = UIImage(named: "timg.jpg") // 将二维图片和头像合成一张新的图片 let newImage = creteImage(bgImage, iconImage: iconImage!) return newImage } /** 合成图片 :param: bgImage 背景图片 :param: iconImage 头像 */ private func creteImage(bgImage: UIImage, iconImage: UIImage) -> UIImage { // 1.开启图片上下文 UIGraphicsBeginImageContext(bgImage.size) // 2.绘制背景图片 bgImage.drawInRect(CGRect(origin: CGPointZero, size: bgImage.size)) // 3.绘制头像 let width:CGFloat = 50 let height:CGFloat = width let x = (bgImage.size.width - width) * 0.5 let y = (bgImage.size.height - height) * 0.5 iconImage.drawInRect(CGRect(x: x, y: y, width: width, height: height)) // 4.取出绘制号的图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 5.关闭上下文 UIGraphicsEndImageContext() // 6.返回合成号的图片 return newImage } /** 根据CIImage生成指定大小的高清UIImage :param: image 指定CIImage :param: size 指定大小 :returns: 生成好的图片 */ private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage { let extent: CGRect = CGRectIntegral(image.extent) let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent)) // 1.创建bitmap; let width = CGRectGetWidth(extent) * scale let height = CGRectGetHeight(extent) * scale let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()! let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)! let context = CIContext(options: nil) let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent) CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None) CGContextScaleCTM(bitmapRef, scale, scale); CGContextDrawImage(bitmapRef, extent, bitmapImage); // 2.保存bitmap到图片 let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)! return UIImage(CGImage: scaledImage) } //MARK:懒加载 private lazy var QRCardImageView:UIImageView = { let qrImageView = UIImageView() return qrImageView }() }
mit
b8f6d349b4af0441f5e25bff0003a055
24.660131
100
0.578451
4.864932
false
false
false
false
LinDing/Positano
PositanoKit/Persistence/RealmConfig.swift
1
640
// // RealmConfig.swift // Yep // // Created by NIX on 16/5/24. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation import RealmSwift public func realmConfig() -> Realm.Configuration { // 默认将 Realm 放在 App Group 里 let directory: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Config.appGroupID)! let realmFileURL = directory.appendingPathComponent("db.realm") var config = Realm.Configuration() config.fileURL = realmFileURL config.schemaVersion = 34 config.migrationBlock = { migration, oldSchemaVersion in } return config }
mit
888e369326c17aea3130ec56dc93f517
22.148148
116
0.72
4.340278
false
true
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Solutions/Making Design Choices_solutions.playground/Pages/Dogspotting.xcplaygroundpage/Contents.swift
1
505
//I have removed repeated code from the Dogspotting example. var dog = "corgi" var holdingOwnLeashInMouth = true var points = 0 for dogName in ["terrier", "kavkazskaya ovcharka", "labrador", "shiba inu", "corgi"] { if dog == dogName { print("I saw a \(dogName)! +1") points += 1 if holdingOwnLeashInMouth { print("Ronin bonus! +4") points += 4 } } else if dog == "bear" { print("Print that wasn't a dog at all! Nice try.") } }
mit
8ce59817e1a50161bbda1d71414f9e61
27.055556
86
0.574257
3.344371
false
false
false
false
maghov/IS-213
LoginV1/LoginV1/QRGenetatorViewController.swift
1
1823
// // QRGenetatorViewController.swift // QRCodeGenerator // // Created by Gruppe10 on 02.05.2017. // Copyright © 2017 Gruppe10. All rights reserved. // import UIKit class QRGenetatorViewController: UIViewController { @IBOutlet weak var tfInput: UITextField! @IBOutlet weak var imageDisplay: UIImageView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func generateBarcode(_ sender: Any) { imageDisplay.image = generateBarcodeFromString(string: tfInput.text!) } @IBAction func generateQRCode(_ sender: Any) { imageDisplay.image = generateQRCodeFromString(string: tfInput.text!) } func generateBarcodeFromString(string : String) -> UIImage? { let data = string.data(using: String.Encoding.ascii) let filter = CIFilter(name: "CICode128BarcodeGenerator") filter?.setValue(data, forKey : "inputMessage") let transform = CGAffineTransform(scaleX: 10, y: 10) let output = filter?.outputImage?.applying(transform) if(output != nil) { return UIImage(ciImage: output!) } return nil; } func generateQRCodeFromString(string : String) -> UIImage? { let data = string.data(using: String.Encoding.ascii) let filter = CIFilter(name: "CIQRCodeGenerator") filter?.setValue(data, forKey : "inputMessage") let transform = CGAffineTransform(scaleX: 10, y: 10) let output = filter?.outputImage?.applying(transform) if(output != nil) { return UIImage(ciImage: output!) } return nil; } }
mit
e9d1e261924db8787175b6c2bfefbe48
30.413793
77
0.635565
4.612658
false
false
false
false
jopamer/swift
test/stdlib/RuntimeObjC.swift
1
23905
// RUN: %empty-directory(%t) // // RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g // RUN: %target-build-swift -parse-stdlib -Xfrontend -disable-access-control -module-name a -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o %s -o %t.out // RUN: %target-run %t.out // REQUIRES: executable_test // REQUIRES: objc_interop import Swift import StdlibUnittest import Foundation import CoreGraphics import SwiftShims import MirrorObjC var nsObjectCanaryCount = 0 @objc class NSObjectCanary : NSObject { override init() { nsObjectCanaryCount += 1 } deinit { nsObjectCanaryCount -= 1 } } struct NSObjectCanaryStruct { var ref = NSObjectCanary() } var swiftObjectCanaryCount = 0 class SwiftObjectCanary { init() { swiftObjectCanaryCount += 1 } deinit { swiftObjectCanaryCount -= 1 } } struct SwiftObjectCanaryStruct { var ref = SwiftObjectCanary() } @objc class ClassA { init(value: Int) { self.value = value } var value: Int } struct BridgedValueType : _ObjectiveCBridgeable { init(value: Int) { self.value = value } func _bridgeToObjectiveC() -> ClassA { return ClassA(value: value) } static func _forceBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedValueType? ) { assert(x.value % 2 == 0, "not bridged to Objective-C") result = BridgedValueType(value: x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedValueType? ) -> Bool { if x.value % 2 == 0 { result = BridgedValueType(value: x.value) return true } result = nil return false } static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?) -> BridgedValueType { var result: BridgedValueType? _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int var canaryRef = SwiftObjectCanary() } struct BridgedLargeValueType : _ObjectiveCBridgeable { init(value: Int) { value0 = value value1 = value value2 = value value3 = value value4 = value value5 = value value6 = value value7 = value } func _bridgeToObjectiveC() -> ClassA { assert(value == value0) return ClassA(value: value0) } static func _forceBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedLargeValueType? ) { assert(x.value % 2 == 0, "not bridged to Objective-C") result = BridgedLargeValueType(value: x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedLargeValueType? ) -> Bool { if x.value % 2 == 0 { result = BridgedLargeValueType(value: x.value) return true } result = nil return false } static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?) -> BridgedLargeValueType { var result: BridgedLargeValueType? _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int { let x = value0 assert(value0 == x && value1 == x && value2 == x && value3 == x && value4 == x && value5 == x && value6 == x && value7 == x) return x } var (value0, value1, value2, value3): (Int, Int, Int, Int) var (value4, value5, value6, value7): (Int, Int, Int, Int) var canaryRef = SwiftObjectCanary() } class BridgedVerbatimRefType { var value: Int = 42 var canaryRef = SwiftObjectCanary() } func withSwiftObjectCanary<T>( _ createValue: () -> T, _ check: (T) -> Void, file: String = #file, line: UInt = #line ) { let stackTrace = SourceLocStack(SourceLoc(file, line)) swiftObjectCanaryCount = 0 autoreleasepool { var valueWithCanary = createValue() expectEqual(1, swiftObjectCanaryCount, stackTrace: stackTrace) check(valueWithCanary) } expectEqual(0, swiftObjectCanaryCount, stackTrace: stackTrace) } var Runtime = TestSuite("Runtime") func _isClassOrObjCExistential_Opaque<T>(_ x: T.Type) -> Bool { return _isClassOrObjCExistential(_opaqueIdentity(x)) } Runtime.test("_isClassOrObjCExistential") { expectTrue(_isClassOrObjCExistential(NSObjectCanary.self)) expectTrue(_isClassOrObjCExistential_Opaque(NSObjectCanary.self)) expectFalse(_isClassOrObjCExistential(NSObjectCanaryStruct.self)) expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanaryStruct.self)) expectTrue(_isClassOrObjCExistential(SwiftObjectCanary.self)) expectTrue(_isClassOrObjCExistential_Opaque(SwiftObjectCanary.self)) expectFalse(_isClassOrObjCExistential(SwiftObjectCanaryStruct.self)) expectFalse(_isClassOrObjCExistential_Opaque(SwiftObjectCanaryStruct.self)) typealias SwiftClosure = () -> () expectFalse(_isClassOrObjCExistential(SwiftClosure.self)) expectFalse(_isClassOrObjCExistential_Opaque(SwiftClosure.self)) typealias ObjCClosure = @convention(block) () -> () expectTrue(_isClassOrObjCExistential(ObjCClosure.self)) expectTrue(_isClassOrObjCExistential_Opaque(ObjCClosure.self)) expectTrue(_isClassOrObjCExistential(CFArray.self)) expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self)) expectTrue(_isClassOrObjCExistential(CFArray.self)) expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self)) expectTrue(_isClassOrObjCExistential(AnyObject.self)) expectTrue(_isClassOrObjCExistential_Opaque(AnyObject.self)) // AnyClass == AnyObject.Type expectFalse(_isClassOrObjCExistential(AnyClass.self)) expectFalse(_isClassOrObjCExistential_Opaque(AnyClass.self)) expectFalse(_isClassOrObjCExistential(AnyObject.Protocol.self)) expectFalse(_isClassOrObjCExistential_Opaque(AnyObject.Protocol.self)) expectFalse(_isClassOrObjCExistential(NSObjectCanary.Type.self)) expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanary.Type.self)) } Runtime.test("_canBeClass") { expectEqual(1, _canBeClass(NSObjectCanary.self)) expectEqual(0, _canBeClass(NSObjectCanaryStruct.self)) typealias ObjCClosure = @convention(block) () -> () expectEqual(1, _canBeClass(ObjCClosure.self)) expectEqual(1, _canBeClass(CFArray.self)) } Runtime.test("bridgeToObjectiveC") { expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedValueType(value: 42)) as! ClassA).value) expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedLargeValueType(value: 42)) as! ClassA).value) var bridgedVerbatimRef = BridgedVerbatimRefType() expectTrue(_bridgeAnythingToObjectiveC(bridgedVerbatimRef) === bridgedVerbatimRef) } Runtime.test("bridgeToObjectiveC/NoLeak") { withSwiftObjectCanary( { BridgedValueType(value: 42) }, { expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) }) withSwiftObjectCanary( { BridgedLargeValueType(value: 42) }, { expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) }) withSwiftObjectCanary( { BridgedVerbatimRefType() }, { expectTrue(_bridgeAnythingToObjectiveC($0) === $0) }) } Runtime.test("forceBridgeFromObjectiveC") { // Bridge back using BridgedValueType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedValueType.self)) expectEqual(42, _forceBridgeFromObjectiveC( ClassA(value: 42), BridgedValueType.self).value) expectEqual(42, _conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedValueType.self)!.value) expectNil(_conditionallyBridgeFromObjectiveC( BridgedVerbatimRefType(), BridgedValueType.self)) // Bridge back using BridgedLargeValueType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedLargeValueType.self)) expectEqual(42, _forceBridgeFromObjectiveC( ClassA(value: 42), BridgedLargeValueType.self).value) expectEqual(42, _conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedLargeValueType.self)!.value) expectNil(_conditionallyBridgeFromObjectiveC( BridgedVerbatimRefType(), BridgedLargeValueType.self)) // Bridge back using BridgedVerbatimRefType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedVerbatimRefType.self)) expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedVerbatimRefType.self)) var bridgedVerbatimRef = BridgedVerbatimRefType() expectTrue(_forceBridgeFromObjectiveC( bridgedVerbatimRef, BridgedVerbatimRefType.self) === bridgedVerbatimRef) expectTrue(_conditionallyBridgeFromObjectiveC( bridgedVerbatimRef, BridgedVerbatimRefType.self)! === bridgedVerbatimRef) } Runtime.test("isBridgedToObjectiveC") { expectTrue(_isBridgedToObjectiveC(BridgedValueType.self)) expectTrue(_isBridgedToObjectiveC(BridgedVerbatimRefType.self)) } Runtime.test("isBridgedVerbatimToObjectiveC") { expectFalse(_isBridgedVerbatimToObjectiveC(BridgedValueType.self)) expectTrue(_isBridgedVerbatimToObjectiveC(BridgedVerbatimRefType.self)) } //===----------------------------------------------------------------------===// class SomeClass {} @objc class SomeObjCClass {} class SomeNSObjectSubclass : NSObject {} Runtime.test("typeName") { expectEqual("a.SomeObjCClass", _typeName(SomeObjCClass.self)) expectEqual("a.SomeNSObjectSubclass", _typeName(SomeNSObjectSubclass.self)) expectEqual("NSObject", _typeName(NSObject.self)) var a : Any = SomeObjCClass() expectEqual("a.SomeObjCClass", _typeName(type(of: a))) a = SomeNSObjectSubclass() expectEqual("a.SomeNSObjectSubclass", _typeName(type(of: a))) a = NSObject() expectEqual("NSObject", _typeName(type(of: a))) } class GenericClass<T> {} class MultiGenericClass<T, U> {} struct GenericStruct<T> {} enum GenericEnum<T> {} struct PlainStruct {} enum PlainEnum {} protocol ProtocolA {} protocol ProtocolB {} Runtime.test("Generic class ObjC runtime names") { expectEqual("_TtGC1a12GenericClassSi_", NSStringFromClass(GenericClass<Int>.self)) expectEqual("_TtGC1a12GenericClassVS_11PlainStruct_", NSStringFromClass(GenericClass<PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassOS_9PlainEnum_", NSStringFromClass(GenericClass<PlainEnum>.self)) expectEqual("_TtGC1a12GenericClassTVS_11PlainStructOS_9PlainEnumS1___", NSStringFromClass(GenericClass<(PlainStruct, PlainEnum, PlainStruct)>.self)) expectEqual("_TtGC1a12GenericClassMVS_11PlainStruct_", NSStringFromClass(GenericClass<PlainStruct.Type>.self)) expectEqual("_TtGC1a12GenericClassFMVS_11PlainStructS1__", NSStringFromClass(GenericClass<(PlainStruct.Type) -> PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassFzMVS_11PlainStructS1__", NSStringFromClass(GenericClass<(PlainStruct.Type) throws -> PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassFTVS_11PlainStructROS_9PlainEnum_Si_", NSStringFromClass(GenericClass<(PlainStruct, inout PlainEnum) -> Int>.self)) expectEqual("_TtGC1a12GenericClassPS_9ProtocolA__", NSStringFromClass(GenericClass<ProtocolA>.self)) expectEqual("_TtGC1a12GenericClassPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<ProtocolA & ProtocolB>.self)) expectEqual("_TtGC1a12GenericClassPMPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<(ProtocolA & ProtocolB).Type>.self)) expectEqual("_TtGC1a12GenericClassMPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<(ProtocolB & ProtocolA).Protocol>.self)) expectEqual("_TtGC1a12GenericClassaSo10CFArrayRef_", NSStringFromClass(GenericClass<CFArray>.self)) expectEqual("_TtGC1a12GenericClassaSo9NSDecimal_", NSStringFromClass(GenericClass<Decimal>.self)) expectEqual("_TtGC1a12GenericClassCSo8NSObject_", NSStringFromClass(GenericClass<NSObject>.self)) expectEqual("_TtGC1a12GenericClassCSo8NSObject_", NSStringFromClass(GenericClass<NSObject>.self)) expectEqual("_TtGC1a12GenericClassPSo9NSCopying__", NSStringFromClass(GenericClass<NSCopying>.self)) expectEqual("_TtGC1a12GenericClassPSo9NSCopyingS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<ProtocolB & NSCopying & ProtocolA>.self)) expectEqual("_TtGC1a12GenericClassXcCS_9SomeClassS_9ProtocolA__", NSStringFromClass(GenericClass<ProtocolA & SomeClass>.self)) expectEqual("_TtGC1a12GenericClassPS_9ProtocolAs9AnyObject__", NSStringFromClass(GenericClass<ProtocolA & AnyObject>.self)) expectEqual("_TtGC1a12GenericClassPs9AnyObject__", NSStringFromClass(GenericClass<AnyObject>.self)) expectEqual("_TtGC1a17MultiGenericClassGVS_13GenericStructSi_GOS_11GenericEnumGS2_Si___", NSStringFromClass(MultiGenericClass<GenericStruct<Int>, GenericEnum<GenericEnum<Int>>>.self)) } @objc protocol P {} struct AnyObjStruct<T: AnyObject> {} Runtime.test("typeByName") { // Make sure we don't crash if we have foreign classes in the // table -- those don't have NominalTypeDescriptors print(CFArray.self) expectTrue(_typeByName("a.SomeClass") == SomeClass.self) expectTrue(_typeByName("DoesNotExist") == nil) expectTrue(_typeByName("1a12AnyObjStructVyAA1P_pG") == AnyObjStruct<P>.self) } Runtime.test("casting AnyObject to class metatypes") { do { var ao: AnyObject = SomeClass.self expectTrue(ao as? Any.Type == SomeClass.self) expectTrue(ao as? AnyClass == SomeClass.self) expectTrue(ao as? SomeClass.Type == SomeClass.self) } do { var ao : AnyObject = SomeNSObjectSubclass() expectTrue(ao as? Any.Type == nil) expectTrue(ao as? AnyClass == nil) ao = SomeNSObjectSubclass.self expectTrue(ao as? Any.Type == SomeNSObjectSubclass.self) expectTrue(ao as? AnyClass == SomeNSObjectSubclass.self) expectTrue(ao as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self) } do { var a : Any = SomeNSObjectSubclass() expectTrue(a as? Any.Type == nil) expectTrue(a as? AnyClass == nil) } do { var nso: NSObject = SomeNSObjectSubclass() expectTrue(nso as? AnyClass == nil) nso = (SomeNSObjectSubclass.self as AnyObject) as! NSObject expectTrue(nso as? Any.Type == SomeNSObjectSubclass.self) expectTrue(nso as? AnyClass == SomeNSObjectSubclass.self) expectTrue(nso as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self) } } var RuntimeFoundationWrappers = TestSuite("RuntimeFoundationWrappers") RuntimeFoundationWrappers.test("_stdlib_NSObject_isEqual/NoLeak") { nsObjectCanaryCount = 0 autoreleasepool { let a = NSObjectCanary() let b = NSObjectCanary() expectEqual(2, nsObjectCanaryCount) _stdlib_NSObject_isEqual(a, b) } expectEqual(0, nsObjectCanaryCount) } var nsStringCanaryCount = 0 @objc class NSStringCanary : NSString { override init() { nsStringCanaryCount += 1 super.init() } required init(coder: NSCoder) { fatalError("don't call this initializer") } required init(itemProviderData data: Data, typeIdentifier: String) throws { fatalError("don't call this initializer") } deinit { nsStringCanaryCount -= 1 } @objc override var length: Int { return 0 } @objc override func character(at index: Int) -> unichar { fatalError("out-of-bounds access") } } RuntimeFoundationWrappers.test("_stdlib_NSStringLowercaseString/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringLowercaseString(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringUppercaseString/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringUppercaseString(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringCreateCopy/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringCreateCopy(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringGetLength/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringGetLength(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringGetCharactersPtr/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringGetCharactersPtr(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("bridgedNSArray") { var c = [NSObject]() autoreleasepool { let a = [NSObject]() let b = a as NSArray c = b as! [NSObject] } c.append(NSObject()) // expect no crash. } var Reflection = TestSuite("Reflection") class SwiftFooMoreDerivedObjCClass : FooMoreDerivedObjCClass { let first: Int = 123 let second: String = "abc" } Reflection.test("Class/ObjectiveCBase/Default") { do { let value = SwiftFooMoreDerivedObjCClass() var output = "" dump(value, to: &output) let expected = "▿ This is FooObjCClass #0\n" + " - super: FooMoreDerivedObjCClass\n" + " - super: FooDerivedObjCClass\n" + " - super: FooObjCClass\n" + " - super: NSObject\n" + " - first: 123\n" + " - second: \"abc\"\n" expectEqual(expected, output) } } protocol SomeNativeProto {} @objc protocol SomeObjCProto {} extension SomeClass: SomeObjCProto {} Reflection.test("MetatypeMirror") { do { let concreteClassMetatype = SomeClass.self let expectedSomeClass = "- a.SomeClass #0\n" let objcProtocolMetatype: SomeObjCProto.Type = SomeClass.self var output = "" dump(objcProtocolMetatype, to: &output) expectEqual(expectedSomeClass, output) let objcProtocolConcreteMetatype = SomeObjCProto.self let expectedObjCProtocolConcrete = "- a.SomeObjCProto #0\n" output = "" dump(objcProtocolConcreteMetatype, to: &output) expectEqual(expectedObjCProtocolConcrete, output) let compositionConcreteMetatype = (SomeNativeProto & SomeObjCProto).self let expectedComposition = "- a.SomeNativeProto & a.SomeObjCProto #0\n" output = "" dump(compositionConcreteMetatype, to: &output) expectEqual(expectedComposition, output) let objcDefinedProtoType = NSObjectProtocol.self expectEqual(String(describing: objcDefinedProtoType), "NSObject") } } Reflection.test("CGPoint") { var output = "" dump(CGPoint(x: 1.25, y: 2.75), to: &output) let expected = "▿ (1.25, 2.75)\n" + " - x: 1.25\n" + " - y: 2.75\n" expectEqual(expected, output) } Reflection.test("CGSize") { var output = "" dump(CGSize(width: 1.25, height: 2.75), to: &output) let expected = "▿ (1.25, 2.75)\n" + " - width: 1.25\n" + " - height: 2.75\n" expectEqual(expected, output) } Reflection.test("CGRect") { var output = "" dump( CGRect( origin: CGPoint(x: 1.25, y: 2.25), size: CGSize(width: 10.25, height: 11.75)), to: &output) let expected = "▿ (1.25, 2.25, 10.25, 11.75)\n" + " ▿ origin: (1.25, 2.25)\n" + " - x: 1.25\n" + " - y: 2.25\n" + " ▿ size: (10.25, 11.75)\n" + " - width: 10.25\n" + " - height: 11.75\n" expectEqual(expected, output) } Reflection.test("Unmanaged/nil") { var output = "" var optionalURL: Unmanaged<CFURL>? dump(optionalURL, to: &output) let expected = "- nil\n" expectEqual(expected, output) } Reflection.test("Unmanaged/not-nil") { var output = "" var optionalURL: Unmanaged<CFURL>? = Unmanaged.passRetained(CFURLCreateWithString(nil, "http://llvm.org/" as CFString, nil)) dump(optionalURL, to: &output) let expected = "▿ Optional(Swift.Unmanaged<__C.CFURLRef>(_value: http://llvm.org/))\n" + " ▿ some: Swift.Unmanaged<__C.CFURLRef>\n" + " - _value: http://llvm.org/ #0\n" + " - super: NSObject\n" expectEqual(expected, output) optionalURL!.release() } Reflection.test("TupleMirror/NoLeak") { do { nsObjectCanaryCount = 0 autoreleasepool { var tuple = (1, NSObjectCanary()) expectEqual(1, nsObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, nsObjectCanaryCount) } do { nsObjectCanaryCount = 0 autoreleasepool { var tuple = (1, NSObjectCanaryStruct()) expectEqual(1, nsObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, nsObjectCanaryCount) } do { swiftObjectCanaryCount = 0 autoreleasepool { var tuple = (1, SwiftObjectCanary()) expectEqual(1, swiftObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, swiftObjectCanaryCount) } do { swiftObjectCanaryCount = 0 autoreleasepool { var tuple = (1, SwiftObjectCanaryStruct()) expectEqual(1, swiftObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, swiftObjectCanaryCount) } } @objc @objcMembers class TestArtificialSubclass: NSObject { dynamic var foo = "foo" } var KVOHandle = 0 Reflection.test("Name of metatype of artificial subclass") { let obj = TestArtificialSubclass() expectEqual("\(type(of: obj))", "TestArtificialSubclass") expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass") expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass") // Trigger the creation of a KVO subclass for TestArtificialSubclass. obj.addObserver(obj, forKeyPath: "foo", options: [.new], context: &KVOHandle) expectEqual("\(type(of: obj))", "TestArtificialSubclass") expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass") expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass") obj.removeObserver(obj, forKeyPath: "foo") expectEqual("\(type(of: obj))", "TestArtificialSubclass") expectEqual(String(describing: type(of: obj)), "TestArtificialSubclass") expectEqual(String(reflecting: type(of: obj)), "a.TestArtificialSubclass") } @objc class StringConvertibleInDebugAndOtherwise : NSObject { override var description: String { return "description" } override var debugDescription: String { return "debugDescription" } } Reflection.test("NSObject is properly CustomDebugStringConvertible") { let object = StringConvertibleInDebugAndOtherwise() expectEqual(String(reflecting: object), object.debugDescription) } Reflection.test("NSRange QuickLook") { let rng = NSRange(location:Int.min, length:5) let ql = PlaygroundQuickLook(reflecting: rng) switch ql { case .range(let loc, let len): expectEqual(loc, Int64(Int.min)) expectEqual(len, 5) default: expectUnreachable("PlaygroundQuickLook for NSRange did not match Range") } } class SomeSubclass : SomeClass {} var ObjCConformsToProtocolTestSuite = TestSuite("ObjCConformsToProtocol") ObjCConformsToProtocolTestSuite.test("cast/instance") { expectTrue(SomeClass() is SomeObjCProto) expectTrue(SomeSubclass() is SomeObjCProto) } ObjCConformsToProtocolTestSuite.test("cast/metatype") { expectTrue(SomeClass.self is SomeObjCProto.Type) expectTrue(SomeSubclass.self is SomeObjCProto.Type) } // SR-7357 extension Optional where Wrapped == NSData { private class Inner { } var asInner: Inner { return Inner() } } var RuntimeClassNamesTestSuite = TestSuite("runtime class names") RuntimeClassNamesTestSuite.test("private class nested in same-type-constrained extension") { let base: NSData? = nil let util = base.asInner let clas = unsafeBitCast(type(of: util), to: NSObject.self) // Name should look like _TtC1aP.*Inner let desc = clas.description expectEqual(desc.prefix(7), "_TtC1aP") expectEqual(desc.suffix(5), "Inner") } runAllTests()
apache-2.0
937b13b529629ab67bec027e8ec2435e
29.31599
149
0.711373
4.432096
false
true
false
false
Huralnyk/rxswift
Networking/Networking/ViewController.swift
1
1750
// // ViewController.swift // Networking // // Created by Scott Gardner on 6/9/16. // Copyright © 2016 Scott Gardner. All rights reserved. // import UIKit import RxSwift import RxCocoa class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let searchController = UISearchController(searchResultsController: nil) var searchBar: UISearchBar { return searchController.searchBar } var viewModel = ViewModel() let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() configureSearchController() viewModel.data .drive(tableView.rx.items(cellIdentifier: "Cell")) { _, repository, cell in cell.textLabel?.text = repository.name cell.detailTextLabel?.text = repository.url } .addDisposableTo(disposeBag) searchBar.rx.text.orEmpty .bind(to: viewModel.searchText) .addDisposableTo(disposeBag) searchBar.rx.cancelButtonClicked .map { "" } .bind(to: viewModel.searchText) .addDisposableTo(disposeBag) viewModel.data.asDriver() .map { "\($0.count) Repositories"} .drive(navigationItem.rx.title) .addDisposableTo(disposeBag) } func configureSearchController() { searchController.obscuresBackgroundDuringPresentation = false searchBar.showsCancelButton = true searchBar.text = "scotteg" searchBar.placeholder = "Enter GitHub ID, e.g., \"scotteg\"" tableView.tableHeaderView = searchController.searchBar definesPresentationContext = true } }
mit
02d2b2f244bc846b254733a070195a47
29.155172
87
0.626072
5.332317
false
false
false
false
VirgilSecurity/virgil-crypto-ios
Source/KeyPairType+String.swift
1
4139
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import VirgilCryptoFoundation // MARK: - String representation extension extension KeyPairType { // Raw value of this enum equals to enum case name itself internal enum KeyPairTypeStr: String { case ed25519 case curve25519 case secp256r1 case rsa2048 case rsa4096 case rsa8192 case curve25519Round5 case curve25519Round5Ed25519Falcon case curve25519Ed25519 } /// Initializer key pair type from string representation /// - Parameter stringRepresentation: string representation /// - Throws: VirgilCryptoError.unknownKeyType if key type is unknown public init(from stringRepresentation: String) throws { switch stringRepresentation { case KeyPairTypeStr.ed25519.rawValue: self = .ed25519 case KeyPairTypeStr.curve25519.rawValue: self = .curve25519 case KeyPairTypeStr.secp256r1.rawValue: self = .secp256r1 case KeyPairTypeStr.rsa2048.rawValue: self = .rsa2048 case KeyPairTypeStr.rsa4096.rawValue: self = .rsa4096 case KeyPairTypeStr.rsa8192.rawValue: self = .rsa8192 case KeyPairTypeStr.curve25519Round5.rawValue: self = .curve25519Round5 case KeyPairTypeStr.curve25519Round5Ed25519Falcon.rawValue: self = .curve25519Round5Ed25519Falcon case KeyPairTypeStr.curve25519Ed25519.rawValue: self = .curve25519Ed25519 default: throw VirgilCryptoError.unknownKeyType } } /// Returns string representation for key type public func getStringRepresentation() -> String { switch self { case .ed25519: return KeyPairTypeStr.ed25519.rawValue case .curve25519: return KeyPairTypeStr.curve25519.rawValue case .secp256r1: return KeyPairTypeStr.secp256r1.rawValue case .rsa2048: return KeyPairTypeStr.rsa2048.rawValue case .rsa4096: return KeyPairTypeStr.rsa4096.rawValue case .rsa8192: return KeyPairTypeStr.rsa8192.rawValue case .curve25519Round5: return KeyPairTypeStr.curve25519Round5.rawValue case .curve25519Round5Ed25519Falcon: return KeyPairTypeStr.curve25519Round5Ed25519Falcon.rawValue case .curve25519Ed25519: return KeyPairTypeStr.curve25519Ed25519.rawValue } } }
bsd-3-clause
0393ee4b5d3d226a4020c412ac8e3dfb
38.04717
76
0.694854
4.640135
false
false
false
false
carabina/ActionSwift3
ActionSwift3/com/actionswift/events/TouchEvent.swift
1
635
// // TouchEvent.swift // ActionSwiftSK // // Created by Craig on 6/05/2015. // Copyright (c) 2015 Interactive Coconut. All rights reserved. // import UIKit /** All interactive event types */ public enum InteractiveEventType:String { case TouchBegin = "TouchBegin" case TouchEnd = "TouchEnd" case TouchMove = "TouchMove" } /** A custom Event class, with information about touches. */ public class TouchEvent: Event { public var touches:[Touch] public init(_ type:InteractiveEventType,_ touches:[Touch],_ bubbles:Bool = true) { self.touches = touches super.init(type.rawValue, bubbles) } }
mit
147012834f5b75b32b91dd875625a366
21.678571
86
0.685039
3.757396
false
false
false
false
urbanthings/urbanthings-sdk-apple
UrbanThingsAPI/Public/Request/RealtimeResourceStatusRequest.swift
1
1573
// // RealtimeResourceStatusRequest.swift // UrbanThingsAPI // // Created by Mark Woollard on 08/05/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation /// Defines a resource status request for a single resource public protocol RealtimeResourceStatusRequest: GetRequest { associatedtype Result = ResourceStatus /// Stop Id of the resource that status is being requested for. var stopID: String { get } } /// Default implementation of `RealtimeResourceStatusRequest` protocol provided by the API as standard means /// of passing parameters to API request methods. You may provide your own implementation if needed to pass to the API /// request methods. public struct UTRealtimeResourceStatusRequest: RealtimeResourceStatusRequest { public typealias Result = ResourceStatus public typealias Parser = (_ json: Any?, _ logger: Logger) throws -> Result public let endpoint = "rti/resources/status" /// Stop Id of the resource that status is being requested for. public let stopID: String /// Parser to use when processing response to the request public let parser: Parser /// Initialize instance of `UTRealtimeResourceStatusRequest`. /// /// - parameters: /// - stopID: The stop ID to request status for. /// - parser: Optional custom parser to process the response from the server. If omitted standard parser will be used. public init(stopID: String, parser: @escaping Parser = urbanThingsParser) { self.parser = parser self.stopID = stopID } }
apache-2.0
67b65c51a0ba68e7a4bce83a1c4d6f46
34.727273
124
0.725827
4.763636
false
false
false
false
tjw/swift
test/Migrator/Inputs/Cities.swift
1
2320
open class Cities { var x: Int public init(x: Int) { self.x = x } public init!(y: Int) { self.x = y } open func mooloolaba(x: Cities, y: Cities?) {} open func toowoomba(x: [Cities], y: [Cities]?) {} open func mareeba(x: [String : Cities?], y: [String : Cities]?) {} open func yandina(x: [[String : Cities]]!) {} open func buderim() -> Cities? { return Cities(x: 1) } open func noosa() -> [[String : Cities]?] { return [] } open func maroochy(x: Int?, y: Int?) {} public struct CityKind { public static let Town = 1 } } public protocol ExtraCities { func coolum(x: [String : [Int : [(((String))?)]]]) func blibli(x: (String?, String) -> String!) func currimundi(x: (Int, (Int, Int))!) } public protocol MoreCities { func setZooLocation(x: Int, y: Int, z: Int) func addZooAt(_ x: Int, y: Int, z: Int) } public func setCityProperty1(_ c : Cities, _ p : Int) {} public func globalCityFunc() {} public func setCityProperty2(_ c : Cities, _ p : Int, _ q: Int) {} public func globalCityFunc2(_ c : Cities) {} public func globalCityFunc3(_ c : Cities, _ p : Int) -> Int { return 0 } public func globalCityFunc4(_ c : Cities, _ p : Int, _ q: Int) -> Int { return 0 } public func globalCityFunc5() -> Int { return 0 } public func globalCityPointerTaker(_ c : UnsafePointer<Cities>, _ p : Int, _ q: Int) -> Int { return 0 } public class Container { public var Value: String = "" public var attrDict: [String: Any] = [:] public var attrArr: [String] = [] public var optionalAttrDict: [String: Any]? = nil public func addingAttributes(_ input: [String: Any]) {} public func adding(attributes: [String: Any]) {} public func adding(optionalAttributes: [String: Any]?) {} public init(optionalAttributes: [String: Any]?) {} public func adding(attrArray: [String]) {} public init(optionalAttrArray: [String]?) {} public func add(single: String) {} public func add(singleOptional: String?) {} public func getAttrArray() -> [String] { return [] } public func getOptionalAttrArray() -> [String]? { return [] } public func getAttrDictionary() -> [String: Any] { return [:] } public func getOptionalAttrDictionary() -> [String: Any]? { return nil } public func getSingleAttr() -> String { return "" } public func getOptionalSingleAttr() -> String? { return nil } }
apache-2.0
e2ad5ee2ad79b1a1967d57a17723b77c
40.428571
104
0.644397
3.396779
false
false
false
false
welcone/SwiftSamples
NestedTpye/NestedTpye/NestedTypeInAction/BlackJackedCard.swift
1
1101
// // BlackJackedCard.swift // NestedTpye // // Created by welcone on 2017/10/17. // Copyright © 2017年 WelCone. All rights reserved. // import Foundation struct BlackJackedCard { let rank: Rank , suit: Suit var description: String { var output = "Suit is \(suit.rawValue)" output += "Value is\(rank.values.first)" if let second = rank.values.second{ output += "or \(second)" } return output } // nested suite enumeration enum Suit: Character { case spades = "♠" case hearts = "♡" case diamonds = "♢" case clubs = "♣" } // nested Rank enumeration enum Rank:Int { case two = 2 ,three, four ,five ,six ,seven, eight,nine,ten case jack, queen, king, ace var values :Values{ switch self { case .ace: return Values(first: 1, second: 11) case .jack,.queen,.king: return Values(first: 10, second: nil) default: return Values(first: self.rawValue, second: nil) } } struct Values { let first: Int , second: Int? } } }
apache-2.0
b3228e2428b73f18ad4af232fac06de9
18.818182
63
0.578899
3.59736
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Welcome/Views/OnboardingPage.swift
1
2375
// Copyright DApps Platform Inc. All rights reserved. import UIKit final class OnboardingPage: UICollectionViewCell { static let identifier = "Page" let style = OnboardingPageStyle() private var imageView: UIImageView! private var titleLabel: UILabel! private var subtitleLabel: UILabel! override var reuseIdentifier: String? { return OnboardingPage.identifier } var model = OnboardingPageViewModel() { didSet { imageView.image = model.image titleLabel.text = model.title subtitleLabel.text = model.subtitle } } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit addSubview(imageView) titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.textAlignment = .center titleLabel.textColor = style.titleColor titleLabel.font = style.titleFont addSubview(titleLabel) subtitleLabel = UILabel() subtitleLabel.translatesAutoresizingMaskIntoConstraints = false subtitleLabel.textAlignment = .center subtitleLabel.textColor = style.subtitleColor subtitleLabel.numberOfLines = 2 subtitleLabel.font = style.subtitleFont addSubview(subtitleLabel) let stackView = UIStackView(arrangedSubviews: [ imageView, titleLabel, subtitleLabel, ]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.alignment = .center stackView.spacing = 15 addSubview(stackView) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -60), stackView.centerXAnchor.constraint(equalTo: centerXAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor), imageView.heightAnchor.constraint(equalToConstant: 240), ]) } }
gpl-3.0
ea766007c8d8159cc4f75a12201bd41d
30.666667
86
0.661895
5.967337
false
false
false
false
shajrawi/swift
stdlib/public/Darwin/Foundation/Data.swift
1
127501
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) import Glibc @inlinable // This is @inlinable as trivially computable. fileprivate func malloc_good_size(_ size: Int) -> Int { return size } #endif import CoreFoundation internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { munmap(mem, length) } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } internal func __NSDataIsCompact(_ data: NSData) -> Bool { return data._isCompact() } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims internal func __NSDataIsCompact(_ data: NSData) -> Bool { if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { return data._isCompact() } else { var compact = true let len = data.length data.enumerateBytes { (_, byteRange, stop) in if byteRange.length != len { compact = false } stop.pointee = true } return compact } } #endif // Underlying storage representation for medium and large data. // Inlinability strategy: methods from here should not inline into InlineSlice or LargeSlice unless trivial. // NOTE: older overlays called this class _DataStorage. The two must // coexist without a conflicting ObjC class name, so it was renamed. // The old name must not be used in the new runtime. @usableFromInline internal final class __DataStorage { @usableFromInline static let maxSize = Int.max >> 1 @usableFromInline static let vmOpsThreshold = NSPageSize() * 4 @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer. static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if __DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } @inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer. static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } @usableFromInline var _bytes: UnsafeMutableRawPointer? @usableFromInline var _length: Int @usableFromInline var _capacity: Int @usableFromInline var _needToZero: Bool @usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? @usableFromInline var _offset: Int @inlinable // This is @inlinable as trivially computable. var bytes: UnsafeRawPointer? { return UnsafeRawPointer(_bytes)?.advanced(by: -_offset) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding. @discardableResult func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding. @discardableResult func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))) } @inlinable // This is @inlinable as trivially computable. var mutableBytes: UnsafeMutableRawPointer? { return _bytes?.advanced(by: -_offset) } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return _capacity } @inlinable // This is @inlinable as trivially computable. var length: Int { get { return _length } set { setLength(newValue) } } @inlinable // This is inlinable as trivially computable. var isExternallyOwned: Bool { // all __DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation // anything with 0 capacity means that we have not allocated this pointer and concequently mutation is not ours to make. return _capacity == 0 } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func ensureUniqueBufferReference(growingTo newLength: Int = 0, clear: Bool = false) { guard isExternallyOwned || newLength > _capacity else { return } if newLength == 0 { if isExternallyOwned { let newCapacity = malloc_good_size(_length) let newBytes = __DataStorage.allocate(newCapacity, false) __DataStorage.move(newBytes!, _bytes!, _length) _freeBytes() _bytes = newBytes _capacity = newCapacity _needToZero = false } } else if isExternallyOwned { let newCapacity = malloc_good_size(newLength) let newBytes = __DataStorage.allocate(newCapacity, clear) if let bytes = _bytes { __DataStorage.move(newBytes!, bytes, _length) } _freeBytes() _bytes = newBytes _capacity = newCapacity _length = newLength _needToZero = true } else { let cap = _capacity var additionalCapacity = (newLength >> (__DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = malloc_good_size(Swift.max(cap, newLength + additionalCapacity)) let origLength = _length var allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = __DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && __DataStorage.shouldAllocateCleared(newLength) newBytes = __DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = malloc_good_size(newLength) allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = __DataStorage.allocate(newCapacity, true) if let newBytes = newBytes { __DataStorage.move(newBytes, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } _deallocator = nil } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stopv: Bool = false block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.upperBound - range.lowerBound, _length)), 0, &stopv) } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func setLength(_ length: Int) { let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { ensureUniqueBufferReference(growingTo: newLength, clear: true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength } @inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer. func append(_ bytes: UnsafeRawPointer, length: Int) { precondition(length >= 0, "Length of appending bytes must not be negative") let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { ensureUniqueBufferReference(growingTo: newLength, clear: false) } _length = newLength __DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) } @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed. func get(_ index: Int) -> UInt8 { return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func set(_ index: Int, to value: UInt8) { ensureUniqueBufferReference() _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { let offsetPointer = UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)) UnsafeMutableRawBufferPointer(start: pointer, count: range.upperBound - range.lowerBound).copyMemory(from: offsetPointer) } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let range = NSRange(location: range_.location - _offset, length: range_.length) let currentLength = _length let resultingLength = currentLength - range.length + replacementLength let shift = resultingLength - currentLength let mutableBytes: UnsafeMutableRawPointer if resultingLength > currentLength { ensureUniqueBufferReference(growingTo: resultingLength) _length = resultingLength } else { ensureUniqueBufferReference() } mutableBytes = _bytes! /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes + start + replacementLength, mutableBytes + start + length, currentLength - start - length) } if replacementLength != 0 { if let replacementBytes = replacementBytes { memmove(mutableBytes + start, replacementBytes, replacementLength) } else { memset(mutableBytes + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func resetBytes(in range_: Range<Int>) { let range = NSRange(location: range_.lowerBound - _offset, length: range_.upperBound - range_.lowerBound) if range.length == 0 { return } if _length < range.location + range.length { let newLength = range.location + range.length if _capacity <= newLength { ensureUniqueBufferReference(growingTo: newLength, clear: false) } _length = newLength } else { ensureUniqueBufferReference() } memset(_bytes!.advanced(by: range.location), 0, range.length) } @usableFromInline // This is not @inlinable as a non-trivial, non-convenience initializer. init(length: Int) { precondition(length < __DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = __DataStorage.shouldAllocateCleared(length) _bytes = __DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 _offset = 0 setLength(length) } @usableFromInline // This is not @inlinable as a non-convience initializer. init(capacity capacity_: Int = 0) { var capacity = capacity_ precondition(capacity < __DataStorage.maxSize) if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _offset = 0 } @usableFromInline // This is not @inlinable as a non-convience initializer. init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < __DataStorage.maxSize) _offset = 0 if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if __DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = __DataStorage.allocate(length, false)! __DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true __DataStorage.move(_bytes!, bytes, length) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) { precondition(length < __DataStorage.maxSize) _offset = offset if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if __DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = __DataStorage.allocate(length, false)! __DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if __DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = __DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true __DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(immutableReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _deallocator = { _, _ in _fixLifetime(immutableReference) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(mutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _deallocator = { _, _ in _fixLifetime(mutableReference) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(customReference: NSData, offset: Int) { _offset = offset _bytes = UnsafeMutableRawPointer(mutating: customReference.bytes) _capacity = 0 _needToZero = false _length = customReference.length _deallocator = { _, _ in _fixLifetime(customReference) } } @usableFromInline // This is not @inlinable as a non-convience initializer. init(customMutableReference: NSMutableData, offset: Int) { _offset = offset _bytes = customMutableReference.mutableBytes _capacity = 0 _needToZero = false _length = customMutableReference.length _deallocator = { _, _ in _fixLifetime(customMutableReference) } } deinit { _freeBytes() } @inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed. func mutableCopy(_ range: Range<Int>) -> __DataStorage { return __DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound) } @inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially computed. func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { if range.isEmpty { return try work(NSData()) // zero length data can be optimized as a singleton } return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, freeWhenDone: false)) } @inline(never) // This is not @inlinable to avoid emission of the private `__NSSwiftData` class name into clients. @usableFromInline func bridgedReference(_ range: Range<Int>) -> NSData { if range.isEmpty { return NSData() // zero length data can be optimized as a singleton } return __NSSwiftData(backing: self, range: range) } } // NOTE: older overlays called this _NSSwiftData. The two must // coexist, so it was renamed. The old name must not be used in the new // runtime. internal class __NSSwiftData : NSData { var _backing: __DataStorage! var _range: Range<Data.Index>! convenience init(backing: __DataStorage, range: Range<Data.Index>) { self.init() _backing = backing _range = range } @objc override var length: Int { return _range.upperBound - _range.lowerBound } @objc override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. guard let bytes = _backing.bytes else { return UnsafeRawPointer(bitPattern: 0xBAD0)! } return bytes.advanced(by: _range.lowerBound) } @objc override func copy(with zone: NSZone? = nil) -> Any { return self } @objc override func mutableCopy(with zone: NSZone? = nil) -> Any { return NSMutableData(bytes: bytes, length: length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc override func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } @_fixed_layout public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection, MutableDataProtocol, ContiguousBytes { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = Range<Int> // A small inline buffer of bytes suitable for stack-allocation of small data. // Inlinability strategy: everything here should be inlined for direct operation on the stack wherever possible. @usableFromInline @_fixed_layout internal struct InlineData { #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum @usableFromInline var bytes: Buffer #elseif arch(i386) || arch(arm) @usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum @usableFromInline var bytes: Buffer #endif @usableFromInline var length: UInt8 @inlinable // This is @inlinable as trivially computable. static func canStore(count: Int) -> Bool { return count <= MemoryLayout<Buffer>.size } @inlinable // This is @inlinable as a convenience initializer. init(_ srcBuffer: UnsafeRawBufferPointer) { self.init(count: srcBuffer.count) if !srcBuffer.isEmpty { Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in dstBuffer.baseAddress?.copyMemory(from: srcBuffer.baseAddress!, byteCount: srcBuffer.count) } } } @inlinable // This is @inlinable as a trivial initializer. init(count: Int = 0) { assert(count <= MemoryLayout<Buffer>.size) #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)) #elseif arch(i386) || arch(arm) bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)) #endif length = UInt8(count) } @inlinable // This is @inlinable as a convenience initializer. init(_ slice: InlineSlice, count: Int) { self.init(count: count) Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in slice.withUnsafeBytes { srcBuffer in dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count)) } } } @inlinable // This is @inlinable as a convenience initializer. init(_ slice: LargeSlice, count: Int) { self.init(count: count) Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in slice.withUnsafeBytes { srcBuffer in dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count)) } } } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return MemoryLayout<Buffer>.size } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return Int(length) } set(newValue) { assert(newValue <= MemoryLayout<Buffer>.size) length = UInt8(newValue) } } @inlinable // This is @inlinable as trivially computable. var startIndex: Int { return 0 } @inlinable // This is @inlinable as trivially computable. var endIndex: Int { return count } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { let count = Int(length) return try Swift.withUnsafeBytes(of: bytes) { (rawBuffer) throws -> Result in return try apply(UnsafeRawBufferPointer(start: rawBuffer.baseAddress, count: count)) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { let count = Int(length) return try Swift.withUnsafeMutableBytes(of: &bytes) { (rawBuffer) throws -> Result in return try apply(UnsafeMutableRawBufferPointer(start: rawBuffer.baseAddress, count: count)) } } @inlinable // This is @inlinable as tribially computable. mutating func append(byte: UInt8) { let count = self.count assert(count + 1 <= MemoryLayout<Buffer>.size) Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte } self.length += 1 } @inlinable // This is @inlinable as trivially computable. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { guard !buffer.isEmpty else { return } assert(count + buffer.count <= MemoryLayout<Buffer>.size) let cnt = count _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in rawBuffer.baseAddress?.advanced(by: cnt).copyMemory(from: buffer.baseAddress!, byteCount: buffer.count) } length += UInt8(buffer.count) } @inlinable // This is @inlinable as trivially computable. subscript(index: Index) -> UInt8 { get { assert(index <= MemoryLayout<Buffer>.size) precondition(index < length, "index \(index) is out of bounds of 0..<\(length)") return Swift.withUnsafeBytes(of: bytes) { rawBuffer -> UInt8 in return rawBuffer[index] } } set(newValue) { assert(index <= MemoryLayout<Buffer>.size) precondition(index < length, "index \(index) is out of bounds of 0..<\(length)") Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in rawBuffer[index] = newValue } } } @inlinable // This is @inlinable as trivially computable. mutating func resetBytes(in range: Range<Index>) { assert(range.lowerBound <= MemoryLayout<Buffer>.size) assert(range.upperBound <= MemoryLayout<Buffer>.size) precondition(range.lowerBound <= length, "index \(range.lowerBound) is out of bounds of 0..<\(length)") if count < range.upperBound { count = range.upperBound } let _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in memset(rawBuffer.baseAddress?.advanced(by: range.lowerBound), 0, range.upperBound - range.lowerBound) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func replaceSubrange(_ subrange: Range<Index>, with replacementBytes: UnsafeRawPointer?, count replacementLength: Int) { assert(subrange.lowerBound <= MemoryLayout<Buffer>.size) assert(subrange.upperBound <= MemoryLayout<Buffer>.size) assert(count - (subrange.upperBound - subrange.lowerBound) + replacementLength <= MemoryLayout<Buffer>.size) precondition(subrange.lowerBound <= length, "index \(subrange.lowerBound) is out of bounds of 0..<\(length)") precondition(subrange.upperBound <= length, "index \(subrange.upperBound) is out of bounds of 0..<\(length)") let currentLength = count let resultingLength = currentLength - (subrange.upperBound - subrange.lowerBound) + replacementLength let shift = resultingLength - currentLength Swift.withUnsafeMutableBytes(of: &bytes) { mutableBytes in /* shift the trailing bytes */ let start = subrange.lowerBound let length = subrange.upperBound - subrange.lowerBound if shift != 0 { memmove(mutableBytes.baseAddress?.advanced(by: start + replacementLength), mutableBytes.baseAddress?.advanced(by: start + length), currentLength - start - length) } if replacementLength != 0 { memmove(mutableBytes.baseAddress?.advanced(by: start), replacementBytes!, replacementLength) } } count = resultingLength } @inlinable // This is @inlinable as trivially computable. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") Swift.withUnsafeBytes(of: bytes) { let cnt = Swift.min($0.count, range.upperBound - range.lowerBound) guard cnt > 0 else { return } pointer.copyMemory(from: $0.baseAddress!.advanced(by: range.lowerBound), byteCount: cnt) } } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { // **NOTE**: this uses `count` (an Int) and NOT `length` (a UInt8) // Despite having the same value, they hash differently. InlineSlice and LargeSlice both use `count` (an Int); if you combine the same bytes but with `length` over `count`, you can get a different hash. // // This affects slices, which are InlineSlice and not InlineData: // // let d = Data([0xFF, 0xFF]) // InlineData // let s = Data([0, 0xFF, 0xFF]).dropFirst() // InlineSlice // assert(s == d) // assert(s.hashValue == d.hashValue) hasher.combine(count) Swift.withUnsafeBytes(of: bytes) { // We have access to the full byte buffer here, but not all of it is meaningfully used (bytes past self.length may be garbage). let bytes = UnsafeRawBufferPointer(start: $0.baseAddress, count: self.count) hasher.combine(bytes: bytes) } } } #if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le) @usableFromInline internal typealias HalfInt = Int32 #elseif arch(i386) || arch(arm) @usableFromInline internal typealias HalfInt = Int16 #endif // A buffer of bytes too large to fit in an InlineData, but still small enough to fit a storage pointer + range in two words. // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here. @usableFromInline @_fixed_layout internal struct InlineSlice { // ***WARNING*** // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last @usableFromInline var slice: Range<HalfInt> @usableFromInline var storage: __DataStorage @inlinable // This is @inlinable as trivially computable. static func canStore(count: Int) -> Bool { return count < HalfInt.max } @inlinable // This is @inlinable as a convenience initializer. init(_ buffer: UnsafeRawBufferPointer) { assert(buffer.count < HalfInt.max) self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count) } @inlinable // This is @inlinable as a convenience initializer. init(capacity: Int) { assert(capacity < HalfInt.max) self.init(__DataStorage(capacity: capacity), count: 0) } @inlinable // This is @inlinable as a convenience initializer. init(count: Int) { assert(count < HalfInt.max) self.init(__DataStorage(length: count), count: count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData) { assert(inline.count < HalfInt.max) self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range) } @inlinable // This is @inlinable as a convenience initializer. init(_ large: LargeSlice) { assert(large.range.lowerBound < HalfInt.max) assert(large.range.upperBound < HalfInt.max) self.init(large.storage, range: large.range) } @inlinable // This is @inlinable as a convenience initializer. init(_ large: LargeSlice, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.init(large.storage, range: range) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { assert(count < HalfInt.max) self.storage = storage slice = 0..<HalfInt(count) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, range: Range<Int>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) self.storage = storage slice = HalfInt(range.lowerBound)..<HalfInt(range.upperBound) } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func ensureUniqueReference() { if !isKnownUniquelyReferenced(&storage) { storage = storage.mutableCopy(self.range) } } @inlinable // This is @inlinable as trivially computable. var startIndex: Int { return Int(slice.lowerBound) } @inlinable // This is @inlinable as trivially computable. var endIndex: Int { return Int(slice.upperBound) } @inlinable // This is @inlinable as trivially computable. var capacity: Int { return storage.capacity } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func reserveCapacity(_ minimumCapacity: Int) { ensureUniqueReference() // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count)) } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return Int(slice.upperBound - slice.lowerBound) } set(newValue) { assert(newValue < HalfInt.max) ensureUniqueReference() storage.length = newValue slice = slice.lowerBound..<(slice.lowerBound + HalfInt(newValue)) } } @inlinable // This is @inlinable as trivially computable. var range: Range<Int> { get { return Int(slice.lowerBound)..<Int(slice.upperBound) } set(newValue) { assert(newValue.lowerBound < HalfInt.max) assert(newValue.upperBound < HalfInt.max) slice = HalfInt(newValue.lowerBound)..<HalfInt(newValue.upperBound) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try storage.withUnsafeBytes(in: range, apply: apply) } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { ensureUniqueReference() return try storage.withUnsafeMutableBytes(in: range, apply: apply) } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { assert(endIndex + buffer.count < HalfInt.max) ensureUniqueReference() storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count) slice = slice.lowerBound..<HalfInt(Int(slice.upperBound) + buffer.count) } @inlinable // This is @inlinable as reasonably small. subscript(index: Index) -> UInt8 { get { assert(index < HalfInt.max) precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") return storage.get(index) } set(newValue) { assert(index < HalfInt.max) precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.set(index, to: newValue) } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { return storage.bridgedReference(self.range) } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Index>) { assert(range.lowerBound < HalfInt.max) assert(range.upperBound < HalfInt.max) precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.resetBytes(in: range) if slice.upperBound < range.upperBound { slice = slice.lowerBound..<HalfInt(range.upperBound) } } @inlinable // This is @inlinable as reasonably small. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) ensureUniqueReference() let upper = range.upperBound storage.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt slice = slice.lowerBound..<HalfInt(resultingUpper) } @inlinable // This is @inlinable as reasonably small. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") storage.copyBytes(to: pointer, from: range) } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { hasher.combine(count) // At most, hash the first 80 bytes of this data. let range = startIndex ..< Swift.min(startIndex + 80, endIndex) storage.withUnsafeBytes(in: range) { hasher.combine(bytes: $0) } } } // A reference wrapper around a Range<Int> for when the range of a data buffer is too large to whole in a single word. // Inlinability strategy: everything should be inlinable as trivial. @usableFromInline @_fixed_layout internal final class RangeReference { @usableFromInline var range: Range<Int> @inlinable @inline(__always) // This is @inlinable as trivially forwarding. var lowerBound: Int { return range.lowerBound } @inlinable @inline(__always) // This is @inlinable as trivially forwarding. var upperBound: Int { return range.upperBound } @inlinable @inline(__always) // This is @inlinable as trivially computable. var count: Int { return range.upperBound - range.lowerBound } @inlinable @inline(__always) // This is @inlinable as a trivial initializer. init(_ range: Range<Int>) { self.range = range } } // A buffer of bytes whose range is too large to fit in a signle word. Used alongside a RangeReference to make it fit into _Representation's two-word size. // Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here. @usableFromInline @_fixed_layout internal struct LargeSlice { // ***WARNING*** // These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last @usableFromInline var slice: RangeReference @usableFromInline var storage: __DataStorage @inlinable // This is @inlinable as a convenience initializer. init(_ buffer: UnsafeRawBufferPointer) { self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count) } @inlinable // This is @inlinable as a convenience initializer. init(capacity: Int) { self.init(__DataStorage(capacity: capacity), count: 0) } @inlinable // This is @inlinable as a convenience initializer. init(count: Int) { self.init(__DataStorage(length: count), count: count) } @inlinable // This is @inlinable as a convenience initializer. init(_ inline: InlineData) { let storage = inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) } self.init(storage, count: inline.count) } @inlinable // This is @inlinable as a trivial initializer. init(_ slice: InlineSlice) { self.storage = slice.storage self.slice = RangeReference(slice.range) } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { self.storage = storage self.slice = RangeReference(0..<count) } @inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic). mutating func ensureUniqueReference() { if !isKnownUniquelyReferenced(&storage) { storage = storage.mutableCopy(range) } if !isKnownUniquelyReferenced(&slice) { slice = RangeReference(range) } } @inlinable // This is @inlinable as trivially forwarding. var startIndex: Int { return slice.range.lowerBound } @inlinable // This is @inlinable as trivially forwarding. var endIndex: Int { return slice.range.upperBound } @inlinable // This is @inlinable as trivially forwarding. var capacity: Int { return storage.capacity } @inlinable // This is @inlinable as trivially computable. mutating func reserveCapacity(_ minimumCapacity: Int) { ensureUniqueReference() // the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count)) } @inlinable // This is @inlinable as trivially computable. var count: Int { get { return slice.count } set(newValue) { ensureUniqueReference() storage.length = newValue slice.range = slice.range.lowerBound..<(slice.range.lowerBound + newValue) } } @inlinable // This is @inlinable as it is trivially forwarding. var range: Range<Int> { return slice.range } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { return try storage.withUnsafeBytes(in: range, apply: apply) } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { ensureUniqueReference() return try storage.withUnsafeMutableBytes(in: range, apply: apply) } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { ensureUniqueReference() storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count) slice.range = slice.range.lowerBound..<slice.range.upperBound + buffer.count } @inlinable // This is @inlinable as trivially computable. subscript(index: Index) -> UInt8 { get { precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") return storage.get(index) } set(newValue) { precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.set(index, to: newValue) } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { return storage.bridgedReference(self.range) } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Int>) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") ensureUniqueReference() storage.resetBytes(in: range) if slice.range.upperBound < range.upperBound { slice.range = slice.range.lowerBound..<range.upperBound } } @inlinable // This is @inlinable as reasonably small. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound) ensureUniqueReference() let upper = range.upperBound storage.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingUpper = upper - nsRange.length + cnt slice.range = slice.range.lowerBound..<resultingUpper } @inlinable // This is @inlinable as reasonably small. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)") storage.copyBytes(to: pointer, from: range) } @inline(__always) // This should always be inlined into _Representation.hash(into:). func hash(into hasher: inout Hasher) { hasher.combine(count) // Hash at most the first 80 bytes of this data. let range = startIndex ..< Swift.min(startIndex + 80, endIndex) storage.withUnsafeBytes(in: range) { hasher.combine(bytes: $0) } } } // The actual storage for Data's various representations. // Inlinability strategy: almost everything should be inlinable as forwarding the underlying implementations. (Inlining can also help avoid retain-release traffic around pulling values out of enums.) @usableFromInline @_frozen internal enum _Representation { case empty case inline(InlineData) case slice(InlineSlice) case large(LargeSlice) @inlinable // This is @inlinable as a trivial initializer. init(_ buffer: UnsafeRawBufferPointer) { if buffer.isEmpty { self = .empty } else if InlineData.canStore(count: buffer.count) { self = .inline(InlineData(buffer)) } else if InlineSlice.canStore(count: buffer.count) { self = .slice(InlineSlice(buffer)) } else { self = .large(LargeSlice(buffer)) } } @inlinable // This is @inlinable as a trivial initializer. init(_ buffer: UnsafeRawBufferPointer, owner: AnyObject) { if buffer.isEmpty { self = .empty } else if InlineData.canStore(count: buffer.count) { self = .inline(InlineData(buffer)) } else { let count = buffer.count let storage = __DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: count, copy: false, deallocator: { _, _ in _fixLifetime(owner) }, offset: 0) if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(storage, count: count)) } else { self = .large(LargeSlice(storage, count: count)) } } } @inlinable // This is @inlinable as a trivial initializer. init(capacity: Int) { if capacity == 0 { self = .empty } else if InlineData.canStore(count: capacity) { self = .inline(InlineData()) } else if InlineSlice.canStore(count: capacity) { self = .slice(InlineSlice(capacity: capacity)) } else { self = .large(LargeSlice(capacity: capacity)) } } @inlinable // This is @inlinable as a trivial initializer. init(count: Int) { if count == 0 { self = .empty } else if InlineData.canStore(count: count) { self = .inline(InlineData(count: count)) } else if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(count: count)) } else { self = .large(LargeSlice(count: count)) } } @inlinable // This is @inlinable as a trivial initializer. init(_ storage: __DataStorage, count: Int) { if count == 0 { self = .empty } else if InlineData.canStore(count: count) { self = .inline(storage.withUnsafeBytes(in: 0..<count) { InlineData($0) }) } else if InlineSlice.canStore(count: count) { self = .slice(InlineSlice(storage, count: count)) } else { self = .large(LargeSlice(storage, count: count)) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func reserveCapacity(_ minimumCapacity: Int) { guard minimumCapacity > 0 else { return } switch self { case .empty: if InlineData.canStore(count: minimumCapacity) { self = .inline(InlineData()) } else if InlineSlice.canStore(count: minimumCapacity) { self = .slice(InlineSlice(capacity: minimumCapacity)) } else { self = .large(LargeSlice(capacity: minimumCapacity)) } case .inline(let inline): guard minimumCapacity > inline.capacity else { return } // we know we are going to be heap promoted if InlineSlice.canStore(count: minimumCapacity) { var slice = InlineSlice(inline) slice.reserveCapacity(minimumCapacity) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.reserveCapacity(minimumCapacity) self = .large(slice) } case .slice(var slice): guard minimumCapacity > slice.capacity else { return } if InlineSlice.canStore(count: minimumCapacity) { self = .empty slice.reserveCapacity(minimumCapacity) self = .slice(slice) } else { var large = LargeSlice(slice) large.reserveCapacity(minimumCapacity) self = .large(large) } case .large(var slice): guard minimumCapacity > slice.capacity else { return } self = .empty slice.reserveCapacity(minimumCapacity) self = .large(slice) } } @inlinable // This is @inlinable as reasonably small. var count: Int { get { switch self { case .empty: return 0 case .inline(let inline): return inline.count case .slice(let slice): return slice.count case .large(let slice): return slice.count } } set(newValue) { // HACK: The definition of this inline function takes an inout reference to self, giving the optimizer a unique referencing guarantee. // This allows us to avoid excessive retain-release traffic around modifying enum values, and inlining the function then avoids the additional frame. @inline(__always) func apply(_ representation: inout _Representation, _ newValue: Int) -> _Representation? { switch representation { case .empty: if newValue == 0 { return nil } else if InlineData.canStore(count: newValue) { return .inline(InlineData()) } else if InlineSlice.canStore(count: newValue) { return .slice(InlineSlice(count: newValue)) } else { return .large(LargeSlice(count: newValue)) } case .inline(var inline): if newValue == 0 { return .empty } else if InlineData.canStore(count: newValue) { guard inline.count != newValue else { return nil } inline.count = newValue return .inline(inline) } else if InlineSlice.canStore(count: newValue) { var slice = InlineSlice(inline) slice.count = newValue return .slice(slice) } else { var slice = LargeSlice(inline) slice.count = newValue return .large(slice) } case .slice(var slice): if newValue == 0 && slice.startIndex == 0 { return .empty } else if slice.startIndex == 0 && InlineData.canStore(count: newValue) { return .inline(InlineData(slice, count: newValue)) } else if InlineSlice.canStore(count: newValue + slice.startIndex) { guard slice.count != newValue else { return nil } representation = .empty // TODO: remove this when mgottesman lands optimizations slice.count = newValue return .slice(slice) } else { var newSlice = LargeSlice(slice) newSlice.count = newValue return .large(newSlice) } case .large(var slice): if newValue == 0 && slice.startIndex == 0 { return .empty } else if slice.startIndex == 0 && InlineData.canStore(count: newValue) { return .inline(InlineData(slice, count: newValue)) } else { guard slice.count != newValue else { return nil} representation = .empty // TODO: remove this when mgottesman lands optimizations slice.count = newValue return .large(slice) } } } if let rep = apply(&self, newValue) { self = rep } } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result { switch self { case .empty: let empty = InlineData() return try empty.withUnsafeBytes(apply) case .inline(let inline): return try inline.withUnsafeBytes(apply) case .slice(let slice): return try slice.withUnsafeBytes(apply) case .large(let slice): return try slice.withUnsafeBytes(apply) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result { switch self { case .empty: var empty = InlineData() return try empty.withUnsafeMutableBytes(apply) case .inline(var inline): defer { self = .inline(inline) } return try inline.withUnsafeMutableBytes(apply) case .slice(var slice): self = .empty defer { self = .slice(slice) } return try slice.withUnsafeMutableBytes(apply) case .large(var slice): self = .empty defer { self = .large(slice) } return try slice.withUnsafeMutableBytes(apply) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. func withInteriorPointerReference<T>(_ work: (NSData) throws -> T) rethrows -> T { switch self { case .empty: return try work(NSData()) case .inline(let inline): return try inline.withUnsafeBytes { return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress ?? UnsafeRawPointer(bitPattern: 0xBAD0)!), length: $0.count, freeWhenDone: false)) } case .slice(let slice): return try slice.storage.withInteriorPointerReference(slice.range, work) case .large(let slice): return try slice.storage.withInteriorPointerReference(slice.range, work) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { switch self { case .empty: var stop = false block(UnsafeBufferPointer<UInt8>(start: nil, count: 0), 0, &stop) case .inline(let inline): inline.withUnsafeBytes { var stop = false block(UnsafeBufferPointer<UInt8>(start: $0.baseAddress?.assumingMemoryBound(to: UInt8.self), count: $0.count), 0, &stop) } case .slice(let slice): slice.storage.enumerateBytes(in: slice.range, block) case .large(let slice): slice.storage.enumerateBytes(in: slice.range, block) } } @inlinable // This is @inlinable as reasonably small. mutating func append(contentsOf buffer: UnsafeRawBufferPointer) { switch self { case .empty: self = _Representation(buffer) case .inline(var inline): if InlineData.canStore(count: inline.count + buffer.count) { inline.append(contentsOf: buffer) self = .inline(inline) } else if InlineSlice.canStore(count: inline.count + buffer.count) { var newSlice = InlineSlice(inline) newSlice.append(contentsOf: buffer) self = .slice(newSlice) } else { var newSlice = LargeSlice(inline) newSlice.append(contentsOf: buffer) self = .large(newSlice) } case .slice(var slice): if InlineSlice.canStore(count: slice.range.upperBound + buffer.count) { self = .empty defer { self = .slice(slice) } slice.append(contentsOf: buffer) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.append(contentsOf: buffer) self = .large(newSlice) } case .large(var slice): self = .empty defer { self = .large(slice) } slice.append(contentsOf: buffer) } } @inlinable // This is @inlinable as reasonably small. mutating func resetBytes(in range: Range<Index>) { switch self { case .empty: if range.upperBound == 0 { self = .empty } else if InlineData.canStore(count: range.upperBound) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .inline(InlineData(count: range.upperBound)) } else if InlineSlice.canStore(count: range.upperBound) { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .slice(InlineSlice(count: range.upperBound)) } else { precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)") self = .large(LargeSlice(count: range.upperBound)) } case .inline(var inline): if inline.count < range.upperBound { if InlineSlice.canStore(count: range.upperBound) { var slice = InlineSlice(inline) slice.resetBytes(in: range) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.resetBytes(in: range) self = .large(slice) } } else { inline.resetBytes(in: range) self = .inline(inline) } case .slice(var slice): if InlineSlice.canStore(count: range.upperBound) { self = .empty slice.resetBytes(in: range) self = .slice(slice) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.resetBytes(in: range) self = .large(newSlice) } case .large(var slice): self = .empty slice.resetBytes(in: range) self = .large(slice) } } @usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function. mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) { switch self { case .empty: precondition(subrange.lowerBound == 0 && subrange.upperBound == 0, "range \(subrange) out of bounds of 0..<0") if cnt == 0 { return } else if InlineData.canStore(count: cnt) { self = .inline(InlineData(UnsafeRawBufferPointer(start: bytes, count: cnt))) } else if InlineSlice.canStore(count: cnt) { self = .slice(InlineSlice(UnsafeRawBufferPointer(start: bytes, count: cnt))) } else { self = .large(LargeSlice(UnsafeRawBufferPointer(start: bytes, count: cnt))) } case .inline(var inline): let resultingCount = inline.count + cnt - (subrange.upperBound - subrange.lowerBound) if resultingCount == 0 { self = .empty } else if InlineData.canStore(count: resultingCount) { inline.replaceSubrange(subrange, with: bytes, count: cnt) self = .inline(inline) } else if InlineSlice.canStore(count: resultingCount) { var slice = InlineSlice(inline) slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(slice) } else { var slice = LargeSlice(inline) slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(slice) } case .slice(var slice): let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound) if slice.startIndex == 0 && resultingUpper == 0 { self = .empty } else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .inline(InlineData(slice, count: slice.count)) } else if InlineSlice.canStore(count: resultingUpper) { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(slice) } else { self = .empty var newSlice = LargeSlice(slice) newSlice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(newSlice) } case .large(var slice): let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound) if slice.startIndex == 0 && resultingUpper == 0 { self = .empty } else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) { var inline = InlineData(count: resultingUpper) inline.withUnsafeMutableBytes { inlineBuffer in if cnt > 0 { inlineBuffer.baseAddress?.advanced(by: subrange.lowerBound).copyMemory(from: bytes!, byteCount: cnt) } slice.withUnsafeBytes { buffer in if subrange.lowerBound > 0 { inlineBuffer.baseAddress?.copyMemory(from: buffer.baseAddress!, byteCount: subrange.lowerBound) } if subrange.upperBound < resultingUpper { inlineBuffer.baseAddress?.advanced(by: subrange.upperBound).copyMemory(from: buffer.baseAddress!.advanced(by: subrange.upperBound), byteCount: resultingUpper - subrange.upperBound) } } } self = .inline(inline) } else if InlineSlice.canStore(count: slice.startIndex) && InlineSlice.canStore(count: resultingUpper) { self = .empty var newSlice = InlineSlice(slice) newSlice.replaceSubrange(subrange, with: bytes, count: cnt) self = .slice(newSlice) } else { self = .empty slice.replaceSubrange(subrange, with: bytes, count: cnt) self = .large(slice) } } } @inlinable // This is @inlinable as trivially forwarding. subscript(index: Index) -> UInt8 { get { switch self { case .empty: preconditionFailure("index \(index) out of range of 0") case .inline(let inline): return inline[index] case .slice(let slice): return slice[index] case .large(let slice): return slice[index] } } set(newValue) { switch self { case .empty: preconditionFailure("index \(index) out of range of 0") case .inline(var inline): inline[index] = newValue self = .inline(inline) case .slice(var slice): self = .empty slice[index] = newValue self = .slice(slice) case .large(var slice): self = .empty slice[index] = newValue self = .large(slice) } } } @inlinable // This is @inlinable as reasonably small. subscript(bounds: Range<Index>) -> Data { get { switch self { case .empty: precondition(bounds.lowerBound == 0 && (bounds.upperBound - bounds.lowerBound) == 0, "Range \(bounds) out of bounds 0..<0") return Data() case .inline(let inline): precondition(bounds.upperBound <= inline.count, "Range \(bounds) out of bounds 0..<\(inline.count)") if bounds.lowerBound == 0 { var newInline = inline newInline.count = bounds.upperBound return Data(representation: .inline(newInline)) } else { return Data(representation: .slice(InlineSlice(inline, range: bounds))) } case .slice(let slice): precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") if bounds.lowerBound == 0 && bounds.upperBound == 0 { return Data() } else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.count) { return Data(representation: .inline(InlineData(slice, count: bounds.count))) } else { var newSlice = slice newSlice.range = bounds return Data(representation: .slice(newSlice)) } case .large(let slice): precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)") precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)") if bounds.lowerBound == 0 && bounds.upperBound == 0 { return Data() } else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.upperBound) { return Data(representation: .inline(InlineData(slice, count: bounds.upperBound))) } else if InlineSlice.canStore(count: bounds.lowerBound) && InlineSlice.canStore(count: bounds.upperBound) { return Data(representation: .slice(InlineSlice(slice, range: bounds))) } else { var newSlice = slice newSlice.slice = RangeReference(bounds) return Data(representation: .large(newSlice)) } } } } @inlinable // This is @inlinable as trivially forwarding. var startIndex: Int { switch self { case .empty: return 0 case .inline: return 0 case .slice(let slice): return slice.startIndex case .large(let slice): return slice.startIndex } } @inlinable // This is @inlinable as trivially forwarding. var endIndex: Int { switch self { case .empty: return 0 case .inline(let inline): return inline.count case .slice(let slice): return slice.endIndex case .large(let slice): return slice.endIndex } } @inlinable // This is @inlinable as trivially forwarding. func bridgedReference() -> NSData { switch self { case .empty: return NSData() case .inline(let inline): return inline.withUnsafeBytes { return NSData(bytes: $0.baseAddress, length: $0.count) } case .slice(let slice): return slice.bridgedReference() case .large(let slice): return slice.bridgedReference() } } @inlinable // This is @inlinable as trivially forwarding. func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { switch self { case .empty: precondition(range.lowerBound == 0 && range.upperBound == 0, "Range \(range) out of bounds 0..<0") return case .inline(let inline): inline.copyBytes(to: pointer, from: range) case .slice(let slice): slice.copyBytes(to: pointer, from: range) case .large(let slice): slice.copyBytes(to: pointer, from: range) } } @inline(__always) // This should always be inlined into Data.hash(into:). func hash(into hasher: inout Hasher) { switch self { case .empty: hasher.combine(0) case .inline(let inline): inline.hash(into: &hasher) case .slice(let slice): slice.hash(into: &hasher) case .large(let large): large.hash(into: &hasher) } } } @usableFromInline internal var _representation: _Representation // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) @usableFromInline internal var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return b } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return b } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. @inlinable // This is @inlinable as a trivial initializer. public init(bytes: UnsafeRawPointer, count: Int) { _representation = _Representation(UnsafeRawBufferPointer(start: bytes, count: count)) } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a trivial, generic initializer. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { _representation = _Representation(UnsafeRawBufferPointer(buffer)) } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a trivial, generic initializer. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { _representation = _Representation(UnsafeRawBufferPointer(buffer)) } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue @inlinable // This is @inlinable as a convenience initializer. public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) -> Void in memset(buffer.baseAddress, Int32(repeatedValue), buffer.count) } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. @inlinable // This is @inlinable as a trivial initializer. public init(capacity: Int) { _representation = _Representation(capacity: capacity) } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. @inlinable // This is @inlinable as a trivial initializer. public init(count: Int) { _representation = _Representation(count: count) } /// Initialize an empty `Data`. @inlinable // This is @inlinable as a trivial initializer. public init() { _representation = .empty } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. @inlinable // This is @inlinable as a trivial initializer. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator if count == 0 { deallocator._deallocator(bytes, count) _representation = .empty } else { _representation = _Representation(__DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0), count: count) } } /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. @inlinable // This is @inlinable as a convenience initializer. public init(contentsOf url: __shared URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) self.init(referencing: d) } /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. @inlinable // This is @inlinable as a convenience initializer. public init?(base64Encoded base64String: __shared String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { self.init(referencing: d) } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. @inlinable // This is @inlinable as a convenience initializer. public init?(base64Encoded base64Data: __shared Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { self.init(referencing: d) } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: __shared NSData) { // This is not marked as inline because _providesConcreteBacking would need to be marked as usable from inline however that is a dynamic lookup in objc contexts. let length = reference.length if length == 0 { _representation = .empty } else { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _representation = _Representation(__DataStorage(immutableReference: reference.copy() as! NSData, offset: 0), count: length) } else { _representation = _Representation(__DataStorage(customReference: reference.copy() as! NSData, offset: 0), count: length) } } } // slightly faster paths for common sequences @inlinable // This is @inlinable as an important generic funnel point, despite being a non-trivial initializer. public init<S: Sequence>(_ elements: S) where S.Element == UInt8 { // If the sequence is already contiguous, access the underlying raw memory directly. if let contiguous = elements as? ContiguousBytes { _representation = contiguous.withUnsafeBytes { return _Representation($0) } return } // The sequence might still be able to provide direct access to typed memory. // NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences. let representation = elements.withContiguousStorageIfAvailable { return _Representation(UnsafeRawBufferPointer($0)) } if let representation = representation { _representation = representation } else { // Dummy assignment so we can capture below. _representation = _Representation(capacity: 0) // Copy as much as we can in one shot from the sequence. let underestimatedCount = Swift.max(elements.underestimatedCount, 1) _withStackOrHeapBuffer(underestimatedCount) { (buffer) in // In order to copy from the sequence, we have to bind the buffer to UInt8. // This is safe since we'll copy out of this buffer as raw memory later. let capacity = buffer.pointee.capacity let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) // Copy the contents of buffer... _representation = _Representation(UnsafeRawBufferPointer(start: base, count: endIndex)) // ... and append the rest byte-wise, buffering through an InlineData. var buffer = InlineData() while let element = iter.next() { buffer.append(byte: element) if buffer.count == buffer.capacity { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them. if buffer.count > 0 { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } } } @available(swift, introduced: 4.2) @available(swift, deprecated: 5, message: "use `init(_:)` instead") public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 { self.init(elements) } @available(swift, obsoleted: 4.2) public init(bytes: Array<UInt8>) { self.init(bytes) } @available(swift, obsoleted: 4.2) public init(bytes: ArraySlice<UInt8>) { self.init(bytes) } @inlinable // This is @inlinable as a trivial initializer. internal init(representation: _Representation) { _representation = representation } // ----------------------------------- // MARK: - Properties and Functions @inlinable // This is @inlinable as trivially forwarding. public mutating func reserveCapacity(_ minimumCapacity: Int) { _representation.reserveCapacity(minimumCapacity) } /// The number of bytes in the data. @inlinable // This is @inlinable as trivially forwarding. public var count: Int { get { return _representation.count } set(newValue) { precondition(newValue >= 0, "count must not be negative") _representation.count = newValue } } @inlinable // This is @inlinable as trivially computable. public var regions: CollectionOfOne<Data> { return CollectionOfOne(self) } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @available(swift, deprecated: 5, message: "use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead") public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeBytes { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeBytes(body) } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @available(swift, deprecated: 5, message: "use `withUnsafeMutableBytes<R>(_: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead") public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeMutableBytes { return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func withUnsafeMutableBytes<ResultType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ResultType) rethrows -> ResultType { return try _representation.withUnsafeMutableBytes(body) } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. @inlinable // This is @inlinable as trivially forwarding. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { precondition(count >= 0, "count of bytes to copy must not be negative") if count == 0 { return } _copyBytesHelper(to: UnsafeMutableRawPointer(pointer), from: startIndex..<(startIndex + count)) } @inlinable // This is @inlinable as trivially forwarding. internal func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) { if range.isEmpty { return } _representation.copyBytes(to: pointer, from: range) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. @inlinable // This is @inlinable as trivially forwarding. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: range) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. @inlinable // This is @inlinable as generic and reasonably small. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.upperBound - r.lowerBound)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } guard !copyRange.isEmpty else { return 0 } _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.upperBound - copyRange.lowerBound } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(macOS) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { // this should not be marked as inline since in objc contexts we correct atomicity via _shouldUseNonAtomicWriteReimplementation try _representation.withInteriorPointerReference { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url, options, &error) else { throw error! } } else { try $0.write(to: url, options: options) } #endif } } // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound) } else { nsRange = NSRange(location: 0, length: count) } let result = _representation.withInteriorPointerReference { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return (result.location + startIndex)..<((result.location + startIndex) + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. @available(swift, deprecated: 5, message: "use `regions` or `for-in` instead") public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _representation.enumerateBytes(block) } @inlinable // This is @inlinable as a generic, trivially forwarding function. internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.isEmpty { return } _representation.append(contentsOf: UnsafeRawBufferPointer(buffer)) } @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } _append(UnsafeBufferPointer(start: bytes, count: count)) } public mutating func append(_ other: Data) { guard !other.isEmpty else { return } other.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in _representation.append(contentsOf: buffer) } } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { _append(buffer) } @inlinable // This is @inlinable as trivially forwarding. public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in _append(buffer) } } @inlinable // This is @inlinable as an important generic funnel point, despite being non-trivial. public mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Element { // If the sequence is already contiguous, access the underlying raw memory directly. if let contiguous = elements as? ContiguousBytes { contiguous.withUnsafeBytes { _representation.append(contentsOf: $0) } return } // The sequence might still be able to provide direct access to typed memory. // NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences. var appended = false elements.withContiguousStorageIfAvailable { _representation.append(contentsOf: UnsafeRawBufferPointer($0)) appended = true } guard !appended else { return } // The sequence is really not contiguous. // Copy as much as we can in one shot. let underestimatedCount = Swift.max(elements.underestimatedCount, 1) _withStackOrHeapBuffer(underestimatedCount) { (buffer) in // In order to copy from the sequence, we have to bind the temporary buffer to `UInt8`. // This is safe since we're the only owners of the buffer and we copy out as raw memory below anyway. let capacity = buffer.pointee.capacity let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity) var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity)) // Copy the contents of the buffer... _representation.append(contentsOf: UnsafeRawBufferPointer(start: base, count: endIndex)) // ... and append the rest byte-wise, buffering through an InlineData. var buffer = InlineData() while let element = iter.next() { buffer.append(byte: element) if buffer.count == buffer.capacity { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } // If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them. if buffer.count > 0 { buffer.withUnsafeBytes { _representation.append(contentsOf: $0) } buffer.count = 0 } } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. @inlinable // This is @inlinable as trivially forwarding. public mutating func resetBytes(in range: Range<Index>) { // it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth) precondition(range.lowerBound >= 0, "Ranges must not be negative bounds") precondition(range.upperBound >= 0, "Ranges must not be negative bounds") _representation.resetBytes(in: range) } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. @inlinable // This is @inlinable as trivially forwarding. public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in _representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count) } } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. @inlinable // This is @inlinable as a generic, trivially forwarding function. public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { guard !buffer.isEmpty else { return } replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. @inlinable // This is @inlinable as generic and reasonably small. public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { let totalCount = Int(newElements.count) _withStackOrHeapBuffer(totalCount) { conditionalBuffer in let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount) var (iterator, index) = newElements._copyContents(initializing: buffer) while let byte = iterator.next() { buffer[index] = byte index = buffer.index(after: index) } replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount) } } @inlinable // This is @inlinable as trivially forwarding. public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { _representation.replaceSubrange(subrange, with: bytes, count: cnt) } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: Range<Index>) -> Data { if isEmpty || range.upperBound - range.lowerBound == 0 { return Data() } let slice = self[range] return slice.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> Data in return Data(bytes: buffer.baseAddress!, count: buffer.count) } } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. @inlinable // This is @inlinable as trivially forwarding. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { return _representation.withInteriorPointerReference { return $0.base64EncodedString(options: options) } } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. @inlinable // This is @inlinable as trivially forwarding. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { return _representation.withInteriorPointerReference { return $0.base64EncodedData(options: options) } } // MARK: - // /// The hash value for the data. @inline(never) // This is not inlinable as emission into clients could cause cross-module inconsistencies if they are not all recompiled together. public func hash(into hasher: inout Hasher) { _representation.hash(into: &hasher) } public func advanced(by amount: Int) -> Data { let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Data in return Data(bytes: ptr.baseAddress!.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. @inlinable // This is @inlinable as trivially forwarding. public subscript(index: Index) -> UInt8 { get { return _representation[index] } set(newValue) { _representation[index] = newValue } } @inlinable // This is @inlinable as trivially forwarding. public subscript(bounds: Range<Index>) -> Data { get { return _representation[bounds] } set { replaceSubrange(bounds, with: newValue) } } @inlinable // This is @inlinable as a generic, trivially forwarding function. public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data where R.Bound: FixedWidthInteger { get { let lower = R.Bound(startIndex) let upper = R.Bound(endIndex) let range = rangeExpression.relative(to: lower..<upper) let start = Int(range.lowerBound) let end = Int(range.upperBound) let r: Range<Int> = start..<end return _representation[r] } set { let lower = R.Bound(startIndex) let upper = R.Bound(endIndex) let range = rangeExpression.relative(to: lower..<upper) let start = Int(range.lowerBound) let end = Int(range.upperBound) let r: Range<Int> = start..<end replaceSubrange(r, with: newValue) } } /// The start `Index` in the data. @inlinable // This is @inlinable as trivially forwarding. public var startIndex: Index { get { return _representation.startIndex } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. @inlinable // This is @inlinable as trivially forwarding. public var endIndex: Index { get { return _representation.endIndex } } @inlinable // This is @inlinable as trivially computable. public func index(before i: Index) -> Index { return i - 1 } @inlinable // This is @inlinable as trivially computable. public func index(after i: Index) -> Index { return i + 1 } @inlinable // This is @inlinable as trivially computable. public var indices: Range<Int> { get { return startIndex..<endIndex } } @inlinable // This is @inlinable as a fast-path for emitting into generic Sequence usages. public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) { guard !isEmpty else { return (makeIterator(), buffer.startIndex) } let cnt = Swift.min(count, buffer.count) withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in _ = memcpy(UnsafeMutableRawPointer(buffer.baseAddress), bytes.baseAddress, cnt) } return (Iterator(self, at: startIndex + cnt), buffer.index(buffer.startIndex, offsetBy: cnt)) } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. @inlinable // This is @inlinable as trivially computable. public func makeIterator() -> Data.Iterator { return Iterator(self, at: startIndex) } public struct Iterator : IteratorProtocol { @usableFromInline internal typealias Buffer = ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) @usableFromInline internal let _data: Data @usableFromInline internal var _buffer: Buffer @usableFromInline internal var _idx: Data.Index @usableFromInline internal let _endIdx: Data.Index @usableFromInline // This is @usableFromInline as a non-trivial initializer. internal init(_ data: Data, at loc: Data.Index) { // The let vars prevent this from being marked as @inlinable _data = data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = loc _endIdx = data.endIndex let bufferSize = MemoryLayout<Buffer>.size Swift.withUnsafeMutableBytes(of: &_buffer) { let ptr = $0.bindMemory(to: UInt8.self) let bufferIdx = (loc - data.startIndex) % bufferSize data.copyBytes(to: ptr, from: (loc - bufferIdx)..<(data.endIndex - (loc - bufferIdx) > bufferSize ? (loc - bufferIdx) + bufferSize : data.endIndex)) } } public mutating func next() -> UInt8? { let idx = _idx let bufferSize = MemoryLayout<Buffer>.size guard idx < _endIdx else { return nil } _idx += 1 let bufferIdx = (idx - _data.startIndex) % bufferSize if bufferIdx == 0 { var buffer = _buffer Swift.withUnsafeMutableBytes(of: &buffer) { let ptr = $0.bindMemory(to: UInt8.self) // populate the buffer _data.copyBytes(to: ptr, from: idx..<(_endIdx - idx > bufferSize ? idx + bufferSize : _endIdx)) } _buffer = buffer } return Swift.withUnsafeMutableBytes(of: &_buffer) { let ptr = $0.bindMemory(to: UInt8.self) return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. @inlinable // This is @inlinable as emission into clients is safe -- the concept of equality on Data will not change. public static func ==(d1 : Data, d2 : Data) -> Bool { let length1 = d1.count if length1 != d2.count { return false } if length1 > 0 { return d1.withUnsafeBytes { (b1: UnsafeRawBufferPointer) in return d2.withUnsafeBytes { (b2: UnsafeRawBufferPointer) in return memcmp(b1.baseAddress!, b2.baseAddress!, b2.count) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafeRawBufferPointer) in children.append((label: "pointer", value: bytes.baseAddress!)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)]))) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. extension Data : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _representation.bridgedReference() } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } // @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { guard let src = source else { return Data() } return Data(referencing: src) } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } } extension Data : Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() // It's more efficient to pre-allocate the buffer if we can. if let count = container.count { self.init(count: count) // Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space. // We don't want to write past the end of what we allocated. for i in 0 ..< count { let byte = try container.decode(UInt8.self) self[i] = byte } } else { self.init() } while !container.isAtEnd { var byte = try container.decode(UInt8.self) self.append(&byte, count: 1) } } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in try container.encode(contentsOf: buffer) } } }
apache-2.0
f7488a234a02baeec1a82590c8b352ac
44.389462
352
0.593848
5.126618
false
false
false
false
cyanzhong/xTextHandler
xFormat/xFormat.swift
1
2227
// // ██╗ ██╗████████╗███████╗██╗ ██╗████████╗ // ╚██╗██╔╝╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝ // ╚███╔╝ ██║ █████╗ ╚███╔╝ ██║ // ██╔██╗ ██║ ██╔══╝ ██╔██╗ ██║ // ██╔╝ ██╗ ██║ ███████╗██╔╝ ██╗ ██║ // ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ // // xFormat.swift // xTextHandler (https://github.com/cyanzhong/xTextHandler/) // // Created by cyan on 16/7/4. // Copyright © 2016年 cyan. All rights reserved. // // Thanks to: https://github.com/vkiryukhin/vkBeautify // // The MIT License (MIT) // // Copyright (c) 2013 Vadim Kiryukhin // // 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. import Foundation import AppKit import JavaScriptCore let xFormatIndentationWidth = 2 func vkBeautify(string: String, type: String) -> String { let context = JSContext()! if let path = Bundle.main.path(forResource: "vkbeautify", ofType: "js") { do { let js = try String(contentsOfFile: path, encoding: .utf8) context.evaluateScript(js) } catch { xTextLog(string: "Load vkbeautify failed") } } if let parser = context.objectForKeyedSubscript("parser").objectForKeyedSubscript(type), let pretty = parser.call(withArguments: [ string, xFormatIndentationWidth ]) { return pretty.isUndefined ? string : pretty.toString() } return string }
mit
9a803478d8482341d9c0c56c2a2dfc86
32.818182
169
0.612366
3.431734
false
false
false
false
rolson/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Route & Navigation/Route around barriers/RouteAroundBarriersViewController.swift
1
11349
// // Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class RouteAroundBarriersViewController: UIViewController, AGSGeoViewTouchDelegate, UIAdaptivePresentationControllerDelegate, DirectionsListVCDelegate { @IBOutlet var mapView:AGSMapView! @IBOutlet var segmentedControl:UISegmentedControl! @IBOutlet var routeParametersBBI:UIBarButtonItem! @IBOutlet var routeBBI:UIBarButtonItem! @IBOutlet var directionsListBBI:UIBarButtonItem! @IBOutlet var directionsBottomConstraint:NSLayoutConstraint! private var stopGraphicsOverlay = AGSGraphicsOverlay() private var barrierGraphicsOverlay = AGSGraphicsOverlay() private var routeGraphicsOverlay = AGSGraphicsOverlay() private var directionsGraphicsOverlay = AGSGraphicsOverlay() private var routeTask:AGSRouteTask! private var routeParameters:AGSRouteParameters! private var isDirectionsListVisible = false private var directionsListViewController:DirectionsListViewController! var generatedRoute:AGSRoute! { didSet { let flag = generatedRoute != nil self.directionsListBBI.enabled = flag self.toggleRouteDetails(flag) self.directionsListViewController.route = generatedRoute } } override func viewDidLoad() { super.viewDidLoad() //add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["RouteAroundBarriersViewController", "DirectionsListViewController", "RouteParametersViewController"] let map = AGSMap(basemap: AGSBasemap.topographicBasemap()) self.mapView.map = map self.mapView.touchDelegate = self //add the graphics overlays to the map view self.mapView.graphicsOverlays.addObjectsFromArray([routeGraphicsOverlay, directionsGraphicsOverlay, barrierGraphicsOverlay, stopGraphicsOverlay]) //zoom to viewpoint self.mapView.setViewpointCenter(AGSPoint(x: -13042254.715252, y: 3857970.236806, spatialReference: AGSSpatialReference(WKID: 3857)), scale: 1e5, completion: nil) //initialize route task self.routeTask = AGSRouteTask(URL: NSURL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route")!) //get default parameters self.getDefaultParameters() //hide directions list self.toggleRouteDetails(false) } //MARK: - Route logic func getDefaultParameters() { self.routeTask.defaultRouteParametersWithCompletion({ [weak self] (params: AGSRouteParameters?, error: NSError?) -> Void in if let error = error { SVProgressHUD.showErrorWithStatus(error.localizedDescription) } else { self?.routeParameters = params //enable bar button item self?.routeParametersBBI.enabled = true } }) } @IBAction func route() { //add check if self.routeParameters == nil || self.stopGraphicsOverlay.graphics.count < 2 { SVProgressHUD.showErrorWithStatus("Either parameters not loaded or not sufficient stops") return } SVProgressHUD.showWithStatus("Routing", maskType: SVProgressHUDMaskType.Gradient) //clear routes self.routeGraphicsOverlay.graphics.removeAllObjects() self.routeParameters.returnStops = true self.routeParameters.returnDirections = true //add stops var stops = [AGSStop]() for graphic in self.stopGraphicsOverlay.graphics as AnyObject as! [AGSGraphic] { let stop = AGSStop(point: graphic.geometry as! AGSPoint) stop.name = "\(self.stopGraphicsOverlay.graphics.indexOfObject(graphic)+1)" stops.append(stop) } self.routeParameters.clearStops() self.routeParameters.setStops(stops) //add barriers var barriers = [AGSPolygonBarrier]() for graphic in self.barrierGraphicsOverlay.graphics as AnyObject as! [AGSGraphic] { let polygon = graphic.geometry as! AGSPolygon let barrier = AGSPolygonBarrier(polygon: polygon) barriers.append(barrier) } self.routeParameters.clearPolygonBarriers() self.routeParameters.setPolygonBarriers(barriers) self.routeTask.solveRouteWithParameters(self.routeParameters) { [weak self] (routeResult:AGSRouteResult?, error:NSError?) -> Void in if let error = error { SVProgressHUD.showErrorWithStatus("\(error.localizedDescription) \(error.localizedFailureReason ?? "")") } else { SVProgressHUD.dismiss() let route = routeResult!.routes[0] let routeGraphic = AGSGraphic(geometry: route.routeGeometry, symbol: self!.routeSymbol(), attributes: nil) self?.routeGraphicsOverlay.graphics.addObject(routeGraphic) self?.generatedRoute = route } } } func routeSymbol() -> AGSSimpleLineSymbol { let symbol = AGSSimpleLineSymbol(style: .Solid, color: UIColor.yellowColor(), width: 5) return symbol } func directionSymbol() -> AGSSimpleLineSymbol { let symbol = AGSSimpleLineSymbol(style: .DashDot, color: UIColor.orangeColor(), width: 5) return symbol } private func symbolForStopGraphic(index: Int) -> AGSSymbol { let markerImage = UIImage(named: "BlueMarker")! let markerSymbol = AGSPictureMarkerSymbol(image: markerImage) markerSymbol.offsetY = markerImage.size.height/2 let textSymbol = AGSTextSymbol(text: "\(index)", color: UIColor.whiteColor(), size: 20, horizontalAlignment: AGSHorizontalAlignment.Center, verticalAlignment: AGSVerticalAlignment.Middle) textSymbol.offsetY = markerSymbol.offsetY let compositeSymbol = AGSCompositeSymbol(symbols: [markerSymbol, textSymbol]) return compositeSymbol } func barrierSymbol() -> AGSSimpleFillSymbol { return AGSSimpleFillSymbol(style: .DiagonalCross, color: UIColor.redColor(), outline: nil) } //MARK: - AGSGeoViewTouchDelegate func geoView(geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { //normalize geometry let normalizedPoint = AGSGeometryEngine.normalizeCentralMeridianOfGeometry(mapPoint)! if segmentedControl.selectedSegmentIndex == 0 { //create a graphic for stop and add to the graphics overlay let graphicsCount = self.stopGraphicsOverlay.graphics.count let symbol = self.symbolForStopGraphic(graphicsCount+1) let graphic = AGSGraphic(geometry: normalizedPoint, symbol: symbol, attributes: nil) self.stopGraphicsOverlay.graphics.addObject(graphic) //enable route button if graphicsCount > 0 { self.routeBBI.enabled = true } } else { let bufferedGeometry = AGSGeometryEngine.bufferGeometry(normalizedPoint, byDistance: 500) let symbol = self.barrierSymbol() let graphic = AGSGraphic(geometry: bufferedGeometry, symbol: symbol, attributes: nil) self.barrierGraphicsOverlay.graphics.addObject(graphic) } } //MARK: - Actions @IBAction func clearAction() { if segmentedControl.selectedSegmentIndex == 0 { self.stopGraphicsOverlay.graphics.removeAllObjects() self.routeBBI.enabled = false } else { self.barrierGraphicsOverlay.graphics.removeAllObjects() } } @IBAction func directionsListAction() { self.directionsBottomConstraint.constant = self.isDirectionsListVisible ? -115 : 0 UIView.animateWithDuration(0.3, animations: { [weak self] () -> Void in self?.view.layoutIfNeeded() }) { [weak self] (finished) -> Void in self?.isDirectionsListVisible = !self!.isDirectionsListVisible } } func toggleRouteDetails(on:Bool) { self.directionsBottomConstraint.constant = on ? -115 : -150 UIView.animateWithDuration(0.3, animations: { [weak self] () -> Void in self?.view.layoutIfNeeded() }) { [weak self] (finished) -> Void in if !on { self?.isDirectionsListVisible = false } } } //MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "RouteSettingsSegue" { let controller = segue.destinationViewController as! RouteParametersViewController controller.presentationController?.delegate = self controller.preferredContentSize = CGSize(width: 300, height: 125) controller.routeParameters = self.routeParameters } else if segue.identifier == "DirectionsListSegue" { self.directionsListViewController = segue.destinationViewController as! DirectionsListViewController self.directionsListViewController.delegate = self } } //MARk: - UIAdaptivePresentationControllerDelegate func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .None } //MARK: - DirectionsListVCDelegate func directionsListViewControllerDidDeleteRoute(directionsListViewController: DirectionsListViewController) { self.generatedRoute = nil; self.routeGraphicsOverlay.graphics.removeAllObjects() self.directionsGraphicsOverlay.graphics.removeAllObjects() } func directionsListViewController(directionsListViewController: DirectionsListViewController, didSelectDirectionManuever directionManeuver: AGSDirectionManeuver) { //remove previous directions self.directionsGraphicsOverlay.graphics.removeAllObjects() //show the maneuver geometry on the map view let directionGraphic = AGSGraphic(geometry: directionManeuver.geometry!, symbol: self.directionSymbol(), attributes: nil) self.directionsGraphicsOverlay.graphics.addObject(directionGraphic) //zoom to the direction self.mapView.setViewpointGeometry(directionManeuver.geometry!.extent, padding: 100, completion: nil) } }
apache-2.0
ac47caffee73fc6a1b36b56477058bc5
41.988636
195
0.671953
5.490566
false
false
false
false
Baglan/MCViewport
Classes/MCViewportItem.swift
1
7487
// // MCViewportItem.swift // MCViewport // // Created by Baglan on 2/11/16. // Copyright © 2016 Mobile Creators. All rights reserved. // import Foundation import UIKit extension MCViewport { /// The general inmlementation of a viewport item class Item: Hashable { /// Reference to the viewport weak var viewport: MCViewport? /// The original frame of the item /// /// Position calculations will be based on it var originalFrame = CGRect.zero /// The parallax ratio of the item in the XY coordinate space var parallax = CGPoint(x: 1, y: 1) /// Item z-index for stacking var zIndex: CGFloat = 0 /// The current calculated frame var frame: CGRect { guard let viewport = viewport else { return originalFrame } var transformedFrame = originalFrame.applying(transformForContentOffset(viewport.contentOffset)) for movementConstraint in movementConstraints { transformedFrame = movementConstraint.applyToFrame(transformedFrame, viewport: viewport) } return transformedFrame } /// Calculate the affine transform for a given content offset of the viewport /// - Parameter contentOffset: The content offset of the viewport to calculate for /// - Returns: The affine transform func transformForContentOffset(_ contentOffset: CGPoint) -> CGAffineTransform { return CGAffineTransform(translationX: -contentOffset.x * (parallax.x - 1), y: -contentOffset.y * (parallax.y - 1)) } /// Position the item in the viewport /// - Parameter frame: The frame rect of the item /// - Parameter viewportOffset: Offset of the viewport for which the frame is set /// - Parameter parallax: The parallax ratio of the item func place(frame: CGRect, viewportOffset: CGPoint = CGPoint.zero, parallax: CGPoint = CGPoint(x: 1, y: 1)) { self.parallax = parallax let referenceOffset = CGPoint.zero.applying(transformForContentOffset(viewportOffset)) originalFrame = frame.applying(CGAffineTransform(translationX: viewportOffset.x - referenceOffset.x, y: viewportOffset.y - referenceOffset.y)) } /// The associated view, if any var view: UIView? { return nil } // MARK: - Distances /// Distances to viewport lazy var distances: Distances = { return Distances(item: self) }() // MARK: - Movement constraints /// The current movement constraints fileprivate var movementConstraints = [MovementConstraint]() /// Add a movement constraint func addMovementConstraint(_ movementConstraint: MovementConstraint) { movementConstraints.append(movementConstraint) movementConstraints.sort { (a, b) -> Bool in a.priority < b.priority } viewport?.setNeedsLayout() } // MARK: - Visibility /// Whether the item is currently visible on the screen var isVisible: Bool { if let viewport = viewport { return viewport.isItemVisible(self) } return false } /// Hook just before the item appears on the screen func willBecomeVisible() { } /// Hook right after the item leaves the screen func didBecomeInvisible() { } // MARK: - Updates /// Update the item position func update() { guard let view = view else { return } view.center = CGPoint(x: frame.midX, y: frame.midY) } // MARK: - Hashable compliance func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(Item.self).hashValue) } } /// An item based on a UIView class ViewItem: Item { /// The associated view fileprivate var _view: UIView? override var view: UIView? { return _view } /// Create a new view /// /// To be implemented by descendants; the default implmenetation returns a simlpe UIView. /// /// - Returns: a new view func newView() -> UIView { return UIView() } override func willBecomeVisible() { guard let viewport = viewport else { return } // Create of dequeue a view _view = viewport.recycler.dequeue(String(describing: type(of: self))) as? UIView ?? newView() guard let view = view else { return } // Reset view.isHidden = false view.alpha = 1 view.transform = CGAffineTransform.identity // Set bounds and zPosition view.frame = originalFrame view.layer.zPosition = zIndex // Add view to viewport viewport.addSubview(view) } override func didBecomeInvisible() { guard let view = view, let viewport = viewport else { return } viewport.hiddenPocket.addSubview(view) viewport.recycler.recycle(String(describing: type(of: self)), object: view) } } /// An item based on a UIViewController class ViewControllerItem: Item { /// The associated view controller, if any var viewController: UIViewController? override var view: UIView? { return viewController?.view } /// Create a new view controller /// /// To beimplemented by descendants; the default implementation returns nil /// /// - Returns: A new view controller or nil func newViewController() -> UIViewController? { return nil } override func willBecomeVisible() { guard let viewport = viewport else { return } // Create of dequeue a view controller viewController = viewport.recycler.dequeue(String(describing: type(of: self))) as? UIViewController ?? newViewController() guard let viewController = viewController, let view = viewController.view else { return } // Reset view.isHidden = false view.alpha = 1 view.transform = CGAffineTransform.identity // Set bounds and zPosition view.frame = originalFrame view.layer.zPosition = zIndex // Add view to viewport viewport.addSubview(view) } override func didBecomeInvisible() { guard let view = view, let viewController = viewController, let viewport = viewport else { return } viewport.hiddenPocket.addSubview(view) viewport.recycler.recycle(String(describing: type(of: self)), object: viewController) } } } /// Check if items are the same func ==(lhs: MCViewport.Item, rhs: MCViewport.Item) -> Bool { return lhs === rhs }
mit
5d99b8d0a14d67aa07f01f66c96935c7
32.873303
154
0.561715
5.512518
false
false
false
false
Ingemark/TVMultiPicker
TVMultiPicker/DatePickerUtilities.swift
1
3674
// // DatePickerUtilities.swift // TVMultiPicker // // Created by Filip Dujmušić on 31/07/2017. // Copyright © 2017 Ingemark. All rights reserved. // // 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 struct DatePickerUtilities { private init() { } static func getDateFromComponents(components: [String]) -> Date? { let year = components[0] let month = components[1] let day = components[2] let dateString = day + " " + month + " " + year let dateFormatter = DateFormatter() dateFormatter.dateFormat = "d M yyyy" dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) guard let date = dateFormatter.date(from: dateString) else { print("Could not convert components: \(components) to Date!") return nil } return date } static func getDaysForYearMonth(for date: Date) -> [String] { guard let daysRange = Calendar.current.range(of: .day, in: .month, for: date) else { return [] } let daysArray = Array(daysRange.lowerBound ..< daysRange.upperBound).map { "\($0)" } return daysArray } static func getYearPicker(startYear: Int, initialYear: Int) -> PickerDefinition { let currentYear = Calendar.current.component(.year, from: Date()) let data = (startYear ... currentYear).map { "\($0)" } let definition = PickerDefinition( data: data, cellWidth: 150, initialValueIndex: initialYear - startYear, remembersLastFocusedElement: true ) return definition } static func getMonthPicker() -> PickerDefinition { let data = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] let definition = PickerDefinition( data: data, cellWidth: 100, initialValueIndex: 0, remembersLastFocusedElement: true ) return definition } static func getDayPicker() -> PickerDefinition { let data = (1...30).map { "\($0)" } let definition = PickerDefinition( data: data, cellWidth: 100, initialValueIndex: 0, remembersLastFocusedElement: false ) return definition } }
mit
0623cc9f6dcc8174db5f772d334646cc
32.990741
92
0.599837
4.606023
false
false
false
false
scottbyrns/Swift-Crate.io
Sources/CrateIO.swift
1
4316
import TCP import JSON import Data import Digest import HTTP import HTTPParser import HTTPSerializer import S4 import ConnectionPool public class CrateIO { var socketPool: ConnectionPool<TCPConnection> public init(pool connections: [TCPConnection], using configuration: CratePoolConfiguration) throws { socketPool = ConnectionPool<TCPConnection>(pool: connections, using: configuration) } public func sql (statement: String) throws -> JSON? { // Get a connection from the pool to use. return try socketPool.with({ connection in let post = "{\"stmt\": \"\(statement)\"}\r\n" let postBytes = [UInt8](post.utf8) let headers: Headers = [ "Content-Length": HeaderValues("\(postBytes.count)"), "Content-Type": HeaderValues("application/json"), "User-Agent": HeaderValues("Swift-CrateIO") ] let request = try Request(method: .post, uri: "/_sql", headers: headers, body: post) let requestData = Data(try self.requestToString(request)) try! connection.send(requestData) let received = try connection.receive(max: 5000000) print("Received: \(received)") //converting data to a string let str = try String(data: received) print("received: \(str)") let parser = ResponseParser() do { if let response = try parser.parse(str) { switch response.body { case .buffer(let data): return try JSONParser().parse(data) default: break } } } catch { } return nil }) as? JSON } public func blob (insert data: Data, into table: String) throws -> String? { // Get a connection from the pool to use. return try socketPool.with({ connection in let digest = Digest.sha1(try String(data: data)) let headers: Headers = [ "Content-Length": HeaderValues("\(data.bytes.count)"), "Content-Type": HeaderValues("application/x-www-form-urlencoded"), "User-Agent": HeaderValues("Swift-CrateIO") ] let request = try Request(method: .put, uri: "/_blobs/\(table)/\(digest)", headers: headers, body: data) try! connection.send(Data(self.requestToString(request))) //receiving data let received = try connection.receive(max: 50000000) //converting data to a string let str = try String(data: received) let parser = ResponseParser() do { guard let response = try parser.parse(str) else { return nil } if response.statusCode == 201 || response.statusCode == 409 { return digest } } catch { } return nil }) as? String } public func blob (fetch digest: String, from table: String) throws -> Data? { // Get a connection from the pool to use. return try socketPool.with({ connection in let headers: Headers = [ "User-Agent": HeaderValues("Swift-CrateIO") ] let request = try Request(method: .get, uri: "/_blobs/\(table)/\(digest)", headers: headers) try connection.send(Data(self.requestToString(request))) //receiving data let received = try connection.receive(max: 50000000) //converting data to a string let str = try String(data: received) let parser = ResponseParser() do { guard let response = try parser.parse(str) else { return nil } if response.statusCode == 200 { switch response.body { case .buffer(let data): return data default: break } } } catch { // Fall through } return nil }) as? Data } private func requestToString (request : Request) throws -> String { var out = "" try RequestSerializer().serialize(request) { data in out += try String(data: data) } return out } deinit { } }
mit
19c3c2392e365b8e41fc82adf3912bd3
24.690476
113
0.552595
4.576882
false
false
false
false
dulingkang/Camera
SSCamera/SSCamera/SSCameraViewController.swift
1
1403
// // SSCameraViewController.swift // SSCamera // // Created by ShawnDu on 15/12/11. // Copyright © 2015年 Shawn. All rights reserved. // import UIKit import AVFoundation class SSCameraViewController: UIViewController, SSCameraViewDelegate { var camera: SSCamera! var cameraView: SSCameraView! //MARK: - life cycle override func viewDidLoad() { self.view.backgroundColor = kBackgroundColor self.navigationController?.setNavigationBarHidden(true, animated: false) cameraView = SSCameraView.init(frame: self.view.bounds) cameraView.delegate = self self.view.addSubview(cameraView) camera = SSCamera.init(sessionPreset: AVCaptureSessionPresetPhoto, position: .Front) cameraView.preview.layer.addSublayer(camera.previewLayer) } override func prefersStatusBarHidden() -> Bool { return true } override func viewWillAppear(animated: Bool) { camera.startCapture() } //MARK: - delegate func backButtonPressed() { self.navigationController?.popViewControllerAnimated(true) } func switchButtonPressed() { camera.switchCamera() } func captureButtonPressed() { camera.takePhoto { (image) -> Void in let _ = SSImageHelper.scaleImage(image!, isFrontCamera: self.camera.isUsingFront) } } }
mit
f821240985ea8378cf0577f7410a6fc3
25.923077
93
0.665
4.778157
false
false
false
false
loudnate/Loop
Common/Extensions/HKUnit.swift
1
1635
// // HKUnit.swift // Loop // // Created by Bharat Mediratta on 12/2/16. // Copyright © 2016 LoopKit Authors. All rights reserved. // import HealthKit import LoopCore // Code in this extension is duplicated from: // https://github.com/LoopKit/LoopKit/blob/master/LoopKit/HKUnit.swift // to avoid pulling in the LoopKit extension since it's not extension-API safe. extension HKUnit { // A formatting helper for determining the preferred decimal style for a given unit var preferredFractionDigits: Int { if self == .milligramsPerDeciliter { return 0 } else { return 1 } } var localizedShortUnitString: String { if self == HKUnit.millimolesPerLiter { return NSLocalizedString("mmol/L", comment: "The short unit display string for millimoles of glucose per liter") } else if self == .milligramsPerDeciliter { return NSLocalizedString("mg/dL", comment: "The short unit display string for milligrams of glucose per decilter") } else if self == .internationalUnit() { return NSLocalizedString("U", comment: "The short unit display string for international units of insulin") } else if self == .gram() { return NSLocalizedString("g", comment: "The short unit display string for grams") } else { return String(describing: self) } } /// The smallest value expected to be visible on a chart var chartableIncrement: Double { if self == .milligramsPerDeciliter { return 1 } else { return 1 / 25 } } }
apache-2.0
93c1e4916681bc0c8b1bad757e993d7b
33.765957
126
0.640147
4.642045
false
false
false
false
aamays/Yelp
Yelp/SearchViewController.swift
1
7646
// // SearchViewController.swift // Yelp // // Created by Amay Singhal on 9/23/15. // Copyright © 2015 Timothy Lee. All rights reserved. // import UIKit @objc protocol SearchViewControllerDelegate: class { optional func initialFilters() -> [YelpFilters] optional func searchViewController(searchViewController: SearchViewController, didSetFilters filters: [YelpFilters]) } class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FilterTableViewCellDelegate { @IBOutlet weak var searchTableView: UITableView! weak var delegate: SearchViewControllerDelegate? var yelpFilters = [YelpDealsFilter(), YelpDistanceFilter(), YelpSortFilter(), YelpCategoryFilter()] struct ViewConfig { static let SelectionCellShowAllText = "Show All" static let SelectionCellShowLessText = "Show Less" } // MARK: - View Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. searchTableView.dataSource = self searchTableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table View Delegate and Data Source methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return yelpFilters.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return yelpFilters[section].filterSectionName } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let yelpFilter = yelpFilters[section] return yelpFilter.numberOfRows } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // get filter option for the row let yelpFilter = yelpFilters[indexPath.section] var cellIndetifier = SearchVCCellIdentifiers.FilterTableViewCell if (yelpFilter as? YelpCategoryFilter) != nil && indexPath.row == (yelpFilter.numberOfRows - 1) && !yelpFilter.isExpanded { cellIndetifier = SearchVCCellIdentifiers.ShowSelectionTableViewCell } else { cellIndetifier = yelpFilter.isExpandable && yelpFilter.isExpanded ? yelpFilter.expandedCellIdentifier : yelpFilter.collapsedCellIdentifier } switch cellIndetifier { case .FilterTableViewCell: let filterCell = getDequeuedFilterCell(indexPath) let index = indexPath.row filterCell.filterNameLabel.text = yelpFilter.expandedOptions[index][YelpFilters.DisplayName] as? String filterCell.filterSwitch.on = yelpFilter.selectedOptions.contains(index) filterCell.delegate = self return filterCell case .PreviewTableViewCell: let previewCell = getDequeuedPreviewCell(indexPath) previewCell.tag = indexPath.section if yelpFilter.isExpanded { previewCell.previewFilterNameLabel.text = yelpFilter.expandedOptions[indexPath.row][YelpFilters.DisplayName] as? String previewCell.cellState = yelpFilter.selectedOptions.contains(indexPath.row) ? PreviewTableViewCell.CellState.Checked : PreviewTableViewCell.CellState.Unchecked } else { previewCell.cellState = PreviewTableViewCell.CellState.Collapsed previewCell.previewFilterNameLabel.text = yelpFilter.expandedOptions[yelpFilter.selectedOptions[indexPath.row]][YelpFilters.DisplayName] as? String } return previewCell case .ShowSelectionTableViewCell: let selectionCell = getDequeuedSelectionCell(indexPath) selectionCell.showSelectionLabel.text = yelpFilter.isExpanded ? ViewConfig.SelectionCellShowLessText : ViewConfig.SelectionCellShowAllText return selectionCell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let selectedCell = searchTableView.cellForRowAtIndexPath(indexPath) as? PreviewTableViewCell { previewCellTapped(selectedCell, forIndexPath: indexPath) } else if let selectedCell = searchTableView.cellForRowAtIndexPath(indexPath) as? ShowSelectionTableViewCell { showSelectionCellTapped(selectedCell, forIndexPath: indexPath) } searchTableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: - FilterCellView Delegate Method func filterCellSwitchDidToggle(cell: FilterTableViewCell, newValue: Bool) { let indexPath = searchTableView.indexPathForCell(cell) if newValue { yelpFilters[(indexPath?.section)!].selectedOptions.append((indexPath?.row)!) yelpFilters[(indexPath?.section)!].selectedOptions.sortInPlace() } else { yelpFilters[(indexPath?.section)!].selectedOptions = yelpFilters[(indexPath?.section)!].selectedOptions.filter { $0 != indexPath?.row } } } // MARK: - View actions methods @IBAction func cancelButtonTapped(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func searchButtonTapped(sender: UIBarButtonItem) { delegate?.searchViewController?(self, didSetFilters: yelpFilters) self.dismissViewControllerAnimated(true, completion: nil) } // MARK: - Helper functions private func getDequeuedPreviewCell(indexPath: NSIndexPath) -> PreviewTableViewCell { return searchTableView.dequeueReusableCellWithIdentifier(SearchVCCellIdentifiers.PreviewTableViewCell.rawValue, forIndexPath: indexPath) as! PreviewTableViewCell } private func getDequeuedFilterCell(indexPath: NSIndexPath) -> FilterTableViewCell { return searchTableView.dequeueReusableCellWithIdentifier(SearchVCCellIdentifiers.FilterTableViewCell.rawValue, forIndexPath: indexPath) as! FilterTableViewCell } private func getDequeuedSelectionCell(indexPath: NSIndexPath) -> ShowSelectionTableViewCell { return searchTableView.dequeueReusableCellWithIdentifier(SearchVCCellIdentifiers.ShowSelectionTableViewCell.rawValue, forIndexPath: indexPath) as! ShowSelectionTableViewCell } private func previewCellTapped(sender: PreviewTableViewCell, forIndexPath indexPath: NSIndexPath) { let section = indexPath.section if yelpFilters[section].isExpanded { if yelpFilters[section].selectedOptions.count > 0 { let prevCell = searchTableView.cellForRowAtIndexPath(NSIndexPath(forRow: yelpFilters[section].selectedOptions[0], inSection: section)) as? PreviewTableViewCell prevCell?.cellState = PreviewTableViewCell.CellState.Unchecked yelpFilters[section].selectedOptions[0] = indexPath.row } else { yelpFilters[section].selectedOptions.append(indexPath.row) } sender.cellState = PreviewTableViewCell.CellState.Checked } yelpFilters[section].isExpanded = !(yelpFilters[section].isExpanded) searchTableView.reloadSections(NSIndexSet(index: section), withRowAnimation: .Automatic) } private func showSelectionCellTapped(sender: ShowSelectionTableViewCell, forIndexPath indexPath: NSIndexPath) { let section = indexPath.section yelpFilters[section].isExpanded = !(yelpFilters[section].isExpanded) searchTableView.reloadSections(NSIndexSet(index: section), withRowAnimation: .Automatic) } }
mit
fb5dffd8989808640bda3b005fea038b
45.333333
181
0.724526
5.445157
false
false
false
false
noppefoxwolf/TVUploader-iOS
TVUploader/STTwitter/Classes/AsyncInitResponce.swift
1
402
// // Created by Tomoya Hirano on 2016/08/30. // import Foundation import Unbox internal struct AsyncInitResponce: Unboxable { var expiresAfterSecs = 0 var mediaId = 0 var mediaIdString = "" init(unboxer: Unboxer) { self.expiresAfterSecs = unboxer.unbox("expires_after_secs") self.mediaId = unboxer.unbox("media_id") self.mediaIdString = unboxer.unbox("media_id_string") } }
mit
32f6402373a303d4d4098862ef9a970a
21.333333
63
0.70398
3.526316
false
false
false
false
react-native-kit/react-native-track-player
ios/RNTrackPlayer/Models/MediaURL.swift
2
1143
// // MediaURL.swift // RNTrackPlayer // // Created by David Chavez on 12.08.17. // Copyright © 2017 David Chavez. All rights reserved. // import Foundation struct MediaURL { let value: URL let isLocal: Bool private let originalObject: Any init?(object: Any?) { guard let object = object else { return nil } originalObject = object // This is based on logic found in RCTConvert NSURLRequest, // and uses RCTConvert NSURL to create a valid URL from various formats if let localObject = object as? [String: Any] { var url = localObject["uri"] as? String ?? localObject["url"] as! String if let bundleName = localObject["bundle"] as? String { url = String(format: "%@.bundle/%@", bundleName, url) } isLocal = url.lowercased().hasPrefix("http") ? false : true value = RCTConvert.nsurl(url) } else { let url = object as! String isLocal = url.lowercased().hasPrefix("file://") value = RCTConvert.nsurl(url) } } }
apache-2.0
3c622457b4ca96203f29013092a4223c
29.864865
84
0.568301
4.44358
false
false
false
false
FirasAKAK/FInAppNotifications
FNotificationSettings.swift
1
2182
// // FNotificationSettings.swift // FInAppNotification // // Created by Firas Al Khatib Al Khalidi on 7/4/17. // Copyright © 2017 Firas Al Khatib Al Khalidi. All rights reserved. // import UIKit class FNotificationSettings { ///background view of the notification var backgroundView : UIView? ///background color of the notification var backgroundColor : UIColor = .lightGray ///title text color of the notification var titleTextColor : UIColor = .black ///subtitle color of the notification var subtitleTextColor : UIColor = .black ///corner radius of the image view of the notification var imageViewCornerRadius: CGFloat = 0 ///font for the title text var titleFont = UIFont.boldSystemFont(ofSize: 17) ///font of the subtitle text var subtitleFont = UIFont.systemFont(ofSize: 13) ///universal initializer for the settings object, has default values init(backgroundView: UIView? = nil, backgroundColor: UIColor = .lightGray, titleTextColor: UIColor = .black, subtitleTextColor: UIColor = .black, imageViewCornerRadius: CGFloat = 25, titleFont: UIFont = UIFont.boldSystemFont(ofSize: 17), subtitleFont: UIFont = UIFont.systemFont(ofSize: 13)){ self.backgroundView = backgroundView self.backgroundColor = backgroundColor self.titleTextColor = titleTextColor self.subtitleTextColor = subtitleTextColor self.imageViewCornerRadius = imageViewCornerRadius self.titleFont = titleFont self.subtitleFont = subtitleFont } ///default style for the notification, set as the style of the notification settings at the beginning static var defaultStyle: FNotificationSettings{ let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurView = UIVisualEffectView(effect: blurEffect) return FNotificationSettings(backgroundView: blurView, backgroundColor: .clear, titleTextColor: .white, subtitleTextColor: .white) } }
mit
4f354a0313f9285af47f93b39413eb81
47.466667
296
0.66575
5.306569
false
false
false
false
chicio/Exploring-SceneKit
ExploringSceneKit/Model/Scenes/BlinnPhong/BlinnPhongScene.swift
1
6256
// // BlinnPhongScene.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 26.08.17. // import SceneKit @objc class BlinnPhongScene: SCNScene, Scene { private var camera: Camera! private var poolSphere: DynamicSphere! override init() { super.init() createCamera() createLight() createObjects() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Camera private func createCamera() { camera = Camera( position: SCNVector3Make(0, 80.0, 100.0), rotation: SCNVector4Make(1.0, 0, 0, -1.0 * Float(CGFloat.pi / 4.0)) ) rootNode.addChildNode(camera.node) } //MARK: Light private func createLight() { rootNode.addChildNode(createOmniDirectionalLight().node) rootNode.addChildNode(createAmbientLight().node) } private func createOmniDirectionalLight() -> OmniDirectionalLight { let lightFeatures = LightFeatures( position: SCNVector3Make(0, 50, 10), orientation: SCNVector3Make(0, 0, 0), color: UIColor.white ) let light = OmniDirectionalLight(lightFeatures: lightFeatures) return light } private func createAmbientLight() -> AmbientLight { let lightFeatures = LightFeatures( position: SCNVector3Make(0, 0, 0), orientation: SCNVector3Make(0, 0, 0), color: UIColor.darkGray ) let light = AmbientLight(lightFeatures: lightFeatures) return light } //MARK: Objects private func createObjects() { addFloor() addWhiteMarbleBox() addBlueMarbleBox() addDarkBlueMarbleBox() addPoolSphere() } private func addFloor() { let floor = KinematicFloor( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "floor.jpg", textureWrapMode: .repeat), specular: 0.0 ), position: SCNVector3Make(0, 0, 0), rotation: SCNVector4Make(0, 0, 0, 0) ) rootNode.addChildNode(floor.node) } private func addWhiteMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble1.jpg"), specular: 0.3 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(0, 5, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addBlueMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble2.jpg"), specular: 0.2 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(-5, 5, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addDarkBlueMarbleBox() { let box = DynamicBox( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "marble3.jpg"), specular: 0.3 ), boxFeatures: BoxFeatures(width: 10.0, height: 10.0, length: 10.0, edgesRadius: 0.2), position: SCNVector3Make(-5, 10, 0), rotation: SCNVector4Make(0, 1, 0, 0.5) ) rootNode.addChildNode(box.node) } private func addPoolSphere() { self.poolSphere = DynamicSphere( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: "pool.jpg"), specular: 0.9 ), physicsBodyFeature: PhysicsBodyFeatures(mass: 1.5, rollingFriction: 0.1), radius: 10.0, position: SCNVector3Make(20, 10, 20), rotation: SCNVector4Make(0, 0, 0, 0) ) rootNode.addChildNode(self.poolSphere.node) } func actionForOnefingerGesture(withLocation location: CGPoint, andHitResult hitResult: [Any]!) { if isThereAHitIn(hitResult: hitResult) { movePoolSphereUsing(hitResult: hitResult) } } private func isThereAHitIn(hitResult: [Any]!) -> Bool { return hitResult.count > 0 } private func movePoolSphereUsing(hitResult: [Any]!) { if let firstHit: SCNHitTestResult = hitResult[0] as? SCNHitTestResult { let force = SCNVector3Make( firstHit.worldCoordinates.x - self.poolSphere.node.position.x, 0, firstHit.worldCoordinates.z - self.poolSphere.node.position.z ) self.poolSphere.node.physicsBody?.applyForce(force, asImpulse: true) } } func actionForTwofingerGesture() { let randomX = CGFloat.randomIn(minRange: 0.0, maxRange: 50.0) let randomZ = CGFloat.randomIn(minRange: 0.0, maxRange: 50.0) let randomRadius = CGFloat.randomIn(minRange: 0.0, maxRange: 15.0) let randomTexture = String(format: "checked%d.jpg", Int.randomIn(minRange: 1, maxRange: 2)) let sphere = DynamicSphere( material: BlinnPhongMaterial( ambient: UIColor.lightGray, diffuse: BlinnPhongDiffuseMaterialComponent(value: randomTexture), specular: CGFloat.randomIn(minRange: 0.0, maxRange: 2.0) ), physicsBodyFeature: PhysicsBodyFeatures(mass: randomRadius * 10.0, rollingFriction: 0.2), radius: randomRadius, position: SCNVector3(randomX, 120, randomZ), rotation: SCNVector4(0, 0, 0, 0) ) rootNode.addChildNode(sphere.node) } }
mit
8f362584bbb5cd0307ab98370bf37e62
33.563536
106
0.586797
4.110381
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch8/8.3.1字典拷贝2.playground/section-1.swift
1
571
// Playground - noun: a place where people can play class Employee { var name : String // 姓名 var salary : Double // 工资 init (n : String) { name = n salary = 0 } } var emps = Dictionary<String, Employee>() let emp1 = Employee(n: "Amy Lee") let emp2 = Employee(n: "Harry Hacker") emps["144-25-5464"] = emp1 emps["567-24-2546"] = emp2 //赋值,发生拷贝 var copyEmps = emps let copyEmp : Employee! = copyEmps["567-24-2546"] copyEmp.name = "Gary Cooper" let emp : Employee! = emps["567-24-2546"] println(emp.name)
gpl-2.0
d509e9ec69986efd30abf4d4ae3d0c59
20.115385
51
0.615665
2.84456
false
false
false
false
yannickl/Cocarde
Cocarde/PieLayer.swift
1
3609
/* * Cocarde * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation import UIKit import QuartzCore internal final class PieLayer: CocardeLayer { var plotScaleDuration: Double = 4.0 var plotMinScale: CGFloat = 0.7 required init(segmentCount segments: UInt, segmentColors colors: [UIColor], loopDuration duration: Double) { super.init(segmentCount: segments, segmentColors: colors, loopDuration: duration) } override init(layer: AnyObject) { super.init(layer: layer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Drawing Cocarde Activity override func drawInRect(rect: CGRect) { let center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)) let angle = CGFloat(2 * M_PI / Double(segmentCount)) let radius = min(CGRectGetWidth(rect), CGRectGetHeight(rect)) / 2 let colorCount = segmentColors.count for i in 0 ..< segmentCount { let startAngle = CGFloat(i) * angle let endAngle = startAngle + angle let plotLayer = CAShapeLayer() addSublayer(plotLayer) let plotPath = UIBezierPath() plotPath.moveToPoint(CGPointZero) plotPath.addArcWithCenter(CGPointZero, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) plotLayer.path = plotPath.CGPath plotLayer.fillColor = segmentColors[Int(i) % colorCount].CGColor plotLayer.strokeColor = plotLayer.fillColor plotLayer.position = center let anim = CAKeyframeAnimation(keyPath: "transform.scale") anim.duration = plotScaleDuration anim.cumulative = false anim.repeatCount = Float.infinity anim.values = [plotMinScale, 1, plotMinScale] anim.timeOffset = (plotScaleDuration / 4) * Double(i % 4) anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) anim.removedOnCompletion = false plotLayer.addAnimation(anim, forKey: "plot.scale") } let anim = CABasicAnimation(keyPath:"transform.rotation.z") anim.duration = loopDuration anim.fromValue = 0 anim.toValue = 2 * M_PI anim.repeatCount = Float.infinity anim.autoreverses = false anim.removedOnCompletion = false addAnimation(anim, forKey: "self.rotation") } }
mit
2de084345392896fe97b7332f65d3535
38.228261
121
0.687725
4.597452
false
false
false
false
swift-server/http
Sources/HTTP/HTTPHeaders.swift
1
22660
/// Representation of the HTTP headers associated with a `HTTPRequest` or `HTTPResponse`. /// Headers are subscriptable using case-insensitive comparison or provide `Name` constants. eg. /// ```swift /// let contentLength = headers["content-length"] /// ``` /// or /// ```swift /// let contentLength = headers[.contentLength] /// ``` public struct HTTPHeaders { var original: [(name: Name, value: String)]? var storage: [Name: [String]] { didSet { original = nil } } /// :nodoc: public subscript(name: Name) -> String? { get { guard let value = storage[name] else { return nil } switch name { case Name.setCookie: // Exception, see note in [RFC7230, section 3.2.2] return value.isEmpty ? nil : value[0] default: return value.joined(separator: ",") } } set { storage[name] = newValue.map { [$0] } } } /// :nodoc: public subscript(valuesFor name: Name) -> [String] { get { return storage[name] ?? [] } set { storage[name] = newValue.isEmpty ? nil : newValue } } } extension HTTPHeaders: ExpressibleByDictionaryLiteral { /// Creates HTTP headers. public init(dictionaryLiteral: (Name, String)...) { storage = [:] for (name, value) in dictionaryLiteral { #if swift(>=4.0) storage[name, default: []].append(value) #else if storage[name] == nil { storage[name] = [value] } else { storage[name]!.append(value) } #endif } original = dictionaryLiteral } } extension HTTPHeaders { // Used instead of HTTPHeaders to save CPU on dictionary construction /// :nodoc: public struct Literal: ExpressibleByDictionaryLiteral { let fields: [(name: Name, value: String)] public init(dictionaryLiteral: (Name, String)...) { fields = dictionaryLiteral } } /// Appends a header to the headers public mutating func append(_ literal: HTTPHeaders.Literal) { for (name, value) in literal.fields { #if swift(>=4.0) storage[name, default: []].append(value) #else if storage[name] == nil { storage[name] = [value] } else { storage[name]!.append(value) } #endif } } /// Replaces a header in the headers public mutating func replace(_ literal: HTTPHeaders.Literal) { for (name, _) in literal.fields { storage[name] = [] } for (name, value) in literal.fields { storage[name]!.append(value) } } } extension HTTPHeaders: Sequence { /// :nodoc: public func makeIterator() -> AnyIterator<(name: Name, value: String)> { if let original = original { return AnyIterator(original.makeIterator()) } else { return AnyIterator(StorageIterator(storage.makeIterator())) } } struct StorageIterator: IteratorProtocol { var headers: DictionaryIterator<Name, [String]> var header: (name: Name, values: IndexingIterator<[String]>)? init(_ iterator: DictionaryIterator<Name, [String]>) { headers = iterator header = headers.next().map { (name: $0.key, values: $0.value.makeIterator()) } } mutating func next() -> (name: Name, value: String)? { while header != nil { if let value = header!.values.next() { return (name: header!.name, value: value) } else { header = headers.next().map { (name: $0.key, values: $0.value.makeIterator()) } } } return nil } } } /// HTTPHeaders structure. extension HTTPHeaders { /// Type used for the name of a HTTP header in the `HTTPHeaders` storage. public struct Name: Hashable, ExpressibleByStringLiteral, CustomStringConvertible { let original: String let lowercased: String public let hashValue: Int /// Create a HTTP header name with the provided String. public init(_ name: String) { original = name lowercased = name.lowercased() hashValue = lowercased.hashValue } public init(stringLiteral: String) { self.init(stringLiteral) } public init(unicodeScalarLiteral: String) { self.init(unicodeScalarLiteral) } public init(extendedGraphemeClusterLiteral: String) { self.init(extendedGraphemeClusterLiteral) } /// :nodoc: public var description: String { return original } /// :nodoc: public static func == (lhs: Name, rhs: Name) -> Bool { return lhs.lowercased == rhs.lowercased } // https://www.iana.org/assignments/message-headers/message-headers.xhtml // Permanent Message Header Field Names /// A-IM header. public static let aIM = Name("A-IM") /// Accept header. public static let accept = Name("Accept") /// Accept-Additions header. public static let acceptAdditions = Name("Accept-Additions") /// Accept-Charset header. public static let acceptCharset = Name("Accept-Charset") /// Accept-Datetime header. public static let acceptDatetime = Name("Accept-Datetime") /// Accept-Encoding header. public static let acceptEncoding = Name("Accept-Encoding") /// Accept-Features header. public static let acceptFeatures = Name("Accept-Features") /// Accept-Language header. public static let acceptLanguage = Name("Accept-Language") /// Accept-Patch header. public static let acceptPatch = Name("Accept-Patch") /// Accept-Post header. public static let acceptPost = Name("Accept-Post") /// Accept-Ranges header. public static let acceptRanges = Name("Accept-Ranges") /// Accept-Age header. public static let age = Name("Age") /// Accept-Allow header. public static let allow = Name("Allow") /// ALPN header. public static let alpn = Name("ALPN") /// Alt-Svc header. public static let altSvc = Name("Alt-Svc") /// Alt-Used header. public static let altUsed = Name("Alt-Used") /// Alternatives header. public static let alternates = Name("Alternates") /// Apply-To-Redirect-Ref header. public static let applyToRedirectRef = Name("Apply-To-Redirect-Ref") /// Authentication-Control header. public static let authenticationControl = Name("Authentication-Control") /// Authentication-Info header. public static let authenticationInfo = Name("Authentication-Info") /// Authorization header. public static let authorization = Name("Authorization") /// C-Ext header. public static let cExt = Name("C-Ext") /// C-Man header. public static let cMan = Name("C-Man") /// C-Opt header. public static let cOpt = Name("C-Opt") /// C-PEP header. public static let cPEP = Name("C-PEP") /// C-PEP-Indo header. public static let cPEPInfo = Name("C-PEP-Info") /// Cache-Control header. public static let cacheControl = Name("Cache-Control") /// CalDav-Timezones header. public static let calDAVTimezones = Name("CalDAV-Timezones") /// Close header. public static let close = Name("Close") /// Connection header. public static let connection = Name("Connection") /// Content-Base. public static let contentBase = Name("Content-Base") /// Content-Disposition header. public static let contentDisposition = Name("Content-Disposition") /// Content-Encoding header. public static let contentEncoding = Name("Content-Encoding") /// Content-ID header. public static let contentID = Name("Content-ID") /// Content-Language header. public static let contentLanguage = Name("Content-Language") /// Content-Length header. public static let contentLength = Name("Content-Length") /// Content-Location header. public static let contentLocation = Name("Content-Location") /// Content-MD5 header. public static let contentMD5 = Name("Content-MD5") /// Content-Range header. public static let contentRange = Name("Content-Range") /// Content-Script-Type header. public static let contentScriptType = Name("Content-Script-Type") /// Content-Style-Type header. public static let contentStyleType = Name("Content-Style-Type") /// Content-Type header. public static let contentType = Name("Content-Type") /// Content-Version header. public static let contentVersion = Name("Content-Version") /// Content-Cookie header. public static let cookie = Name("Cookie") /// Content-Cookie2 header. public static let cookie2 = Name("Cookie2") /// DASL header. public static let dasl = Name("DASL") /// DASV header. public static let dav = Name("DAV") /// Date header. public static let date = Name("Date") /// Default-Style header. public static let defaultStyle = Name("Default-Style") /// Delta-Base header. public static let deltaBase = Name("Delta-Base") /// Depth header. public static let depth = Name("Depth") /// Derived-From header. public static let derivedFrom = Name("Derived-From") /// Destination header. public static let destination = Name("Destination") /// Differential-ID header. public static let differentialID = Name("Differential-ID") /// Digest header. public static let digest = Name("Digest") /// ETag header. public static let eTag = Name("ETag") /// Expect header. public static let expect = Name("Expect") /// Expires header. public static let expires = Name("Expires") /// Ext header. public static let ext = Name("Ext") /// Forwarded header. public static let forwarded = Name("Forwarded") /// From header. public static let from = Name("From") /// GetProfile header. public static let getProfile = Name("GetProfile") /// Hobareg header. public static let hobareg = Name("Hobareg") /// Host header. public static let host = Name("Host") /// HTTP2-Settings header. public static let http2Settings = Name("HTTP2-Settings") /// IM header. public static let im = Name("IM") /// If header. public static let `if` = Name("If") /// If-Match header. public static let ifMatch = Name("If-Match") /// If-Modified-Since header. public static let ifModifiedSince = Name("If-Modified-Since") /// If-None-Match header. public static let ifNoneMatch = Name("If-None-Match") /// If-Range header. public static let ifRange = Name("If-Range") /// If-Schedule-Tag-Match header. public static let ifScheduleTagMatch = Name("If-Schedule-Tag-Match") /// If-Unmodified-Since header. public static let ifUnmodifiedSince = Name("If-Unmodified-Since") /// Keep-Alive header. public static let keepAlive = Name("Keep-Alive") /// Label header. public static let label = Name("Label") /// Last-Modified header. public static let lastModified = Name("Last-Modified") /// Link header. public static let link = Name("Link") /// Location header. public static let location = Name("Location") /// Lock-Token header. public static let lockToken = Name("Lock-Token") /// Man header. public static let man = Name("Man") /// Max-Forwards header. public static let maxForwards = Name("Max-Forwards") /// Memento-Date header. public static let mementoDatetime = Name("Memento-Datetime") /// Meter header. public static let meter = Name("Meter") /// MIME-Version header. public static let mimeVersion = Name("MIME-Version") /// Negotiate header. public static let negotiate = Name("Negotiate") /// Opt header. public static let opt = Name("Opt") /// Optional-WWW-Authenticate header. public static let optionalWWWAuthenticate = Name("Optional-WWW-Authenticate") /// Ordering-Type header. public static let orderingType = Name("Ordering-Type") /// Origin header. public static let origin = Name("Origin") /// Overwrite header. public static let overwrite = Name("Overwrite") /// P3P header. public static let p3p = Name("P3P") /// PEP header. public static let pep = Name("PEP") /// PICS-Label header. public static let picsLabel = Name("PICS-Label") /// Pep-Info header. public static let pepInfo = Name("Pep-Info") /// Position header. public static let position = Name("Position") /// Pragma header. public static let pragma = Name("Pragma") /// Prefer header. public static let prefer = Name("Prefer") /// Preference-Applied header. public static let preferenceApplied = Name("Preference-Applied") /// ProfileObject header. public static let profileObject = Name("ProfileObject") /// Protocol header. public static let `protocol` = Name("Protocol") /// Protocol-Info header. public static let protocolInfo = Name("Protocol-Info") /// Protocol-Query header. public static let protocolQuery = Name("Protocol-Query") /// Protocol-Request header. public static let protocolRequest = Name("Protocol-Request") /// Proxy-Authenticate header. public static let proxyAuthenticate = Name("Proxy-Authenticate") /// Proxy-Authentication-Info header. public static let proxyAuthenticationInfo = Name("Proxy-Authentication-Info") /// Proxy-Authorization header. public static let proxyAuthorization = Name("Proxy-Authorization") /// Proxy-Features header. public static let proxyFeatures = Name("Proxy-Features") /// Proxy-Instruction header. public static let proxyInstruction = Name("Proxy-Instruction") /// Public header. public static let `public` = Name("Public") /// Public-Key-Pins header. public static let publicKeyPins = Name("Public-Key-Pins") /// Public-Key-Pins-Report-Only header. public static let publicKeyPinsReportOnly = Name("Public-Key-Pins-Report-Only") /// Range header. public static let range = Name("Range") /// Redirect-Ref header. public static let redirectRef = Name("Redirect-Ref") /// Referer header. public static let referer = Name("Referer") /// Retry-After header. public static let retryAfter = Name("Retry-After") /// Safe header. public static let safe = Name("Safe") /// Schedule-Reply header. public static let scheduleReply = Name("Schedule-Reply") /// Schedule-Tag header. public static let scheduleTag = Name("Schedule-Tag") /// Sec-WebSocket-Accept header. public static let secWebSocketAccept = Name("Sec-WebSocket-Accept") /// Sec-WebSocket-Extensions header. public static let secWebSocketExtensions = Name("Sec-WebSocket-Extensions") /// Sec-WebSocket-Key header. public static let secWebSocketKey = Name("Sec-WebSocket-Key") /// Sec-WebSocket-Protocol header. public static let secWebSocketProtocol = Name("Sec-WebSocket-Protocol") /// Sec-WebSocket-Version header. public static let secWebSocketVersion = Name("Sec-WebSocket-Version") /// Security-Scheme header. public static let securityScheme = Name("Security-Scheme") /// Server header. public static let server = Name("Server") /// Set-Cookie header. public static let setCookie = Name("Set-Cookie") /// Set-Cookie2 header. public static let setCookie2 = Name("Set-Cookie2") /// SetProfile header. public static let setProfile = Name("SetProfile") /// SLUG header. public static let slug = Name("SLUG") /// SoapAction header. public static let soapAction = Name("SoapAction") /// Status-URI header. public static let statusURI = Name("Status-URI") /// Strict-Transport-Security header. public static let strictTransportSecurity = Name("Strict-Transport-Security") /// Surrogate-Capability header. public static let surrogateCapability = Name("Surrogate-Capability") /// Surrogate-Control header. public static let surrogateControl = Name("Surrogate-Control") /// TCN header. public static let tcn = Name("TCN") /// TE header. public static let te = Name("TE") /// Timeout header. public static let timeout = Name("Timeout") /// Topic header. public static let topic = Name("Topic") /// Trailer header. public static let trailer = Name("Trailer") /// Transfer-Encoding header. public static let transferEncoding = Name("Transfer-Encoding") /// TTL header. public static let ttl = Name("TTL") /// Urgency header. public static let urgency = Name("Urgency") /// URI header. public static let uri = Name("URI") /// Upgrade header. public static let upgrade = Name("Upgrade") /// User-Agent header. public static let userAgent = Name("User-Agent") /// Variant-Vary header. public static let variantVary = Name("Variant-Vary") /// Vary header. public static let vary = Name("Vary") /// Via header. public static let via = Name("Via") /// WWW-Authenticate header. public static let wwwAuthenticate = Name("WWW-Authenticate") /// Want-Digest header. public static let wantDigest = Name("Want-Digest") /// Warning header. public static let warning = Name("Warning") /// X-Frame-Options header. public static let xFrameOptions = Name("X-Frame-Options") // https://www.iana.org/assignments/message-headers/message-headers.xhtml // Provisional Message Header Field Names /// Access-Control header. public static let accessControl = Name("Access-Control") /// Access-Control-Allow-Credentials header. public static let accessControlAllowCredentials = Name("Access-Control-Allow-Credentials") /// Access-Control-Allow-Headers header. public static let accessControlAllowHeaders = Name("Access-Control-Allow-Headers") /// Access-Control-Allow-Methods header. public static let accessControlAllowMethods = Name("Access-Control-Allow-Methods") /// Access-Control-Allow-Origin header. public static let accessControlAllowOrigin = Name("Access-Control-Allow-Origin") /// Access-Control-Max-Age header. public static let accessControlMaxAge = Name("Access-Control-Max-Age") /// Access-Control-Request-Method header. public static let accessControlRequestMethod = Name("Access-Control-Request-Method") /// Access-Control-Request-Headers header. public static let accessControlRequestHeaders = Name("Access-Control-Request-Headers") /// Compliance header. public static let compliance = Name("Compliance") /// Content-Transfer-Encoding header. public static let contentTransferEncoding = Name("Content-Transfer-Encoding") /// Cost header. public static let cost = Name("Cost") /// EDIINT-Features header. public static let ediintFeatures = Name("EDIINT-Features") /// Message-ID header. public static let messageID = Name("Message-ID") /// Method-Check header. public static let methodCheck = Name("Method-Check") /// Method-Check-Expires header. public static let methodCheckExpires = Name("Method-Check-Expires") /// Non-Compliance header. public static let nonCompliance = Name("Non-Compliance") /// Optional header. public static let optional = Name("Optional") /// Referer-Root header. public static let refererRoot = Name("Referer-Root") /// Resolution-Hint header. public static let resolutionHint = Name("Resolution-Hint") /// Resolver-Location header. public static let resolverLocation = Name("Resolver-Location") /// SubOK header. public static let subOK = Name("SubOK") /// Subst header. public static let subst = Name("Subst") /// Title header. public static let title = Name("Title") /// UA-Color header. public static let uaColor = Name("UA-Color") /// UA-Media header. public static let uaMedia = Name("UA-Media") /// UA-Pixels header. public static let uaPixels = Name("UA-Pixels") /// UA-Resolution header. public static let uaResolution = Name("UA-Resolution") /// UA-Windowpixels header. public static let uaWindowpixels = Name("UA-Windowpixels") /// Version header. public static let version = Name("Version") /// X-Device-Accept header. public static let xDeviceAccept = Name("X-Device-Accept") /// X-Device-Accept-Charset header. public static let xDeviceAcceptCharset = Name("X-Device-Accept-Charset") /// X-Device-Accept-Encoding header. public static let xDeviceAcceptEncoding = Name("X-Device-Accept-Encoding") /// X-Device-Accept-Language header. public static let xDeviceAcceptLanguage = Name("X-Device-Accept-Language") /// X-Device-User-Agent header. public static let xDeviceUserAgent = Name("X-Device-User-Agent") } }
apache-2.0
87da4631a6e7feb91aad2c4b784f2874
40.731123
99
0.604987
4.712978
false
false
false
false
jaouahbi/OMShadingGradientLayer
Example/OShadingGradientLayerViewController.swift
1
17855
// // Copyright 2015 - Jorge Ouahbi // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import OMShadingGradientLayer import LibControl let kDefaultAnimationDuration: TimeInterval = 5.0 class OShadingGradientLayerViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var pointStartX : UISlider! @IBOutlet weak var pointEndX : UISlider! @IBOutlet weak var pointStartY : UISlider! @IBOutlet weak var pointEndY : UISlider! @IBOutlet weak var endPointSliderValueLabel : UILabel! @IBOutlet weak var startPointSliderValueLabel : UILabel! @IBOutlet weak var viewForGradientLayer : UIView! @IBOutlet weak var startRadiusSlider : UISlider! @IBOutlet weak var endRadiusSlider : UISlider! @IBOutlet weak var startRadiusSliderValueLabel : UILabel! @IBOutlet weak var endRadiusSliderValueLabel : UILabel! @IBOutlet weak var typeGardientSwitch: UISwitch! @IBOutlet weak var extendsPastEnd : UISwitch! @IBOutlet weak var extendsPastStart : UISwitch! @IBOutlet weak var segmenFunction : UISegmentedControl! @IBOutlet weak var strokePath : UISwitch! @IBOutlet weak var randomPath : UISwitch! var colors : [UIColor] = [] var locations : [CGFloat] = [0.0,1.0] var subviewForGradientLayer : OMView<OMShadingGradientLayer>! var gradientLayer: OMShadingGradientLayer = OMShadingGradientLayer(type:.radial) var animate = true lazy var slopeFunction: [(Double) -> Double] = { return [ Linear, QuadraticEaseIn, QuadraticEaseOut, QuadraticEaseInOut, CubicEaseIn, CubicEaseOut, CubicEaseInOut, QuarticEaseIn, QuarticEaseOut, QuarticEaseInOut, QuinticEaseIn, QuinticEaseOut, QuinticEaseInOut, SineEaseIn, SineEaseOut, SineEaseInOut, CircularEaseIn, CircularEaseOut, CircularEaseInOut, ExponentialEaseIn, ExponentialEaseOut, ExponentialEaseInOut, ElasticEaseIn, ElasticEaseOut, ElasticEaseInOut, BackEaseIn, BackEaseOut, BackEaseInOut, BounceEaseIn, BounceEaseOut, BounceEaseInOut, ] }() lazy var slopeFunctionString:[String] = { return [ "Linear", "QuadraticEaseIn", "QuadraticEaseOut", "QuadraticEaseInOut", "CubicEaseIn", "CubicEaseOut", "CubicEaseInOut", "QuarticEaseIn", "QuarticEaseOut", "QuarticEaseInOut", "QuinticEaseIn", "QuinticEaseOut", "QuinticEaseInOut", "SineEaseIn", "SineEaseOut", "SineEaseInOut", "CircularEaseIn", "CircularEaseOut", "CircularEaseInOut", "ExponentialEaseIn", "ExponentialEaseOut", "ExponentialEaseInOut", "ElasticEaseIn", "ElasticEaseOut", "ElasticEaseInOut", "BackEaseIn", "BackEaseOut", "BackEaseInOut", "BounceEaseIn", "BounceEaseOut", "BounceEaseInOut", ] }() // MARK: - UITableView Helpers func selectIndexPath(_ row:Int, section:Int = 0) { let indexPath = IndexPath(item: row, section: section) self.tableView.selectRow(at: indexPath,animated: true,scrollPosition: .bottom) self.gradientLayer.slopeFunction = self.slopeFunction[(indexPath as NSIndexPath).row]; } // MARK: - UITableView Datasource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return slopeFunction.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) assert(self.slopeFunctionString.count == self.slopeFunction.count) cell.textLabel?.textAlignment = .center cell.textLabel?.font = UIFont(name: "Helvetica", size: 9) cell.textLabel?.text = "\(self.slopeFunctionString[(indexPath as NSIndexPath).row])" cell.layer.cornerRadius = 8 cell.layer.masksToBounds = true return cell } // MARK: - UITableView Delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.gradientLayer.slopeFunction = self.slopeFunction[(indexPath as NSIndexPath).row]; } @IBAction func maskTextSwitchChanged(_ sender: UISwitch) { if (sender.isOn) { textLayer.removeFromSuperlayer() gradientLayer.mask = textLayer } else { gradientLayer.mask = nil gradientLayer.addSublayer(textLayer) } updateGradientLayer() } // MARK: - View life cycle var textLayer: OMTextLayer = OMTextLayer(string: "Hello text shading", font: UIFont(name: "Helvetica",size: 50)!) override func viewDidLoad() { super.viewDidLoad() subviewForGradientLayer = OMView<OMShadingGradientLayer>(frame: viewForGradientLayer.frame) viewForGradientLayer.addSubview(subviewForGradientLayer) gradientLayer = subviewForGradientLayer!.gradientLayer gradientLayer.addSublayer(textLayer) randomizeColors() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let viewBounds = viewForGradientLayer.bounds pointStartX.maximumValue = 1.0 pointStartY.minimumValue = 0.0 pointEndX.maximumValue = 1.0 pointEndY.minimumValue = 0.0 let startPoint = CGPoint(x:viewBounds.minX / viewBounds.size.width,y: viewBounds.minY / viewBounds.size.height) let endPoint = CGPoint(x:viewBounds.minX / viewBounds.size.width,y: viewBounds.maxY / viewBounds.size.height) pointStartX.value = Float(startPoint.x) pointStartY.value = Float(startPoint.y) pointEndX.value = Float(endPoint.x) pointEndY.value = Float(endPoint.y) extendsPastEnd.isOn = true extendsPastStart.isOn = true // radius endRadiusSlider.maximumValue = 1.0 endRadiusSlider.minimumValue = 0 startRadiusSlider.maximumValue = 1.0 startRadiusSlider.minimumValue = 0 startRadiusSlider.value = 1.0 endRadiusSlider.value = 0 // select the first element selectIndexPath(0) gradientLayer.frame = viewBounds gradientLayer.locations = locations // update the gradient layer frame self.gradientLayer.frame = self.viewForGradientLayer.bounds // text layers self.textLayer.frame = self.viewForGradientLayer.bounds // 2% // textLayer.borderWidth = 100 // self.textLayer.frame = self.viewForGradientLayer.bounds // // viewForGradientLayer.layer.addSublayer(gradientLayer) // viewForGradientLayer.backgroundColor = UIColor.clear #if DEBUG viewForGradientLayer.layer.borderWidth = 1.0 viewForGradientLayer.layer.borderColor = UIColor.blackColor().CGColor #endif updateTextPointsUI() updateGradientLayer() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: {(UIViewControllerTransitionCoordinatorContext) in }) {(UIViewControllerTransitionCoordinatorContext) in // update the gradient layer frame self.gradientLayer.frame = self.viewForGradientLayer.bounds } } // MARK: - Triggered actions @IBAction func extendsPastStartChanged(_ sender: UISwitch) { gradientLayer.extendsBeforeStart = sender.isOn } @IBAction func extendsPastEndChanged(_ sender: UISwitch) { gradientLayer.extendsPastEnd = sender.isOn } @IBAction func gradientSliderChanged(_ sender: UISlider) { updateTextPointsUI() updateGradientLayer() } @IBAction func strokeSwitchChanged(_ sender: UISwitch) { if ((gradientLayer.path) != nil) { gradientLayer.stroke = sender.isOn } sender.isOn = gradientLayer.stroke } @IBAction func maskSwitchChanged(_ sender: UISwitch) { if sender.isOn { let style = PolygonStyle(rawValue:Int(arc4random_uniform(6)))! let radius = CGFloat(drand48()) * viewForGradientLayer.bounds.size.min let sides = Int(arc4random_uniform(32)) + 4 let path = UIBezierPath.polygon(frame: viewForGradientLayer.bounds, sides: sides, radius: radius, startAngle: 0, style: style, percentInflection: CGFloat(drand48())) gradientLayer.path = path.cgPath } else{ gradientLayer.path = nil strokePath.isOn = false } updateGradientLayer() } @IBAction func typeSwitchChanged(_ sender: UISwitch) { self.gradientLayer.gradientType = sender.isOn ? .radial : .axial; updateGradientLayer() } fileprivate func updateSlopeFunction(_ index: Int) { switch(index) { case 0: self.gradientLayer.function = .linear break case 1: self.gradientLayer.function = .exponential break case 2: self.gradientLayer.function = .cosine break default: self.gradientLayer.function = .linear assertionFailure(); } } @IBAction func functionSwitchChanged(_ sender: UISegmentedControl) { updateSlopeFunction(sender.selectedSegmentIndex) updateGradientLayer() } @IBAction func animateSwitchChanged(_ sender: UISwitch) { self.animate = sender.isOn updateGradientLayer() } @IBAction func randomButtonTouchUpInside(_ sender: UIButton) { // random points pointStartX.value = Float(CGFloat(drand48())) pointStartY.value = Float(CGFloat(drand48())) pointEndX.value = Float(CGFloat(drand48())) pointEndY.value = Float(CGFloat(drand48())) // select random slope function selectIndexPath(Int(arc4random()) % tableView.numberOfRows(inSection: 0)) let segmentIndex = Int(arc4random()) % segmenFunction.numberOfSegments updateSlopeFunction(segmentIndex) segmenFunction.selectedSegmentIndex = segmentIndex typeGardientSwitch.isOn = Float(drand48()) > 0.5 ? true : false extendsPastEnd.isOn = Float(drand48()) > 0.5 ? true : false extendsPastStart.isOn = Float(drand48()) > 0.5 ? true : false if (typeGardientSwitch.isOn) { // random radius endRadiusSlider.value = Float(drand48()); startRadiusSlider.value = Float(drand48()); // random scale CGAffineTransform gradientLayer.radialTransform = CGAffineTransform.randomScale() } // random colors randomizeColors() // update the UI updateTextPointsUI(); // update the gradient layer updateGradientLayer() } // MARK: - Helpers func randomizeColors() { self.locations = [] self.colors.removeAll() var numberOfColor = round(Float(drand48()) * 16) while numberOfColor > 0 { let color = UIColor.random self.colors.append(color) numberOfColor = numberOfColor - 1 } self.gradientLayer.colors = colors } func updateGradientLayer() { viewForGradientLayer.layoutIfNeeded() let endRadius = Double(endRadiusSlider.value) let startRadius = Double(startRadiusSlider.value) let startPoint = CGPoint(x:CGFloat(pointStartX.value),y:CGFloat(pointStartY.value)) let endPoint = CGPoint(x:CGFloat(pointEndX.value),y:CGFloat(pointEndY.value)) gradientLayer.extendsPastEnd = extendsPastEnd.isOn gradientLayer.extendsBeforeStart = extendsPastStart.isOn gradientLayer.gradientType = typeGardientSwitch.isOn ? .radial: .axial if (self.animate) { // allways remove all animations gradientLayer.removeAllAnimations() let mediaTime = CACurrentMediaTime() CATransaction.begin() gradientLayer.animateKeyPath("colors", fromValue:nil, toValue: colors as AnyObject?, beginTime: mediaTime, duration: kDefaultAnimationDuration, delegate: nil) gradientLayer.animateKeyPath("locations", fromValue:nil, toValue: self.locations as AnyObject?, beginTime: mediaTime, duration: kDefaultAnimationDuration, delegate: nil) gradientLayer.animateKeyPath("startPoint", fromValue: NSValue(cgPoint: gradientLayer.startPoint), toValue: NSValue(cgPoint:startPoint), beginTime: mediaTime , duration: kDefaultAnimationDuration, delegate: nil) gradientLayer.animateKeyPath("endPoint", fromValue: NSValue(cgPoint:gradientLayer.endPoint), toValue: NSValue(cgPoint:endPoint), beginTime: mediaTime, duration: kDefaultAnimationDuration, delegate: nil) if gradientLayer.gradientType == .radial { gradientLayer.animateKeyPath("startRadius", fromValue: Double(gradientLayer.startRadius) as AnyObject?, toValue: startRadius as AnyObject?, beginTime: mediaTime , duration: kDefaultAnimationDuration, delegate: nil) gradientLayer.animateKeyPath("endRadius", fromValue: Double(gradientLayer.endRadius) as AnyObject?, toValue: endRadius as AnyObject?, beginTime: mediaTime, duration: kDefaultAnimationDuration, delegate: nil) } CATransaction.commit() } else { gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint gradientLayer.colors = self.colors // gradientLayer.locations = self.locations gradientLayer.startRadius = CGFloat(startRadius) gradientLayer.endRadius = CGFloat(endRadius) self.gradientLayer.setNeedsDisplay() } } func updateTextPointsUI() { // points text startPointSliderValueLabel.text = String(format: "%.1f,%.1f", pointStartX.value,pointStartY.value) endPointSliderValueLabel.text = String(format: "%.1f,%.1f", pointEndX.value,pointEndY.value) //radius text startRadiusSliderValueLabel.text = String(format: "%.1f", Double(startRadiusSlider.value)) endRadiusSliderValueLabel.text = String(format: "%.1f", Double(endRadiusSlider.value)) } }
apache-2.0
3cca2052c58c56414e5172ba9a19e76c
34.853414
119
0.562419
5.662861
false
false
false
false
RemyDCF/tpg-offline
tpg offline SiriUI/IntentViewController.swift
1
3229
// // IntentViewController.swift // tpg offline SiriUI // // Created by レミー on 13/07/2018. // Copyright © 2018 Remy. All rights reserved. // import IntentsUI class IntentViewController: UIViewController, INUIHostedViewControlling { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var titleLabel: UILabel! var departures: [String] = [] { didSet { self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() } func configureView(for parameters: Set<INParameter>, of interaction: INInteraction, interactiveBehavior: INUIInteractiveBehavior, context: INUIHostedViewContext, completion: @escaping (Bool, Set<INParameter>, CGSize) -> Void) { // swiftlint:disable:previous line_length guard let intent = interaction.intent as? DeparturesIntent, let intentResponse = interaction.intentResponse as? DeparturesIntentResponse else { return } titleLabel.text = intent.stop?.displayString ?? "" var departuresTemp: [String] = [] for departure in (intentResponse.departures ?? []) { if let id = departure.identifier { departuresTemp.append(id) } } departures = departuresTemp self.tableView.layoutIfNeeded() completion(true, parameters, self.desiredSize) } var desiredSize: CGSize { return CGSize(width: self.extensionContext!.hostedViewMaximumAllowedSize.width, height: CGFloat(self.departures.count * 44) + 45 + 16) } } extension IntentViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return departures.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "departureCell", for: indexPath) as? SiriDepartureCell else { return UITableViewCell() } cell.departureString = self.departures[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } } class SiriDepartureCell: UITableViewCell { @IBOutlet weak var lineLabel: UILabel! @IBOutlet weak var destinationLabel: UILabel! @IBOutlet weak var leftTimeLabel: UILabel! var departureString = "" { didSet { let components = departureString.split(separator: ",") guard components.count == 3 else { return } let line = String(components[0]) let destination = String(components[1]) var leftTime = String(components[2]) if leftTime == "&gt;1h" { leftTime = ">1h" } lineLabel.text = line destinationLabel.text = destination leftTimeLabel.text = "\(leftTime)'" lineLabel.textColor = LineColorManager.color(for: line).contrast lineLabel.backgroundColor = LineColorManager.color(for: line) lineLabel.layer.cornerRadius = lineLabel.bounds.height / 2 lineLabel.clipsToBounds = true } } }
mit
153643017e6eaf4aa692828b696ceba9
30.281553
86
0.662322
4.710526
false
false
false
false
getconnect/connect-swift
Pod/Classes/RelativeTimeframe.swift
1
1690
// // RelativeTimeframe.swift // Pods // // Created by Chad Edrupt on 4/01/2016. // // import Foundation public enum RelativeTimeframe { case Minutes(Int) case Hours(Int) case Days(Int) case Weeks(Int) case Months(Int) case Quarters(Int) case Years(Int) var jsonObject: AnyObject { switch self { case let .Minutes(value): return ["minutes": value] case let .Hours(value): return ["hours": value] case let .Days(value): return ["days": value] case let .Weeks(value): return ["weeks": value] case let .Months(value): return ["months": value] case let .Quarters(value): return ["quarters": value] case let .Years(value): return ["years": value] } } } extension RelativeTimeframe: Equatable { } public func ==(lhs: RelativeTimeframe, rhs: RelativeTimeframe) -> Bool { switch (lhs, rhs) { case (let .Minutes(lhsValue), let .Minutes(rhsValue)): return lhsValue == rhsValue case (let .Hours(lhsValue), let .Hours(rhsValue)): return lhsValue == rhsValue case (let .Days(lhsValue), let .Days(rhsValue)): return lhsValue == rhsValue case (let .Weeks(lhsValue), let .Weeks(rhsValue)): return lhsValue == rhsValue case (let .Months(lhsValue), let .Months(rhsValue)): return lhsValue == rhsValue case (let .Quarters(lhsValue), let .Quarters(rhsValue)): return lhsValue == rhsValue case (let .Years(lhsValue), let .Years(rhsValue)): return lhsValue == rhsValue default: return false } }
mit
e380883770b982067f125eb383175bfc
26.258065
72
0.588166
4.152334
false
false
false
false
buyiyang/iosstar
iOSStar/AppAPI/SocketAPI/SocketReqeust/SocketRequest.swift
3
1855
// // SocketRequest.swift // viossvc // // Created by yaowang on 2016/11/23. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit //import XCGLogger class SocketRequest { static var errorDict:NSDictionary?; var error: ErrorBlock? var complete: CompleteBlock? var timestamp: TimeInterval = Date().timeIntervalSince1970 class func errorString(_ code:Int) ->String { if errorDict == nil { if let bundlePath = Bundle.main.path(forResource: "errorcode", ofType: "plist") { errorDict = NSDictionary(contentsOfFile: bundlePath) } } let key:String = String(format: "%d", code); var message = "unknown" if errorDict?.object(forKey: key) != nil { message = errorDict!.object(forKey: key) as! String } return AppConst.isMock ? "\(key):\(message)" : message; } deinit { // XCGLogger.debug(" \(self)") } func isReqeustTimeout() -> Bool { return timestamp + Double(AppConst.Network.TimeoutSec) <= Date().timeIntervalSince1970 } fileprivate func dispatch_main_async(_ block:@escaping ()->()) { DispatchQueue.main.async(execute: { block() }) } func onComplete(_ obj:AnyObject!) { dispatch_main_async { self.complete?(obj) } } func onError(_ errorCode:Int!) { let errorStr:String = SocketRequest.errorString(errorCode) let error = NSError(domain: AppConst.Text.ErrorDomain, code: errorCode , userInfo: [NSLocalizedDescriptionKey:errorStr]); onError(error) } func onError(_ error:NSError!) { dispatch_main_async { self.error?(error) } } }
gpl-3.0
50528efc1ca0537f9102bf26337044fb
24.027027
95
0.570734
4.653266
false
false
false
false
rockgarden/swift_language
Playground/Swift Standard Library.playground/Pages/foundation Classes.xcplaygroundpage/Contents.swift
1
12849
//: [Previous](@previous) import Foundation import UIKit class Dog : NSObject { var name : String init(_ name:String) {self.name = name} } do { let arr = ["hey"] as NSArray let ix = arr.index(of: "ho") if ix == NSNotFound { print("it wasn't found") } } do { let r = NSRange(location: 1, length: 3) print(r) let r2 = r.toRange() print(r2) // let r3 = Range(r) // print(r3) } do { let s = "hello" let r = s.range(of: "ha") // nil; an Optional wrapping a Swift Range if r == nil { print("it wasn't found") } } do { let s = "hello" as NSString let r = s.range(of: "ha") // an NSRange if r.location == NSNotFound { print("it wasn't found") } } do { let s = "hello" let s2 = s.capitalized // -[NSString capitalizedString] _ = s2 } do { let s = "hello" // let s2 = s.substringToIndex(4) // compile error let s2 = s.substring(to: s.characters.index(s.startIndex, offsetBy: 4)) let ss2 = (s as NSString).substring(to: 4) _ = s2 _ = ss2 } do { let s = "MyFile" let s2 = (s as NSString).appendingPathExtension("txt") // let s3 = s.stringByAppendingPathExtension("txt") // compile error print(s2) } do { let s = "hello" let ms = NSMutableString(string: s) ms.deleteCharacters(in: NSMakeRange(ms.length-1,1)) let s2 = (ms as String) + "ion" // now s2 is a Swift String print(s2) } do { let s = NSMutableString(string:"hello world, go to hell") let r = try! NSRegularExpression( pattern: "\\bhell\\b", options: .caseInsensitive) r.replaceMatches( in: s, options: [], range: NSMakeRange(0,s.length), withTemplate: "heaven") print(s) } do { let greg = Calendar(identifier:Calendar.Identifier.gregorian) var comp = DateComponents() comp.year = 2016 comp.month = 8 comp.day = 10 comp.hour = 15 let d = greg.date(from: comp) // Optional wrapping NSDate if let d = d { print(d) print(d.description(with: Locale.current)) } } do { let d = Date() // or whatever var comp = DateComponents() comp.month = 1 let greg = Calendar(identifier:Calendar.Identifier.gregorian) let d2 = (greg as NSCalendar).date(byAdding: comp, to:d, options:[]) _ = d2 } do { let df = DateFormatter() let format = DateFormatter.dateFormat( fromTemplate: "dMMMMyyyyhmmaz", options:0, locale:Locale.current) df.dateFormat = format let s = df.string(from: Date()) // just now print(s) } do { let ud = UserDefaults.standard ud.set(0, forKey: "Score") ud.set(0, forKey: "Score") let n = 0 as NSNumber let n2 = NSNumber(value: 0 as Float) do { // I regard these as bugs // let n = UInt32(0) as NSNumber // compile error // let i = n as! UInt32 // "always fails" } let dec1 = NSDecimalNumber(value: 4.0 as Float) let dec2 = NSDecimalNumber(value: 5.0 as Float) let sum = dec1.adding(dec2) // 9.0 _ = n _ = n2 _ = sum } do { // perhaps the first example is more convincing if we use a variable let ud = UserDefaults.standard let i = 0 ud.set(i, forKey: "Score") ud.set(i, forKey: "Score") } do { let ud = UserDefaults.standard let c = UIColor.blue let cdata = NSKeyedArchiver.archivedData(withRootObject: c) ud.set(cdata, forKey: "myColor") } do { let n1 = NSNumber(value: 1 as Int) let n2 = NSNumber(value: 2 as Int) let n3 = NSNumber(value: 3 as Int) let ok = n2 == 2 // true let ok2 = n2 == NSNumber(value: 2 as Int) // true let ix = [n1,n2,n3].index(of: 2) // Optional wrapping 1 // let ok3 = n1 < n2 // compile error let ok4 = n1.compare(n2) == .orderedAscending // true print(ok) print(ok2) print(ix) print(ok4) } do { let d1 = Dog("Fido") let d2 = Dog("Fido") let ok = d1 == d2 // false print(ok) } do { let arr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] var ixs = IndexSet() ixs.insert(integersIn: Range(1...4)) ixs.insert(integersIn: Range(8...10)) let arr2 = (arr as NSArray).objects(at:ixs) print(arr2) } do { let marr = NSMutableArray() marr.add(1) //NSNumber marr.add(2) //NSNumber print(type(of: marr[0])) let arr = marr as NSArray as! [Int] let arr2 = marr as! [Int] // warns, but it _looks_ like it succeeds... print(arr2) print(type(of: arr2[0])) let pep = ["Manny", "Moe", "Jack"] as NSArray /// Swift 3 indexesOfObjects has given a default value for the parameter options, which has made a simple call like .indexesOfObjects (passingTest: ...) ambiguous. let ems = pep.objects( at: pep.indexesOfObjects(options: [], passingTest: { obj, idx, stop in return (obj as! NSString).range( of: "m", options:.caseInsensitive ).location == 0 }) ) // ["Manny", "Moe"] _ = arr print(ems) let arr3 = marr.copy() _ = arr3 /// using Swift's collection methods, rather than using an NSArrays method: // let swift_pep = ["Manny", "Moe", "Jack"] // let swift_ems = swift_pep.enumerated().lazy // .filter {(a, b) in // //... // }.map{$0.offset} } do { let oldButtonCenter = CGPoint.zero let button = UIButton(type:.system) do { // let obj = NSObject().copy(with:nil) // compile error let s = "hello".copy() _ = s let s2 = ("hello" as NSString).copy(with: nil) _ = s2 } do { let arr = ["hey"] as NSArray let ix = arr.index(of:"ho") if ix == NSNotFound { print("it wasn't found") } } do { // let rr = NSRange(1...3) let r = NSRange(Range(1...3)) print(r) debugPrint(r) // that didn't help print(NSStringFromRange(r)) let r2 = r.toRange() print(r2) // let r3 = Range(r) // print(r3) } do { let s = "hello" let r = s.range(of:"ha") // nil; an Optional wrapping a Swift Range if r == nil { print("it wasn't found") } } do { let s = "hello" as NSString let r = s.range(of:"ha") // an NSRange if r.location == NSNotFound { print("it wasn't found") } } do { let s = "hello" let s2 = s.capitalized // -[NSString capitalizedString] } do { let s = "hello" let ix = "hello".startIndex // let s2a = s.substringToIndex(4) // compile error let s2 = s.substring(to:s.index(s.startIndex, offsetBy:4)) let ss2 = (s as NSString).substring(to:4) } do { let s = "MyFile" let s2 = (s as NSString).appendingPathExtension("txt") // let s3 = s.stringByAppendingPathExtension("txt") // compile error } do { let s = "hello" let ms = NSMutableString(string:s) ms.deleteCharacters(in: NSRange(location:ms.length-1,length:1)) let s2 = (ms as String) + "ion" // now s2 is a Swift String print(s2) } do { let s = NSMutableString(string:"hello world, go to hell") let r = try! NSRegularExpression( pattern: "\\bhell\\b", options: .caseInsensitive) r.replaceMatches( in: s, range: NSRange(location:0, length:s.length), withTemplate: "heaven") // I loooove being able to omit the options: parameter! print(s) } do { let greg = Calendar(identifier:.gregorian) let comp = DateComponents(calendar: greg, year: 2016, month: 8, day: 10, hour: 15) let d = comp.date // Optional wrapping Date if let d = d { print(d) print(d.description(with:Locale.current)) } } do { let d = Date() // or whatever let comp = DateComponents(month:1) let greg = Calendar(identifier:.gregorian) let d2 = greg.date(byAdding: comp, to:d) // Optional wrapping Date print("one month from now:", d2) } do { let greg = Calendar(identifier:.gregorian) let d1 = DateComponents(calendar: greg, year: 2016, month: 1, day: 1, hour: 0).date! let d2 = DateComponents(calendar: greg, year: 2016, month: 8, day: 10, hour: 15).date! let di = DateInterval(start: d1, end: d2) if di.contains(Date()) { // are we currently between those two dates? print("yep") } } do { let df = DateFormatter() let format = DateFormatter.dateFormat( fromTemplate:"dMMMMyyyyhmmaz", options:0, locale:Locale.current) df.dateFormat = format let s = df.string(from: Date()) // just now print(s) } do { UserDefaults.standard.set(1, forKey: "Score") // wow - unable to call setObject:forKey: while supplying a number! // ud.set(object: 0, forKey: "Score") let n = 1 as NSNumber // similarly, unable to call NSNumber initWithFloat: // instead we just supply a float and let it disambiguate let i : UInt8 = 1 // let n2 = i as NSNumber // not bridged let n2 = NSNumber(value:i) do { // I regard these as bugs // let n = UInt32(0) as NSNumber // compile error // let i = n as! UInt32 // "always fails" } let dec1 = NSDecimalNumber(value: 4.0) let dec2 = NSDecimalNumber(value: 5.0) let sum = dec1.adding(dec2) // 9.0 } do { // perhaps the first example is more convincing if we use a variable let ud = UserDefaults.standard let i = 0 ud.set(i, forKey: "Score") // ud.setObject(i, forKey: "Score") } do { let goal = CGPoint.zero // dummy let ba = CABasicAnimation(keyPath:"position") ba.duration = 10 ba.fromValue = NSValue(cgPoint: oldButtonCenter) ba.toValue = NSValue(cgPoint:goal) button.layer.add(ba, forKey:nil) } do { let anim = CAKeyframeAnimation(keyPath:"position") // dummy let (oldP,p1,p2,newP) = (CGPoint.zero,CGPoint.zero,CGPoint.zero,CGPoint.zero) // dummy anim.values = [oldP,p1,p2,newP].map {NSValue(cgPoint:$0)} } do { let ud = UserDefaults.standard let c = UIColor.blue let cdata = NSKeyedArchiver.archivedData(withRootObject:c) ud.set(cdata, forKey: "myColor") } do { let m1 = Measurement(value:5, unit: UnitLength.miles) let m2 = Measurement(value:6, unit: UnitLength.kilometers) let total = m1 + m2 print(total) let totalFeet = total.converted(to: .feet).value // 46084.9737532808 print(totalFeet) let mf = MeasurementFormatter() let s = mf.string(from:total) // "8.728 mi" print(s) } do { let n1 = NSNumber(value:1) let n2 = NSNumber(value:2) let n3 = NSNumber(value:3) let ok = n2 == 2 // true let ok2 = n2 == NSNumber(value:2) // true let ix = [n1,n2,n3].index(of:2) // Optional wrapping 1 // let ok3 = n1 < n2 // compile error let ok4 = n1.compare(n2) == .orderedAscending // true print(ok) print(ok2) print(ix) print(ok4) } do { let d1 = Dog("Fido") let d2 = Dog("Fido") let ok = d1 == d2 // false print(ok) } do { let arr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] var ixs = IndexSet() ixs.insert(integersIn: Range(1...4)) ixs.insert(integersIn: Range(8...10)) let arr2 = (arr as NSArray).objects(at:ixs) print(arr2) } do { let marr = NSMutableArray() marr.add(1) // an NSNumber marr.add(1) // an NSNumber print(type(of:marr[0])) let arr = marr as NSArray as! [Int] let arr2 = marr as! [Int] // warns, but it _looks_ like it succeeds... print(arr2) print(type(of:arr2[0])) let pep = ["Manny", "Moe", "Jack"] as NSArray // filed a bug: "ambiguous" without the [] let ems = pep.objects( at: pep.indexesOfObjects(options:[]) { (obj, idx, stop) -> Bool in return (obj as! NSString).range( of: "m", options:.caseInsensitive ).location == 0 } ) // ["Manny", "Moe"] print(ems) let arr3 = marr.copy() } } //: [Next](@next)
mit
cbac7d11f3ded756b045183a444df6e9
25.993697
167
0.544245
3.51642
false
false
false
false
qRoC/Loobee
Tests/LoobeeTests/Library/AssertionConcern/Assertion/BetweenRangeComparableTypesTests.swift
1
1816
// This file is part of the Loobee package. // // (c) Andrey Savitsky <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. import XCTest #if canImport(Loobee) @testable import Loobee #else @testable import LoobeeAssertionConcern #endif internal final class BetweenRangeComparableTypesTests: BaseAssertionsTests { /// func testOutOfRangeMinimum() { let value = 1 let range = 2..<5 self.assertMustBeNotValid( assert(value, between: range) ) } /// func testOutOfRangeMaximum() { let value = 6 let range = 2..<5 self.assertMustBeNotValid( assert(value, between: range) ) } /// func testMinimumEqual() { let value = 2 let range = 2..<5 self.assertMustBeValid(assert(value, between: range)) } /// func testMaximumEqual() { let value = 5 let range = 2..<5 self.assertMustBeNotValid( assert(value, between: range) ) } /// func testInRange() { let value = 4 let range = 2..<5 self.assertMustBeValid(assert(value, between: range)) } /// func testDefaultMessage() { let value = 1 let range = 2..<5 let message = kBetweenDefaultMessage.description self.assertMustBeNotValid( assert(value, between: range), withMessage: message ) } /// func testCustomMessage() { let value = 1 let range = 2..<5 let message = "Test" self.assertMustBeNotValid( assert(value, between: range, orNotification: message), withMessage: message ) } }
mit
fe999453517d39a49723754e48a072a7
20.364706
76
0.573789
4.344498
false
true
false
false
suncry/MLHybrid
Example/Pods/Kingfisher/Sources/ImageProcessor.swift
2
29464
// // ImageProcessor.swift // Kingfisher // // Created by Wei Wang on 2016/08/26. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics #if os(macOS) import AppKit #endif /// The item which could be processed by an `ImageProcessor` /// /// - image: Input image /// - data: Input data public enum ImageProcessItem { case image(Image) case data(Data) } /// An `ImageProcessor` would be used to convert some downloaded data to an image. public protocol ImageProcessor { /// Identifier of the processor. It will be used to identify the processor when /// caching and retrieving an image. You might want to make sure that processors with /// same properties/functionality have the same identifiers, so correct processed images /// could be retrived with proper key. /// /// - Note: Do not supply an empty string for a customized processor, which is already taken by /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation /// string of your own for the identifier. var identifier: String { get } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: The return value will be `nil` if processing failed while converting data to image. /// If input item is already an image and there is any errors in processing, the input /// image itself will be returned. /// - Note: Most processor only supports CG-based images. /// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? } typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?) public extension ImageProcessor { /// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor` /// will be "\(self.identifier)|>\(another.identifier)". /// /// - parameter another: An `ImageProcessor` you want to append to `self`. /// /// - returns: The new `ImageProcessor` will process the image in the order /// of the two processors concatenated. public func append(another: ImageProcessor) -> ImageProcessor { let newIdentifier = identifier.appending("|>\(another.identifier)") return GeneralProcessor(identifier: newIdentifier) { item, options in if let image = self.process(item: item, options: options) { return another.process(item: .image(image), options: options) } else { return nil } } } } func ==(left: ImageProcessor, right: ImageProcessor) -> Bool { return left.identifier == right.identifier } func !=(left: ImageProcessor, right: ImageProcessor) -> Bool { return !(left == right) } fileprivate struct GeneralProcessor: ImageProcessor { let identifier: String let p: ProcessorImp func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { return p(item, options) } } /// The default processor. It convert the input data to a valid image. /// Images of .PNG, .JPEG and .GIF format are supported. /// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image. public struct DefaultImageProcessor: ImageProcessor { /// A default `DefaultImageProcessor` could be used across. public static let `default` = DefaultImageProcessor() /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "" /// Initialize a `DefaultImageProcessor` public init() {} /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) case .data(let data): return Kingfisher<Image>.image( data: data, scale: options.scaleFactor, preloadAllAnimationData: options.preloadAllAnimationData, onlyFirstFrame: options.onlyLoadFirstFrame) } } } public struct RectCorner: OptionSet { public let rawValue: Int public static let topLeft = RectCorner(rawValue: 1 << 0) public static let topRight = RectCorner(rawValue: 1 << 1) public static let bottomLeft = RectCorner(rawValue: 1 << 2) public static let bottomRight = RectCorner(rawValue: 1 << 3) public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight] public init(rawValue: Int) { self.rawValue = rawValue } var cornerIdentifier: String { if self == .all { return "" } return "_corner(\(rawValue))" } } #if !os(macOS) /// Processor for adding an blend mode to images. Only CG-based images are supported. public struct BlendImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blend Mode will be used to blend the input image. public let blendMode: CGBlendMode /// Alpha will be used when blend image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: Color? /// Initialize an `BlendImageProcessor` /// /// - parameter blendMode: Blend Mode will be used to blend the input image. /// - parameter alpha: Alpha will be used when blend image. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image. /// Default is 1.0. /// - parameter backgroundColor: Backgroud color to apply for the output image. Default is `nil`. public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: Color? = nil) { self.blendMode = blendMode self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } #endif #if os(macOS) /// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS. public struct CompositingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Compositing operation will be used to the input image. public let compositingOperation: NSCompositingOperation /// Alpha will be used when compositing image. public let alpha: CGFloat /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: Color? /// Initialize an `CompositingImageProcessor` /// /// - parameter compositingOperation: Compositing operation will be used to the input image. /// - parameter alpha: Alpha will be used when compositing image. /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image. /// Default is 1.0. /// - parameter backgroundColor: Backgroud color to apply for the output image. Default is `nil`. public init(compositingOperation: NSCompositingOperation, alpha: CGFloat = 1.0, backgroundColor: Color? = nil) { self.compositingOperation = compositingOperation self.alpha = alpha self.backgroundColor = backgroundColor var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))" if let color = backgroundColor { identifier.append("_\(color.hex)") } self.identifier = identifier } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.image(withCompositingOperation: compositingOperation, alpha: alpha, backgroundColor: backgroundColor) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } #endif /// Processor for making round corner images. Only CG-based images are supported in macOS, /// if a non-CG image passed in, the processor will do nothing. public struct RoundCornerImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Corner radius will be applied in processing. public let cornerRadius: CGFloat /// The target corners which will be applied rounding. public let roundingCorners: RectCorner /// Target size of output image should be. If `nil`, the image will keep its original size after processing. public let targetSize: CGSize? /// Background color of the output image. If `nil`, it will stay transparent. public let backgroundColor: Color? /// Initialize a `RoundCornerImageProcessor` /// /// - parameter cornerRadius: Corner radius will be applied in processing. /// - parameter targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// - parameter corners: The target corners which will be applied rounding. Default is `.all`. /// - parameter backgroundColor: Backgroud color to apply for the output image. Default is `nil`. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil, roundingCorners corners: RectCorner = .all, backgroundColor: Color? = nil) { self.cornerRadius = cornerRadius self.targetSize = targetSize self.roundingCorners = corners self.backgroundColor = backgroundColor self.identifier = { var identifier = "" if let size = targetSize { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size)\(corners.cornerIdentifier))" } else { identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)\(corners.cornerIdentifier))" } if let backgroundColor = backgroundColor { identifier += "_\(backgroundColor)" } return identifier }() } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): let size = targetSize ?? image.kf.size return image.kf.scaled(to: options.scaleFactor) .kf.image(withRoundRadius: cornerRadius, fit: size, roundingCorners: roundingCorners, backgroundColor: backgroundColor) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Specify how a size adjusts itself to fit a target size. /// /// - none: Not scale the content. /// - aspectFit: Scale the content to fit the size of the view by maintaining the aspect ratio. /// - aspectFill: Scale the content to fill the size of the view public enum ContentMode { case none case aspectFit case aspectFill } /// Processor for resizing images. Only CG-based images are supported in macOS. public struct ResizingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// The reference size for resizing operation. public let referenceSize: CGSize /// Target content mode of output image should be. /// Default to ContentMode.none public let targetContentMode: ContentMode /// Initialize a `ResizingImageProcessor`. /// /// - Parameters: /// - referenceSize: The reference size for resizing operation. /// - mode: Target content mode of output image should be. /// /// - Note: /// The instance of `ResizingImageProcessor` will follow its `mode` property /// and try to resizing the input images to fit or fill the `referenceSize`. /// That means if you are using a `mode` besides of `.none`, you may get an /// image with its size not be the same as the `referenceSize`. /// /// **Example**: With input image size: {100, 200}, /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`, /// you will get an output image with size of {50, 100}, which "fit"s /// the `referenceSize`. /// /// If you need an output image exactly to be a specified size, append or use /// a `CroppingImageProcessor`. public init(referenceSize: CGSize, mode: ContentMode = .none) { self.referenceSize = referenceSize self.targetContentMode = mode if mode == .none { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))" } else { self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))" } } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.resize(to: referenceSize, for: targetContentMode) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for /// a better performance. A simulated Gaussian blur with specified blur radius will be applied. public struct BlurImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Blur radius for the simulated Gaussian blur. public let blurRadius: CGFloat /// Initialize a `BlurImageProcessor` /// /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. public init(blurRadius: CGFloat) { self.blurRadius = blurRadius self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): let radius = blurRadius * options.scaleFactor return image.kf.scaled(to: options.scaleFactor) .kf.blurred(withRadius: radius) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for adding an overlay to images. Only CG-based images are supported in macOS. public struct OverlayImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Overlay color will be used to overlay the input image. public let overlay: Color /// Fraction will be used when overlay the color to image. public let fraction: CGFloat /// Initialize an `OverlayImageProcessor` /// /// - parameter overlay: Overlay color will be used to overlay the input image. /// - parameter fraction: Fraction will be used when overlay the color to image. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. public init(overlay: Color, fraction: CGFloat = 0.5) { self.overlay = overlay self.fraction = fraction self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))" } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.overlaying(with: overlay, fraction: fraction) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for tint images with color. Only CG-based images are supported. public struct TintImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Tint color will be used to tint the input image. public let tint: Color /// Initialize a `TintImageProcessor` /// /// - parameter tint: Tint color will be used to tint the input image. public init(tint: Color) { self.tint = tint self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))" } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.tinted(with: tint) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for applying some color control to images. Only CG-based images are supported. /// watchOS is not supported. public struct ColorControlsProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Brightness changing to image. public let brightness: CGFloat /// Contrast changing to image. public let contrast: CGFloat /// Saturation changing to image. public let saturation: CGFloat /// InputEV changing to image. public let inputEV: CGFloat /// Initialize a `ColorControlsProcessor` /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { self.brightness = brightness self.contrast = contrast self.saturation = saturation self.inputEV = inputEV self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for applying black and white effect to images. Only CG-based images are supported. /// watchOS is not supported. public struct BlackWhiteProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" /// Initialize a `BlackWhiteProcessor` public init() {} /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) .process(item: item, options: options) } } /// Processor for cropping an image. Only CG-based images are supported. /// watchOS is not supported. public struct CroppingImageProcessor: ImageProcessor { /// Identifier of the processor. /// - Note: See documentation of `ImageProcessor` protocol for more. public let identifier: String /// Target size of output image should be. public let size: CGSize /// Anchor point from which the output size should be calculate. /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image. /// See `CroppingImageProcessor.init(size:anchor:)` for more. public let anchor: CGPoint /// Initialize a `CroppingImageProcessor` /// /// - Parameters: /// - size: Target size of output image should be. /// - anchor: The anchor point from which the size should be calculated. /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image. /// - Note: /// The anchor point is consisted by two values between 0.0 and 1.0. /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner. /// The `size` property of `CroppingImageProcessor` will be used along with /// `anchor` to calculate a target rectange in the size of image. /// /// The target size will be automatically calculated with a reasonable behavior. /// For example, when you have an image size of `CGSize(width: 100, height: 100)`, /// and a target size of `CGSize(width: 20, height: 20)`: /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`; /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}` /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}` public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) { self.size = size self.anchor = anchor self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))" } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.scaled(to: options.scaleFactor) .kf.crop(to: size, anchorOn: anchor) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally. /// /// - parameter left: First processor. /// - parameter right: Second processor. /// /// - returns: The concatenated processor. public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { return left.append(another: right) } fileprivate extension Color { var hex: String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 #if os(macOS) (usingColorSpace(.genericRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a) #else getRed(&r, green: &g, blue: &b, alpha: &a) #endif let rInt = Int(r * 255) << 24 let gInt = Int(g * 255) << 16 let bInt = Int(b * 255) << 8 let aInt = Int(a * 255) let rgba = rInt | gInt | bInt | aInt return String(format:"#%08x", rgba) } }
mit
c481f486e9188c7242c23a6075d1d7c1
40.323983
143
0.648283
4.748429
false
false
false
false
JGiola/swift
test/SILGen/protocols.swift
1
22732
// RUN: %target-swift-emit-silgen -module-name protocols %s | %FileCheck %s //===----------------------------------------------------------------------===// // Calling Existential Subscripts //===----------------------------------------------------------------------===// protocol SubscriptableGet { subscript(a : Int) -> Int { get } } protocol SubscriptableGetSet { subscript(a : Int) -> Int { get set } } var subscriptableGet : SubscriptableGet var subscriptableGetSet : SubscriptableGetSet func use_subscript_rvalue_get(_ i : Int) -> Int { return subscriptableGet[i] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_rvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols16subscriptableGetAA013SubscriptableC0_pvp : $*SubscriptableGet // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGet to $*[[OPENED:@opened\(.*, SubscriptableGet\) Self]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: end_access [[READ]] : $*SubscriptableGet // CHECK-NEXT: [[TMP:%.*]] = alloc_stack // CHECK-NEXT: copy_addr [[ALLOCSTACK]] to [initialization] [[TMP]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[TMP]]) // CHECK-NEXT: destroy_addr [[TMP]] // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_get(_ i : Int) -> Int { return subscriptableGetSet[i] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened\(.*, SubscriptableGetSet\) Self]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]]) // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: end_access [[READ]] : $*SubscriptableGetSet // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_set(_ i : Int) { subscriptableGetSet[i] = i } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet // CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened\(.*, SubscriptableGetSet\) Self]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Subscripts //===----------------------------------------------------------------------===// func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_rvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter // CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK: } // end sil function '${{.*}}use_subscript_archetype_rvalue_get func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T // CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr [[READ]] to [initialization] [[GUARANTEEDSTACK]] : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter // CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]]) // CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T // CHECK: return [[APPLYRESULT]] func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) { generic[idx] = idx } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter // CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[WRITE]]) //===----------------------------------------------------------------------===// // Calling Existential Properties //===----------------------------------------------------------------------===// protocol PropertyWithGetter { var a : Int { get } } protocol PropertyWithGetterSetter { var b : Int { get set } } var propertyGet : PropertyWithGetter var propertyGetSet : PropertyWithGetterSetter func use_property_rvalue_get() -> Int { return propertyGet.a } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_rvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols11propertyGetAA18PropertyWithGetter_pvp : $*PropertyWithGetter // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetter to $*[[OPENED:@opened\(.*, PropertyWithGetter\) Self]] // CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]] // CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]] // CHECK-NEXT: end_access [[READ]] : $*PropertyWithGetter // CHECK: [[BORROW:%.*]] = alloc_stack $[[OPENED]] // CHECK-NEXT: copy_addr [[COPY]] to [initialization] [[BORROW]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[BORROW]]) func use_property_lvalue_get() -> Int { return propertyGetSet.b } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened\(.*, PropertyWithGetterSetter\) Self]] // CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]]) func use_property_lvalue_set(_ x : Int) { propertyGetSet.b = x } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter // CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened\(.*, PropertyWithGetterSetter\) Self]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Properties //===----------------------------------------------------------------------===// func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int { return generic.a } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_rvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] // CHECK-NEXT: dealloc_stack [[STACK]] // CHECK: } // end sil function '{{.*}}use_property_archetype_rvalue_get func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int { return generic.b } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK: } // end sil function '${{.*}}use_property_archetype_lvalue_get func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) { generic.b = v } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter // CHECK-NEXT: apply [[METH]]<T>(%1, [[WRITE]]) //===----------------------------------------------------------------------===// // Calling Initializers //===----------------------------------------------------------------------===// protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden [ossa] @$s9protocols27use_initializable_archetype{{[_0-9a-zA-Z]*}}F func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) { // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator : {{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[T_RESULT]] : $*T // CHECK: dealloc_stack [[T_RESULT]] : $*T // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() T(int: i) } // CHECK: sil hidden [ossa] @$s9protocols29use_initializable_existential{{[_0-9a-zA-Z]*}}F func use_initializable_existential(_ im: Initializable.Type, i: Int) { // CHECK: bb0([[IM:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]], Initializable) Self).Type // CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]], Initializable) Self, #Initializable.init!allocator : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]], Initializable) Self // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]], Initializable) Self>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable // CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable im.init(int: i) // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } //===----------------------------------------------------------------------===// // Protocol conformance and witness table generation //===----------------------------------------------------------------------===// class ClassWithGetter : PropertyWithGetter { var a: Int { get { return 42 } } } // Make sure we are generating a protocol witness that calls the class method on // ClassWithGetter. // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW : // CHECK: bb0([[C:%.*]] : $*ClassWithGetter): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0 // CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter : (ClassWithGetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetter) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[CCOPY_LOADED]] // CHECK-NEXT: return class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter { var a: Int { get { return 1 } set {} } var b: Int { get { return 2 } set {} } } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW : // CHECK: bb0([[C:%.*]] : $*ClassWithGetterSetter): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0 // CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter : (ClassWithGetterSetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[CCOPY_LOADED]] // CHECK-NEXT: return // Stored variables fulfilling property requirements // class ClassWithStoredProperty : PropertyWithGetter { var a : Int = 0 // Make sure that accesses go through the generated accessors for classes. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9protocols23ClassWithStoredPropertyC011methodUsingE0SiyF // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithStoredProperty): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NOT: copy_value // CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter : (ClassWithStoredProperty) -> () -> Int, $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int // CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]]) // CHECK-NOT: destroy_value // CHECK-NEXT: return [[RESULT]] : $Int } struct StructWithStoredProperty : PropertyWithGetter { var a : Int // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9protocols24StructWithStoredPropertyV011methodUsingE0SiyF // CHECK: bb0(%0 : $StructWithStoredProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a // CHECK-NEXT: return %2 : $Int } // Make sure that we generate direct function calls for out struct protocol // witness since structs don't do virtual calls for methods. // // *NOTE* Even though at first glance the copy_addr looks like a leak // here, StructWithStoredProperty is a trivial struct implying that no // leak is occurring. See the test with StructWithStoredClassProperty // that makes sure in such a case we don't leak. This is due to the // thunking code being too dumb but it is harmless to program // correctness. // // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW : // CHECK: bb0([[C:%.*]] : $*StructWithStoredProperty): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [trivial] [[C]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols24StructWithStoredPropertyV1aSivg : $@convention(method) (StructWithStoredProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: return class C {} // Make sure that if the getter has a class property, we pass it in // in_guaranteed and don't leak. struct StructWithStoredClassProperty : PropertyWithGetter { var a : Int var c: C = C() // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9protocols29StructWithStoredClassPropertyV011methodUsingF0SiyF // CHECK: bb0(%0 : @guaranteed $StructWithStoredClassProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a // CHECK-NEXT: return %2 : $Int } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW : // CHECK: bb0([[C:%.*]] : $*StructWithStoredClassProperty): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow [[C]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols29StructWithStoredClassPropertyV1aSivg : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[CCOPY_LOADED]] // CHECK-NEXT: return // rdar://22676810 protocol ExistentialProperty { var p: PropertyWithGetterSetter { get set } } func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) { let b = t.p.b } // CHECK-LABEL: sil hidden [ossa] @$s9protocols27testExistentialPropertyRead{{[_0-9a-zA-Z]*}}F // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T // CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter // CHECK: [[T_TEMP:%.*]] = alloc_stack $T // CHECK: copy_addr [[READ]] to [initialization] [[T_TEMP]] : $*T // CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter : // CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]]) // CHECK-NEXT: destroy_addr [[T_TEMP]] // CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr immutable_access [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened\(.*, PropertyWithGetterSetter\) Self]] // CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]] // CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]] // CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter // CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]]) // CHECK-NEXT: debug_value // CHECK-NEXT: destroy_addr [[T0]] // CHECK-NOT: witness_method // CHECK: return func modify(_ x: inout Int) {} func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) { modify(&x.b) } // CHECK-LABEL: sil hidden [ossa] @$s9protocols14modifyPropertyyyxzAA0C16WithGetterSetterRzlF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T // CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!modify // CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[WITNESS_FN]]<T> // CHECK: [[MODIFY_FN:%.*]] = function_ref @$s9protocols6modifyyySizF // CHECK: apply [[MODIFY_FN]]([[ADDR]]) // CHECK: end_apply [[TOKEN]] public struct Val { public var x: Int = 0 } public protocol Proto { var val: Val { get nonmutating set} } public func test(_ p: Proto) { p.val.x += 1 } // CHECK-LABEL: sil [ossa] @$s9protocols4testyyAA5Proto_pF : $@convention(thin) (@in_guaranteed Proto) -> () // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access // CHECK: [[MAT:%.*]] = witness_method $@opened("{{.*}}", Proto) Self, #Proto.val!modify // CHECK: ([[BUF:%.*]], [[TOKEN:%.*]]) = begin_apply [[MAT]] // CHECK: end_apply [[TOKEN]] // CHECK: return // SR-11748 protocol SelfReturningSubscript { subscript(b: Int) -> Self { get } } public func testSelfReturningSubscript() { // CHECK-LABEL: sil private [ossa] @$s9protocols26testSelfReturningSubscriptyyFAA0cdE0_pAaC_pXEfU_ // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access // CHECK: [[OPEN_ADDR:%.*]] = alloc_stack $@opened("{{.*}}", SelfReturningSubscript) Self // CHECK: copy_addr [[OPEN]] to [initialization] [[OPEN_ADDR]] : $*@opened("{{.*}}", SelfReturningSubscript) Self // CHECK: [[WIT_M:%.*]] = witness_method $@opened("{{.*}}", SelfReturningSubscript) Self, #SelfReturningSubscript.subscript!getter // CHECK: apply [[WIT_M]]<@opened("{{.*}}", SelfReturningSubscript) Self>({{%.*}}, {{%.*}}, [[OPEN_ADDR]]) _ = [String: SelfReturningSubscript]().mapValues { $0[2] } } // CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols { // CHECK-NEXT: method #PropertyWithGetterSetter.b!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW // CHECK-NEXT: method #PropertyWithGetterSetter.b!setter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivsTW // CHECK-NEXT: method #PropertyWithGetterSetter.b!modify: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivMTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycD0A2aDP1aSivgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW // CHECK-NEXT: }
apache-2.0
e6c8bf1213d3654d66eb779c3198410d
47.538462
276
0.637348
3.765915
false
false
false
false
wvteijlingen/Spine
Spine/ResourceFactory.swift
1
2614
// // ResourceFactory.swift // Spine // // Created by Ward van Teijlingen on 06/01/16. // Copyright © 2016 Ward van Teijlingen. All rights reserved. // import Foundation /// A ResourceFactory creates resources from given factory funtions. struct ResourceFactory { fileprivate var resourceTypes: [ResourceType: Resource.Type] = [:] /// Registers a given resource type so it can be instantiated by the factory. /// Registering a type that was alsreay registered will override it. /// /// - parameter resourceClass: <#resourceClass description#> mutating func registerResource(_ type: Resource.Type) { resourceTypes[type.resourceType] = type } /// Instantiates a resource with the given type, by using a registered factory function. /// /// - parameter type: The resource type to instantiate. /// /// - throws: A SerializerError.resourceTypeUnregistered erro when the type is not registered. /// /// - returns: An instantiated resource. func instantiate(_ type: ResourceType) throws -> Resource { if resourceTypes[type] == nil { throw SerializerError.resourceTypeUnregistered(type) } return resourceTypes[type]!.init() } /// Dispenses a resource with the given type and id, optionally by finding it in a pool of existing resource instances. /// /// This methods tries to find a resource with the given type and id in the pool. If no matching resource is found, /// it tries to find the nth resource, indicated by `index`, of the given type from the pool. If still no resource is found, /// it instantiates a new resource with the given id and adds this to the pool. /// /// - parameter type: The resource type to dispense. /// - parameter id: The id of the resource to dispense. /// - parameter pool: An array of resources in which to find exisiting matching resources. /// - parameter index: Optional index of the resource in the pool. /// /// - throws: A SerializerError.resourceTypeUnregistered erro when the type is not registered. /// /// - returns: A resource with the given type and id. func dispense(_ type: ResourceType, id: String, pool: inout [Resource], index: Int? = nil) throws -> Resource { var resource: Resource! = pool.filter { $0.resourceType == type && $0.id == id }.first if resource == nil && index != nil && !pool.isEmpty { let applicableResources = pool.filter { $0.resourceType == type } if index! < applicableResources.count { resource = applicableResources[index!] } } if resource == nil { resource = try instantiate(type) resource.id = id pool.append(resource) } return resource } }
mit
f08b8b9d13f9d21abcb5eca8ed152d5f
35.291667
125
0.707616
3.859675
false
false
false
false
BGDigital/mcwa
mcwa/mcwa/Tools/SwiftNotice.swift
1
13788
// // SwiftNotice.swift // SwiftNotice // // Created by JohnLui on 15/4/15. // Copyright (c) 2015年 com.lvwenhan. All rights reserved. // import Foundation import UIKit extension UIViewController { /// wait with your own animated images func pleaseWaitWithImages(imageNames: Array<UIImage>, timeInterval: Int) { SwiftNotice.wait(imageNames, timeInterval: timeInterval) } // api changed from v3.3 func noticeTop(text: String, autoClear: Bool = true, autoClearTime: Int = 1) { SwiftNotice.noticeOnSatusBar(text, autoClear: autoClear, autoClearTime: autoClearTime) } // new apis from v3.3 func noticeSuccess(text: String, autoClear: Bool = true, autoClearTime: Int = 3) { SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } func noticeError(text: String, autoClear: Bool = true, autoClearTime: Int = 3) { SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } func noticeInfo(text: String, autoClear: Bool = true, autoClearTime: Int = 3) { SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } // old apis func successNotice(text: String, autoClear: Bool = true) { SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: 3) } func errorNotice(text: String, autoClear: Bool = true) { SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: 3) } func infoNotice(text: String, autoClear: Bool = true) { SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: 3) } func notice(text: String, type: NoticeType, autoClear: Bool, autoClearTime: Int = 3) { SwiftNotice.showNoticeWithText(type, text: text, autoClear: autoClear, autoClearTime: autoClearTime) } func pleaseWait() { SwiftNotice.wait() } func noticeOnlyText(text: String) { SwiftNotice.showText(text) NSTimer.after(3) { () -> Void in SwiftNotice.clear() } } func clearAllNotice() { SwiftNotice.clear() } } enum NoticeType{ case success case error case info } class SwiftNotice: NSObject { static var windows = Array<UIWindow!>() static let rv = UIApplication.sharedApplication().keyWindow?.subviews.first as UIView! static var timer: dispatch_source_t! static var timerTimes = 0 static var degree: Double { get { return [0, 0, 180, 270, 90][UIApplication.sharedApplication().statusBarOrientation.hashValue] as Double } } static var center: CGPoint { get { var array = [UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height] array = array.sort(<) let screenWidth = array[0] let screenHeight = array[1] let x = [0, screenWidth/2, screenWidth/2, 10, screenWidth-10][UIApplication.sharedApplication().statusBarOrientation.hashValue] as CGFloat let y = [0, 10, screenHeight-10, screenHeight/2, screenHeight/2][UIApplication.sharedApplication().statusBarOrientation.hashValue] as CGFloat return CGPointMake(x, y) } } // fix https://github.com/johnlui/SwiftNotice/issues/2 // thanks broccolii(https://github.com/broccolii) and his PR https://github.com/johnlui/SwiftNotice/pull/5 static func clear() { self.cancelPreviousPerformRequestsWithTarget(self) if let _ = timer { dispatch_source_cancel(timer) timer = nil timerTimes = 0 } windows.removeAll(keepCapacity: false) } static func noticeOnSatusBar(text: String, autoClear: Bool, autoClearTime: Int) { let frame = UIApplication.sharedApplication().statusBarFrame let window = UIWindow() window.backgroundColor = UIColor.clearColor() let view = UIView() view.backgroundColor = UIColor(red: 0x6a/0x100, green: 0xb4/0x100, blue: 0x9f/0x100, alpha: 1) let label = UILabel(frame: frame) label.textAlignment = NSTextAlignment.Center label.font = UIFont.systemFontOfSize(12) label.textColor = UIColor.whiteColor() label.text = text view.addSubview(label) window.frame = frame view.frame = frame window.windowLevel = UIWindowLevelStatusBar window.hidden = false // change orientation window.center = center window.transform = CGAffineTransformMakeRotation(CGFloat(degree * M_PI / 180)) window.addSubview(view) windows.append(window) if autoClear { let selector = Selector("hideNotice:") self.performSelector(selector, withObject: window, afterDelay: NSTimeInterval(autoClearTime)) } } static func wait(imageNames: Array<UIImage> = Array<UIImage>(), timeInterval: Int = 0) { let frame = CGRectMake(0, 0, 78, 78) let window = UIWindow() window.backgroundColor = UIColor.clearColor() let mainView = UIView() mainView.layer.cornerRadius = 12 mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8) if imageNames.count > 0 { if imageNames.count > timerTimes { let iv = UIImageView(frame: frame) iv.image = imageNames.first! iv.contentMode = UIViewContentMode.ScaleAspectFit mainView.addSubview(iv) timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()) dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, UInt64(timeInterval) * NSEC_PER_MSEC, 0) dispatch_source_set_event_handler(timer, { () -> Void in let name = imageNames[timerTimes % imageNames.count] iv.image = name timerTimes++ }) dispatch_resume(timer) } } else { let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) ai.frame = CGRectMake(21, 21, 36, 36) ai.startAnimating() mainView.addSubview(ai) } window.frame = frame mainView.frame = frame window.windowLevel = UIWindowLevelAlert window.center = getRealCenter() // change orientation window.transform = CGAffineTransformMakeRotation(CGFloat(degree * M_PI / 180)) window.hidden = false window.addSubview(mainView) windows.append(window) } static func showText(text: String) { let window = UIWindow() window.backgroundColor = UIColor.clearColor() let mainView = UIView() mainView.layer.cornerRadius = 12 mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8) let label = UILabel() label.text = text label.numberOfLines = 0 label.font = UIFont.systemFontOfSize(13) label.textAlignment = NSTextAlignment.Center label.textColor = UIColor.whiteColor() label.sizeToFit() mainView.addSubview(label) let superFrame = CGRectMake(0, 0, label.frame.width + 50 , label.frame.height + 30) window.frame = superFrame mainView.frame = superFrame label.center = mainView.center window.windowLevel = UIWindowLevelAlert window.center = getRealCenter() // change orientation window.transform = CGAffineTransformMakeRotation(CGFloat(degree * M_PI / 180)) window.hidden = false window.addSubview(mainView) windows.append(window) } static func showNoticeWithText(type: NoticeType,text: String, autoClear: Bool, autoClearTime: Int) { let frame = CGRectMake(0, 0, 90, 90) let window = UIWindow() window.backgroundColor = UIColor.clearColor() let mainView = UIView() mainView.layer.cornerRadius = 10 mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.7) var image = UIImage() switch type { case .success: image = SwiftNoticeSDK.imageOfCheckmark case .error: image = SwiftNoticeSDK.imageOfCross case .info: image = SwiftNoticeSDK.imageOfInfo } let checkmarkView = UIImageView(image: image) checkmarkView.frame = CGRectMake(27, 15, 36, 36) mainView.addSubview(checkmarkView) let label = UILabel(frame: CGRectMake(0, 60, 90, 16)) label.font = UIFont.systemFontOfSize(13) label.textColor = UIColor.whiteColor() label.text = text label.textAlignment = NSTextAlignment.Center mainView.addSubview(label) window.frame = frame mainView.frame = frame window.windowLevel = UIWindowLevelAlert window.center = getRealCenter() // change orientation window.transform = CGAffineTransformMakeRotation(CGFloat(degree * M_PI / 180)) window.hidden = false window.addSubview(mainView) windows.append(window) if autoClear { let selector = Selector("hideNotice:") self.performSelector(selector, withObject: window, afterDelay: NSTimeInterval(autoClearTime)) } } // fix https://github.com/johnlui/SwiftNotice/issues/2 static func hideNotice(sender: AnyObject) { if let window = sender as? UIWindow { if let index = windows.indexOf({ (item) -> Bool in return item == window }) { windows.removeAtIndex(index) } } } // fix orientation problem static func getRealCenter() -> CGPoint { if UIApplication.sharedApplication().statusBarOrientation.hashValue >= 3 { return CGPoint(x: rv.center.y, y: rv.center.x) } else { return rv.center } } } class SwiftNoticeSDK { struct Cache { static var imageOfCheckmark: UIImage? static var imageOfCross: UIImage? static var imageOfInfo: UIImage? } class func draw(type: NoticeType) { let checkmarkShapePath = UIBezierPath() // draw circle checkmarkShapePath.moveToPoint(CGPointMake(36, 18)) checkmarkShapePath.addArcWithCenter(CGPointMake(18, 18), radius: 17.5, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) checkmarkShapePath.closePath() switch type { case .success: // draw checkmark checkmarkShapePath.moveToPoint(CGPointMake(10, 18)) checkmarkShapePath.addLineToPoint(CGPointMake(16, 24)) checkmarkShapePath.addLineToPoint(CGPointMake(27, 13)) checkmarkShapePath.moveToPoint(CGPointMake(10, 18)) checkmarkShapePath.closePath() case .error: // draw X checkmarkShapePath.moveToPoint(CGPointMake(10, 10)) checkmarkShapePath.addLineToPoint(CGPointMake(26, 26)) checkmarkShapePath.moveToPoint(CGPointMake(10, 26)) checkmarkShapePath.addLineToPoint(CGPointMake(26, 10)) checkmarkShapePath.moveToPoint(CGPointMake(10, 10)) checkmarkShapePath.closePath() case .info: checkmarkShapePath.moveToPoint(CGPointMake(18, 6)) checkmarkShapePath.addLineToPoint(CGPointMake(18, 22)) checkmarkShapePath.moveToPoint(CGPointMake(18, 6)) checkmarkShapePath.closePath() UIColor.whiteColor().setStroke() checkmarkShapePath.stroke() let checkmarkShapePath = UIBezierPath() checkmarkShapePath.moveToPoint(CGPointMake(18, 27)) checkmarkShapePath.addArcWithCenter(CGPointMake(18, 27), radius: 1, startAngle: 0, endAngle: CGFloat(M_PI*2), clockwise: true) checkmarkShapePath.closePath() UIColor.whiteColor().setFill() checkmarkShapePath.fill() } UIColor.whiteColor().setStroke() checkmarkShapePath.stroke() } class var imageOfCheckmark: UIImage { if (Cache.imageOfCheckmark != nil) { return Cache.imageOfCheckmark! } UIGraphicsBeginImageContextWithOptions(CGSizeMake(36, 36), false, 0) SwiftNoticeSDK.draw(NoticeType.success) Cache.imageOfCheckmark = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Cache.imageOfCheckmark! } class var imageOfCross: UIImage { if (Cache.imageOfCross != nil) { return Cache.imageOfCross! } UIGraphicsBeginImageContextWithOptions(CGSizeMake(36, 36), false, 0) SwiftNoticeSDK.draw(NoticeType.error) Cache.imageOfCross = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Cache.imageOfCross! } class var imageOfInfo: UIImage { if (Cache.imageOfInfo != nil) { return Cache.imageOfInfo! } UIGraphicsBeginImageContextWithOptions(CGSizeMake(36, 36), false, 0) SwiftNoticeSDK.draw(NoticeType.info) Cache.imageOfInfo = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Cache.imageOfInfo! } }
mit
a298d03ea7e666d3dd27e39d4b7862c7
37.946328
153
0.629624
4.934145
false
false
false
false
itouch2/LeetCode
LeetCode/ValidAnagram.swift
1
1355
// // ValidAnagram.swift // LeetCode // // Created by You Tu on 2017/9/12. // Copyright © 2017年 You Tu. All rights reserved. // /* Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case? */ import Cocoa class ValidAnagram: NSObject { func isAnagram(_ s: String, _ t: String) -> Bool { let sArray = arrayFromString(s) let tArray = arrayFromString(t) for index in 0..<26 { if sArray[index] != tArray[index] { return false } } return true } func arrayFromString(_ s: String) -> [Int] { var array:[Int] = Array.init(repeating: 0, count: 26) for c in s.characters { let index = characterValue(c) array[index - 97] += 1 } return array } func characterValue(_ a: Character) -> Int { let charaterString = String(a) let scalars = charaterString.unicodeScalars let value = scalars[scalars.startIndex].value return Int(value) } }
mit
a0869bcad9cb006cc9d92b4d15f3f65b
24.037037
95
0.58432
3.907514
false
false
false
false
schibsted/layout
LayoutTool/Formatter.swift
1
9964
// Copyright © 2017 Schibsted. All rights reserved. import Foundation func format(_ files: [String]) -> (filesChecked: Int, filesUpdated: Int, errors: [FormatError]) { var filesChecked = 0, filesUpdated = 0, errors = [Error]() for path in files { let url = expandPath(path) errors += enumerateFiles(withInputURL: url, concurrent: false) { inputURL, outputURL in var checked = false, updated = false do { let data = try Data(contentsOf: inputURL) if let input = String(data: data, encoding: .utf8), let xml = try parseLayoutXML(data, for: inputURL) { checked = true let output = try format(xml) if output != input { try output.write(to: outputURL, atomically: true, encoding: .utf8) updated = true } } return { if checked { filesChecked += 1 } if updated { filesUpdated += 1 } } } catch let FormatError.parsing(error) { return { if checked { filesChecked += 1 } throw FormatError.parsing("\(error) in \(inputURL.path)") } } catch { return { if checked { filesChecked += 1 } throw error } } } } return (filesChecked, filesUpdated, errors.map(FormatError.init)) } func format(_ xml: String) throws -> String { guard let data = xml.data(using: .utf8, allowLossyConversion: true) else { throw FormatError.parsing("Invalid xml string") } let xml = try FormatError.wrap { try XMLParser.parse(data: data) } return try format(xml) } func format(_ xml: [XMLNode]) throws -> String { return try xml.toString(withIndent: "") } extension Collection where Iterator.Element == XMLNode { func toString(withIndent indent: String, indentFirstLine: Bool = true, isHTML: Bool = false) throws -> String { var output = "" var previous: XMLNode? var indentNextLine = indentFirstLine var params = [XMLNode]() var macros = [XMLNode]() var nodes = Array(self) if !isHTML { for (index, node) in nodes.enumerated().reversed() { if node.isParameter { var i = index while i > 0, nodes[i - 1].isComment { i -= 1 } params = nodes[i ... index] + params nodes[i ... index] = [] } else if node.isMacro { var i = index while i > 0, nodes[i - 1].isComment { i -= 1 } macros = nodes[i ... index] + macros nodes[i ... index] = [] } else if node.isChildren || node.isHTML || node.isText { break } } } for node in params + macros + nodes { if node.isLinebreak, previous?.isHTML != true { continue } switch node { case .text("\n"): continue case .comment: if let previous = previous, !previous.isComment, !previous.isLinebreak { output += "\n" indentNextLine = true } fallthrough default: if let previous = previous { if previous.isParameterOrMacro, !node.isParameterOrMacro, !node.isComment { if !node.isHTML { output += "\n" } output += "\n" } else if !(node.isText && (previous.isHTML || previous.isText)), !(node.isHTML && previous.isText) { output += "\n" } } if output.hasSuffix("\n") { indentNextLine = true } output += try node.toString(withIndent: indent, indentFirstLine: indentNextLine) } previous = node indentNextLine = false } if !output.hasSuffix("\n") { output += "\n" } return output } } // Threshold for min number of attributes to begin linewrapping private let attributeWrap = 2 extension XMLNode { private func formatAttribute(key: String, value: String) throws -> String { do { let description: String if attributeIsString(key, inNode: self) ?? true { // We have to treat everying we aren't sure about as a string expression, because if // we attempt to format text outside of {...} as an expression, it will get messed up let parts = try parseStringExpression(value) for part in parts { switch part { case .string, .comment: break case let .expression(expression): try validateLayoutExpression(expression) } } description = parts.description } else { let expression = try parseExpression(value) try validateLayoutExpression(expression) description = expression.description } return "\(key)=\"\(description.xmlEncoded(forAttribute: true))\"" } catch { throw FormatError.parsing("\(error) in \(key) attribute") } } func toString(withIndent indent: String, indentFirstLine: Bool = true) throws -> String { switch self { case let .node(name, attributes, children): do { var xml = indentFirstLine ? indent : "" xml += "<\(name)" let attributes = attributes.sorted(by: { a, b in a.key < b.key // sort alphabetically }) if attributes.count < attributeWrap || isParameterOrMacro || isHTML { for (key, value) in attributes { xml += try " \(formatAttribute(key: key, value: value))" } } else { for (key, value) in attributes { xml += try "\n\(indent) \(formatAttribute(key: key, value: value))" } } if isParameterOrMacro || isChildren { xml += "/>" } else if isEmpty { if !isHTML, attributes.count >= attributeWrap { xml += "\n\(indent)" } if !isHTML || emptyHTMLTags.contains(name) { xml += "/>" } else { xml += "></\(name)>" } } else if children.count == 1, children[0].isComment || children[0].isText { xml += ">" var body = try children[0].toString(withIndent: indent + " ", indentFirstLine: false) if isHTML { if !body.hasPrefix("\n") { body = body.replacingOccurrences(of: "\\s*\\n\\s*", with: "\n\(indent)", options: .regularExpression) } if body.hasSuffix("\n") { body = "\(body)\(indent)" } } else if attributes.count >= attributeWrap { if !body.hasPrefix("\n") { body = "\n\(indent)\(body)" } else { body = "\(indent)\(body)" } if !body.hasSuffix("\n") { body = "\(body)\n\(indent)" } else { body = "\(body)\(indent)" } } else { body = body.trimmingCharacters(in: .whitespacesAndNewlines) } xml += "\(body)</\(name)>" } else { xml += ">\n" let body = try children.toString(withIndent: indent + " ", isHTML: isHTML) if (!isHTML && attributes.count >= attributeWrap) || children.first(where: { !$0.isLinebreak })?.isComment == true { xml += "\n" } xml += "\(body)\(indent)</\(name)>" } return xml } catch { throw FormatError.parsing("\(error) in <\(name)>") } case let .text(text): if text == "\n" { return text } var body = text .xmlEncoded(forAttribute: false) .replacingOccurrences(of: "\\s*\\n\\s*", with: "\n\(indent)", options: .regularExpression) if body.hasSuffix("\n\(indent)") { body = String(body[body.startIndex ..< body.index(body.endIndex, offsetBy: -indent.count)]) } if indentFirstLine { body = body.replacingOccurrences(of: "^\\s*", with: indent, options: .regularExpression) } return body case let .comment(comment): let body = comment .trimmingCharacters(in: .whitespacesAndNewlines) .replacingOccurrences(of: "\\s*\\n\\s*", with: "\n\(indent)", options: .regularExpression) return "\(indentFirstLine ? indent : "")<!-- \(body) -->" } } }
mit
c99f171970b023e4588674792fcaa5ab
40.340249
129
0.44585
5.224436
false
false
false
false
mapsme/omim
iphone/Maps/Classes/CarPlay/CarPlayRouter.swift
4
13024
import CarPlay import Contacts @available(iOS 12.0, *) protocol CarPlayRouterListener: class { func didCreateRoute(routeInfo: RouteInfo, trip: CPTrip) func didUpdateRouteInfo(_ routeInfo: RouteInfo, forTrip trip: CPTrip) func didFailureBuildRoute(forTrip trip: CPTrip, code: RouterResultCode, countries: [String]) func routeDidFinish(_ trip: CPTrip) } @available(iOS 12.0, *) @objc(MWMCarPlayRouter) final class CarPlayRouter: NSObject { private let listenerContainer: ListenerContainer<CarPlayRouterListener> private var routeSession: CPNavigationSession? private var initialSpeedCamSettings: SpeedCameraManagerMode var currentTrip: CPTrip? { return routeSession?.trip } var previewTrip: CPTrip? var speedCameraMode: SpeedCameraManagerMode { return RoutingManager.routingManager.speedCameraMode } override init() { listenerContainer = ListenerContainer<CarPlayRouterListener>() initialSpeedCamSettings = RoutingManager.routingManager.speedCameraMode super.init() } func addListener(_ listener: CarPlayRouterListener) { listenerContainer.addListener(listener) } func removeListener(_ listener: CarPlayRouterListener) { listenerContainer.removeListener(listener) } func subscribeToEvents() { RoutingManager.routingManager.add(self) } func unsubscribeFromEvents() { RoutingManager.routingManager.remove(self) } func completeRouteAndRemovePoints() { let manager = RoutingManager.routingManager manager.stopRoutingAndRemoveRoutePoints(true) manager.deleteSavedRoutePoints() manager.apply(routeType: .vehicle) previewTrip = nil } func rebuildRoute() { guard let trip = previewTrip else { return } do { try RoutingManager.routingManager.buildRoute() } catch let error as NSError { listenerContainer.forEach({ let code = RouterResultCode(rawValue: UInt(error.code)) ?? .internalError $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) } } func buildRoute(trip: CPTrip) { completeRouteAndRemovePoints() previewTrip = trip guard let info = trip.userInfo as? [String: MWMRoutePoint] else { listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: .routeNotFound, countries: []) }) return } guard let startPoint = info[CPConstants.Trip.start], let endPoint = info[CPConstants.Trip.end] else { listenerContainer.forEach({ var code: RouterResultCode! if info[CPConstants.Trip.end] == nil { code = .endPointNotFound } else { code = .startPointNotFound } $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) return } let manager = RoutingManager.routingManager manager.add(routePoint: startPoint) manager.add(routePoint: endPoint) do { try manager.buildRoute() } catch let error as NSError { listenerContainer.forEach({ let code = RouterResultCode(rawValue: UInt(error.code)) ?? .internalError $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) } } func updateStartPointAndRebuild(trip: CPTrip) { let manager = RoutingManager.routingManager previewTrip = trip guard let info = trip.userInfo as? [String: MWMRoutePoint] else { listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: .routeNotFound, countries: []) }) return } guard let startPoint = info[CPConstants.Trip.start] else { listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: .startPointNotFound, countries: []) }) return } manager.add(routePoint: startPoint) manager.apply(routeType: .vehicle) do { try manager.buildRoute() } catch let error as NSError { listenerContainer.forEach({ let code = RouterResultCode(rawValue: UInt(error.code)) ?? .internalError $0.didFailureBuildRoute(forTrip: trip, code: code, countries: []) }) } } func startRoute() { let manager = RoutingManager.routingManager manager.startRoute() Statistics.logEvent(kStatRoutingRouteStart, withParameters: [kStatMode : kStatCarplay]) } func setupCarPlaySpeedCameraMode() { if case .auto = initialSpeedCamSettings { RoutingManager.routingManager.speedCameraMode = .always } } func setupInitialSpeedCameraMode() { RoutingManager.routingManager.speedCameraMode = initialSpeedCamSettings } func updateSpeedCameraMode(_ mode: SpeedCameraManagerMode) { initialSpeedCamSettings = mode RoutingManager.routingManager.speedCameraMode = mode } func restoreTripPreviewOnCarplay(beforeRootTemplateDidAppear: Bool) { guard MWMRouter.isRestoreProcessCompleted() else { DispatchQueue.main.async { [weak self] in self?.restoreTripPreviewOnCarplay(beforeRootTemplateDidAppear: false) } return } let manager = RoutingManager.routingManager MWMRouter.hideNavigationMapControls() guard manager.isRoutingActive, let startPoint = manager.startPoint, let endPoint = manager.endPoint else { completeRouteAndRemovePoints() return } let trip = createTrip(startPoint: startPoint, endPoint: endPoint, routeInfo: manager.routeInfo) previewTrip = trip if manager.type != .vehicle { CarPlayService.shared.showRecoverRouteAlert(trip: trip, isTypeCorrect: false) return } if !startPoint.isMyPosition { CarPlayService.shared.showRecoverRouteAlert(trip: trip, isTypeCorrect: true) return } if beforeRootTemplateDidAppear { CarPlayService.shared.preparedToPreviewTrips = [trip] } else { CarPlayService.shared.preparePreview(trips: [trip]) } } func restoredNavigationSession() -> (CPTrip, RouteInfo)? { let manager = RoutingManager.routingManager if manager.isOnRoute, manager.type == .vehicle, let startPoint = manager.startPoint, let endPoint = manager.endPoint, let routeInfo = manager.routeInfo { MWMRouter.hideNavigationMapControls() let trip = createTrip(startPoint: startPoint, endPoint: endPoint, routeInfo: routeInfo) previewTrip = trip return (trip, routeInfo) } return nil } } // MARK: - Navigation session management @available(iOS 12.0, *) extension CarPlayRouter { func startNavigationSession(forTrip trip: CPTrip, template: CPMapTemplate) { routeSession = template.startNavigationSession(for: trip) routeSession?.pauseTrip(for: .loading, description: nil) updateUpcomingManeuvers() RoutingManager.routingManager.setOnNewTurnCallback { [weak self] in self?.updateUpcomingManeuvers() } } func cancelTrip() { routeSession?.cancelTrip() routeSession = nil completeRouteAndRemovePoints() RoutingManager.routingManager.resetOnNewTurnCallback() } func finishTrip() { routeSession?.finishTrip() routeSession = nil completeRouteAndRemovePoints() RoutingManager.routingManager.resetOnNewTurnCallback() } func updateUpcomingManeuvers() { let maneuvers = createUpcomingManeuvers() routeSession?.upcomingManeuvers = maneuvers } func updateEstimates() { guard let routeSession = routeSession, let routeInfo = RoutingManager.routingManager.routeInfo, let primaryManeuver = routeSession.upcomingManeuvers.first, let estimates = createEstimates(routeInfo) else { return } routeSession.updateEstimates(estimates, for: primaryManeuver) } private func createEstimates(_ routeInfo: RouteInfo) -> CPTravelEstimates? { guard let distance = Double(routeInfo.distanceToTurn) else { return nil } let measurement = Measurement(value: distance, unit: routeInfo.turnUnits) return CPTravelEstimates(distanceRemaining: measurement, timeRemaining: 0.0) } private func createUpcomingManeuvers() -> [CPManeuver] { guard let routeInfo = RoutingManager.routingManager.routeInfo else { return [] } var maneuvers = [CPManeuver]() let primaryManeuver = CPManeuver() primaryManeuver.userInfo = CPConstants.Maneuvers.primary var instructionVariant = routeInfo.streetName if routeInfo.roundExitNumber != 0 { let ordinalExitNumber = NumberFormatter.localizedString(from: NSNumber(value: routeInfo.roundExitNumber), number: .ordinal) let exitNumber = String(coreFormat: L("carplay_roundabout_exit"), arguments: [ordinalExitNumber]) instructionVariant = instructionVariant.isEmpty ? exitNumber : (exitNumber + ", " + instructionVariant) } primaryManeuver.instructionVariants = [instructionVariant] if let imageName = routeInfo.turnImageName, let symbol = UIImage(named: imageName) { primaryManeuver.symbolSet = CPImageSet(lightContentImage: symbol, darkContentImage: symbol) } if let estimates = createEstimates(routeInfo) { primaryManeuver.initialTravelEstimates = estimates } maneuvers.append(primaryManeuver) if let imageName = routeInfo.nextTurnImageName, let symbol = UIImage(named: imageName) { let secondaryManeuver = CPManeuver() secondaryManeuver.userInfo = CPConstants.Maneuvers.secondary secondaryManeuver.instructionVariants = [L("then_turn")] secondaryManeuver.symbolSet = CPImageSet(lightContentImage: symbol, darkContentImage: symbol) maneuvers.append(secondaryManeuver) } return maneuvers } func createTrip(startPoint: MWMRoutePoint, endPoint: MWMRoutePoint, routeInfo: RouteInfo? = nil) -> CPTrip { let startPlacemark = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: startPoint.latitude, longitude: startPoint.longitude)) let endPlacemark = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: endPoint.latitude, longitude: endPoint.longitude), addressDictionary: [CNPostalAddressStreetKey: endPoint.subtitle ?? ""]) let startItem = MKMapItem(placemark: startPlacemark) let endItem = MKMapItem(placemark: endPlacemark) endItem.name = endPoint.title let routeChoice = CPRouteChoice(summaryVariants: [" "], additionalInformationVariants: [], selectionSummaryVariants: []) routeChoice.userInfo = routeInfo let trip = CPTrip(origin: startItem, destination: endItem, routeChoices: [routeChoice]) trip.userInfo = [CPConstants.Trip.start: startPoint, CPConstants.Trip.end: endPoint] return trip } } // MARK: - RoutingManagerListener implementation @available(iOS 12.0, *) extension CarPlayRouter: RoutingManagerListener { func updateCameraInfo(isCameraOnRoute: Bool, speedLimit limit: String?) { CarPlayService.shared.updateCameraUI(isCameraOnRoute: isCameraOnRoute, speedLimit: limit) } func processRouteBuilderEvent(with code: RouterResultCode, countries: [String]) { guard let trip = previewTrip else { return } switch code { case .noError, .hasWarnings: let manager = RoutingManager.routingManager if manager.isRouteFinished { listenerContainer.forEach({ $0.routeDidFinish(trip) }) return } if let info = manager.routeInfo { previewTrip?.routeChoices.first?.userInfo = info if routeSession == nil { listenerContainer.forEach({ $0.didCreateRoute(routeInfo: info, trip: trip) }) } else { listenerContainer.forEach({ $0.didUpdateRouteInfo(info, forTrip: trip) }) updateUpcomingManeuvers() } } default: listenerContainer.forEach({ $0.didFailureBuildRoute(forTrip: trip, code: code, countries: countries) }) } } func didLocationUpdate(_ notifications: [String]) { guard let trip = previewTrip else { return } let manager = RoutingManager.routingManager if manager.isRouteFinished { listenerContainer.forEach({ $0.routeDidFinish(trip) }) return } guard let routeInfo = manager.routeInfo, manager.isRoutingActive else { return } listenerContainer.forEach({ $0.didUpdateRouteInfo(routeInfo, forTrip: trip) }) let tts = MWMTextToSpeech.tts()! if manager.isOnRoute && tts.active { tts.playTurnNotifications(notifications) tts.playWarningSound() } } }
apache-2.0
f8dfa00e171f7b918eeebc82322d3f1c
33.546419
124
0.675522
4.967201
false
false
false
false
ArnavChawla/InteliChat
CodedayProject/settingsViewController.swift
1
2566
import UIKit var french = false var spanish = false var arabic = false var olive = false class settingsViewController: UIViewController { @IBAction func Arabic(_ sender: Any) { arabic = !arabic } @IBAction func Italy(_ sender: Any) { olive = !olive } @IBAction func Bacl(_ sender: Any) { var storyboard = UIStoryboard(name: "Main", bundle: nil) if s == true { storyboard = UIStoryboard(name: "Main", bundle: nil) } else if p == true{ storyboard = UIStoryboard(name: "big", bundle: nil) } else if se == true { storyboard = UIStoryboard(name: "se", bundle: nil) } else if os == true{ storyboard = UIStoryboard(name: "4s", bundle: nil) } else if ip1 == true { storyboard = UIStoryboard(name: "ipad1", bundle: nil) } else if ipb == true { storyboard = UIStoryboard(name: "ipadbig", bundle: nil) } let naviVC = storyboard.instantiateViewController(withIdentifier: "VC")as! UIViewController let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = naviVC } @IBOutlet weak var bro: UISwitch! @IBOutlet weak var italy: UISwitch! @IBOutlet weak var SpanishSwitch: UISwitch! @IBAction func SpanishChanged(_ sender: Any) { spanish = !spanish } @IBOutlet weak var French: UISwitch! @IBAction func yofrench(_ sender: Any) { french = !french } override func viewDidLoad() { super.viewDidLoad() if arabic == false { bro.isOn = false } if olive == false { italy.isOn = false } if spanish == false { SpanishSwitch.isOn = false } if french == false { French.isOn = false } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
dd0fbad0165361dd78b444515f5ad0ea
26.891304
106
0.577163
4.648551
false
false
false
false
danthorpe/Pipe
Source/Pipe.swift
1
3687
// // Pipe.swift // // Created by Daniel Thorpe on 11/05/2015. // import Foundation infix operator |> { precedence 50 associativity left } /** Pipe. e.g. x |> f is transformed into f(x). But it's chainable so that x |> f |> g |> h is transformed into h(g(f(x))) */ public func |> <Input, Output>(lhs: Input, rhs: Input -> Output) -> Output { return rhs(lhs) } /// Curried version of map public func map<S: SequenceType, T>(transform: (S.Generator.Element) -> T)(source: S) -> [T] { return map(source, transform) } /// Curried version of filter public func filter<S: SequenceType>(includeElement: (S.Generator.Element) -> Bool)(source: S) -> [S.Generator.Element] { return filter(source, includeElement) } /// Curried version of reduce public func reduce<S: SequenceType, U>(initial: U, combine: (U, S.Generator.Element) -> U)(source: S) -> U { return reduce(source, initial, combine) } /// Curried version of sorted public func sorted<S: SequenceType>(isOrderedBefore: (S.Generator.Element, S.Generator.Element) -> Bool)(source: S) -> [S.Generator.Element] { return sorted(source, isOrderedBefore) } /// Curried version of find public func find<C: CollectionType where C.Generator.Element: Equatable>(value: C.Generator.Element) -> (C) -> C.Index? { return { find($0, value) } } /// Curried version Array.append public func append<T>(element: T) -> [T] -> [T] { return { (var array) in array.append(element) return array } } /// Curried version Array.insert:atIndex: public func insert<T>(element: T, atIndex index: Int) -> [T] -> [T] { return { (var array) in array.insert(element, atIndex: index) return array } } /// Curried version Array.removeAtIndex: public func removeAtIndex<T>(index: Int) -> [T] -> [T] { return { (var array) in array.removeAtIndex(index) return array } } /// Curried version of sum public func sum<S: SequenceType where S.Generator.Element == UInt8>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == Int8>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == UInt16>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == Int16>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == UInt32>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == Int32>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == UInt64>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == Int64>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == UInt>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == Int>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == Double>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == Float>(source: S) -> S.Generator.Element { return reduce(source, 0, +) } public func sum<S: SequenceType where S.Generator.Element == CGFloat>(source: S) -> S.Generator.Element { return reduce(source, 0, +) }
mit
75f8f979d97819893de8d65f13ba5fa8
44.518519
142
0.679143
3.465226
false
false
false
false
royratcliffe/Snippets
Sources/UIApplication+NetworkActivity.swift
1
3055
// Snippets UIApplication+NetworkActivity.swift // // Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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 extension UIApplication { struct NetworkActivity { static var indicatorVisibility: UInt8 = 0 } /// Indicator visibility is an integer. The indicator becomes visible when the /// level increments from zero to one; invisible when it decrements from one /// to zero. All other transitions do nothing. Do not directly set the /// indicator visibility; instead, use the show and hide methods. public private(set) var networkActivityIndicatorVisibility: Int { get { return (objc_getAssociatedObject(self, &UIApplication.NetworkActivity.indicatorVisibility) as? NSNumber ?? NSNumber(integerLiteral: 0)).intValue } set { objc_setAssociatedObject(self, &UIApplication.NetworkActivity.indicatorVisibility, NSNumber(integerLiteral: newValue), .OBJC_ASSOCIATION_COPY_NONATOMIC) } } /// Increments the indicator visibility. Makes the indicator visible when the /// visibility level transitions from zero to one. /// /// Application property `isNetworkActivityIndicatorVisible` is true when the /// app shows network activity using a spinning gear in the status bar; false /// when not. public func showNetworkActivityIndicator() { let visibility = networkActivityIndicatorVisibility networkActivityIndicatorVisibility = visibility + 1 if visibility == 0 { isNetworkActivityIndicatorVisible = true } } /// Makes the network activity indicator invisible when the visibility level /// decrements from one to zero. public func hideNetworkActivityIndicator() { let visibility = networkActivityIndicatorVisibility networkActivityIndicatorVisibility = visibility - 1 if visibility == 1 { isNetworkActivityIndicatorVisible = false } } }
mit
4885e77e5833b2125071f3c81d6b9902
42.514286
158
0.735719
5.180272
false
false
false
false