repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
cnoon/swift-compiler-crashes
crashes-duplicates/17172-swift-sourcemanager-getmessage.swift
11
256
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing n( { case [ { func b { enum b { let NSObject { protocol P { { } class b { class case ,
mit
cnoon/swift-compiler-crashes
crashes-duplicates/12100-swift-availabilityattr-isunavailable.swift
11
250
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { { } protocol a { typealias F = b protocol b : e func T typealias e : e
mit
exponent/exponent
packages/expo-modules-core/ios/Swift/Arguments/Types/EnumArgumentType.swift
2
2834
// Copyright 2021-present 650 Industries. All rights reserved. /** An argument type representing an enum that conforms to `EnumArgument`. */ internal struct EnumArgumentType: AnyArgumentType { let innerType: EnumArgument.Type func cast<ArgType>(_ value: ArgType) throws -> Any { return try innerType.create(fromRawValue: value) } var description: String { "Enum<\(innerType)>" } } /** A protocol that allows converting raw values to enum cases. */ public protocol EnumArgument: AnyArgument { /** Tries to create an enum case using given raw value. May throw errors, e.g. when the raw value doesn't match any case. */ static func create<ArgType>(fromRawValue rawValue: ArgType) throws -> Self /** Returns an array of all raw values available in the enum. */ static var allRawValues: [Any] { get } /** Type-erased enum's raw value. */ var anyRawValue: Any { get } } /** Extension for `EnumArgument` that also conforms to `RawRepresentable`. This constraint allows us to reference the associated `RawValue` type. */ public extension EnumArgument where Self: RawRepresentable, Self: Hashable { static func create<ArgType>(fromRawValue rawValue: ArgType) throws -> Self { guard let rawValue = rawValue as? RawValue else { throw EnumCastingException((type: RawValue.self, value: rawValue)) } guard let enumCase = Self.init(rawValue: rawValue) else { throw EnumNoSuchValueException((type: Self.self, value: rawValue)) } return enumCase } var anyRawValue: Any { rawValue } static var allRawValues: [Any] { // Be careful — it operates on unsafe pointers! let sequence = AnySequence { () -> AnyIterator<RawValue> in var raw = 0 return AnyIterator { let current: Self? = withUnsafePointer(to: &raw) { ptr in ptr.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee } } guard let value = current?.rawValue else { return nil } raw += 1 return value } } return Array(sequence) } } /** An error that is thrown when the value cannot be cast to associated `RawValue`. */ internal class EnumCastingException: GenericException<(type: Any.Type, value: Any)> { override var reason: String { "Unable to cast '\(param.value)' to expected type \(param.type)" } } /** An error that is thrown when the value doesn't match any available case. */ internal class EnumNoSuchValueException: GenericException<(type: EnumArgument.Type, value: Any)> { var allRawValuesFormatted: String { return param.type.allRawValues .map { "'\($0)'" } .joined(separator: ", ") } override var reason: String { "'\(param.value)' is not present in \(param.type) enum, it must be one of: \(allRawValuesFormatted)" } }
bsd-3-clause
DenHeadless/DTTableViewManager
Example/App/SceneDelegate.swift
1
721
// // SceneDelegate.swift // Example // // Created by Denys Telezhkin on 23.08.2020. // Copyright © 2020 Denys Telezhkin. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? // MARK: - UIWindowSceneDelegate func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = scene as? UIWindowScene else { return } window = UIWindow(windowScene: windowScene) window?.rootViewController = UINavigationController(rootViewController: ExamplesListViewController(style: .plain)) window?.makeKeyAndVisible() } }
mit
drewag/Swiftlier
Sources/Swiftlier/Model/Types/Price.swift
1
1189
// // Price.swift // web // // Created by Andrew J Wagner on 4/23/17. // // import Foundation public struct Price: CustomStringConvertible { private static let currencyFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.currencySymbol = "" return formatter }() enum Value { case pennies(Int) case dollars(Double) } private let value: Value public init(pennies: Int) { self.value = .pennies(pennies) } public init(dollars: Double) { self.value = .dollars(dollars) } public var pennies: Int { switch self.value { case .pennies(let pennies): return pennies case .dollars(let dollars): return Int(round(dollars * 100)) } } public var dollars: Double { switch self.value { case .pennies(let pennies): return Double(pennies) / 100 case .dollars(let dollars): return dollars } } public var description: String { return Price.currencyFormatter.string(for: self.dollars) ?? "NA" } }
mit
box/box-ios-sdk
Sources/Responses/RetentionPolicyEntry.swift
1
1147
// // RetentionPolicyEntry.swift // BoxSDK-iOS // // Created by Martina Stremeňová on 9/2/19. // Copyright © 2019 box. All rights reserved. // import Foundation /// Retention policy entry public class RetentionPolicyEntry: BoxModel { private static var resourceType: String = "retention_policy" public private(set) var rawData: [String: Any] /// Box item type public var type: String /// Identifier public let id: String /// The name of the retention policy. public let name: String? public required init(json: [String: Any]) throws { guard let itemType = json["type"] as? String else { throw BoxCodingError(message: .typeMismatch(key: "type")) } guard itemType == RetentionPolicyEntry.resourceType else { throw BoxCodingError(message: .valueMismatch(key: "type", value: itemType, acceptedValues: [RetentionPolicyEntry.resourceType])) } rawData = json type = itemType id = try BoxJSONDecoder.decode(json: json, forKey: "id") name = try BoxJSONDecoder.optionalDecode(json: json, forKey: "policy_name") } }
apache-2.0
Viddi/ios-process-button
ProcessButton/ProcessButton/FlatButton.swift
1
2884
// // FlatButton.swift // ProcessButton // // Created by Vidar Ottosson on 2/7/15. // Copyright (c) 2015 Vidar Ottosson. All rights reserved. // import UIKit protocol FlatButtonDelegate { func showSuccess() func showError() } class FlatButton: UIButton { enum Colors { static let Success = UIColor(red: 153 / 255.0, green: 204 / 255.0, blue: 0 / 255.0, alpha: 1.0) static let Error = UIColor(red: 255 / 255.0, green: 68 / 255.0, blue: 68 / 255.0, alpha: 1.0) } var delegate: FlatButtonDelegate? override init(frame: CGRect) { super.init(frame: frame) prepareView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareView() } private func prepareView() { titleLabel?.font = UIFont.boldSystemFontOfSize(36.0) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Disabled) } private func showSuccess(text: String, seconds: Double) { delegate?.showSuccess() enabled = false var tempBackground = backgroundColor backgroundColor = Colors.Success var tempText = titleLabel?.text setTitle(text, forState: UIControlState.Normal) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.backgroundColor = tempBackground self.setTitle(tempText, forState: UIControlState.Normal) self.enabled = true } } private func showError(text: String, seconds: Double) { delegate?.showError() enabled = false var tempBackground = backgroundColor backgroundColor = Colors.Error var tempText = titleLabel?.text setTitle(text, forState: UIControlState.Normal) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.backgroundColor = tempBackground self.setTitle(tempText, forState: UIControlState.Normal) self.enabled = true } } func showSuccessText(text: String, seconds: Double) { showSuccess(text, seconds: seconds) } func showSuccessText(text: String) { showSuccess(text, seconds: ProcessButtonUtil.Length.Short) } func showErrorText(text: String, seconds: Double) { showError(text, seconds: seconds) } func showErrorText(text: String) { showError(text, seconds: ProcessButtonUtil.Length.Long) } func setBackgroundColor(normalState: UIColor, highlightedState: UIColor) { backgroundColor = normalState setBackgroundImage(ProcessButtonUtil.imageWithColor(highlightedState), forState: UIControlState.Highlighted) } }
mit
sudeepunnikrishnan/ios-sdk
Instamojo/WalletOptions.swift
1
531
// // WalletOptions.swift // Instamojo // // Created by Sukanya Raj on 15/02/17. // Copyright © 2017 Sukanya Raj. All rights reserved. // import UIKit public class WalletOptions: NSObject { public var url: String! public var wallets: [Wallet]! public init(url: String, wallets: [Wallet]) { self.url = url self.wallets = wallets } public func getPostData(accessToken: String, walletID: String) -> String { return "access_token=" + accessToken + "&wallet_id=" + walletID } }
lgpl-3.0
felipecarreramo/BSImagePicker
Pod/Classes/Extension/UIButton+NoAnimation.swift
1
1892
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 /** Extension on UIButton for settings the title without an animation */ extension UIButton { /** Sets title without an animation :param: title The String to use as title :param: forState Which state it applies to */ func bs_setTitleWithoutAnimation(_ title: String?, forState state: UIControlState) { // Store enabled let wasEnabled = self.isEnabled // Disable/enable animations UIView.setAnimationsEnabled(false) // A little hack to set title without animation self.isEnabled = true self.setTitle(title, for: state) self.layoutIfNeeded() // Enable animations UIView.setAnimationsEnabled(true) } }
mit
safakge/TimeIntervalPicker
Example/TimeIntervalPicker/ViewController.swift
1
585
// // ViewController.swift // TimeIntervalPicker // // Created by Taras Chernyshenko on 02/08/2017. // Copyright (c) 2017 Taras Chernyshenko. All rights reserved. // import UIKit import TimeIntervalPicker class ViewController: UIViewController { @IBAction private func showButtonPressed(button: UIButton) { let timePicker = TimeIntervalPicker() timePicker.titleString = "Select time:" timePicker.maxMinutes = 180 timePicker.completion = { (timeInterval) in print(timeInterval) } timePicker.show(at: 0) } }
mit
realm/SwiftLint
Source/SwiftLintFramework/Rules/Lint/WeakDelegateRule.swift
1
5629
import SwiftSyntax struct WeakDelegateRule: OptInRule, SwiftSyntaxRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "weak_delegate", name: "Weak Delegate", description: "Delegates should be weak to avoid reference cycles.", kind: .lint, nonTriggeringExamples: [ Example("class Foo {\n weak var delegate: SomeProtocol?\n}\n"), Example("class Foo {\n weak var someDelegate: SomeDelegateProtocol?\n}\n"), Example("class Foo {\n weak var delegateScroll: ScrollDelegate?\n}\n"), // We only consider properties to be a delegate if it has "delegate" in its name Example("class Foo {\n var scrollHandler: ScrollDelegate?\n}\n"), // Only trigger on instance variables, not local variables Example("func foo() {\n var delegate: SomeDelegate\n}\n"), // Only trigger when variable has the suffix "-delegate" to avoid false positives Example("class Foo {\n var delegateNotified: Bool?\n}\n"), // There's no way to declare a property weak in a protocol Example("protocol P {\n var delegate: AnyObject? { get set }\n}\n"), Example("class Foo {\n protocol P {\n var delegate: AnyObject? { get set }\n}\n}\n"), Example("class Foo {\n var computedDelegate: ComputedDelegate {\n return bar() \n} \n}"), Example(""" class Foo { var computedDelegate: ComputedDelegate { get { return bar() } } """), Example("struct Foo {\n @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate \n}"), Example("struct Foo {\n @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate \n}"), Example("struct Foo {\n @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate \n}"), Example(""" class Foo { func makeDelegate() -> SomeDelegate { let delegate = SomeDelegate() return delegate } } """), Example(""" class Foo { var bar: Bool { let appDelegate = AppDelegate.bar return appDelegate.bar } } """, excludeFromDocumentation: true), Example("private var appDelegate: String?", excludeFromDocumentation: true) ], triggeringExamples: [ Example("class Foo {\n ↓var delegate: SomeProtocol?\n}\n"), Example("class Foo {\n ↓var scrollDelegate: ScrollDelegate?\n}\n"), Example(""" class Foo { ↓var delegate: SomeProtocol? { didSet { print("Updated delegate") } } """) ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } } private extension WeakDelegateRule { final class Visitor: ViolationsSyntaxVisitor { override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ ProtocolDeclSyntax.self ] } override func visitPost(_ node: VariableDeclSyntax) { guard node.hasDelegateSuffix, node.weakOrUnownedModifier == nil, !node.hasComputedBody, !node.containsIgnoredAttribute, let parent = node.parent, Syntax(parent).enclosingClass() != nil else { return } violations.append(node.letOrVarKeyword.positionAfterSkippingLeadingTrivia) } } } private extension Syntax { func enclosingClass() -> ClassDeclSyntax? { if let classExpr = self.as(ClassDeclSyntax.self) { return classExpr } else if self.as(DeclSyntax.self) != nil { return nil } return parent?.enclosingClass() } } private extension VariableDeclSyntax { var hasDelegateSuffix: Bool { bindings.allSatisfy { binding in guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self) else { return false } return pattern.identifier.withoutTrivia().text.lowercased().hasSuffix("delegate") } } var hasComputedBody: Bool { bindings.allSatisfy { binding in guard let accessor = binding.accessor else { return false } if accessor.is(CodeBlockSyntax.self) { return true } else if accessor.as(AccessorBlockSyntax.self)?.getAccessor != nil { return true } return false } } var containsIgnoredAttribute: Bool { let ignoredAttributes: Set = [ "UIApplicationDelegateAdaptor", "NSApplicationDelegateAdaptor", "WKExtensionDelegateAdaptor" ] return attributes?.contains { attr in guard let customAttr = attr.as(CustomAttributeSyntax.self), let typeIdentifier = customAttr.attributeName.as(SimpleTypeIdentifierSyntax.self) else { return false } return ignoredAttributes.contains(typeIdentifier.name.withoutTrivia().text) } ?? false } }
mit
narner/AudioKit
AudioKit/Common/Operations/Math/Random Number Generators/jitter.swift
1
939
// // jitter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // extension AKOperation { /// A signal with random fluctuations /// This is useful for emulating jitter found in analogue equipment. /// /// - Parameters: /// - amplitude: The amplitude of the line. Will produce values in the range of (+/-)amp. (Default: 0.5) /// - minimumFrequency: The minimum frequency of change in Hz. (Default: 0.5) /// - maximumFrequency: The maximum frequency of change in Hz. (Default: 4) /// public static func jitter( amplitude: AKParameter = 0.5, minimumFrequency: AKParameter = 0.5, maximumFrequency: AKParameter = 4 ) -> AKOperation { return AKOperation(module: "jitter", inputs: amplitude, minimumFrequency, maximumFrequency) } }
mit
zhouxinv/SwiftThirdTest
SwiftTestUITests/SwiftTestUITests.swift
1
1244
// // SwiftTestUITests.swift // SwiftTestUITests // // Created by GeWei on 2016/12/19. // Copyright © 2016年 GeWei. All rights reserved. // import XCTest class SwiftTestUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
maximbilan/UICollectionViewHorizontalPaging
UICollectionViewHorizontalPaging/UIColorExtensions.swift
1
485
// // UIColorExtensions.swift // UICollectionViewHorizontalPaging // // Created by Maxim on 2/6/16. // Copyright © 2016 Maxim Bilan. All rights reserved. // import UIKit extension UIColor { class func randomColor() -> UIColor { let hue = CGFloat(arc4random() % 100) / 100 let saturation = CGFloat(arc4random() % 100) / 100 let brightness = CGFloat(arc4random() % 100) / 100 return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0) } }
mit
zakkhoyt/ColorPicKit
ColorPicKit/Classes/HSLASlider.swift
1
1430
// // HSLASlider.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/28/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit class HSLASlider: Slider { private var _saturation: CGFloat = 0.5 @IBInspectable public var saturation: CGFloat { get { return _saturation } set { if _saturation != newValue { _saturation = newValue hslaView.saturation = newValue updateKnobColor() } } } private var _lightness: CGFloat = 0.5 public var lightness: CGFloat { get { return _lightness } set { if _lightness != newValue { _lightness = newValue hslaView.lightness = newValue updateKnobColor() } } } fileprivate var hslaView = HSLASliderView() override func configureBackgroundView() { hslaView.borderColor = borderColor hslaView.borderWidth = borderWidth hslaView.roundedCorners = roundedCorners addSubview(hslaView) self.sliderView = hslaView } override func colorFrom(value: CGFloat) -> UIColor { let hue = value let hsla = HSLA(hue: hue, saturation: saturation, lightness: lightness) let color = hsla.color() return color } }
mit
h-n-y/UICollectionView-TheCompleteGuide
chapter-6/ImprovedCoverFlow/CoverFlow/CoverFlowFlowLayout.swift
1
9520
// // CoverFlowFlowLayout.swift // CoverFlow // // Created by Hans Yelek on 5/1/16. // Copyright © 2016 Hans Yelek. All rights reserved. // import UIKit class CoverFlowFlowLayout: UICollectionViewFlowLayout { override class func layoutAttributesClass() -> AnyClass { return CollectionViewLayoutAttributes.self } override init() { super.init() setDefaultPropertyValues() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setDefaultPropertyValues() } private func setDefaultPropertyValues() { scrollDirection = .Horizontal itemSize = CGSize(width: 180, height: 180) // Get items up close to one another minimumLineSpacing = -60 // Makes sure we only have one row of items in portrait mode minimumInteritemSpacing = 200 } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { // Very important - need to re-layout the cells when scrolling return true } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let layoutAttributesArray = super.layoutAttributesForElementsInRect(rect) else { return nil } guard let collectionView = self.collectionView else { return layoutAttributesArray } // Calculate the rect of the collection view visible to the user let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) for attributes in layoutAttributesArray { // Only modify attributes whose frames intersect the visible portion of the collection view if CGRectIntersectsRect(attributes.frame, rect) { applyLayoutAttributes(attributes, forVisibleRect: visibleRect) } } return layoutAttributesArray } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { guard let attributes = super.layoutAttributesForItemAtIndexPath(indexPath) else { return nil } guard let collectionView = self.collectionView else { return attributes } // Calculate the rect of the collection view visible to the user let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) applyLayoutAttributes(attributes, forVisibleRect: visibleRect) return attributes } // Forces collection view to center a cell once scrolling has stopped. override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = self.collectionView else { return super.targetContentOffsetForProposedContentOffset(proposedContentOffset, withScrollingVelocity: velocity) } var offsetAdjustment = MAXFLOAT let horizontalCenter: CGFloat = proposedContentOffset.x + collectionView.bounds.width / 2.0 // Use the center to find the proposed visible rect. let proposedRect = CGRect(x: 0, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height) // Get the attributes for the cells in that rect. guard let layoutAttributes = layoutAttributesForElementsInRect(proposedRect) else { return super.targetContentOffsetForProposedContentOffset(proposedContentOffset, withScrollingVelocity: velocity) } // This loop will find the closest cell to proposed center // of the collection view for attributes in layoutAttributes { // Skip supplementary views if attributes.representedElementCategory != .Cell { continue } // Determine if this layout attribute's cell is closer than the closest // we have so far. let itemHorizontalCenter: CGFloat = attributes.center.x if fabs(itemHorizontalCenter - horizontalCenter) < CGFloat(fabs(offsetAdjustment)) { offsetAdjustment = Float(itemHorizontalCenter - horizontalCenter) } } return CGPoint(x: proposedContentOffset.x + CGFloat(offsetAdjustment), y: proposedContentOffset.y) } // Applies the cover flow effect to the given layout attributes private func applyLayoutAttributes(attributes: UICollectionViewLayoutAttributes, forVisibleRect visibleRect: CGRect) { // Ignore supplementary views. guard attributes.representedElementKind == nil else { return } guard let attributes = attributes as? CollectionViewLayoutAttributes else { return } let ACTIVE_DISTANCE: CGFloat = 100.0 let TRANSLATE_DISTANCE: CGFloat = 100.0 let ZOOM_FACTOR: CGFloat = 0.2 let FLOW_OFFSET: CGFloat = 40.0 let INACTIVE_GRAY_VALUE: CGFloat = 0.6 // Calculate the distance from the center of the visible rect to the center // of the attributes. Then normalize the distance so we can compare them all. // This way, all items further away than the active get the same transform. let distanceFromVisibleRectToItem: CGFloat = CGRectGetMidX(visibleRect) - attributes.center.x let normalizedDistance: CGFloat = distanceFromVisibleRectToItem / ACTIVE_DISTANCE let isLeft = distanceFromVisibleRectToItem > 0 // Default values var transform = CATransform3DIdentity var maskAlpha: CGFloat = 0.0 if fabs(distanceFromVisibleRectToItem) < ACTIVE_DISTANCE { // We're close enough to apply the transform in relation to // how far away from the center we are transform = CATransform3DTranslate(CATransform3DIdentity, (isLeft ? -FLOW_OFFSET: FLOW_OFFSET) * abs(distanceFromVisibleRectToItem / TRANSLATE_DISTANCE ), 0, (1 - fabs(normalizedDistance)) * 40_000.0 + (isLeft ? 200.0 : 0.0)) // Set the perspective of the transform transform.m34 = -1.0 / (4.6777 * itemSize.width) // Set the rotation of the transform transform = CATransform3DRotate(transform, (isLeft ? 1 : -1) * fabs(normalizedDistance) * CGFloat(45).radians(), 0, 1, 0) // Set the zoom factor let zoom: CGFloat = 1 + ZOOM_FACTOR * ( 1 - abs(normalizedDistance) ) transform = CATransform3DScale(transform, zoom, zoom, 1) attributes.zIndex = 1 let ratioToCenter = ( ACTIVE_DISTANCE - fabs(distanceFromVisibleRectToItem)) / ACTIVE_DISTANCE // Interpolate between 0.0 and INACTIVE_GRAY_VALUE maskAlpha = INACTIVE_GRAY_VALUE + ratioToCenter * (-INACTIVE_GRAY_VALUE) } else { // We're too far away; just apply a standard perpective transform transform.m34 = -1 / ( 4.6777 * itemSize.width ) transform = CATransform3DTranslate(transform, isLeft ? -FLOW_OFFSET : FLOW_OFFSET, 0, 0) transform = CATransform3DRotate(transform, ( isLeft ? 1 : -1 ) * CGFloat(45).radians(), 0, 1, 0) attributes.zIndex = 0 maskAlpha = INACTIVE_GRAY_VALUE } attributes.transform3D = transform // Rasterize the cells for smoother edges attributes.shouldRasterize = true attributes.maskingValue = maskAlpha } } extension CoverFlowFlowLayout { func indexPathIsCentered(indexPath: NSIndexPath) -> Bool { guard let collectionView = self.collectionView else { return false } guard let attributes = layoutAttributesForItemAtIndexPath(indexPath) else { return false } let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) let distanceFromVisibleRectToItem: CGFloat = CGRectGetMidX(visibleRect) - attributes.center.x return fabs(distanceFromVisibleRectToItem) < 1 } } extension CGFloat { /// Assumes that `self`'s current value is in terms of *degrees* and returns /// the *radian* equivalent. func radians() -> CGFloat { return self * CGFloat(M_PI / 180.0) } }
mit
ontouchstart/swift3-playground
Learn to Code 1.playgroundbook/Contents/Chapters/Document8.playgroundchapter/Pages/Exercise3.playgroundpage/Contents.swift
1
1337
//#-hidden-code // // Contents.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // //#-end-hidden-code /*: **Goal:** Use the right-hand rule to help Byte navigate through a complex maze. An algorithm that follows the right-hand rule works well for simple walled puzzles, but you can also use it to solve more complicated puzzles, such as mazes. For this puzzle, walk through the maze in your mind. If you always keep your right hand on the wall, you’ll eventually reach the last gem. Write code that uses the right-hand rule to get through the maze and collect the gem. 1. steps: Start by writing your [pseudocode](glossary://pseudocode), including instructions for what to do when you’re blocked. 2. Test your pseudocode by walking through it in your mind as you move around the puzzle world. 3. Write the code to implement your algorithm. */ //#-code-completion(everything, hide) //#-code-completion(currentmodule, show) //#-code-completion(identifier, show, isOnOpenSwitch, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, isOnClosedSwitch, isBlocked, isBlockedLeft, &&, ||, !, isBlockedRight, if, while, func, for) //#-hidden-code playgroundPrologue() //#-end-hidden-code //#-editable-code //#-end-editable-code //#-hidden-code playgroundEpilogue() //#-end-hidden-code
mit
mozilla-mobile/firefox-ios
Client/TabEventHandlers.swift
2
850
// 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 Foundation import Shared class TabEventHandlers { /// Create handlers that observe specified tab events. /// /// For anything that needs to react to tab events notifications (see `TabEventLabel`), the /// pattern is to implement a handler and specify which events to observe. static func create(with profile: Profile) -> [TabEventHandler] { let handlers: [TabEventHandler] = [ FaviconHandler(), UserActivityHandler(), MetadataParserHelper(), MediaImageLoader(profile.prefs), AccountSyncHandler(with: profile) ] return handlers } }
mpl-2.0
aestusLabs/ASChatApp
Colours.swift
1
5538
// // Colours.swift // ChatAppOrigionalFiles // // Created by Ian Kohlert on 2017-07-19. // Copyright © 2017 aestusLabs. All rights reserved. // import Foundation import UIKit enum ColourTheme { case light, dark } struct Colours { func getMainAppColour() -> UIColor{ return appInfo.appColourMain } let appColourLeft = UIColor(red: 1.0, green: 0.325490196, blue: 0.541176471, alpha: 1.0) let appColourRight = UIColor(red: 1.0, green: 0.494117647, blue: 0.435294118, alpha: 1.0) private let lightBackground = UIColor(red: 0.960784314, green: 0.960784314, blue: 0.960784314, alpha: 1.0) private let darkBackground = UIColor.black private let lightHelperBarBackground = UIColor.white private let darkHelperBarBackground = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightTextColour = UIColor.black private let darkTextColour = UIColor.white private let lightEmptyHelperCircle = UIColor(red: 0.290196078, green: 0.290196078, blue: 0.290196078, alpha: 1.0) private let darkEmptyHelperCircle = UIColor.white //UIColor(red: 0.901960784, green: 0.901960784, blue: 0.901960784, alpha: 1.0) private let lightHelperSuggestionColour = UIColor.white private let darkHelperSuggestionColour = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightSliderColour = UIColor.black private let darkSliderColour = UIColor.white private let appGradientLeft = UIColor(red: 1.0, green: 0.325490196, blue: 0.541176471, alpha: 1.0) private let appGradientRight = UIColor(red: 1.0, green: 0.494117647, blue: 0.435294118, alpha: 1.0) private let lightOnboardBehindTextField = UIColor.white private let darktOnboardBehindTextField = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightWhite = UIColor.white private let darkGrey = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightMask = UIColor.white private let darkMask = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightHelperSuggestionExpandedBackground = UIColor(red: 0.956862745, green: 0.956862745, blue: 0.956862745, alpha: 1.0) private let lightBehindHelperTextHomeBackground = UIColor(red: 0.988235294, green: 0.988235294, blue: 0.988235294, alpha: 1.0) private let lightCardBackgroundColour = UIColor.white private let darkCardBackgroundColour = UIColor.lightGray private let lightSessionWidgetHighlightColour = UIColor(red: 0.980392157, green: 0.980392157, blue: 0.980392157, alpha: 1.0) private let darkSessionWidgetHighlightColour = UIColor(red: 0.094117647, green: 0.094117647, blue: 0.094117647, alpha: 1.0) func getBackgroundColour() -> UIColor { if ASUser.colourTheme == .light { return lightBackground } else { return darkBackground } } func getHelperBarBackgroundColour() -> UIColor { if ASUser.colourTheme == .light { return lightHelperBarBackground } else { return darkHelperBarBackground } } func getTextColour() -> UIColor { if ASUser.colourTheme == .light { return lightTextColour } else { return darkTextColour } } func getEmptyHelperColour() -> UIColor { if ASUser.colourTheme == .light { return lightEmptyHelperCircle } else { return darkEmptyHelperCircle } } func getHelperSuggestionColour() -> UIColor { if ASUser.colourTheme == .light { return lightHelperSuggestionColour } else { return darkHelperSuggestionColour } } func getSliderColour() -> UIColor { if ASUser.colourTheme == .light { return lightSliderColour } else { return darkSliderColour } } func getGradientColours() -> (UIColor, UIColor) { return (appGradientLeft, appGradientRight) } func getOnboardBehindTextFieldColours() -> UIColor { if ASUser.colourTheme == .light { return lightOnboardBehindTextField } else { return darktOnboardBehindTextField } } func getLineBackground() -> UIColor { if ASUser.colourTheme == .light { return lightWhite } else { return darkGrey } } func getMaskColour() -> UIColor { if ASUser.colourTheme == .light { return lightMask } else { return darkMask } } func getHelperExpandedSuggestionBackground() -> UIColor { return lightHelperSuggestionExpandedBackground } func getBehindHelperTextHomeBackground() -> UIColor { return lightBehindHelperTextHomeBackground } func getCardBackgroundColour() -> UIColor { if ASUser.colourTheme == .light { return lightCardBackgroundColour } else { return darkCardBackgroundColour } } func getContentSessionWidgetHightlightColout () -> UIColor { if ASUser.colourTheme == .light { return lightSessionWidgetHighlightColour } else { return darkSessionWidgetHighlightColour } } } let appColours = Colours()
mit
drawRect/Instagram_Stories
InstagramStories/Modules/Home/IGHomeViewModel.swift
1
1135
// // IGHomeViewModel.swift // InstagramStories // // Created by Boominadha Prakash on 01/11/17. // Copyright © 2017 DrawRect. All rights reserved. // import Foundation struct IGHomeViewModel { //MARK: - iVars //Keep it Immutable! don't get Dirty :P private let stories: IGStories? = { do { return try IGMockLoader.loadMockFile(named: "stories.json", bundle: .main) }catch let e as MockLoaderError { debugPrint(e.description) }catch{ debugPrint("could not read Mock json file :(") } return nil }() //MARK: - Public functions public func getStories() -> IGStories? { return stories } public func numberOfItemsInSection(_ section:Int) -> Int { if let count = stories?.otherStoriesCount { return count + 1 } return 1 } public func cellForItemAt(indexPath:IndexPath) -> IGStory? { if indexPath.row == 0 { return stories?.myStory[indexPath.row] }else { return stories?.otherStories[indexPath.row-1] } } }
mit
qxuewei/XWSwiftWB
XWSwiftWB/XWSwiftWB/Classes/Discover/DiscoverTableVC.swift
1
444
// // DiscoverTableVC.swift // XWSwiftWB // // Created by 邱学伟 on 16/10/25. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit class DiscoverTableVC: BaseTableVC { override func viewDidLoad() { super.viewDidLoad() visitorView.setupVisitorViewInfo(iconName: "visitordiscover_image_message", tip: "登录后,别人评论你的微博,给你发消息,都会在这里收到通知") } }
apache-2.0
Pyroh/Fluor
Fluor/Controllers/ViewControllers/DefaultModeViewController.swift
1
2054
// // DefaultModeViewController.swift // // Fluor // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // 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 Cocoa @objc protocol DefaultModeViewControllerDelegate: class { @objc optional func defaultModeController(_ controller: DefaultModeViewController, willChangeModeTo mode: FKeyMode) func defaultModeController(_ controller: DefaultModeViewController, didChangeModeTo mode: FKeyMode) } class DefaultModeViewController: NSViewController { @IBOutlet weak var delegate: (AnyObject & DefaultModeViewControllerDelegate)? /// Change the current keyboard state. /// /// - parameter sender: The object that sent the action. @IBAction func changeMode(_ sender: NSSegmentedControl) { guard let state = FKeyMode(rawValue: sender.selectedSegment) else { return } delegate?.defaultModeController?(self, willChangeModeTo: state) delegate?.defaultModeController(self, didChangeModeTo: state) } }
mit
nheagy/WordPress-iOS
WordPress/Classes/Networking/PushAuthenticationServiceRemote.swift
1
1418
import Foundation import AFNetworking /** * @class PushAuthenticationServiceRemote * @brief The purpose of this class is to encapsulate all of the interaction with the REST endpoint, * required to handle WordPress.com 2FA Code Veritication via Push Notifications */ @objc public class PushAuthenticationServiceRemote : ServiceRemoteREST { /** * @details Verifies a WordPress.com Login. * @param token The token passed on by WordPress.com's 2FA Push Notification. * @param success Closure to be executed on success. Can be nil. * @param failure Closure to be executed on failure. Can be nil. */ public func authorizeLogin(token: String, success: (() -> ())?, failure: (() -> ())?) { let path = "me/two-step/push-authentication" let requestUrl = self.pathForEndpoint(path, withVersion: ServiceRemoteRESTApiVersion_1_1) let parameters = [ "action" : "authorize_login", "push_token" : token ] api.POST(requestUrl, parameters: parameters, success: { (operation: AFHTTPRequestOperation, response: AnyObject) -> Void in success?() }, failure:{ (operation: AFHTTPRequestOperation?, error: NSError) -> Void in failure?() }) } }
gpl-2.0
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/Analytics/EditorAnalytics/PostEditorAnalyticsSessionTests.swift
1
7033
import Foundation import XCTest @testable import WordPress class PostEditorAnalyticsSessionTests: CoreDataTestCase { enum PostContent { static let classic = """ Text <strong>bold</strong> <em>italic</em> """ static let gutenberg = """ <!-- wp:image {"id":-181231834} --> <figure class="wp-block-image"><img src="file://tmp/EC856C66-7B79-4631-9503-2FB9FF0E6C66.jpg" alt="" class="wp-image--181231834"/></figure> <!-- /wp:image --> """ } override func setUp() { TestAnalyticsTracker.setup() } override func tearDown() { TestAnalyticsTracker.tearDown() } func testStartGutenbergSessionWithoutContentAndTitle() { startSession(editor: .gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "content_type"), PostEditorAnalyticsSession.ContentType.new.rawValue) XCTAssertEqual(tracked?.value(for: "editor"), PostEditorAnalyticsSession.Editor.gutenberg.rawValue) } func testStartGutenbergSessionWithTitleButNoContent() { startSession(editor: .gutenberg, postTitle: "Title") XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "content_type"), PostEditorAnalyticsSession.ContentType.new.rawValue) XCTAssertEqual(tracked?.value(for: "editor"), PostEditorAnalyticsSession.Editor.gutenberg.rawValue) } func testStartGutenbergSessionWithTitleAndContent() { startSession(editor: .gutenberg, postTitle: "Title", postContent: PostContent.gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "content_type"), PostEditorAnalyticsSession.ContentType.gutenberg.rawValue) XCTAssertEqual(tracked?.value(for: "editor"), PostEditorAnalyticsSession.Editor.gutenberg.rawValue) } func testTrackUnsupportedBlocksOnStart() { let unsupportedBlocks = ["unsupported"] startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) let serializedArray = String(data: try! JSONSerialization.data(withJSONObject: unsupportedBlocks, options: .fragmentsAllowed), encoding: .utf8) XCTAssertEqual(tracked?.value(for: "unsupported_blocks"), serializedArray) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "1") } func testTrackUnsupportedBlocksOnStartWithEmptyList() { let unsupportedBlocks = [String]() startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) let serializedArray = String(data: try! JSONSerialization.data(withJSONObject: unsupportedBlocks, options: .fragmentsAllowed), encoding: .utf8) XCTAssertEqual(tracked?.value(for: "unsupported_blocks"), serializedArray) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "0") } func testTrackUnsupportedBlocksOnSwitch() { let unsupportedBlocks = ["unsupported"] var session = startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) session.switch(editor: .gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionSwitchEditor) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "1") let trackedUnsupportedBlocks: [String]? = tracked?.value(for: "unsupported_blocks") XCTAssertNil(trackedUnsupportedBlocks) } func testTrackUnsupportedBlocksOnEnd() { let unsupportedBlocks = ["unsupported"] let session = startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) session.end(outcome: .publish) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionEnd) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "1") let trackedUnsupportedBlocks: [String]? = tracked?.value(for: "unsupported_blocks") XCTAssertNil(trackedUnsupportedBlocks) } func testTrackBlogIdOnStart() { startSession(editor: .gutenberg, blogID: 123) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "blog_id"), "123") } func testTrackBlogIdOnSwitch() { var session = startSession(editor: .gutenberg, blogID: 456) session.switch(editor: .gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionSwitchEditor) XCTAssertEqual(tracked?.value(for: "blog_id"), "456") } func testTrackBlogIdOnEnd() { let session = startSession(editor: .gutenberg, blogID: 789) session.end(outcome: .publish) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionEnd) XCTAssertEqual(tracked?.value(for: "blog_id"), "789") } } extension PostEditorAnalyticsSessionTests { func createPost(title: String? = nil, body: String? = nil, blogID: NSNumber? = nil) -> AbstractPost { let post = AbstractPost(context: mainContext) post.postTitle = title post.content = body post.blog = Blog(context: mainContext) post.blog.dotComID = blogID return post } @discardableResult func startSession(editor: PostEditorAnalyticsSession.Editor, postTitle: String? = nil, postContent: String? = nil, unsupportedBlocks: [String] = [], blogID: NSNumber? = nil) -> PostEditorAnalyticsSession { let post = createPost(title: postTitle, body: postContent, blogID: blogID) var session = PostEditorAnalyticsSession(editor: .gutenberg, post: post) session.start(unsupportedBlocks: unsupportedBlocks) return session } }
gpl-2.0
NobodyNada/SwiftStack
Sources/SwiftStack/Post.swift
1
5883
// // Post.swift // SwiftStack // // Created by FelixSFD on 06.12.16. // // import Foundation // - MARK: The type of the post /** Defines the type of a post. Either a question or an answer - author: FelixSFD */ public enum PostType: String, StringRepresentable { case answer = "answer" case question = "question" } // - MARK: Post /** The base class of `Question`s and `Answer`s - author: FelixSFD - seealso: [StackExchange API](https://api.stackexchange.com/docs/types/post) */ public class Post: Content { // - MARK: Post.Notice /** Represents a notice on a post. - author: FelixSFD */ public struct Notice: JsonConvertible { public init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public init(dictionary: [String: Any]) { self.body = dictionary["body"] as? String if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } self.owner_user_id = dictionary["owner_user_id"] as? Int } public var dictionary: [String: Any] { var dict = [String: Any]() dict["body"] = body dict["creation_date"] = creation_date dict["owner_user_id"] = owner_user_id return dict } public var jsonString: String? { return (try? JsonHelper.jsonString(from: self)) ?? nil } public var body: String? public var creation_date: Date? public var owner_user_id: Int? } // - MARK: Initializers /** Basic initializer without default values */ public override init() { super.init() } /** Initializes the object from a JSON string. - parameter json: The JSON string returned by the API - author: FelixSFD */ public required convenience init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public required init(dictionary: [String: Any]) { super.init(dictionary: dictionary) //only initialize the properties that are not part of the superclass self.comment_count = dictionary["comment_count"] as? Int if let commentsArray = dictionary["comments"] as? [[String: Any]] { var commentsTmp = [Comment]() for commentDictionary in commentsArray { let commentTmp = Comment(dictionary: commentDictionary) commentsTmp.append(commentTmp) } } self.down_vote_count = dictionary["down_vote_count"] as? Int self.downvoted = dictionary["downvoted"] as? Bool if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_activity_date"] as? Int { self.last_activity_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_edit_date"] as? Int { self.last_edit_date = Date(timeIntervalSince1970: Double(timestamp)) } if let user = dictionary["last_editor"] as? [String: Any] { self.last_editor = User(dictionary: user) } if let urlString = dictionary["share_link"] as? String { self.share_link = URL(string: urlString) } self.title = (dictionary["title"] as? String)?.stringByDecodingHTMLEntities self.up_vote_count = dictionary["up_vote_count"] as? Int } // - MARK: JsonConvertible public override var dictionary: [String: Any] { var dict = super.dictionary dict["creation_date"] = creation_date dict["comment_count"] = comment_count if comments != nil && (comments?.count)! > 0 { var tmpComments = [[String: Any]]() for comment in comments! { tmpComments.append(comment.dictionary) } dict["comments"] = tmpComments } dict["down_vote_count"] = down_vote_count dict["downvoted"] = downvoted dict["last_activity_date"] = last_activity_date dict["last_edit_date"] = last_edit_date dict["last_editor"] = last_editor?.dictionary dict["share_link"] = share_link dict["title"] = title dict["up_vote_count"] = up_vote_count return dict } // - MARK: Fields public var creation_date: Date? public var comment_count: Int? public var comments: [Comment]? public var down_vote_count: Int? public var downvoted: Bool? public var last_activity_date: Date? public var last_edit_date: Date? public var last_editor: User? public var share_link: URL? public var title: String? public var up_vote_count: Int? }
mit
mgiraldo/watchOS-animations-test
watchSample/FrameLoader.swift
1
1100
// // FrameLoader.swift // watchSample // // Created by Mauricio Giraldo on 2/5/16. // import Foundation class FrameLoader { static func loadFrames()-> Array<NSData> { let frame1 = FrameLoader.getFile("1") let frame2 = FrameLoader.getFile("2") let frame3 = FrameLoader.getFile("3") let frame4 = FrameLoader.getFile("4") let frame5 = FrameLoader.getFile("5") let frame6 = FrameLoader.getFile("6") var frames = [NSData]() frames.append(frame1) frames.append(frame2) frames.append(frame3) frames.append(frame4) frames.append(frame5) frames.append(frame6) return frames } static func getFile(name:String)-> NSData { let bundles = NSBundle.allBundles() var file : NSData? for bundle in bundles { if let resourcePath = (bundle).pathForResource(name, ofType: "png") { file = NSData(contentsOfFile: resourcePath) return file! } } return file! } }
mit
elpassion/el-space-ios
ELSpace/Network/Services/HolidaysService.swift
1
934
import RxSwift import Mapper protocol HolidaysServiceProtocol { func getHolidays(month: Int, year: Int) -> Observable<HolidaysDTO> } class HolidaysService: HolidaysServiceProtocol { init(apiClient: ApiClientProtocol) { self.apiClient = apiClient } // MARK: - HolidaysServiceProtocol func getHolidays(month: Int, year: Int) -> Observable<HolidaysDTO> { let params: [String: Int] = [ "month": month, "year": year ] return apiClient.request(path: "holidays", method: .get, parameters: params, encoding: nil, headers: nil) .map { reponse -> HolidaysDTO in if let error = ApiError(response: reponse) { throw error } let json = reponse.data.json return try HolidaysDTO(map: Mapper(JSON: json as NSDictionary)) } } // MARK: - Private private let apiClient: ApiClientProtocol }
gpl-3.0
sol/aeson
tests/JSONTestSuite/parsers/test_PMJSON_1_1_0/Encoder.swift
6
6183
// // Encoder.swift // PMJSON // // Created by Kevin Ballard on 2/1/16. // Copyright © 2016 Postmates. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // extension JSON { /// Encodes a `JSON` to a `String`. /// - Parameter json: The `JSON` to encode. /// - Parameter pretty: If `true`, include extra whitespace for formatting. Default is `false`. /// - Returns: A `String` with the JSON representation of *json*. public static func encodeAsString(_ json: JSON, pretty: Bool = false) -> String { var s = "" encode(json, toStream: &s, pretty: pretty) return s } /// Encodes a `JSON` to an output stream. /// - Parameter json: The `JSON` to encode. /// - Parameter stream: The output stream to write the encoded JSON to. /// - Parameter pretty: If `true`, include extra whitespace for formatting. Default is `false`. public static func encode<Target: TextOutputStream>(_ json: JSON, toStream stream: inout Target, pretty: Bool = false) { encode(json, toStream: &stream, indent: pretty ? 0 : nil) } private static func encode<Target: TextOutputStream>(_ json: JSON, toStream stream: inout Target, indent: Int?) { switch json { case .null: encodeNull(&stream) case .bool(let b): encodeBool(b, toStream: &stream) case .int64(let i): encodeInt64(i, toStream: &stream) case .double(let d): encodeDouble(d, toStream: &stream) case .string(let s): encodeString(s, toStream: &stream) case .object(let obj): encodeObject(obj, toStream: &stream, indent: indent) case .array(let ary): encodeArray(ary, toStream: &stream, indent: indent) } } private static func encodeNull<Target: TextOutputStream>(_ stream: inout Target) { stream.write("null") } private static func encodeBool<Target: TextOutputStream>(_ value: Bool, toStream stream: inout Target) { stream.write(value ? "true" : "false") } private static func encodeInt64<Target: TextOutputStream>(_ value: Int64, toStream stream: inout Target) { stream.write(String(value)) } private static func encodeDouble<Target: TextOutputStream>(_ value: Double, toStream stream: inout Target) { stream.write(String(value)) } private static func encodeString<Target: TextOutputStream>(_ value: String, toStream stream: inout Target) { stream.write("\"") let scalars = value.unicodeScalars var start = scalars.startIndex let end = scalars.endIndex var idx = start while idx < scalars.endIndex { let s: String let c = scalars[idx] switch c { case "\\": s = "\\\\" case "\"": s = "\\\"" case "\n": s = "\\n" case "\r": s = "\\r" case "\t": s = "\\t" case "\u{8}": s = "\\b" case "\u{C}": s = "\\f" case "\0"..<"\u{10}": s = "\\u000\(String(c.value, radix: 16, uppercase: true))" case "\u{10}"..<" ": s = "\\u00\(String(c.value, radix: 16, uppercase: true))" default: idx = scalars.index(after: idx) continue } if idx != start { stream.write(String(scalars[start..<idx])) } stream.write(s) idx = scalars.index(after: idx) start = idx } if start != end { String(scalars[start..<end]).write(to: &stream) } stream.write("\"") } private static func encodeObject<Target: TextOutputStream>(_ object: JSONObject, toStream stream: inout Target, indent: Int?) { let indented = indent.map({$0+1}) if let indent = indented { stream.write("{\n") writeIndent(indent, toStream: &stream) } else { stream.write("{") } var first = true for (key, value) in object { if first { first = false } else if let indent = indented { stream.write(",\n") writeIndent(indent, toStream: &stream) } else { stream.write(",") } encodeString(key, toStream: &stream) stream.write(indented != nil ? ": " : ":") encode(value, toStream: &stream, indent: indented) } if let indent = indent { stream.write("\n") writeIndent(indent, toStream: &stream) } stream.write("}") } private static func encodeArray<Target: TextOutputStream>(_ array: JSONArray, toStream stream: inout Target, indent: Int?) { let indented = indent.map({$0+1}) if let indent = indented { stream.write("[\n") writeIndent(indent, toStream: &stream) } else { stream.write("[") } var first = true for elt in array { if first { first = false } else if let indent = indented { stream.write(",\n") writeIndent(indent, toStream: &stream) } else { stream.write(",") } encode(elt, toStream: &stream, indent: indented) } if let indent = indent { stream.write("\n") writeIndent(indent, toStream: &stream) } stream.write("]") } private static func writeIndent<Target: TextOutputStream>(_ indent: Int, toStream stream: inout Target) { for _ in stride(from: 4, through: indent, by: 4) { stream.write(" ") } switch indent % 4 { case 1: stream.write(" ") case 2: stream.write(" ") case 3: stream.write(" ") default: break } } }
bsd-3-clause
LittoCats/coffee-mobile
CoffeeMobile/Base/Utils/UIKitExtension/CMNSAttributedStringExtension.swift
1
8954
// // CMNSAttributedStringExtension.swift // CoffeeMobile // // Created by 程巍巍 on 5/25/15. // Copyright (c) 2015 Littocats. All rights reserved. // import Foundation import UIKit import XMLNode extension NSAttributedString { /** MARK: 由自定义的 xml 字符串生成 attributedString 支持的 属性参照 NSAttributedString.XMLParser.ExpressionMap */ convenience init(xml: String){ self.init(xml:xml, defaultAttribute: [String: AnyObject]()) } convenience init(xml: String, defaultAttribute: [String: AnyObject]){ self.init(attributedString: XMLParser(xml: xml,defaultAttribute: defaultAttribute).start().maString) } private class XMLParser: NSObject, NSXMLParserDelegate { private var maString = NSMutableAttributedString() private var xml: String! private var attrStack = [[String: AnyObject]]() init(xml: String, defaultAttribute: [String: AnyObject]){ super.init() attrStack.append(defaultAttribute) self.xml = "<xml>\(xml)</xml>" } func start()-> XMLParser { let parser = NSXMLParser(data: xml.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) parser.delegate = self var flag = parser.parse() return self } //MARK: 解析标签 @objc func parserDidStartDocument(parser: NSXMLParser){ if attrStack.isEmpty { attrStack.append([String: AnyObject]()) } } @objc func parserDidEndDocument(parser: NSXMLParser){ } @objc func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]){ var attr = attrStack.last! for (key, value) in attributeDict { if let name = (key as? String)?.lowercaseString { if let closure = XMLParser.ExpressionMap[(key as! String).lowercaseString] { for (k,v) in closure(key: name, value: value as! String){ attr[k] = v } } } } attrStack.append(attr) } @objc func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){ attrStack.removeLast() } @objc func parser(parser: NSXMLParser, foundCharacters string: String?){ if let str = string { buildString(str) } } @objc func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError){ println(parseError) } //MARK: 解析文本 private func buildString(str: String) { var string = str if var at = attrStack.last{ // font var font: UIFont? var family = at[CMTextFontFamilyAttributeName] as? String var size = at[CMTextFontSizeAttributeName] as? Float if size == nil {size = 17} if family == nil { font = UIFont.systemFontOfSize(CGFloat(size!)) }else{ font = UIFont(name: family!, size: CGFloat(size!)) } if font != nil { at[NSFontAttributeName] = font! } at.removeValueForKey(CMTextFontFamilyAttributeName) at.removeValueForKey(CMTextFontSizeAttributeName) // paragraph var para = NSMutableParagraphStyle() if let align = at[CMTextAlignmentAttributeName] as? Int { para.alignment = NSTextAlignment(rawValue: align)! at.removeValueForKey(CMTextAlignmentAttributeName) } if let firstLineHeadIndent = at[CMTextFirstLineHeadIndentAttributeName] as? Float { para.firstLineHeadIndent = CGFloat(firstLineHeadIndent) at.removeValueForKey(CMTextFirstLineHeadIndentAttributeName) } if let headIndent = at[CMTextHeadIndentAttributeName] as? Float { para.headIndent = CGFloat(headIndent) at.removeValueForKey(CMTextHeadIndentAttributeName) } if let tailIndent = at[CMTextTailIndentAttributeName] as? Float { para.tailIndent = CGFloat(tailIndent) at.removeValueForKey(CMTextTailIndentAttributeName) } if let lineSpace = at[CMTextLineSpaceAttributeName] as? Float { para.lineSpacing = CGFloat(lineSpace) at.removeValueForKey(CMTextLineSpaceAttributeName) } at[NSParagraphStyleAttributeName] = para // append maString.appendAttributedString(NSAttributedString(string: str, attributes: at)) }else{ maString.appendAttributedString(NSAttributedString(string: str)) } } } } private let CMTextFontFamilyAttributeName = "CMTextFontFamilyAttributeName" private let CMTextFontSizeAttributeName = "CMTextFontSizeAttributeName" private let CMTextAlignmentAttributeName = "NSTextAlignmentAttributeName" private let CMTextFirstLineHeadIndentAttributeName = "CMTextFirstLineHeadIndentAttributeName" private let CMTextHeadIndentAttributeName = "CMTextHeadIndentAttributeName" private let CMTextTailIndentAttributeName = "CMTextTailIndentAttributeName" private let CMTextLineSpaceAttributeName = "CMTextLineSpaceAttributeName" private func FloatValue(str: String)->Float { var float = (str as NSString).floatValue return float } extension NSAttributedString.XMLParser { typealias EXP = (key: String, value: String)->[String: AnyObject] static var ExpressionMap: [String: EXP] = [ // foreground/background color "color": {EXP in [NSForegroundColorAttributeName: UIColor(script: EXP.1)]}, "bgcolor": {EXP in [NSBackgroundColorAttributeName: UIColor(script: EXP.1)]}, // font "font": {EXP in [CMTextFontFamilyAttributeName: EXP.1]}, "size": {EXP in [CMTextFontSizeAttributeName: FloatValue(EXP.1)]}, // under line "underline": {EXP in [NSUnderlineStyleAttributeName: FloatValue(EXP.1)]}, "ul": {EXP in if EXP.0 == EXP.1 { return [NSUnderlineStyleAttributeName: 1] } return [NSUnderlineStyleAttributeName: FloatValue(EXP.1)] }, "underlinecolor": {EXP in [NSUnderlineColorAttributeName: UIColor(script: EXP.1)]}, "ulcolor": {EXP in [NSUnderlineColorAttributeName: UIColor(script: EXP.1)]}, // strike though "strikethrough": {EXP in [NSStrikethroughStyleAttributeName: FloatValue(EXP.1)]}, "st": {EXP in if EXP.0 == EXP.1 { return [NSStrikethroughStyleAttributeName: 1] } return [NSStrikethroughStyleAttributeName: FloatValue(EXP.1)] }, "strikethroughcolor": {EXP in [NSStrikethroughColorAttributeName: UIColor(script: EXP.1)]}, "stcolor": {EXP in [NSStrikethroughColorAttributeName: UIColor(script: EXP.1)]}, // stroke 可以间接实现 字体加粗效果 "strokecolor": {EXP in [NSStrikethroughColorAttributeName: UIColor(script: EXP.1)]}, "stroke": {EXP in [NSStrokeWidthAttributeName: FloatValue(EXP.1)]}, // paragraph // text align "algin": { EXP in switch EXP.1 { case "-|","right": return [CMTextAlignmentAttributeName: NSTextAlignment.Right.rawValue] case "||","center": return [CMTextAlignmentAttributeName: NSTextAlignment.Center.rawValue] default: return [CMTextAlignmentAttributeName: NSTextAlignment.Left.rawValue] } }, // 缩紧 "firstlineindent": {EXP in [CMTextFirstLineHeadIndentAttributeName: FloatValue(EXP.1)]}, "flindent": {EXP in [CMTextFirstLineHeadIndentAttributeName: FloatValue(EXP.1)]}, "headindent": {EXP in [CMTextHeadIndentAttributeName: FloatValue(EXP.1)]}, "hindent": {EXP in [CMTextHeadIndentAttributeName: FloatValue(EXP.1)]}, "trailindent": {EXP in [CMTextTailIndentAttributeName: FloatValue(EXP.1)]}, "tindent": {EXP in [CMTextTailIndentAttributeName: FloatValue(EXP.1)]}, "linespace": {EXP in [CMTextLineSpaceAttributeName: FloatValue(EXP.1)]}, ] }
apache-2.0
michael-lehew/swift-corelibs-foundation
Foundation/NSError.swift
1
57255
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import CoreFoundation public typealias NSErrorDomain = NSString /// Predefined domain for errors from most Foundation APIs. public let NSCocoaErrorDomain: String = "NSCocoaErrorDomain" // Other predefined domains; value of "code" will correspond to preexisting values in these domains. public let NSPOSIXErrorDomain: String = "NSPOSIXErrorDomain" public let NSOSStatusErrorDomain: String = "NSOSStatusErrorDomain" public let NSMachErrorDomain: String = "NSMachErrorDomain" // Key in userInfo. A recommended standard way to embed NSErrors from underlying calls. The value of this key should be an NSError. public let NSUnderlyingErrorKey: String = "NSUnderlyingError" // Keys in userInfo, for subsystems wishing to provide their error messages up-front. Note that NSError will also consult the userInfoValueProvider for the domain when these values are not present in the userInfo dictionary. public let NSLocalizedDescriptionKey: String = "NSLocalizedDescription" public let NSLocalizedFailureReasonErrorKey: String = "NSLocalizedFailureReason" public let NSLocalizedRecoverySuggestionErrorKey: String = "NSLocalizedRecoverySuggestion" public let NSLocalizedRecoveryOptionsErrorKey: String = "NSLocalizedRecoveryOptions" public let NSRecoveryAttempterErrorKey: String = "NSRecoveryAttempter" public let NSHelpAnchorErrorKey: String = "NSHelpAnchor" // Other standard keys in userInfo, for various error codes public let NSStringEncodingErrorKey: String = "NSStringEncodingErrorKey" public let NSURLErrorKey: String = "NSURL" public let NSFilePathErrorKey: String = "NSFilePathErrorKey" open class NSError : NSObject, NSCopying, NSSecureCoding, NSCoding { typealias CFType = CFError internal var _cfObject: CFType { return CFErrorCreate(kCFAllocatorSystemDefault, domain._cfObject, code, nil) } // ErrorType forbids this being internal open var _domain: String open var _code: Int /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. private var _userInfo: [String : Any]? /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. public init(domain: String, code: Int, userInfo dict: [String : Any]? = nil) { _domain = domain _code = code _userInfo = dict } public required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } _code = aDecoder.decodeInteger(forKey: "NSCode") _domain = aDecoder.decodeObject(of: NSString.self, forKey: "NSDomain")!._swiftObject if let info = aDecoder.decodeObject(of: [NSSet.self, NSDictionary.self, NSArray.self, NSString.self, NSNumber.self, NSData.self, NSURL.self], forKey: "NSUserInfo") as? NSDictionary { var filteredUserInfo = [String : Any]() // user info must be filtered so that the keys are all strings info.enumerateKeysAndObjects(options: []) { if let key = $0.0 as? NSString { filteredUserInfo[key._swiftObject] = $0.1 } } _userInfo = filteredUserInfo } } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(_domain._bridgeToObjectiveC(), forKey: "NSDomain") aCoder.encode(Int32(_code), forKey: "NSCode") aCoder.encode(_userInfo?._bridgeToObjectiveC(), forKey: "NSUserInfo") } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open var domain: String { return _domain } open var code: Int { return _code } /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. open var userInfo: [String : Any] { if let info = _userInfo { return info } else { return Dictionary<String, Any>() } } open var localizedDescription: String { let desc = userInfo[NSLocalizedDescriptionKey] as? String return desc ?? "The operation could not be completed" } open var localizedFailureReason: String? { return userInfo[NSLocalizedFailureReasonErrorKey] as? String } open var localizedRecoverySuggestion: String? { return userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String } open var localizedRecoveryOptions: [String]? { return userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String] } open var recoveryAttempter: Any? { return userInfo[NSRecoveryAttempterErrorKey] } open var helpAnchor: String? { return userInfo[NSHelpAnchorErrorKey] as? String } internal typealias NSErrorProvider = (_ error: NSError, _ key: String) -> AnyObject? internal static var userInfoProviders = [String: NSErrorProvider]() open class func setUserInfoValueProvider(forDomain errorDomain: String, provider: (/* @escaping */ (NSError, String) -> AnyObject?)?) { NSError.userInfoProviders[errorDomain] = provider } open class func userInfoValueProvider(forDomain errorDomain: String) -> ((NSError, String) -> AnyObject?)? { return NSError.userInfoProviders[errorDomain] } override open var description: String { return localizedDescription } // -- NSObject Overrides -- // The compiler has special paths for attempting to do some bridging on NSError (and equivalent Error instances) -- in particular, in the lookup of NSError objects' superclass. // On platforms where we don't have bridging (i.e. Linux), this causes a silgen failure. We can avoid the issue by overriding methods inherited by NSObject ourselves. override open var hashValue: Int { // CFHash does the appropriate casting/bridging on platforms where we support it. return Int(bitPattern: CFHash(self)) } override open func isEqual(_ object: Any?) -> Bool { // Pulled from NSObject itself; this works on all platforms. if let obj = object as? NSError { return obj === self } return false } } extension NSError : Swift.Error { } extension NSError : _CFBridgeable { } extension CFError : _NSBridgeable { typealias NSType = NSError internal var _nsObject: NSType { let userInfo = CFErrorCopyUserInfo(self)._swiftObject var newUserInfo: [String: Any] = [:] for (key, value) in userInfo { if let key = key as? String { newUserInfo[key] = value } } return NSError(domain: CFErrorGetDomain(self)._swiftObject, code: CFErrorGetCode(self), userInfo: newUserInfo) } } /// Describes an error that provides localized messages describing why /// an error occurred and provides more information about the error. public protocol LocalizedError : Error { /// A localized message describing what error occurred. var errorDescription: String? { get } /// A localized message describing the reason for the failure. var failureReason: String? { get } /// A localized message describing how one might recover from the failure. var recoverySuggestion: String? { get } /// A localized message providing "help" text if the user requests help. var helpAnchor: String? { get } } public extension LocalizedError { var errorDescription: String? { return nil } var failureReason: String? { return nil } var recoverySuggestion: String? { return nil } var helpAnchor: String? { return nil } } /// Class that implements the informal protocol /// NSErrorRecoveryAttempting, which is used by NSError when it /// attempts recovery from an error. class _NSErrorRecoveryAttempter { func attemptRecovery(fromError nsError: NSError, optionIndex recoveryOptionIndex: Int) -> Bool { let error = nsError as Error as! RecoverableError return error.attemptRecovery(optionIndex: recoveryOptionIndex) } } /// Describes an error that may be recoverable by presenting several /// potential recovery options to the user. public protocol RecoverableError : Error { /// Provides a set of possible recovery options to present to the user. var recoveryOptions: [String] { get } /// Attempt to recover from this error when the user selected the /// option at the given index. This routine must call handler and /// indicate whether recovery was successful (or not). /// /// This entry point is used for recovery of errors handled at a /// "document" granularity, that do not affect the entire /// application. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) /// Attempt to recover from this error when the user selected the /// option at the given index. Returns true to indicate /// successful recovery, and false otherwise. /// /// This entry point is used for recovery of errors handled at /// the "application" granularity, where nothing else in the /// application can proceed until the attempted error recovery /// completes. func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool } public extension RecoverableError { /// Default implementation that uses the application-model recovery /// mechanism (``attemptRecovery(optionIndex:)``) to implement /// document-modal recovery. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) { handler(attemptRecovery(optionIndex: recoveryOptionIndex)) } } /// Describes an error type that specifically provides a domain, code, /// and user-info dictionary. public protocol CustomNSError : Error { /// The domain of the error. static var errorDomain: String { get } /// The error code within the given domain. var errorCode: Int { get } /// The user-info dictionary. var errorUserInfo: [String : Any] { get } } public extension Error where Self : CustomNSError { /// Default implementation for customized NSErrors. var _domain: String { return Self.errorDomain } /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error { /// Retrieve the localized description for this error. var localizedDescription: String { return NSError(domain: _domain, code: _code, userInfo: nil).localizedDescription } } /// Retrieve the default userInfo dictionary for a given error. public func _swift_Foundation_getErrorDefaultUserInfo(_ error: Error) -> Any? { // TODO: Implement info value providers and return the code that was deleted here. let hasUserInfoValueProvider = false // Populate the user-info dictionary var result: [String : Any] // Initialize with custom user-info. if let customNSError = error as? CustomNSError { result = customNSError.errorUserInfo } else { result = [:] } // Handle localized errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let localizedError = error as? LocalizedError { if let description = localizedError.errorDescription { result[NSLocalizedDescriptionKey] = description } if let reason = localizedError.failureReason { result[NSLocalizedFailureReasonErrorKey] = reason } if let suggestion = localizedError.recoverySuggestion { result[NSLocalizedRecoverySuggestionErrorKey] = suggestion } if let helpAnchor = localizedError.helpAnchor { result[NSHelpAnchorErrorKey] = helpAnchor } } // Handle recoverable errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let recoverableError = error as? RecoverableError { result[NSLocalizedRecoveryOptionsErrorKey] = recoverableError.recoveryOptions result[NSRecoveryAttempterErrorKey] = _NSErrorRecoveryAttempter() } return result } // NSError and CFError conform to the standard Error protocol. Compiler // magic allows this to be done as a "toll-free" conversion when an NSError // or CFError is used as an Error existential. extension CFError : Error { public var _domain: String { return CFErrorGetDomain(self)._swiftObject } public var _code: Int { return CFErrorGetCode(self) } public var _userInfo: Any? { return CFErrorCopyUserInfo(self) as Any } } /// An internal protocol to represent Swift error enums that map to standard /// Cocoa NSError domains. public protocol _ObjectTypeBridgeableError : Error { /// Produce a value of the error type corresponding to the given NSError, /// or return nil if it cannot be bridged. init?(_bridgedNSError: NSError) } /// Helper protocol for _BridgedNSError, which used to provide /// default implementations. public protocol __BridgedNSError : Error { static var _nsErrorDomain: String { get } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax() } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(rawValue.toIntMax()) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(IntMax(_bridgedNSError.code))) } public final var hashValue: Int { return _code } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax() } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(bitPattern: UInt(rawValue.toUIntMax())) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code)))) } public final var hashValue: Int { return _code } } /// Describes a raw representable type that is bridged to a particular /// NSError domain. /// /// This protocol is used primarily to generate the conformance to /// _ObjectTypeBridgeableError for such an enum. public protocol _BridgedNSError : __BridgedNSError, RawRepresentable, _ObjectTypeBridgeableError, Hashable { /// The NSError domain to which this type is bridged. static var _nsErrorDomain: String { get } } /// Describes a bridged error that stores the underlying NSError, so /// it can be queried. public protocol _BridgedStoredNSError : __BridgedNSError, _ObjectTypeBridgeableError, CustomNSError, Hashable { /// The type of an error code. associatedtype Code: _ErrorCodeProtocol /// The error code for the given error. var code: Code { get } //// Retrieves the embedded NSError. var _nsError: NSError { get } /// Create a new instance of the error type with the given embedded /// NSError. /// /// The \c error must have the appropriate domain for this error /// type. init(_nsError error: NSError) } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: SignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: userInfo)) } /// The user-info dictionary for an error that was bridged from /// NSError. var userInfo: [String : Any] { return errorUserInfo } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: UnsignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: userInfo)) } } /// Implementation of __BridgedNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { /// Default implementation of ``init(_bridgedNSError)`` to provide /// bridging from NSError. public init?(_bridgedNSError error: NSError) { if error.domain != Self._nsErrorDomain { return nil } self.init(_nsError: error) } } /// Implementation of CustomNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { static var errorDomain: String { return _nsErrorDomain } var errorCode: Int { return _nsError.code } var errorUserInfo: [String : Any] { return _nsError.userInfo } } /// Implementation of Hashable for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { var hashValue: Int { return _nsError.hashValue } } /// Describes the code of an error. public protocol _ErrorCodeProtocol : Equatable { /// The corresponding error code. associatedtype _ErrorType // FIXME: We want _ErrorType to be _BridgedStoredNSError and have its // Code match Self, but we cannot express those requirements yet. } extension _ErrorCodeProtocol where Self._ErrorType: _BridgedStoredNSError { /// Allow one to match an error code against an arbitrary error. public static func ~=(match: Self, error: Error) -> Bool { guard let specificError = error as? Self._ErrorType else { return false } // FIXME: Work around IRGen crash when we set Code == Code._ErrorType.Code. let specificCode = specificError.code as! Self return match == specificCode } } extension _BridgedStoredNSError { public static func == (lhs: Self, rhs: Self) -> Bool { return lhs._nsError.isEqual(rhs._nsError) } } /// Describes errors within the Cocoa error domain. public struct CocoaError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSCocoaErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSCocoaErrorDomain } /// The error code itself. public struct Code : RawRepresentable, _ErrorCodeProtocol { public typealias _ErrorType = CocoaError public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 4) } public static var fileLocking: CocoaError.Code { return CocoaError.Code(rawValue: 255) } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 256) } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 257) } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 258) } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code(rawValue: 259) } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 260) } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 261) } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 262) } public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 263) } public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 264) } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 512) } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 513) } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 514) } public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code(rawValue: 516) } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 517) } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 518) } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code(rawValue: 640) } public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code(rawValue: 642) } public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 768) } public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code(rawValue: 769) } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } public static var formatting: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } public static var userCancelled: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } public static var featureUnsupported: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } public static var executableLoad: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } public static var executableLink: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code(rawValue: 4097) } public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4099) } public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4101) } public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code(rawValue: 4355) } public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } } public extension CocoaError { private var _nsUserInfo: [AnyHashable : Any] { return NSError(domain: _domain, code: _code, userInfo: nil).userInfo } /// The file path associated with the error, if any. var filePath: String? { return _nsUserInfo[NSFilePathErrorKey._bridgeToObjectiveC()] as? String } /// The string encoding associated with this error, if any. var stringEncoding: String.Encoding? { return (_nsUserInfo[NSStringEncodingErrorKey._bridgeToObjectiveC()] as? NSNumber) .map { String.Encoding(rawValue: $0.uintValue) } } /// The underlying error behind this error, if any. var underlying: Error? { return _nsUserInfo[NSUnderlyingErrorKey._bridgeToObjectiveC()] as? Error } /// The URL associated with this error, if any. var url: URL? { return _nsUserInfo[NSURLErrorKey._bridgeToObjectiveC()] as? URL } } extension CocoaError.Code { } extension CocoaError { public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code.fileNoSuchFile } public static var fileLocking: CocoaError.Code { return CocoaError.Code.fileLocking } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code.fileReadUnknown } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code.fileReadNoPermission } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code.fileReadInvalidFileName } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code.fileReadCorruptFile } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code.fileReadNoSuchFile } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code.fileReadInapplicableStringEncoding } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code.fileReadUnsupportedScheme } public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code.fileReadTooLarge } public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code.fileReadUnknownStringEncoding } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code.fileWriteUnknown } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code.fileWriteNoPermission } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code.fileWriteInvalidFileName } public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code.fileWriteFileExists } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code.fileWriteInapplicableStringEncoding } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code.fileWriteUnsupportedScheme } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code.fileWriteOutOfSpace } public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code.fileWriteVolumeReadOnly } public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code.fileManagerUnmountUnknown } public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code.fileManagerUnmountBusy } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code.keyValueValidation } public static var formatting: CocoaError.Code { return CocoaError.Code.formatting } public static var userCancelled: CocoaError.Code { return CocoaError.Code.userCancelled } public static var featureUnsupported: CocoaError.Code { return CocoaError.Code.featureUnsupported } public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code.executableNotLoadable } public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code.executableArchitectureMismatch } public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code.executableRuntimeMismatch } public static var executableLoad: CocoaError.Code { return CocoaError.Code.executableLoad } public static var executableLink: CocoaError.Code { return CocoaError.Code.executableLink } public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code.propertyListReadCorrupt } public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code.propertyListReadUnknownVersion } public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code.propertyListReadStream } public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code.propertyListWriteStream } public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code.propertyListWriteInvalid } public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code.xpcConnectionInterrupted } public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code.xpcConnectionInvalid } public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code.xpcConnectionReplyInvalid } public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code.ubiquitousFileUnavailable } public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code.ubiquitousFileNotUploadedDueToQuota } public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code.ubiquitousFileUbiquityServerNotAvailable } public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code.userActivityHandoffFailed } public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code.userActivityConnectionUnavailable } public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code.userActivityRemoteApplicationTimedOut } public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code.userActivityHandoffUserInfoTooLarge } public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code.coderReadCorrupt } public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code.coderValueNotFound } } extension CocoaError { public var isCoderError: Bool { return code.rawValue >= 4864 && code.rawValue <= 4991 } public var isExecutableError: Bool { return code.rawValue >= 3584 && code.rawValue <= 3839 } public var isFileError: Bool { return code.rawValue >= 0 && code.rawValue <= 1023 } public var isFormattingError: Bool { return code.rawValue >= 2048 && code.rawValue <= 2559 } public var isPropertyListError: Bool { return code.rawValue >= 3840 && code.rawValue <= 4095 } public var isUbiquitousFileError: Bool { return code.rawValue >= 4352 && code.rawValue <= 4607 } public var isUserActivityError: Bool { return code.rawValue >= 4608 && code.rawValue <= 4863 } public var isValidationError: Bool { return code.rawValue >= 1024 && code.rawValue <= 2047 } public var isXPCConnectionError: Bool { return code.rawValue >= 4096 && code.rawValue <= 4224 } } /// Describes errors in the URL error domain. public struct URLError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSURLErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSURLErrorDomain } public enum Code : Int, _ErrorCodeProtocol { public typealias _ErrorType = URLError case unknown = -1 case cancelled = -999 case badURL = -1000 case timedOut = -1001 case unsupportedURL = -1002 case cannotFindHost = -1003 case cannotConnectToHost = -1004 case networkConnectionLost = -1005 case dnsLookupFailed = -1006 case httpTooManyRedirects = -1007 case resourceUnavailable = -1008 case notConnectedToInternet = -1009 case redirectToNonExistentLocation = -1010 case badServerResponse = -1011 case userCancelledAuthentication = -1012 case userAuthenticationRequired = -1013 case zeroByteResource = -1014 case cannotDecodeRawData = -1015 case cannotDecodeContentData = -1016 case cannotParseResponse = -1017 case fileDoesNotExist = -1100 case fileIsDirectory = -1101 case noPermissionsToReadFile = -1102 case secureConnectionFailed = -1200 case serverCertificateHasBadDate = -1201 case serverCertificateUntrusted = -1202 case serverCertificateHasUnknownRoot = -1203 case serverCertificateNotYetValid = -1204 case clientCertificateRejected = -1205 case clientCertificateRequired = -1206 case cannotLoadFromNetwork = -2000 case cannotCreateFile = -3000 case cannotOpenFile = -3001 case cannotCloseFile = -3002 case cannotWriteToFile = -3003 case cannotRemoveFile = -3004 case cannotMoveFile = -3005 case downloadDecodingFailedMidStream = -3006 case downloadDecodingFailedToComplete = -3007 case internationalRoamingOff = -1018 case callIsActive = -1019 case dataNotAllowed = -1020 case requestBodyStreamExhausted = -1021 case backgroundSessionRequiresSharedContainer = -995 case backgroundSessionInUseByAnotherProcess = -996 case backgroundSessionWasDisconnected = -997 } } public extension URLError { private var _nsUserInfo: [AnyHashable : Any] { return NSError(domain: _domain, code: _code, userInfo: nil).userInfo } /// The URL which caused a load to fail. public var failingURL: URL? { return _nsUserInfo[NSURLErrorFailingURLErrorKey._bridgeToObjectiveC()] as? URL } /// The string for the URL which caused a load to fail. public var failureURLString: String? { return _nsUserInfo[NSURLErrorFailingURLStringErrorKey._bridgeToObjectiveC()] as? String } } public extension URLError { public static var unknown: URLError.Code { return .unknown } public static var cancelled: URLError.Code { return .cancelled } public static var badURL: URLError.Code { return .badURL } public static var timedOut: URLError.Code { return .timedOut } public static var unsupportedURL: URLError.Code { return .unsupportedURL } public static var cannotFindHost: URLError.Code { return .cannotFindHost } public static var cannotConnectToHost: URLError.Code { return .cannotConnectToHost } public static var networkConnectionLost: URLError.Code { return .networkConnectionLost } public static var dnsLookupFailed: URLError.Code { return .dnsLookupFailed } public static var httpTooManyRedirects: URLError.Code { return .httpTooManyRedirects } public static var resourceUnavailable: URLError.Code { return .resourceUnavailable } public static var notConnectedToInternet: URLError.Code { return .notConnectedToInternet } public static var redirectToNonExistentLocation: URLError.Code { return .redirectToNonExistentLocation } public static var badServerResponse: URLError.Code { return .badServerResponse } public static var userCancelledAuthentication: URLError.Code { return .userCancelledAuthentication } public static var userAuthenticationRequired: URLError.Code { return .userAuthenticationRequired } public static var zeroByteResource: URLError.Code { return .zeroByteResource } public static var cannotDecodeRawData: URLError.Code { return .cannotDecodeRawData } public static var cannotDecodeContentData: URLError.Code { return .cannotDecodeContentData } public static var cannotParseResponse: URLError.Code { return .cannotParseResponse } public static var fileDoesNotExist: URLError.Code { return .fileDoesNotExist } public static var fileIsDirectory: URLError.Code { return .fileIsDirectory } public static var noPermissionsToReadFile: URLError.Code { return .noPermissionsToReadFile } public static var secureConnectionFailed: URLError.Code { return .secureConnectionFailed } public static var serverCertificateHasBadDate: URLError.Code { return .serverCertificateHasBadDate } public static var serverCertificateUntrusted: URLError.Code { return .serverCertificateUntrusted } public static var serverCertificateHasUnknownRoot: URLError.Code { return .serverCertificateHasUnknownRoot } public static var serverCertificateNotYetValid: URLError.Code { return .serverCertificateNotYetValid } public static var clientCertificateRejected: URLError.Code { return .clientCertificateRejected } public static var clientCertificateRequired: URLError.Code { return .clientCertificateRequired } public static var cannotLoadFromNetwork: URLError.Code { return .cannotLoadFromNetwork } public static var cannotCreateFile: URLError.Code { return .cannotCreateFile } public static var cannotOpenFile: URLError.Code { return .cannotOpenFile } public static var cannotCloseFile: URLError.Code { return .cannotCloseFile } public static var cannotWriteToFile: URLError.Code { return .cannotWriteToFile } public static var cannotRemoveFile: URLError.Code { return .cannotRemoveFile } public static var cannotMoveFile: URLError.Code { return .cannotMoveFile } public static var downloadDecodingFailedMidStream: URLError.Code { return .downloadDecodingFailedMidStream } public static var downloadDecodingFailedToComplete: URLError.Code { return .downloadDecodingFailedToComplete } public static var internationalRoamingOff: URLError.Code { return .internationalRoamingOff } public static var callIsActive: URLError.Code { return .callIsActive } public static var dataNotAllowed: URLError.Code { return .dataNotAllowed } public static var requestBodyStreamExhausted: URLError.Code { return .requestBodyStreamExhausted } public static var backgroundSessionRequiresSharedContainer: URLError.Code { return .backgroundSessionRequiresSharedContainer } public static var backgroundSessionInUseByAnotherProcess: URLError.Code { return .backgroundSessionInUseByAnotherProcess } public static var backgroundSessionWasDisconnected: URLError.Code { return .backgroundSessionWasDisconnected } } /// Describes an error in the POSIX error domain. public struct POSIXError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSPOSIXErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSPOSIXErrorDomain } public enum Code : Int, _ErrorCodeProtocol { public typealias _ErrorType = POSIXError case EPERM case ENOENT case ESRCH case EINTR case EIO case ENXIO case E2BIG case ENOEXEC case EBADF case ECHILD case EDEADLK case ENOMEM case EACCES case EFAULT case ENOTBLK case EBUSY case EEXIST case EXDEV case ENODEV case ENOTDIR case EISDIR case EINVAL case ENFILE case EMFILE case ENOTTY case ETXTBSY case EFBIG case ENOSPC case ESPIPE case EROFS case EMLINK case EPIPE case EDOM case ERANGE case EAGAIN case EWOULDBLOCK case EINPROGRESS case EALREADY case ENOTSOCK case EDESTADDRREQ case EMSGSIZE case EPROTOTYPE case ENOPROTOOPT case EPROTONOSUPPORT case ESOCKTNOSUPPORT case ENOTSUP case EPFNOSUPPORT case EAFNOSUPPORT case EADDRINUSE case EADDRNOTAVAIL case ENETDOWN case ENETUNREACH case ENETRESET case ECONNABORTED case ECONNRESET case ENOBUFS case EISCONN case ENOTCONN case ESHUTDOWN case ETOOMANYREFS case ETIMEDOUT case ECONNREFUSED case ELOOP case ENAMETOOLONG case EHOSTDOWN case EHOSTUNREACH case ENOTEMPTY case EPROCLIM case EUSERS case EDQUOT case ESTALE case EREMOTE case EBADRPC case ERPCMISMATCH case EPROGUNAVAIL case EPROGMISMATCH case EPROCUNAVAIL case ENOLCK case ENOSYS case EFTYPE case EAUTH case ENEEDAUTH case EPWROFF case EDEVERR case EOVERFLOW case EBADEXEC case EBADARCH case ESHLIBVERS case EBADMACHO case ECANCELED case EIDRM case ENOMSG case EILSEQ case ENOATTR case EBADMSG case EMULTIHOP case ENODATA case ENOLINK case ENOSR case ENOSTR case EPROTO case ETIME case ENOPOLICY case ENOTRECOVERABLE case EOWNERDEAD case EQFULL } } extension POSIXError { /// Operation not permitted. public static var EPERM: POSIXError.Code { return .EPERM } /// No such file or directory. public static var ENOENT: POSIXError.Code { return .ENOENT } /// No such process. public static var ESRCH: POSIXError.Code { return .ESRCH } /// Interrupted system call. public static var EINTR: POSIXError.Code { return .EINTR } /// Input/output error. public static var EIO: POSIXError.Code { return .EIO } /// Device not configured. public static var ENXIO: POSIXError.Code { return .ENXIO } /// Argument list too long. public static var E2BIG: POSIXError.Code { return .E2BIG } /// Exec format error. public static var ENOEXEC: POSIXError.Code { return .ENOEXEC } /// Bad file descriptor. public static var EBADF: POSIXError.Code { return .EBADF } /// No child processes. public static var ECHILD: POSIXError.Code { return .ECHILD } /// Resource deadlock avoided. public static var EDEADLK: POSIXError.Code { return .EDEADLK } /// Cannot allocate memory. public static var ENOMEM: POSIXError.Code { return .ENOMEM } /// Permission denied. public static var EACCES: POSIXError.Code { return .EACCES } /// Bad address. public static var EFAULT: POSIXError.Code { return .EFAULT } /// Block device required. public static var ENOTBLK: POSIXError.Code { return .ENOTBLK } /// Device / Resource busy. public static var EBUSY: POSIXError.Code { return .EBUSY } /// File exists. public static var EEXIST: POSIXError.Code { return .EEXIST } /// Cross-device link. public static var EXDEV: POSIXError.Code { return .EXDEV } /// Operation not supported by device. public static var ENODEV: POSIXError.Code { return .ENODEV } /// Not a directory. public static var ENOTDIR: POSIXError.Code { return .ENOTDIR } /// Is a directory. public static var EISDIR: POSIXError.Code { return .EISDIR } /// Invalid argument. public static var EINVAL: POSIXError.Code { return .EINVAL } /// Too many open files in system. public static var ENFILE: POSIXError.Code { return .ENFILE } /// Too many open files. public static var EMFILE: POSIXError.Code { return .EMFILE } /// Inappropriate ioctl for device. public static var ENOTTY: POSIXError.Code { return .ENOTTY } /// Text file busy. public static var ETXTBSY: POSIXError.Code { return .ETXTBSY } /// File too large. public static var EFBIG: POSIXError.Code { return .EFBIG } /// No space left on device. public static var ENOSPC: POSIXError.Code { return .ENOSPC } /// Illegal seek. public static var ESPIPE: POSIXError.Code { return .ESPIPE } /// Read-only file system. public static var EROFS: POSIXError.Code { return .EROFS } /// Too many links. public static var EMLINK: POSIXError.Code { return .EMLINK } /// Broken pipe. public static var EPIPE: POSIXError.Code { return .EPIPE } /// Math Software /// Numerical argument out of domain. public static var EDOM: POSIXError.Code { return .EDOM } /// Result too large. public static var ERANGE: POSIXError.Code { return .ERANGE } /// Non-blocking and interrupt I/O. /// Resource temporarily unavailable. public static var EAGAIN: POSIXError.Code { return .EAGAIN } /// Operation would block. public static var EWOULDBLOCK: POSIXError.Code { return .EWOULDBLOCK } /// Operation now in progress. public static var EINPROGRESS: POSIXError.Code { return .EINPROGRESS } /// Operation already in progress. public static var EALREADY: POSIXError.Code { return .EALREADY } /// IPC/Network software -- argument errors. /// Socket operation on non-socket. public static var ENOTSOCK: POSIXError.Code { return .ENOTSOCK } /// Destination address required. public static var EDESTADDRREQ: POSIXError.Code { return .EDESTADDRREQ } /// Message too long. public static var EMSGSIZE: POSIXError.Code { return .EMSGSIZE } /// Protocol wrong type for socket. public static var EPROTOTYPE: POSIXError.Code { return .EPROTOTYPE } /// Protocol not available. public static var ENOPROTOOPT: POSIXError.Code { return .ENOPROTOOPT } /// Protocol not supported. public static var EPROTONOSUPPORT: POSIXError.Code { return .EPROTONOSUPPORT } /// Socket type not supported. public static var ESOCKTNOSUPPORT: POSIXError.Code { return .ESOCKTNOSUPPORT } /// Operation not supported. public static var ENOTSUP: POSIXError.Code { return .ENOTSUP } /// Protocol family not supported. public static var EPFNOSUPPORT: POSIXError.Code { return .EPFNOSUPPORT } /// Address family not supported by protocol family. public static var EAFNOSUPPORT: POSIXError.Code { return .EAFNOSUPPORT } /// Address already in use. public static var EADDRINUSE: POSIXError.Code { return .EADDRINUSE } /// Can't assign requested address. public static var EADDRNOTAVAIL: POSIXError.Code { return .EADDRNOTAVAIL } /// IPC/Network software -- operational errors /// Network is down. public static var ENETDOWN: POSIXError.Code { return .ENETDOWN } /// Network is unreachable. public static var ENETUNREACH: POSIXError.Code { return .ENETUNREACH } /// Network dropped connection on reset. public static var ENETRESET: POSIXError.Code { return .ENETRESET } /// Software caused connection abort. public static var ECONNABORTED: POSIXError.Code { return .ECONNABORTED } /// Connection reset by peer. public static var ECONNRESET: POSIXError.Code { return .ECONNRESET } /// No buffer space available. public static var ENOBUFS: POSIXError.Code { return .ENOBUFS } /// Socket is already connected. public static var EISCONN: POSIXError.Code { return .EISCONN } /// Socket is not connected. public static var ENOTCONN: POSIXError.Code { return .ENOTCONN } /// Can't send after socket shutdown. public static var ESHUTDOWN: POSIXError.Code { return .ESHUTDOWN } /// Too many references: can't splice. public static var ETOOMANYREFS: POSIXError.Code { return .ETOOMANYREFS } /// Operation timed out. public static var ETIMEDOUT: POSIXError.Code { return .ETIMEDOUT } /// Connection refused. public static var ECONNREFUSED: POSIXError.Code { return .ECONNREFUSED } /// Too many levels of symbolic links. public static var ELOOP: POSIXError.Code { return .ELOOP } /// File name too long. public static var ENAMETOOLONG: POSIXError.Code { return .ENAMETOOLONG } /// Host is down. public static var EHOSTDOWN: POSIXError.Code { return .EHOSTDOWN } /// No route to host. public static var EHOSTUNREACH: POSIXError.Code { return .EHOSTUNREACH } /// Directory not empty. public static var ENOTEMPTY: POSIXError.Code { return .ENOTEMPTY } /// Quotas /// Too many processes. public static var EPROCLIM: POSIXError.Code { return .EPROCLIM } /// Too many users. public static var EUSERS: POSIXError.Code { return .EUSERS } /// Disk quota exceeded. public static var EDQUOT: POSIXError.Code { return .EDQUOT } /// Network File System /// Stale NFS file handle. public static var ESTALE: POSIXError.Code { return .ESTALE } /// Too many levels of remote in path. public static var EREMOTE: POSIXError.Code { return .EREMOTE } /// RPC struct is bad. public static var EBADRPC: POSIXError.Code { return .EBADRPC } /// RPC version wrong. public static var ERPCMISMATCH: POSIXError.Code { return .ERPCMISMATCH } /// RPC prog. not avail. public static var EPROGUNAVAIL: POSIXError.Code { return .EPROGUNAVAIL } /// Program version wrong. public static var EPROGMISMATCH: POSIXError.Code { return .EPROGMISMATCH } /// Bad procedure for program. public static var EPROCUNAVAIL: POSIXError.Code { return .EPROCUNAVAIL } /// No locks available. public static var ENOLCK: POSIXError.Code { return .ENOLCK } /// Function not implemented. public static var ENOSYS: POSIXError.Code { return .ENOSYS } /// Inappropriate file type or format. public static var EFTYPE: POSIXError.Code { return .EFTYPE } /// Authentication error. public static var EAUTH: POSIXError.Code { return .EAUTH } /// Need authenticator. public static var ENEEDAUTH: POSIXError.Code { return .ENEEDAUTH } /// Intelligent device errors. /// Device power is off. public static var EPWROFF: POSIXError.Code { return .EPWROFF } /// Device error, e.g. paper out. public static var EDEVERR: POSIXError.Code { return .EDEVERR } /// Value too large to be stored in data type. public static var EOVERFLOW: POSIXError.Code { return .EOVERFLOW } /// Program loading errors. /// Bad executable. public static var EBADEXEC: POSIXError.Code { return .EBADEXEC } /// Bad CPU type in executable. public static var EBADARCH: POSIXError.Code { return .EBADARCH } /// Shared library version mismatch. public static var ESHLIBVERS: POSIXError.Code { return .ESHLIBVERS } /// Malformed Macho file. public static var EBADMACHO: POSIXError.Code { return .EBADMACHO } /// Operation canceled. public static var ECANCELED: POSIXError.Code { return .ECANCELED } /// Identifier removed. public static var EIDRM: POSIXError.Code { return .EIDRM } /// No message of desired type. public static var ENOMSG: POSIXError.Code { return .ENOMSG } /// Illegal byte sequence. public static var EILSEQ: POSIXError.Code { return .EILSEQ } /// Attribute not found. public static var ENOATTR: POSIXError.Code { return .ENOATTR } /// Bad message. public static var EBADMSG: POSIXError.Code { return .EBADMSG } /// Reserved. public static var EMULTIHOP: POSIXError.Code { return .EMULTIHOP } /// No message available on STREAM. public static var ENODATA: POSIXError.Code { return .ENODATA } /// Reserved. public static var ENOLINK: POSIXError.Code { return .ENOLINK } /// No STREAM resources. public static var ENOSR: POSIXError.Code { return .ENOSR } /// Not a STREAM. public static var ENOSTR: POSIXError.Code { return .ENOSTR } /// Protocol error. public static var EPROTO: POSIXError.Code { return .EPROTO } /// STREAM ioctl timeout. public static var ETIME: POSIXError.Code { return .ETIME } /// No such policy registered. public static var ENOPOLICY: POSIXError.Code { return .ENOPOLICY } /// State not recoverable. public static var ENOTRECOVERABLE: POSIXError.Code { return .ENOTRECOVERABLE } /// Previous owner died. public static var EOWNERDEAD: POSIXError.Code { return .EOWNERDEAD } /// Interface output queue is full. public static var EQFULL: POSIXError.Code { return .EQFULL } }
apache-2.0
ahoppen/swift
stdlib/public/core/UnicodeData.swift
10
6756
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims internal typealias ScalarAndNormData = ( scalar: Unicode.Scalar, normData: Unicode._NormData ) extension Unicode { // A wrapper type over the normalization data value we receive when we // lookup a scalar's normalization information. The layout of the underlying // 16 bit value we receive is as follows: // // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // └───┬───┘ └──── CCC ────┘ └─┘ │ // │ │ └── NFD_QC // │ └── NFC_QC // └── Unused // // NFD_QC: This is a simple Yes/No on whether the scalar has canonical // decomposition. Note: Yes is indicated via 0 instead of 1. // // NFC_QC: This is either Yes/No/Maybe on whether the scalar is NFC quick // check. Yes, represented as 0, means the scalar can NEVER compose // with another scalar previous to it. No, represented as 1, means the // scalar can NEVER appear within a well formed NFC string. Maybe, // represented as 2, means the scalar could appear with an NFC string, // but further information is required to determine if that is the // case. At the moment, we really only care about Yes/No. // // CCC: This is the canonical combining class property of a scalar that is // used when sorting scalars of a normalization segment after NFD // computation. A scalar with a CCC value of 128 can NEVER appear before // a scalar with a CCC value of 100, unless there are normalization // boundaries between them. // internal struct _NormData { var rawValue: UInt16 var ccc: UInt8 { UInt8(truncatingIfNeeded: rawValue >> 3) } var isNFCQC: Bool { rawValue & 0x6 == 0 } var isNFDQC: Bool { rawValue & 0x1 == 0 } init(_ scalar: Unicode.Scalar, fastUpperbound: UInt32 = 0xC0) { if _fastPath(scalar.value < fastUpperbound) { // CCC = 0, NFC_QC = Yes, NFD_QC = Yes rawValue = 0 } else { rawValue = _swift_stdlib_getNormData(scalar.value) // Because we don't store precomposed hangul in our NFD_QC data, these // will return true for NFD_QC when in fact they are not. if (0xAC00 ... 0xD7A3).contains(scalar.value) { // NFD_QC = false rawValue |= 0x1 } } } init(rawValue: UInt16) { self.rawValue = rawValue } } } extension Unicode { // A wrapper type for normalization buffers in the NFC and NFD iterators. // This helps remove some of the buffer logic like removal and sorting out of // the iterators and into this type. internal struct _NormDataBuffer { var storage: [ScalarAndNormData] = [] // This is simply a marker denoting that we've built up our storage, and // now everything within it needs to be emitted. We reverse the buffer and // pop elements from the back as a way to remove them. var isReversed = false var isEmpty: Bool { storage.isEmpty } var last: ScalarAndNormData? { storage.last } mutating func append(_ scalarAndNormData: ScalarAndNormData) { _internalInvariant(!isReversed) storage.append(scalarAndNormData) } // Removes the first element from the buffer. Note: it is not safe to append // to the buffer after this function has been called. We reverse the storage // internally for everything to be emitted out, so appending would insert // into the storage at the wrong location. One must continue to call this // function until a 'nil' return value has been received before appending. mutating func next() -> ScalarAndNormData? { guard !storage.isEmpty else { isReversed = false return nil } // If our storage hasn't been reversed yet, do so now. if !isReversed { storage.reverse() isReversed = true } return storage.removeLast() } // Sort the entire buffer based on the canonical combining class. mutating func sort() { storage._insertionSort(within: storage.indices) { $0.normData.ccc < $1.normData.ccc } } } } extension Unicode { // A wrapper type over the decomposition entry value we receive when we // lookup a scalar's canonical decomposition. The layout of the underlying // 32 bit value we receive is as follows: // // Top 14 bits Bottom 18 bits // // 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 // └───────── Index ─────────┘ └───────── Hashed Scalar ─────────┘ // // Index: This is the direct index into '_swift_stdlib_nfd_decompositions' // that points to a size byte indicating the overall size of the // UTF-8 decomposition string. Following the size byte is said string. // // Hashed Scalar: Because perfect hashing doesn't know the original set of // keys it was hashed with, we store the original scalar in the // decomposition entry so that we can guard against scalars // who happen to hash to the same index. // internal struct _DecompositionEntry { let rawValue: UInt32 // Our original scalar is stored in the first 18 bits of this entry. var hashedScalar: Unicode.Scalar { Unicode.Scalar(_value: (rawValue << 14) >> 14) } // The index into the decomposition array is stored in the top 14 bits. var index: Int { Int(truncatingIfNeeded: rawValue >> 18) } // A buffer pointer to the UTF8 decomposition string. var utf8: UnsafeBufferPointer<UInt8> { let decompPtr = _swift_stdlib_nfd_decompositions._unsafelyUnwrappedUnchecked // This size is the utf8 length of the decomposition. let size = Int(truncatingIfNeeded: decompPtr[index]) return UnsafeBufferPointer( // We add 1 here to skip the size byte. start: decompPtr + index + 1, count: size ) } init(_ scalar: Unicode.Scalar) { rawValue = _swift_stdlib_getDecompositionEntry(scalar.value) } } }
apache-2.0
overtake/TelegramSwift
packages/TGVideoCameraMovie/Package.swift
1
1153
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "TGVideoCameraMovie", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "TGVideoCameraMovie", targets: ["TGVideoCameraMovie"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "TGVideoCameraMovie", dependencies: [], path: ".", publicHeadersPath: "PublicHeaders/TGVideoCameraMovie", cSettings: [ .headerSearchPath("PublicHeaders/TGVideoCameraMovie") ]), ] )
gpl-2.0
wokalski/Hourglass
Hourglass/Actions.swift
1
682
import Foundation import RealmSwift import AppKit import EventKit typealias HGDuration = IntMax enum Action { case newTask(task: Task?) case removeTask(task: Task) case taskUpdate(task: TaskProtocol) case sessionUpdate(action: WorkSessionAction) case calendar(action: CalendarAction) case select(indexPath: IndexPath?) case initialize case quit } enum WorkSessionAction { case start(task: Task) case terminate(session: Session) } enum CalendarAction { case initDefault case chooseDefault(logTarget: EventLogTarget?) case logTask(task: Task, startTime: HGDuration) } enum LifeCycleAction { case initialize case quit }
mit
Johennes/firefox-ios
StorageTests/TestLogins.swift
2
31154
/* 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 Foundation import Shared @testable import Storage import XCGLogger import XCTest private let log = XCGLogger.defaultInstance() class TestSQLiteLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! let formSubmitURL = "http://submit.me" let login = Login.createWithHostname("hostname1", username: "username1", password: "password1", formSubmitURL: "http://submit.me") override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsqlitelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectationWithDescription("Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectationsWithTimeout(10.0, handler: nil) } func testAddLogin() { log.debug("Created \(self.login)") let expectation = self.expectationWithDescription("Add login") addLogin(login) >>> getLoginsFor(login.protectionSpace, expected: [login]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testGetOrder() { let expectation = self.expectationWithDescription("Add login") // Different GUID. let login2 = Login.createWithHostname("hostname1", username: "username2", password: "password2") login2.formSubmitURL = "http://submit.me" addLogin(login) >>> { self.addLogin(login2) } >>> getLoginsFor(login.protectionSpace, expected: [login2, login]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testRemoveLogin() { let expectation = self.expectationWithDescription("Remove login") addLogin(login) >>> removeLogin(login) >>> getLoginsFor(login.protectionSpace, expected: []) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testRemoveLogins() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL) let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL) let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL) let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL) func addLogins() -> Success { addLogin(loginA).value addLogin(loginB).value addLogin(loginC).value addLogin(loginD).value return succeed() } addLogins().value let guids = [loginA.guid, loginB.guid] logins.removeLoginsWithGUIDs(guids).value let result = logins.getAllLogins().value.successValue! XCTAssertEqual(result.count, 2) } func testRemoveManyLogins() { log.debug("Remove a large number of logins at once") var guids: [GUID] = [] for i in 0..<2000 { let login = Login.createWithHostname("mozilla.org", username: "Fire", password: "fox", formSubmitURL: formSubmitURL) if i <= 1000 { guids += [login.guid] } addLogin(login).value } logins.removeLoginsWithGUIDs(guids).value let result = logins.getAllLogins().value.successValue! XCTAssertEqual(result.count, 999) } func testUpdateLogin() { let expectation = self.expectationWithDescription("Update login") let updated = Login.createWithHostname("hostname1", username: "username1", password: "password3", formSubmitURL: formSubmitURL) updated.guid = self.login.guid addLogin(login) >>> updateLogin(updated) >>> getLoginsFor(login.protectionSpace, expected: [updated]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testAddInvalidLogin() { let emptyPasswordLogin = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL) var result = logins.addLogin(emptyPasswordLogin).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.") let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "password", formSubmitURL: formSubmitURL) result = logins.addLogin(emptyHostnameLogin).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.") let credential = NSURLCredential(user: "username", password: "password", persistence: .ForSession) let protectionSpace = NSURLProtectionSpace(host: "https://website.com", port: 443, protocol: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth") let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace) bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me" result = logins.addLogin(bothFormSubmitURLAndRealm).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.") let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil) result = logins.addLogin(noFormSubmitURLOrRealm).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.") } func testUpdateInvalidLogin() { let updated = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL) updated.guid = self.login.guid addLogin(login).value var result = logins.updateLoginByGUID(login.guid, new: updated, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.") let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "", formSubmitURL: formSubmitURL) emptyHostnameLogin.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: emptyHostnameLogin, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.") let credential = NSURLCredential(user: "username", password: "password", persistence: .ForSession) let protectionSpace = NSURLProtectionSpace(host: "https://website.com", port: 443, protocol: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth") let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace) bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me" bothFormSubmitURLAndRealm.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: bothFormSubmitURLAndRealm, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.") let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil) noFormSubmitURLOrRealm.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: noFormSubmitURLOrRealm, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.") } func testSearchLogins() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL) let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL) let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL) let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL) func addLogins() -> Success { addLogin(loginA).value addLogin(loginB).value addLogin(loginC).value addLogin(loginD).value return succeed() } func checkAllLogins() -> Success { return logins.getAllLogins() >>== { results in XCTAssertEqual(results.count, 4) return succeed() } } func checkSearchHostnames() -> Success { return logins.searchLoginsWithQuery("pha") >>== { results in XCTAssertEqual(results.count, 2) XCTAssertEqual(results[0]!.hostname, "http://alpha.com") XCTAssertEqual(results[1]!.hostname, "http://alphabet.com") return succeed() } } func checkSearchUsernames() -> Success { return logins.searchLoginsWithQuery("username") >>== { results in XCTAssertEqual(results.count, 4) XCTAssertEqual(results[0]!.username, "username2") XCTAssertEqual(results[1]!.username, "username1") XCTAssertEqual(results[2]!.username, "username3") XCTAssertEqual(results[3]!.username, "username4") return succeed() } } func checkSearchPasswords() -> Success { return logins.searchLoginsWithQuery("pass") >>== { results in XCTAssertEqual(results.count, 4) XCTAssertEqual(results[0]!.password, "password2") XCTAssertEqual(results[1]!.password, "password1") XCTAssertEqual(results[2]!.password, "password3") XCTAssertEqual(results[3]!.password, "password4") return succeed() } } XCTAssertTrue(addLogins().value.isSuccess) XCTAssertTrue(checkAllLogins().value.isSuccess) XCTAssertTrue(checkSearchHostnames().value.isSuccess) XCTAssertTrue(checkSearchUsernames().value.isSuccess) XCTAssertTrue(checkSearchPasswords().value.isSuccess) XCTAssertTrue(removeAllLogins().value.isSuccess) } /* func testAddUseOfLogin() { let expectation = self.expectationWithDescription("Add visit") if var usageData = login as? LoginUsageData { usageData.timeCreated = NSDate.nowMicroseconds() } addLogin(login) >>> addUseDelayed(login, time: 1) >>> getLoginDetailsFor(login, expected: login as! LoginUsageData) >>> done(login.protectionSpace, expectation: expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } */ func done(expectation: XCTestExpectation)() -> Success { return removeAllLogins() >>> getLoginsFor(login.protectionSpace, expected: []) >>> { expectation.fulfill() return succeed() } } // Note: These functions are all curried so that we pass arguments, but still chain them below func addLogin(login: LoginData) -> Success { log.debug("Add \(login)") return logins.addLogin(login) } func updateLogin(login: LoginData)() -> Success { log.debug("Update \(login)") return logins.updateLoginByGUID(login.guid, new: login, significant: true) } func addUseDelayed(login: Login, time: UInt32)() -> Success { sleep(time) login.timeLastUsed = NSDate.nowMicroseconds() let res = logins.addUseOfLoginByGUID(login.guid) sleep(time) return res } func getLoginsFor(protectionSpace: NSURLProtectionSpace, expected: [LoginData]) -> (() -> Success) { return { log.debug("Get logins for \(protectionSpace)") return self.logins.getLoginsForProtectionSpace(protectionSpace) >>== { results in XCTAssertEqual(expected.count, results.count) for (index, login) in expected.enumerate() { XCTAssertEqual(results[index]!.username!, login.username!) XCTAssertEqual(results[index]!.hostname, login.hostname) XCTAssertEqual(results[index]!.password, login.password) } return succeed() } } } /* func getLoginDetailsFor(login: LoginData, expected: LoginUsageData) -> (() -> Success) { return { log.debug("Get details for \(login)") let deferred = self.logins.getUsageDataForLogin(login) log.debug("Final result \(deferred)") return deferred >>== { l in log.debug("Got cursor") XCTAssertLessThan(expected.timePasswordChanged - l.timePasswordChanged, 10) XCTAssertLessThan(expected.timeLastUsed - l.timeLastUsed, 10) XCTAssertLessThan(expected.timeCreated - l.timeCreated, 10) return succeed() } } } */ func removeLogin(login: LoginData)() -> Success { log.debug("Remove \(login)") return logins.removeLoginByGUID(login.guid) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } } class TestSQLiteLoginsPerf: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsqlitelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) } func testLoginsSearchMatchOnePerf() { populateTestLogins() // Measure time to find one entry amongst the 1000 of them self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.searchLoginsWithQuery("username500").value } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func testLoginsSearchMatchAllPerf() { populateTestLogins() // Measure time to find all matching results self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.searchLoginsWithQuery("username").value } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func testLoginsGetAllPerf() { populateTestLogins() // Measure time to find all matching results self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.getAllLogins().value } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func populateTestLogins() { for i in 0..<1000 { let login = Login.createWithHostname("website\(i).com", username: "username\(i)", password: "password\(i)") addLogin(login).value } } func addLogin(login: LoginData) -> Success { return logins.addLogin(login) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } } class TestSyncableLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsyncablelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectationWithDescription("Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectationsWithTimeout(10.0, handler: nil) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } func testDiffers() { let guid = "abcdabcdabcd" let host = "http://example.com" let user = "username" let loginA1 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA1.formSubmitURL = "\(host)/form1/" loginA1.usernameField = "afield" let loginA2 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA2.formSubmitURL = "\(host)/form1/" loginA2.usernameField = "somefield" let loginB = Login(guid: guid, hostname: host, username: user, password: "password2") loginB.formSubmitURL = "\(host)/form1/" let loginC = Login(guid: guid, hostname: host, username: user, password: "password") loginC.formSubmitURL = "\(host)/form2/" XCTAssert(loginA1.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA1.isSignificantlyDifferentFrom(loginC)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginC)) XCTAssert(!loginA1.isSignificantlyDifferentFrom(loginA2)) } func testLocalNewStaysNewAndIsRemoved() { let guidA = "abcdabcdabcd" let loginA1 = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "password") loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 1 XCTAssertTrue((self.logins as BrowserLogins).addLogin(loginA1).value.isSuccess) let local1 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local1) XCTAssertEqual(local1!.guid, guidA) XCTAssertEqual(local1!.syncStatus, SyncStatus.New) XCTAssertEqual(local1!.timesUsed, 1) XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) // It's still new. let local2 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local2) XCTAssertEqual(local2!.guid, guidA) XCTAssertEqual(local2!.syncStatus, SyncStatus.New) XCTAssertEqual(local2!.timesUsed, 2) // It's removed immediately, because it was never synced. XCTAssertTrue((self.logins as BrowserLogins).removeLoginByGUID(guidA).value.isSuccess) XCTAssertNil(self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!) } func testApplyLogin() { let guidA = "abcdabcdabcd" let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 XCTAssertTrue(self.logins.applyChangedLogin(loginA1).value.isSuccess) let local = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirror = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil == local) XCTAssertTrue(nil != mirror) XCTAssertEqual(mirror!.guid, guidA) XCTAssertFalse(mirror!.isOverridden) XCTAssertEqual(mirror!.serverModified, Timestamp(1234), "Timestamp matches.") XCTAssertEqual(mirror!.timesUsed, 3) XCTAssertTrue(nil == mirror!.httpRealm) XCTAssertTrue(nil == mirror!.passwordField) XCTAssertTrue(nil == mirror!.usernameField) XCTAssertEqual(mirror!.formSubmitURL!, "http://example.com/form/") XCTAssertEqual(mirror!.hostname, "http://example.com") XCTAssertEqual(mirror!.username!, "username") XCTAssertEqual(mirror!.password, "password") // Change it. let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "newpassword", modified: 2234) loginA2.formSubmitURL = "http://example.com/form/" loginA2.timesUsed = 4 XCTAssertTrue(self.logins.applyChangedLogin(loginA2).value.isSuccess) let changed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil != changed) XCTAssertFalse(changed!.isOverridden) XCTAssertEqual(changed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertEqual(changed!.username!, "username") XCTAssertEqual(changed!.password, "newpassword") XCTAssertEqual(changed!.timesUsed, 4) // Change it locally. let preUse = NSDate.now() XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) let localUsed = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorUsed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertNotNil(localUsed) XCTAssertNotNil(mirrorUsed) XCTAssertEqual(mirrorUsed!.guid, guidA) XCTAssertEqual(localUsed!.guid, guidA) XCTAssertEqual(mirrorUsed!.password, "newpassword") XCTAssertEqual(localUsed!.password, "newpassword") XCTAssertTrue(mirrorUsed!.isOverridden) // It's now overridden. XCTAssertEqual(mirrorUsed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertTrue(localUsed!.localModified >= preUse) // Local record is modified. XCTAssertEqual(localUsed!.syncStatus, SyncStatus.Synced) // Uses aren't enough to warrant upload. // Uses are local until reconciled. XCTAssertEqual(localUsed!.timesUsed, 5) XCTAssertEqual(mirrorUsed!.timesUsed, 4) // Change the password and form URL locally. let newLocalPassword = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "yupyup") newLocalPassword.formSubmitURL = "http://example.com/form2/" let preUpdate = NSDate.now() // Updates always bump our usages, too. XCTAssertTrue(self.logins.updateLoginByGUID(guidA, new: newLocalPassword, significant: true).value.isSuccess) let localAltered = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorAltered = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(mirrorUsed!)) // The mirror is unchanged. XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertTrue(mirrorAltered!.isOverridden) // It's still overridden. XCTAssertTrue(localAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertEqual(localAltered!.password, "yupyup") XCTAssertEqual(localAltered!.formSubmitURL!, "http://example.com/form2/") XCTAssertTrue(localAltered!.localModified >= preUpdate) XCTAssertEqual(localAltered!.syncStatus, SyncStatus.Changed) // Changes are enough to warrant upload. XCTAssertEqual(localAltered!.timesUsed, 6) XCTAssertEqual(mirrorAltered!.timesUsed, 4) } func testDeltas() { // Shared. let guidA = "abcdabcdabcd" let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.timeCreated = 1200 loginA1.timeLastUsed = 1234 loginA1.timePasswordChanged = 1200 loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 let a1a1 = loginA1.deltas(from: loginA1) XCTAssertEqual(0, a1a1.nonCommutative.count) XCTAssertEqual(0, a1a1.nonConflicting.count) XCTAssertEqual(0, a1a1.commutative.count) let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1235) loginA2.timeCreated = 1200 loginA2.timeLastUsed = 1235 loginA2.timePasswordChanged = 1200 loginA2.timesUsed = 4 let a1a2 = loginA2.deltas(from: loginA1) XCTAssertEqual(2, a1a2.nonCommutative.count) XCTAssertEqual(0, a1a2.nonConflicting.count) XCTAssertEqual(1, a1a2.commutative.count) switch a1a2.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(increment, 1) break } switch a1a2.nonCommutative[0] { case let .FormSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a2.nonCommutative[1] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1235) break default: XCTFail("Unexpected non-commutative login field.") } let loginA3 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "something else", modified: 1280) loginA3.timeCreated = 1200 loginA3.timeLastUsed = 1250 loginA3.timePasswordChanged = 1250 loginA3.formSubmitURL = "http://example.com/form/" loginA3.timesUsed = 5 let a1a3 = loginA3.deltas(from: loginA1) XCTAssertEqual(3, a1a3.nonCommutative.count) XCTAssertEqual(0, a1a3.nonConflicting.count) XCTAssertEqual(1, a1a3.commutative.count) switch a1a3.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(increment, 2) break } switch a1a3.nonCommutative[0] { case let .Password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[1] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[2] { case let .TimePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Now apply the deltas to the original record and check that they match! XCTAssertFalse(loginA1.applyDeltas(a1a2).isSignificantlyDifferentFrom(loginA2)) XCTAssertFalse(loginA1.applyDeltas(a1a3).isSignificantlyDifferentFrom(loginA3)) let merged = Login.mergeDeltas(a: (loginA2.serverModified, a1a2), b: (loginA3.serverModified, a1a3)) let mCCount = merged.commutative.count let a2CCount = a1a2.commutative.count let a3CCount = a1a3.commutative.count XCTAssertEqual(mCCount, a2CCount + a3CCount) let mNCount = merged.nonCommutative.count let a2NCount = a1a2.nonCommutative.count let a3NCount = a1a3.nonCommutative.count XCTAssertLessThanOrEqual(mNCount, a2NCount + a3NCount) XCTAssertGreaterThanOrEqual(mNCount, max(a2NCount, a3NCount)) let mFCount = merged.nonConflicting.count let a2FCount = a1a2.nonConflicting.count let a3FCount = a1a3.nonConflicting.count XCTAssertLessThanOrEqual(mFCount, a2FCount + a3FCount) XCTAssertGreaterThanOrEqual(mFCount, max(a2FCount, a3FCount)) switch merged.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(1, increment) } switch merged.commutative[1] { case let .TimesUsed(increment): XCTAssertEqual(2, increment) } switch merged.nonCommutative[0] { case let .Password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[1] { case let .FormSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[2] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[3] { case let .TimePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Applying the merged deltas gives us the expected login. let expected = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "something else") expected.timeCreated = 1200 expected.timeLastUsed = 1250 expected.timePasswordChanged = 1250 expected.formSubmitURL = nil expected.timesUsed = 6 let applied = loginA1.applyDeltas(merged) XCTAssertFalse(applied.isSignificantlyDifferentFrom(expected)) XCTAssertFalse(expected.isSignificantlyDifferentFrom(applied)) } func testLoginsIsSynced() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1") let serverLoginA = ServerLogin(guid: loginA.guid, hostname: "alpha.com", username: "username1", password: "password1", modified: NSDate.now()) XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? true) logins.addLogin(loginA).value XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? false) logins.applyChangedLogin(serverLoginA).value XCTAssertTrue(logins.hasSyncedLogins().value.successValue ?? false) } }
mpl-2.0
IMcD23/Proton
Source/Core/View/View+Size.swift
1
1230
// // View+Size.swift // Proton // // Created by McDowell, Ian J [ITACD] on 4/5/16. // Copyright © 2016 Ian McDowell. All rights reserved. // public extension View { public func size(width width: Percent, height: Percent) -> Self { self.size = LayoutSize(type: .Percent, width: width.value, height: height.value) return self } public func size(width width: CGFloat, height: CGFloat) -> Self { return self.size(size: CGSizeMake(width, height)) } public func size(size size: CGSize) -> Self { self.size = LayoutSize(type: .Fixed, width: size.width, height: size.height) return self } public func width(width: CGFloat) -> Self { self.size.type = .Fixed self.size.width = width return self } public func height(height: CGFloat) -> Self { self.size.type = .Fixed self.size.height = height return self } public func width(width: Percent) -> Self { self.size.type = .Percent self.size.width = width.value return self } public func height(height: Percent) -> Self { self.size.type = .Percent self.size.height = height.value return self } }
mit
antlr/antlr4
runtime/Swift/Sources/Antlr4/misc/IntSet.swift
8
5744
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// A generic set of integers. /// /// - seealso: org.antlr.v4.runtime.misc.IntervalSet /// public protocol IntSet { /// /// Adds the specified value to the current set. /// /// - parameter el: the value to add /// /// - throws: _ANTLRError.illegalState_ if the current set is read-only /// func add(_ el: Int) throws /// /// Modify the current _org.antlr.v4.runtime.misc.IntSet_ object to contain all elements that are /// present in itself, the specified `set`, or both. /// /// - parameter set: The set to add to the current set. A `null` argument is /// treated as though it were an empty set. /// - returns: `this` (to support chained calls) /// /// - throws: _ANTLRError.illegalState_ if the current set is read-only /// func addAll(_ set: IntSet?) throws -> IntSet /// /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are /// present in both the current set and the specified set `a`. /// /// - parameter a: The set to intersect with the current set. A `null` /// argument is treated as though it were an empty set. /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the intersection of the /// current set and `a`. The value `null` may be returned in /// place of an empty result set. /// func and(_ a: IntSet?) -> IntSet? /// /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are /// present in `elements` but not present in the current set. The /// following expressions are equivalent for input non-null _org.antlr.v4.runtime.misc.IntSet_ /// instances `x` and `y`. /// /// * `x.complement(y)` /// *`y.subtract(x)` /// /// - parameter elements: The set to compare with the current set. A `null` /// argument is treated as though it were an empty set. /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the elements present in /// `elements` but not present in the current set. The value /// `null` may be returned in place of an empty result set. /// func complement(_ elements: IntSet?) -> IntSet? /// /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are /// present in the current set, the specified set `a`, or both. /// /// /// This method is similar to _#addAll(org.antlr.v4.runtime.misc.IntSet)_, but returns a new /// _org.antlr.v4.runtime.misc.IntSet_ instance instead of modifying the current set. /// /// - parameter a: The set to union with the current set. A `null` argument /// is treated as though it were an empty set. /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the union of the current /// set and `a`. The value `null` may be returned in place of an /// empty result set. /// func or(_ a: IntSet) -> IntSet /// /// Return a new _org.antlr.v4.runtime.misc.IntSet_ object containing all elements that are /// present in the current set but not present in the input set `a`. /// The following expressions are equivalent for input non-null /// _org.antlr.v4.runtime.misc.IntSet_ instances `x` and `y`. /// /// * `y.subtract(x)` /// * `x.complement(y)` /// /// - parameter a: The set to compare with the current set. A `null` /// argument is treated as though it were an empty set. /// - returns: A new _org.antlr.v4.runtime.misc.IntSet_ instance containing the elements present in /// `elements` but not present in the current set. The value /// `null` may be returned in place of an empty result set. /// func subtract(_ a: IntSet?) -> IntSet /// /// Return the total number of elements represented by the current set. /// /// - returns: the total number of elements represented by the current set, /// regardless of the manner in which the elements are stored. /// func size() -> Int /// /// Returns `true` if this set contains no elements. /// /// - returns: `true` if the current set contains no elements; otherwise, /// `false`. /// func isNil() -> Bool /// /// Returns the single value contained in the set, if _#size_ is 1; /// otherwise, returns _org.antlr.v4.runtime.Token#INVALID_TYPE_. /// /// - returns: the single value contained in the set, if _#size_ is 1; /// otherwise, returns _org.antlr.v4.runtime.Token#INVALID_TYPE_. /// func getSingleElement() -> Int /// /// Returns `true` if the set contains the specified element. /// /// - parameter el: The element to check for. /// - returns: `true` if the set contains `el`; otherwise `false`. /// func contains(_ el: Int) -> Bool /// /// Removes the specified value from the current set. If the current set does /// not contain the element, no changes are made. /// /// - parameter el: the value to remove /// /// - throws: _ANTLRError.illegalState_ if the current set is read-only /// func remove(_ el: Int) throws /// /// Return a list containing the elements represented by the current set. The /// list is returned in ascending numerical order. /// /// - returns: A list containing all element present in the current set, sorted /// in ascending numerical order. /// func toList() -> [Int] }
bsd-3-clause
huonw/swift
stdlib/public/core/WriteBackMutableSlice.swift
12
1730
//===--- WriteBackMutableSlice.swift --------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @inlinable internal func _writeBackMutableSlice<C, Slice_>( _ self_: inout C, bounds: Range<C.Index>, slice: Slice_ ) where C : MutableCollection, Slice_ : Collection, C.Element == Slice_.Element, C.Index == Slice_.Index { self_._failEarlyRangeCheck(bounds, bounds: self_.startIndex..<self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.lowerBound let selfElementsEndIndex = bounds.upperBound var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] self_.formIndex(after: &selfElementIndex) slice.formIndex(after: &newElementIndex) } _precondition( selfElementIndex == selfElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a smaller size") _precondition( newElementIndex == newElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a larger size") }
apache-2.0
AlesTsurko/AudioKit
Tests/Tests/AKBalance.swift
2
1253
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/21/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: Float = 4.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let amplitude = AKOscillator() amplitude.frequency = 1.ak let oscillator = AKOscillator() oscillator.amplitude = amplitude auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:oscillator) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let synth = AKFMOscillator() let balanced = AKBalance(input: synth, comparatorAudioSource: audioSource) setAudioOutput(balanced) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() let manager = AKManager.sharedManager() while(manager.isRunning) {} //do nothing println("Test complete!")
lgpl-3.0
KasunApplications/susi_iOS
SusiUITests/AnonymousModeUITests.swift
1
1749
// // AnonymousMode.swift // Susi // // Created by Chashmeet Singh on 2017-07-03. // Copyright © 2017 FOSSAsia. All rights reserved. // import XCTest class AnonymousUITests: XCTestCase { private let app = XCUIApplication() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. app.launchArguments += ["UI-Testing"] // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. app.launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testAnonymousMode() { app.buttons[ControllerConstants.TestKeys.skip].tap() let textView = app.textViews[ControllerConstants.TestKeys.chatInputView] textView.tap() textView.typeText("hello") let sendButton = app.buttons[ControllerConstants.TestKeys.send] sendButton.tap() sleep(5) let collectionViewsQuery = app.collectionViews let responseMessage = collectionViewsQuery.children(matching: .cell).element(boundBy: 1).children(matching: .textView).element XCTAssertTrue(responseMessage.exists) } }
apache-2.0
Yvent/YVImagePickerController
YVImagePickerController/YVImagePickerCell.swift
2
2425
// // YVImagePickerCell.swift // Demo // // Created by 周逸文 on 2017/10/12. // Copyright © 2017年 YV. All rights reserved. // import UIKit class YVImagePickerCell: UICollectionViewCell { var closeBtnColor: UIColor = UIColor(red: 88/255.0, green: 197/255.0, blue: 141/255.0, alpha: 1) var imageV: UIImageView! var closeBtn: UIButton! var timeLab: UILabel! override init(frame: CGRect) { super.init(frame: frame) initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initUI() { contentView.backgroundColor = UIColor.white let imagevFrame: CGRect = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) imageV = UIImageView(frame: imagevFrame) let closeBtnFrame: CGRect = CGRect(x: self.frame.width-3-24, y: 3, width: 24, height: 24) closeBtn = UIButton(frame: closeBtnFrame) let bundle = Bundle(for: YVImagePickerController.self) let path = bundle.path(forResource: "YVImagePickerController", ofType: "bundle") let imageBundle = Bundle(path: path!) let nolImage = UIImage(contentsOfFile: (imageBundle?.path(forResource: "yvCloseBtn_nol", ofType: "png"))!) let selImage = UIImage(contentsOfFile: (imageBundle?.path(forResource: "yvCloseBtn_sel", ofType: "png"))!) closeBtn.setImage(nolImage, for: .normal) closeBtn.setImage(selImage, for: .selected) closeBtn.isUserInteractionEnabled = false let timeLabFrame: CGRect = CGRect(x: 5, y: self.frame.height-20, width: self.frame.width-10, height: 20) timeLab = UILabel(frame: timeLabFrame) timeLab.textAlignment = .right timeLab.textColor = UIColor.white timeLab.font = UIFont.systemFont(ofSize: 12) self.contentView.addSubview(imageV) self.contentView.addSubview(closeBtn) self.contentView.addSubview(timeLab) } func createImageWithColor(clolr: UIColor,rect: CGRect) -> UIImage{ UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(clolr.cgColor) context!.fill(rect) let theImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return theImage! } }
mit
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Classify/Views/SingleGiftSectionViewModel.swift
1
797
// // SingleGiftSectionViewModel.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/21. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit class SingleGiftSectionDataModel: NSObject { let title = ["美物","手工","吃货","萌萌哒","动漫迷","小清新","科技范","熊孩子","烂漫","任性","欧巴","御姐","公主","音乐范","艺术气质","闺蜜","同学","创意"] var classifyTitle:String? init(withIndex index:Int) { classifyTitle = title[index] } } class SingleGiftSectionViewModel: NSObject { var dataModel:SingleGiftSectionDataModel var titleLabelText:String? init(withModel model:SingleGiftSectionDataModel) { self.dataModel = model titleLabelText = model.classifyTitle } }
mit
linhaosunny/yeehaiyake
椰海雅客微博/椰海雅客微博/Classes/Main/LSXVisitorView.swift
1
4660
// // LSXVisitorView.swift // 椰海雅客微博 // // Created by 李莎鑫 on 2017/4/3. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit class LSXVisitorView: UIView { //MARK: 懒加载 //: 转盘 lazy var rotationView:UIImageView = { () -> UIImageView in let imageView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_image_smallicon")) return imageView }() //: 转盘遮盖 lazy var rotationCoverView:UIImageView = { () -> UIImageView in let coverView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_mask_smallicon")) return coverView }() //: 图片 lazy var imageView:UIImageView = { () -> UIImageView in let iconView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_image_house")) return iconView }() //: 标题 lazy var titleLable:UILabel = { () -> UILabel in let label = UILabel() label.textColor = UIColor.gray label.numberOfLines = 0; label.text = "新特性,抢先试玩,注册就能体验新的生活方式" return label }() //: 注册 lazy var registerButton:UIButton = { () -> UIButton in let button = UIButton() button.setTitleColor(SystemTintColor, for: .normal) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitle("注册", for: .normal) button.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .normal) return button }() //: 登录 lazy var loginButton:UIButton = { () -> UIButton in let button = UIButton() button.setTitleColor(UIColor.gray, for: .normal) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitle("登录", for: .normal) button.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .normal) return button }() //MARK: 构造方法 class func visitorView() -> LSXVisitorView { let view = self.init() view.addSubview(view.rotationView) view.addSubview(view.rotationCoverView) view.addSubview(view.imageView) view.addSubview(view.titleLable) view.addSubview(view.registerButton) view.addSubview(view.loginButton) return view } //MARK: 私有方法 //: 使用自动布局工具snapkit override func layoutSubviews() { super.layoutSubviews() rotationView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-100) } rotationCoverView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-100) } imageView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-100) } titleLable.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalTo(240) make.top.equalTo(imageView.snp.bottom).offset(40) } registerButton.snp.makeConstraints { (make) in make.left.equalTo(titleLable.snp.left) make.top.equalTo(titleLable.snp.bottom).offset(20) make.width.equalTo(100) make.height.equalTo(40) } loginButton.snp.makeConstraints { (make) in make.right.equalTo(titleLable.snp.right) make.top.width.height.equalTo(registerButton) } } func startAnimation() { let animation = CABasicAnimation(keyPath: "transform.rotation") //: 设置动画属性 animation.toValue = 2 * M_PI animation.duration = 10.0 animation.repeatCount = MAXFLOAT // 注意: 默认情况下只要视图消失, 系统就会自动移除动画 // 只要设置removedOnCompletion为false, 系统就不会移除动画 animation.isRemovedOnCompletion = false rotationView.layer.add(animation, forKey: "transform.rotation") } //MARK: 外部调用方法 func setupVisitorInfo(imageName: String? ,title: String){ titleLable.text = title guard let name = imageName else { startAnimation() return } rotationView.isHidden = true imageView.image = UIImage(named: name) } }
mit
austinzheng/swift
test/decl/protocol/req/associated_type_ambiguity.swift
27
1748
// RUN: %target-typecheck-verify-swift // Reference to associated type from 'where' clause should not be // ambiguous when there's a typealias with the same name in another // protocol. // // FIXME: The semantics here are still really iffy. There's also a // case to be made that type aliases in protocol extensions should // only act as defaults and not as same-type constraints. However, // if we decide to go down that route, it's important that *both* // the unqualified (T) and qualified (Self.T) lookups behave the // same. protocol P1 { typealias T = Int // expected-note {{found this candidate}} } protocol P2 { associatedtype T // expected-note {{found this candidate}} } // FIXME: This extension's generic signature is still minimized differently from // the next one. We need to decide if 'T == Int' is a redundant requirement or // not. extension P1 where Self : P2, T == Int { func takeT1(_: T) {} func takeT2(_: Self.T) {} } extension P1 where Self : P2 { // FIXME: This doesn't make sense -- either both should // succeed, or both should be ambiguous. func takeT1(_: T) {} // expected-error {{'T' is ambiguous for type lookup in this context}} func takeT2(_: Self.T) {} } // Same as above, but now we have two visible associated types with the same // name. protocol P3 { associatedtype T } // FIXME: This extension's generic signature is still minimized differently from // the next one. We need to decide if 'T == Int' is a redundant requirement or // not. extension P2 where Self : P3, T == Int { func takeT1(_: T) {} func takeT2(_: Self.T) {} } extension P2 where Self : P3 { func takeT1(_: T) {} func takeT2(_: Self.T) {} } protocol P4 : P2, P3 { func takeT1(_: T) func takeT2(_: Self.T) }
apache-2.0
iabudiab/gdg-devfestka-2015-swift
Swift Intro.playground/Pages/Variables & Constants.xcplaygroundpage/Contents.swift
1
292
var answerToTheQuestionOfLife = 42 // Type is inferred answerToTheQuestionOfLife = 9001 // answerToTheQuestionOfLife = 3.14 // Compile error ~> Int var numberOfTalks: Int = 1 let language = "Swift" let pi: Double = 3.141592 // pi = 3.1415927 // Compile error ~> constant //: [Next](@next)
mit
SkilpaddeLabs/SPLBlockButton
BlockButtonTests/BlockButtonTests.swift
1
986
// // BlockButtonTests.swift // BlockButtonTests // // Created by bolstad on 4/12/16. // Copyright © 2016 Tim Bolstad. All rights reserved. // import XCTest @testable import BlockButton class BlockButtonTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
WLChopSticks/weibo-swift-
weibo(swift)/weibo(swift)/Classes/Tools/Extention/UILabel+Extention.swift
2
684
// // UILabel+Extention.swift // weibo(swift) // // Created by 王 on 15/12/16. // Copyright © 2015年 王. All rights reserved. // import UIKit //构造便利函数,扩展label的方法 extension UILabel { convenience init(title: String, color: UIColor, fontSize: CGFloat, margin: CGFloat = 0) { self.init() text = title numberOfLines = 0 textColor = color textAlignment = .Center font = UIFont.systemFontOfSize(fontSize) //针对参数设置label的宽度 if margin != 0 { preferredMaxLayoutWidth = screenWidth - 2 * margin textAlignment = .Left } } }
mit
austinzheng/swift
validation-test/compiler_crashers_fixed/28531-swift-modulefile-getdecl-llvm-pointerembeddedint-unsigned-int-31-llvm-optional-s.swift
65
498
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -emit-ir : class T:Range<T>o)typealias e{func<T.p if(print{let bass B<A.c== A:f)typealias f:A>:d:A {}} proclas
apache-2.0
Ruenzuo/fansabisu
FanSabisu/Sources/MediaViewController.swift
1
10542
import UIKit import Photos import FanSabisuKit class MediaViewController: GAITrackedViewController { @IBOutlet var collectionView: UICollectionView? var itemsPerRow: CGFloat? var dataSource: [PHAsset] = [] var activityIndicatorView: UIActivityIndicatorView? override func viewDidLoad() { super.viewDidLoad() self.title = String.localizedString(for: "MEDIA") self.screenName = "Media" setupItemsPerRow(with: self.view.frame.size) automaticallyAdjustsScrollViewInsets = false setupNavigationItems() PHPhotoLibrary.requestAuthorization { (status) in if status != .authorized { DispatchQueue.main.async { self.presentAuthorizationError() } } else { self.loadAssets() } } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { if hasUserInterfaceIdiomPadTrait() { self.collectionView?.reloadSections(IndexSet(integer: 0)) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) setupItemsPerRow(with: size) self.collectionView?.collectionViewLayout.invalidateLayout() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MediaDetail" { let controller = segue.destination as! MediaDetailViewController let indexPath = collectionView?.indexPath(for: sender as! UICollectionViewCell) let asset = dataSource[indexPath!.row] controller.asset = asset } } func checkPasteboard() { if PHPhotoLibrary.authorizationStatus() != .authorized { DispatchQueue.main.async { self.presentAuthorizationError() } } else { processPasteboard() } } func setupItemsPerRow(with viewSize: CGSize) { let landscape = viewSize.width > viewSize.height if hasUserInterfaceIdiomPadTrait() { if landscape { itemsPerRow = 7 } else { itemsPerRow = 5 } } else { if landscape { itemsPerRow = 7 } else { itemsPerRow = 4 } } } func presentAuthorizationError() { self.activityIndicatorView?.stopAnimating() self.presentMessage(title: String.localizedString(for: "AUTHORIZATION_NOT_GRANTED"), message: String.localizedString(for: "USAGE_DESCRIPTION"), actionHandler: { let url = URL(string: UIApplicationOpenSettingsURLString)! UIApplication.shared.openURL(url) }) } func setupNavigationItems() { activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicatorView?.startAnimating() navigationItem.setLeftBarButton(UIBarButtonItem(customView: activityIndicatorView!), animated: true) let refreshBarButonItem = UIBarButtonItem(image: UIImage(named: "Refresh"), style: .plain, target: self, action: #selector(loadAssets)) let pasteboardBarButonItem = UIBarButtonItem(image: UIImage(named: "Clipboard"), style: .plain, target: self, action: #selector(checkPasteboard)) navigationItem.setRightBarButtonItems([refreshBarButonItem, pasteboardBarButonItem], animated: true) } func processPasteboard() { guard let pasteboard = UIPasteboard.general.string else { presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "PASTEBOARD_NOT_FOUND"), actionHandler: nil) return } guard let url = URL(string: pasteboard) else { presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "CONTENTS_NOT_SUITABLE"), actionHandler: nil) return } if !url.isValidURL { let message = String(format: String.localizedString(for: "INVALID_URL"), url.absoluteString) presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: message, actionHandler: nil) return } let message = String(format: String.localizedString(for: "URL_FOUND"), url.absoluteString) let controller = UIAlertController(title: String.localizedString(for: "PASTEBOARD_FOUND"), message: message, preferredStyle: .alert) controller.addAction(UIAlertAction(title: String.localizedString(for: "CANCEL"), style: .cancel, handler: nil)) controller.addAction(UIAlertAction(title: String.localizedString(for: "DOWNLOAD"), style: .default, handler: { (action) in self.activityIndicatorView?.startAnimating() let mediaDownloader = MediaDownloader(session: Session.shared) mediaDownloader.downloadMedia(with: url, completionHandler: { (result) in do { let videoUrl = try result.resolve() let videoProcessor = VideoProcessor() videoProcessor.processVideo(with: videoUrl, completionHandler: { (result) in guard let url = try? result.resolve() else { self.activityIndicatorView?.stopAnimating() return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "PROCESS_VIDEO_ERROR"), actionHandler: nil) } let manager = FileManager.default try? manager.removeItem(at: url) self.activityIndicatorView?.stopAnimating() self.presentMessage(title: String.localizedString(for: "FINISHED"), message: String.localizedString(for: "GIF_STORED"), actionHandler: nil) self.loadAssets() }) } catch MediaDownloaderError.tooManyRequests { self.activityIndicatorView?.stopAnimating() return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "TOO_MANY_REQUESTS"), actionHandler: nil) } catch MediaDownloaderError.forbidden { self.activityIndicatorView?.stopAnimating() return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "FORBIDDEN"), actionHandler: nil) } catch { return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "DOWNLOAD_VIDEO_ERROR"), actionHandler: nil) } }) })) present(controller, animated: true, completion: nil) } func loadAssets() { dataSource.removeAll() let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) let fetchResult = PHAsset.fetchAssets(with: options) fetchResult.enumerateObjects({ (asset, index, _) in let resources = PHAssetResource.assetResources(for: asset) for (_, resource) in resources.enumerated() { if resource.uniformTypeIdentifier == "com.compuserve.gif" { self.dataSource.append(asset) break } } }) DispatchQueue.main.async { self.activityIndicatorView?.stopAnimating() self.collectionView?.reloadSections(IndexSet(integer: 0)) } } @IBAction func unwindToMedia(sender: UIStoryboardSegue) { self.activityIndicatorView?.startAnimating() self.loadAssets() } } extension MediaViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AssetCell", for: indexPath) as! MediaCell cell.asset = dataSource[indexPath.row] if hasCompactHorizontalTrait() { cell.imageView?.contentMode = .scaleAspectFill } else { cell.imageView?.contentMode = .scaleAspectFit } return cell } } extension MediaViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { performSegue(withIdentifier: "MediaDetail", sender: collectionView.cellForItem(at: indexPath)) } } extension MediaViewController: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let interItemSpace: CGFloat if hasCompactHorizontalTrait() { interItemSpace = 1 } else { if hasUserInterfaceIdiomPadTrait() { interItemSpace = 20 } else { interItemSpace = 1 } } let paddingSpace = interItemSpace * (itemsPerRow! + 1) let availableWidth = view.frame.width - paddingSpace let widthPerItem = availableWidth / itemsPerRow! return CGSize(width: widthPerItem, height: widthPerItem) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { if hasCompactHorizontalTrait() { return .zero } else { return UIEdgeInsets.init(top: 16, left: 16, bottom: 16, right: 16) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { if hasCompactHorizontalTrait() { return 1 } else { return 10 } } }
mit
kreshikhin/scituner
SciTuner/ViewControllers/FiltersAlertController.swift
1
935
// // FiltersAlertController.swift // SciTuner // // Created by Denis Kreshikhin on 17.03.15. // Copyright (c) 2015 Denis Kreshikhin. All rights reserved. // import Foundation import UIKit protocol FiltersAlertControllerDelegate: class { func didChange(filter: Filter) } class FiltersAlertController: UIAlertController { weak var parentDelegate: FiltersAlertControllerDelegate? override func viewDidLoad() { Filter.allFilters.forEach { self.add(filter: $0) } addAction(UIAlertAction(title: "cancel".localized(), style: UIAlertActionStyle.cancel, handler: nil)) } func add(filter: Filter){ let action = UIAlertAction( title: filter.localized(), style: UIAlertActionStyle.default, handler: {(action: UIAlertAction) -> Void in self.parentDelegate?.didChange(filter: filter) }) addAction(action) } }
mit
tardieu/swift
test/IRGen/vtable_multi_file.swift
3
831
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -primary-file %s %S/Inputs/vtable_multi_file_helper.swift -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 func markUsed<T>(_ t: T) {} // CHECK-LABEL: define hidden void @_T017vtable_multi_file36baseClassVtablesIncludeImplicitInitsyyF() {{.*}} { func baseClassVtablesIncludeImplicitInits() { // CHECK: [[T0:%.*]] = call %swift.type* @_T017vtable_multi_file8SubclassCMa() // CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to { i64, i64, i64 } (%swift.type*)** // CHECK: [[T2:%.*]] = getelementptr inbounds { i64, i64, i64 } (%swift.type*)*, { i64, i64, i64 } (%swift.type*)** [[T1]], i64 11 // CHECK: load { i64, i64, i64 } (%swift.type*)*, { i64, i64, i64 } (%swift.type*)** [[T2]] markUsed(Subclass.classProp) }
apache-2.0
LeeMinglu/WeiBo_Swift3.0
WeiBo_Swift3.0/WeiBo_Swift3.0/Model/Weibo.swift
1
930
// // Weibo.swift // WeiBo_Swift3.0 // // Created by 李明禄 on 2016/11/26. // Copyright © 2016年 SocererGroup. All rights reserved. // import UIKit class Weibo: NSObject { var text: String? var name: String? var icon: String? var vip: Bool = true var picture: String? let properties = ["text", "name", "icon", "vip", "picture"] override var description: String { let dict = dictionaryWithValues(forKeys: properties) return ("\(dict)") } // MARK: - 构造函数 init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } class func dictModel(list: [[String: AnyObject]]) -> [Weibo] { var models = [Weibo]() for dict in list { models.append(Weibo(dict: dict)) } return models } }
apache-2.0
vary-llc/SugarRecord
spec/CoreData/DefaultCDStackTests.swift
10
6513
// // DefaultCDStackTests.swift // SugarRecord // // Created by Pedro Piñera Buendía on 27/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import UIKit import XCTest import CoreData class DefaultCDStackTests: XCTestCase { var stack: DefaultCDStack? = nil override func setUp() { super.setUp() let bundle: NSBundle = NSBundle(forClass: CoreDataObjectTests.classForCoder()) let modelPath: NSString = bundle.pathForResource("TestsDataModel", ofType: "momd")! let model: NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: NSURL(fileURLWithPath: modelPath)!)! stack = DefaultCDStack(databaseName: "TestDB.sqlite", model: model, automigrating: true) SugarRecord.addStack(stack!) } override func tearDown() { SugarRecord.cleanup() SugarRecord.removeAllStacks() SugarRecord.removeDatabase() super.tearDown() } func testThatTheRootSavingContextIsSavedInApplicationWillTerminate() { class MockCDStack: DefaultCDStack { var savedChangesInRootSavingContext: Bool = false override func saveChanges() { savedChangesInRootSavingContext = true } } let context: MockCDStack = MockCDStack(databaseName: "test", automigrating: false) context.applicationWillTerminate() XCTAssertTrue(context.savedChangesInRootSavingContext, "Root saving context should be saved when application will terminate") context.removeDatabase() } func testThatTheRootSavingContextIsSavedInApplicationWillResignActive() { class MockCDStack: DefaultCDStack { var savedChangesInRootSavingContext: Bool = false override func saveChanges() { savedChangesInRootSavingContext = true } } let context: MockCDStack = MockCDStack(databaseName: "test", automigrating: false) context.applicationWillResignActive() XCTAssertTrue(context.savedChangesInRootSavingContext, "Root saving context should be saved when application will resign active") context.removeDatabase() } func testInitializeOfComponents() { class MockCDStack: DefaultCDStack { var pscCreated: Bool = false var databaseAdded: Bool = false var rootSavingContextCreated: Bool = false var mainContextAdded: Bool = false override func createPersistentStoreCoordinator() -> NSPersistentStoreCoordinator { pscCreated = true return NSPersistentStoreCoordinator() } override func addDatabase(completionClosure: CompletionClosure) { databaseAdded = true completionClosure(error: nil) } override func createRootSavingContext(persistentStoreCoordinator: NSPersistentStoreCoordinator?) -> NSManagedObjectContext { rootSavingContextCreated = true return NSManagedObjectContext() } override func createMainContext(parentContext: NSManagedObjectContext?) -> NSManagedObjectContext { mainContextAdded = true return NSManagedObjectContext() } } let stack: MockCDStack = MockCDStack(databaseName: "test", automigrating: false) stack.initialize() XCTAssertTrue(stack.pscCreated, "Should initialize the persistent store coordinator") XCTAssertTrue(stack.databaseAdded, "Should add the database") XCTAssertTrue(stack.rootSavingContextCreated, "Should create the root saving context") XCTAssertTrue(stack.mainContextAdded, "Should add a main context") XCTAssertTrue(stack.stackInitialized, "Stack should be set as initialized") stack.removeDatabase() } func testBackgroundContextShouldHaveTheRootSavingContextAsParent() { XCTAssertEqual((stack!.backgroundContext() as SugarRecordCDContext).contextCD.parentContext!, stack!.rootSavingContext!, "The private context should have the root saving context as parent") } func testMainContextShouldHaveTheRootSavingContextAsParent() { XCTAssertEqual(stack!.mainContext!.parentContext!, stack!.rootSavingContext!, "Main saving context should have the root saving context as parent") } func testRootSavingContextShouldHaveThePersistentStoreCoordinatorAsParent() { XCTAssertEqual(stack!.rootSavingContext!.persistentStoreCoordinator!, stack!.persistentStoreCoordinator!, "Root saving context should have the PSC as parent") } func testBackgroundContextConcurrencyType() { XCTAssertEqual(stack!.rootSavingContext!.concurrencyType, NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType, "The concurrency type should be PrivateQueueConcurrencyType") } func testMainContextConcurrencyType() { XCTAssertEqual(stack!.mainContext!.concurrencyType, NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType, "The concurrency type should be MainQueueConcurrencyType") } func testRootSavingContextConcurrencyType() { XCTAssertEqual((stack!.backgroundContext() as SugarRecordCDContext).contextCD.concurrencyType, NSManagedObjectContextConcurrencyType.ConfinementConcurrencyType, "The concurrency type should be MainQueueConcurrencyType") } func testIfTheAutoSavingClosureIsCalledDependingOnTheAutoSavingProperty() { class MockDefaultStack: DefaultCDStack { var autoSavingClosureCalled: Bool = true override func autoSavingClosure() -> () -> () { return { [weak self] (notification) -> Void in self!.autoSavingClosureCalled = true } } } let mockStack: MockDefaultStack = MockDefaultStack(databaseName: "test", automigrating: false) mockStack.initialize() mockStack.autoSaving = true XCTAssertTrue(mockStack.autoSavingClosureCalled, "The AutoSavingClosure should be called if the autosaving is enabled") mockStack.autoSavingClosureCalled = false mockStack.autoSaving = false XCTAssertFalse(mockStack.autoSavingClosureCalled, "The AutoSavingClosure shouldn't be called if the autosaving is disabled") } }
mit
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/BadgeImageView/Accessibility+BadgeImageView.swift
1
201
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation extension Accessibility.Identifier { enum BadgeImageView { static let prefix = "BadgeImageView." } }
lgpl-3.0
madcato/OSFramework
Sources/OSFramework/PropertyListHelper.swift
1
797
// // PropertyListHelper.swift // BasketPrice // // Created by Daniel Vela on 11/06/2017. // Copyright © 2017 Daniel Vela. All rights reserved. // import Foundation class PropertyListHelper { static func loadArray(fromFile fileName: String) -> [Any]? { if let fileUrl = Bundle.main.url(forResource: fileName, withExtension: "plist"), let data = try? Data(contentsOf: fileUrl) { if let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [Any] { return result } } return nil } }
mit
WalletOne/P2P
P2PCoreTests/CoreModelsTests.swift
1
2574
// // CoreModelsTests.swift // P2P_iOS // // Created by Vitaliy Kuzmenko on 03/08/2017. // Copyright © 2017 Wallet One. All rights reserved. // import XCTest class CoreModelsTests: XCTestCase { override func setUp() { super.setUp() } func testDealModel() { let json: [String: Any] = [ "PlatformDealId": "BC477907-D7AA-4497-A2C4-FFFFFB1B441D", "DealStateId": "Paid", "CreateDate": "2017-08-03T13:23:08.47Z", "UpdateDate": "2017-08-03T13:23:17.697Z", "ExpireDate": "2017-12-01T13:23:08.47Z", "Amount": 1.0000, "CurrencyId": 643, "PlatformPayerId": "vitaliykuzmenko", "PayerCommissionAmount": 0, "PlatformBonusAmount": 0, "PayerPhoneNumber": "79281234567", "PayerPaymentToolId": 99, "PlatformBeneficiaryId": "alinakuzmenko", "BeneficiaryPaymentToolId": 98, "ShortDescription": "2", "FullDescription": "3", "DealTypeId": "Deferred" ] let deal = Deal(json: json) XCTAssertEqual(deal.platformDealId, json["PlatformDealId"] as! String) XCTAssertEqual(deal.dealStateId, json["DealStateId"] as! String) // XCTAssertEqual(deal.createDate., json["CreateDate"] as! String) // XCTAssertEqual(deal.expireDate, json["ExpireDate"] as! String) // XCTAssertEqual(deal.updatedate, json["UpdateDate"] as! String) XCTAssertEqual(deal.amount, 1) XCTAssertEqual(deal.currencyId.rawValue, json["CurrencyId"] as! Int) XCTAssertEqual(deal.platformPayerId, json["PlatformPayerId"] as! String) XCTAssertEqual(deal.payerCommissionAmount, json["PayerCommissionAmount"] as! NSNumber) XCTAssertEqual(deal.platformBonusAmount, json["PlatformBonusAmount"] as! NSNumber) XCTAssertEqual(deal.payerPhoneNumber, json["PayerPhoneNumber"] as! String) XCTAssertEqual(deal.payerPaymentToolId, json["PayerPaymentToolId"] as! Int) XCTAssertEqual(deal.platformBeneficiaryId, json["PlatformBeneficiaryId"] as! String) XCTAssertEqual(deal.beneficiaryPaymentToolId, json["BeneficiaryPaymentToolId"] as! Int) XCTAssertEqual(deal.shortDescription, json["ShortDescription"] as! String) XCTAssertEqual(deal.fullDescription, json["FullDescription"] as! String) XCTAssertEqual(deal.dealTypeId, json["DealTypeId"] as! String) } func testPaymentToolModel() { } }
mit
couchbits/iOSToolbox
Sources/RestClient/RestClientResponse.swift
1
467
// // ResponseEntity.swift // Alamofire // // Created by Dominik Gauggel on 29.11.18. // import Foundation public struct RestClientResponse { public let body: Data } public extension RestClientResponse { init(json: Any) throws { body = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) } func asJson() throws -> Any { return try JSONSerialization.jsonObject(with: body, options: .allowFragments) } }
mit
drunknbass/Emby.ApiClient.Swift
Emby.ApiClient/model/logging/ILogger.swift
2
1719
// // ILogger.swift // Emby.ApiClient // // Created by Vedran Ozir on 07/10/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation //package mediabrowser.model.logging; /** Interface ILogger */ public protocol ILogger { /** Infoes the specified message. @param message The message. @param paramList The param list. */ // func Info(message: String, _: AnyObject...) func Info(message: String) // /** // Errors the specified message. // @param message The message. // @param paramList The param list. // */ // void Error(String message, Object... paramList); // // /** // Warns the specified message. // @param message The message. // @param paramList The param list. // */ // void Warn(String message, Object... paramList); /** Debugs the specified message. @param message The message. @param paramList The param list. */ // func Debug(message: String, _: AnyObject...) func Debug(message: String) // /** // Fatals the specified message. // @param message The message. // @param paramList The param list. // */ // void Fatal(String message, Object... paramList); // // /** // Fatals the exception. // @param message The message. // @param exception The exception. // @param paramList The param list. // */ // void FatalException(String message, Exception exception, Object... paramList); // // /** // Logs the exception. // @param message The message. // @param exception The exception. // @param paramList The param list. // */ // void ErrorException(String message, Exception exception, Object... paramList); }
mit
lorentey/swift
test/Constraints/patterns.swift
1
10741
// RUN: %target-typecheck-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is ExpressibleByIntegerLiteral case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () default: () } switch (1, 2) { case (var a, a): // expected-error {{use of unresolved identifier 'a'}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () default: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() default: () } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () default: () } // Raise an error if pattern productions are used in expressions. var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}} () case Watch.Edition: // expected-warning {{cast from 'HairType' to unrelated type 'Watch' always fails}} () case .HairForceOne: // expected-error{{type 'HairType' has no member 'HairForceOne'}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} case nil: break } func SR2066(x: Int?) { // nil literals should still work when wrapped in parentheses switch x { case (nil): break case _?: break } switch x { case ((nil)): break case _?: break } switch (x, x) { case ((nil), _): break case (_?, _): break } } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x as Any, terminator: "") case let x?: print(x as Any, terminator: "") case 4???: break case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}} default: break } switch ("foo" as String?) { case "what": break default: break } // Test some value patterns. let x : Int? extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value default: break } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} // expected-note@-1 2 {{in call to function 'map'}} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { a.map { // expected-error {{generic parameter 'T' could not be inferred}} let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { a.map { // expected-error {{generic parameter 'T' could not be inferred}} switch $0 { case .A: return 1 default: return 2 } } } // SR-2057 enum SR2057 { case foo } let sr2057: SR2057? if case .foo = sr2057 { } // Ok // Invalid 'is' pattern class SomeClass {} if case let doesNotExist as SomeClass:AlsoDoesNotExist {} // expected-error@-1 {{use of undeclared type 'AlsoDoesNotExist'}} // expected-error@-2 {{variable binding in a condition requires an initializer}} // `.foo` and `.bar(...)` pattern syntax should also be able to match // static members as expr patterns struct StaticMembers: Equatable { init() {} init(_: Int) {} init?(opt: Int) {} static var prop = StaticMembers() static var optProp: Optional = StaticMembers() static func method(_: Int) -> StaticMembers { return prop } // expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}} static func method(withLabel: Int) -> StaticMembers { return prop } // expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}} static func optMethod(_: Int) -> StaticMembers? { return optProp } static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true } } let staticMembers = StaticMembers() let optStaticMembers: Optional = StaticMembers() switch staticMembers { case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(): break case .init(0): break case .init(_): break // expected-error{{'_' can only appear in a pattern}} case .init(let x): break // expected-error{{cannot appear in an expression}} case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} // expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} case .prop: break // TODO: repeated error message case .optProp: break // expected-error* {{not unwrapped}} case .method: break // expected-error{{no exact matches in call to static method 'method'}} case .method(0): break case .method(_): break // expected-error{{'_' can only appear in a pattern}} case .method(let x): break // expected-error{{cannot appear in an expression}} case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}} case .method(withLabel: 0): break case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}} case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}} case .optMethod(0): break // expected-error@-1 {{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-2 {{coalesce}} // expected-note@-3 {{force-unwrap}} } _ = 0 // rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining struct S_32241441 { enum E_32241441 { case foo case bar } var type: E_32241441 = E_32241441.foo } func rdar32241441() { let s: S_32241441? = S_32241441() switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}} case .foo: // Ok break; case .bar: // Ok break; } } // SR-6100 struct One<Two> { public enum E: Error { // if you remove associated value, everything works case SomeError(String) } } func testOne() { do { } catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}} if case One.E.SomeError = error {} // expected-error{{generic enum type 'One.E' is ambiguous without explicit generic parameters when matching value of type 'Error'}} } } // SR-8347 // constrain initializer expressions of optional some pattern bindings to be optional func test8347() -> String { struct C { subscript (s: String) -> String? { return "" } subscript (s: String) -> [String] { return [""] } func f() -> String? { return "" } func f() -> Int { return 3 } func g() -> String { return "" } func h() -> String { return "" } func h() -> Double { return 3.0 } func h() -> Int? { //expected-note{{found this candidate}} return 2 } func h() -> Float? { //expected-note{{found this candidate}} return nil } } let c = C() if let s = c[""] { return s } if let s = c.f() { return s } if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}} return s } if let s = c.h() { //expected-error{{ambiguous use of 'h()'}} return s } } enum SR_7799 { case baz case bar } let sr7799: SR_7799? = .bar switch sr7799 { case .bar?: break // Ok case .baz: break // Ok default: break } let sr7799_1: SR_7799?? = .baz switch sr7799_1 { case .bar?: break // Ok case .baz: break // Ok default: break } if case .baz = sr7799_1 {} // Ok if case .bar? = sr7799_1 {} // Ok
apache-2.0
lorentey/swift
test/SILGen/dynamically_replaceable.swift
3
19328
// RUN: %target-swift-emit-silgen -swift-version 5 %s | %FileCheck %s // RUN: %target-swift-emit-silgen -swift-version 5 %s -enable-implicit-dynamic | %FileCheck %s --check-prefix=IMPLICIT // RUN: %target-swift-emit-silgen -swift-version 5 %s -disable-previous-implementation-calls-in-dynamic-replacements | %FileCheck %s --check-prefix=NOPREVIOUS // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () { // IMPLICIT-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () { func maybe_dynamic_replaceable() { } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable08dynamic_B0yyF : $@convention(thin) () -> () { dynamic func dynamic_replaceable() { } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV1xACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B0yyF : $@convention(method) (Strukt) -> () { // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icig : $@convention(method) (Int, Strukt) -> Int // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icis : $@convention(method) (Int, Int, @inout Strukt) -> () // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivW // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivw struct Strukt { dynamic init(x: Int) { } dynamic func dynamic_replaceable() { } dynamic var dynamic_replaceable_var : Int { get { return 10 } set { } } dynamic subscript(x : Int) -> Int { get { return 10 } set { } } dynamic var property_with_observer : Int { didSet { } willSet { } } } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC1xACSi_tcfc : $@convention(method) (Int, @owned Klass) -> @owned Klass // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B0yyF : $@convention(method) (@guaranteed Klass) -> () { // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icig : $@convention(method) (Int, @guaranteed Klass) -> Int // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icis : $@convention(method) (Int, Int, @guaranteed Klass) -> () // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivW // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivw class Klass { dynamic init(x: Int) { } dynamic convenience init(c: Int) { self.init(x: c) } dynamic convenience init(a: Int, b: Int) { } dynamic func dynamic_replaceable() { } dynamic func dynamic_replaceable2() { } dynamic var dynamic_replaceable_var : Int { get { return 10 } set { } } dynamic subscript(x : Int) -> Int { get { return 10 } set { } } dynamic var property_with_observer : Int { didSet { } willSet { } } } class SubKlass : Klass { // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable8SubKlassC1xACSi_tcfc // CHECK: // dynamic_function_ref Klass.init(x:) // CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1xACSi_tcfc // CHECK: apply [[FUN]] dynamic override init(x: Int) { super.init(x: x) } } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6globalSivg : $@convention(thin) () -> Int { dynamic var global : Int { return 1 } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable11replacementyyF : $@convention(thin) () -> () { @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { } extension Klass { // Calls to the replaced function inside the replacing function should be // statically dispatched. // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () { // CHECK: [[FN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC11replacementyyF // CHECK: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> () // CHECK: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2!1 // CHECK: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> () // CHECK: return // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () { // NOPREVIOUS: [[FN:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable // NOPREVIOUS: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> () // NOPREVIOUS: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2!1 // NOPREVIOUS: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> () // NOPREVIOUS: return @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { dynamic_replaceable() dynamic_replaceable2() } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass { // CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC2crACSi_tcfC // CHECK: apply [[FUN]]({{.*}}, %1) // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass { // NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC // NOPREVIOUS: apply [[FUN]]({{.*}}, %1) @_dynamicReplacement(for: init(c:)) convenience init(cr: Int) { self.init(c: cr + 1) } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC // CHECK: // dynamic_function_ref Klass.__allocating_init(c:) // CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC // CHECK: apply [[FUN]]({{.*}}, %2) // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC // NOPREVIOUS: // dynamic_function_ref Klass.__allocating_init(c:) // NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC // NOPREVIOUS: apply [[FUN]]({{.*}}, %2) @_dynamicReplacement(for: init(a: b:)) convenience init(ar: Int, br: Int) { self.init(c: ar + br) } @_dynamicReplacement(for: init(x:)) init(xr: Int) { } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivg // CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int { // NOPREVIOUS: bb0([[ARG:%.*]] : @guaranteed $Klass): // NOPREVIOUS: [[ORIG:%.*]] = class_method [[ARG]] : $Klass, #Klass.dynamic_replaceable_var!getter.1 // NOPREVIOUS: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () { // CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivs // CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () { // NOPREVIOUS: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // NOPREVIOUS: [[ORIG:%.*]] = class_method [[SELF]] : $Klass, #Klass.dynamic_replaceable_var!setter // NOPREVIOUS: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) @_dynamicReplacement(for: dynamic_replaceable_var) var r : Int { get { return dynamic_replaceable_var + 1 } set { dynamic_replaceable_var = newValue + 1 } } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icig"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcig // CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcig // CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, @guaranteed Klass) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icis"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcis // CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcis // CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[SELF]]) : $@convention(method) (Int, Int, @guaranteed Klass) -> () @_dynamicReplacement(for: subscript(_:)) subscript(x y: Int) -> Int { get { return self[y] } set { self[y] = newValue } } } extension Strukt { // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable6StruktV11replacementyyF : $@convention(method) (Strukt) -> () { // CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV11replacementyyF // CHECK: apply [[FUN]](%0) : $@convention(method) (Strukt) -> () @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { dynamic_replaceable() } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV1xACSi_tcfC"] [ossa] @$s23dynamically_replaceable6StruktV1yACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt { // CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1yACSi_tcfC // CHECK: apply [[FUN]]({{.*}}, %1) @_dynamicReplacement(for: init(x:)) init(y: Int) { self.init(x: y + 1) } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable6StruktV1rSivg // CHECK: bb0([[ARG:%.*]] : $Strukt): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivg // CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (Strukt) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable6StruktV1rSivs // CHECK: bb0({{.*}} : $Int, [[ARG:%.*]] : $*Strukt): // CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[ARG]] : $*Strukt // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivs // CHECK: apply [[ORIG]]({{.*}}, [[BA]]) : $@convention(method) (Int, @inout Strukt) -> () // CHECK: end_access [[BA]] : $*Strukt @_dynamicReplacement(for: dynamic_replaceable_var) var r : Int { get { return dynamic_replaceable_var + 1 } set { dynamic_replaceable_var = newValue + 1 } } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icig"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcig // CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : $Strukt): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcig // CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, Strukt) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icis"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcis // CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : $*Strukt): // CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*Strukt // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcis // CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[BA]]) : $@convention(method) (Int, Int, @inout Strukt) -> () // CHECK: end_access [[BA]] : $*Strukt @_dynamicReplacement(for: subscript(_:)) subscript(x y: Int) -> Int { get { return self[y] } set { self[y] = newValue } } } struct GenericS<T> { dynamic init(x: Int) { } dynamic func dynamic_replaceable() { } dynamic var dynamic_replaceable_var : Int { get { return 10 } set { } } dynamic subscript(x : Int) -> Int { get { return 10 } set { } } // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivW // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivw dynamic var property_with_observer : Int { didSet { } willSet { } } } extension GenericS { // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable8GenericSV11replacementyyF // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV11replacementyyF @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { dynamic_replaceable() } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV1xACyxGSi_tcfC"] [ossa] @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC @_dynamicReplacement(for: init(x:)) init(y: Int) { self.init(x: y + 1) } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivg // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivg // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivs // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivs @_dynamicReplacement(for: dynamic_replaceable_var) var r : Int { get { return dynamic_replaceable_var + 1 } set { dynamic_replaceable_var = newValue + 1 } } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icig"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcig // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcig // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icis"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcis // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcis @_dynamicReplacement(for: subscript(_:)) subscript(x y: Int) -> Int { get { return self[y] } set { self[y] = newValue } } // CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivW"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivW // CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivw"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivw @_dynamicReplacement(for: property_with_observer) var replacement_property_with_observer : Int { didSet { } willSet { } } } dynamic var globalX = 0 // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivg : $@convention(thin) () -> Int // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivs : $@convention(thin) (Int) -> () // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable7getsetXyS2iF // CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivs // CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivg func getsetX(_ x: Int) -> Int { globalX = x return globalX } // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSFfA_ // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSF dynamic func funcWithDefaultArg(_ arg : String = String("hello")) { print("hello") } // IMPLICIT-LABEL: sil hidden [thunk] [ossa] @barfoo @_cdecl("barfoo") func foobar() { } // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable6$deferL_yyF var x = 10 defer { let y = x } // IMPLICIT-LABEL: sil [dynamically_replacable] [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF0geF0L_yyF // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyFyycfU_ public func testWithLocalFun() { func localFun() { func localLocalFun() { print("bar") } print("foo") localLocalFun() } localFun() let unamedClosure = { print("foo") } unamedClosure() } @propertyWrapper struct WrapperWithInitialValue<T> { var wrappedValue: T init(wrappedValue initialValue: T) { self.wrappedValue = initialValue } } // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable10SomeStructV1tSbvpfP public struct SomeStruct { @WrapperWithInitialValue var t = false }
apache-2.0
wircho/D3Workshop
HelloWorld/HelloWorld/MontrealViewController.swift
1
1471
// // MontrealViewController.swift // HelloWorld // // Created by Adolfo Rodriguez on 2015-08-01. // Copyright (c) 2015 Relevant. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import BrightFutures class MontrealViewController: UIViewController { @IBOutlet weak var contentLabel: UILabel! @IBAction func touchRefresh(sender: AnyObject) { let url = "http://api.whatthetrend.com/api/v2/trends.json?woeid=3534" request(.GET, url).responseJSON { (_, _, object, _) -> Void in Queue.main.async { if let obj:AnyObject = object { let json = JSON(obj) self.contentLabel.text = "\n".join(json["trends"].arrayValue.map{$0["name"].stringValue}) }else { self.contentLabel.text = "ERROR" } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.touchRefresh(self) } }
mit
178inaba/SwiftCollatz
SwiftCollatz/ViewController.swift
1
1621
// // ViewController.swift // SwiftCollatz // // Created by 178inaba on 2015/10/18. // Copyright © 2015年 178inaba. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var targetNumField: UITextField! @IBOutlet weak var resultView: UITableView! // collatz results var results: [UInt64] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. targetNumField.keyboardType = .NumberPad resultView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tapCalc(sender: UIButton) { targetNumField.resignFirstResponder() results = [] calcCollatz(UInt64(targetNumField.text!)!) resultView.reloadData() } func calcCollatz(num: UInt64) { results.append(num) print(num) if num % 2 == 1 && num > 1 { calcCollatz(3 * num + 1) } else if num % 2 == 0 { calcCollatz(num / 2) } } // cell rows func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } // change cell value func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel!.text = String(results[indexPath.row]) return cell } }
mit
urbanthings/urbanthings-sdk-apple
UTAPIObjCAdapter/Public/TransitTripInfo.swift
1
2596
// // TransitTripInfo.swift // UrbanThingsAPI // // Created by Mark Woollard on 15/05/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation import UTAPI @objc public protocol TransitTripInfo : NSObjectProtocol { /// A unique identifier representing the agency that operates this trip. var agencyCode:String? { get } /// A unique code that represents this trip. Note that IDs in some regions may change periodically and thus should not be stored on the client. var tripID:String? { get } /// The name of the origin stop on this trip. var originName:String? { get } /// The primary code of the origin stop on this trip. var originPrimaryCode:String? { get } /// The name of the ultimate destination on this trip. var headsign:String? { get } /// A descriptive name for the direction travelled on this trip, with relation to the route - e.g. 'Outbound'. Does not apply to all transit modes. var directionName:String? { get } /// A numeric identifier for the direction travelled on this trip, with relation to the route. e.g. A bus route may designate one direction as 'outbound' (1) and another direction as 'inbound' (2). Does not apply to all transit modes. var directionID:UInt { get } /// The ID of the vehicle scheduled to make the trip. This may or may not be the same as the VehicleID that is assigned when the vehicle actually runs (see VehicleRTI) var vehicleID:String? { get } /// Whether this trip is accessible to wheelchair users. This information may not be available in some data sets. var isWheelchairAccessible: TriState { get } } @objc public class UTTransitTripInfo : NSObject, TransitTripInfo { let adapted:UTAPI.TransitTripInfo public init?(adapt:UTAPI.TransitTripInfo?) { guard let adapt = adapt else { return nil } self.adapted = adapt } public var agencyCode:String? { return self.adapted.agencyCode } public var tripID:String? { return self.adapted.tripID } public var originName:String? { return self.adapted.originName } public var originPrimaryCode:String? { return self.adapted.originPrimaryCode } public var headsign:String? { return self.adapted.headsign } public var directionName:String? { return self.adapted.directionName } public var directionID:UInt { return self.adapted.directionID ?? 0} public var vehicleID:String? { return self.adapted.vehicleID } public var isWheelchairAccessible: TriState { return TriState(self.adapted.isWheelchairAccessible) } }
apache-2.0
aerogear/aerogear-ios-http
AeroGearHttp/MultiPartData.swift
2
2141
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * 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 /** Represents a multipart object containing a file plus metadata to be processed during upload. */ open class MultiPartData { /// The 'name' to be used on the request. open var name: String /// The 'filename' to be used on the request. open var filename: String /// The 'MIME type' to be used on the request. open var mimeType: String /// The actual data to be sent. open var data: Data /** Initialize a multipart object using an NSURL and a corresponding MIME type. :param: url the url of the local file. :param: mimeType the MIME type. :returns: the newly created multipart data. */ public init(url: URL, mimeType: String) { self.name = url.lastPathComponent self.filename = url.lastPathComponent self.mimeType = mimeType; self.data = try! Data(contentsOf: url) } /** Initialize a multipart object using an NSData plus metadata. :param: data the actual data to be uploaded. :param: name the 'name' to be used on the request. :param: filename the 'filename' to be used on the request. :param: mimeType the 'MIME type' to be used on the request. :returns: the newly created multipart data. */ public init(data: Data, name: String, filename: String, mimeType: String) { self.data = data; self.name = name; self.filename = filename; self.mimeType = mimeType; } }
apache-2.0
Navdy/protobuf-swift
plugin/ProtocolBuffers/ProtocolBuffersTests/pbTests/ProtobufUnittestImport.UnittestImportLite.proto.swift
1
13113
// Generated by the Protocol Buffers 3.0 compiler. DO NOT EDIT! // Source file "unittest_import_lite.proto" // Syntax "Proto2" import Foundation import ProtocolBuffers public extension ProtobufUnittestImport{} public extension ProtobufUnittestImport { public struct UnittestImportLiteRoot { public static let `default` = UnittestImportLiteRoot() public var extensionRegistry:ExtensionRegistry init() { extensionRegistry = ExtensionRegistry() registerAllExtensions(registry: extensionRegistry) ProtobufUnittestImport.UnittestImportPublicLiteRoot.default.registerAllExtensions(registry: extensionRegistry) } public func registerAllExtensions(registry: ExtensionRegistry) { } } //Enum type declaration start public enum ImportEnumLite:Int32, CustomDebugStringConvertible, CustomStringConvertible { case importLiteFoo = 7 case importLiteBar = 8 case importLiteBaz = 9 public func toString() -> String { switch self { case .importLiteFoo: return "IMPORT_LITE_FOO" case .importLiteBar: return "IMPORT_LITE_BAR" case .importLiteBaz: return "IMPORT_LITE_BAZ" } } public static func fromString(str:String) throws -> ProtobufUnittestImport.ImportEnumLite { switch str { case "IMPORT_LITE_FOO": return .importLiteFoo case "IMPORT_LITE_BAR": return .importLiteBar case "IMPORT_LITE_BAZ": return .importLiteBaz default: throw ProtocolBuffersError.invalidProtocolBuffer("Conversion String to Enum has failed.") } } public var debugDescription:String { return getDescription() } public var description:String { return getDescription() } private func getDescription() -> String { switch self { case .importLiteFoo: return ".importLiteFoo" case .importLiteBar: return ".importLiteBar" case .importLiteBaz: return ".importLiteBaz" } } } //Enum type declaration end final public class ImportMessageLite : GeneratedMessage { public static func == (lhs: ProtobufUnittestImport.ImportMessageLite, rhs: ProtobufUnittestImport.ImportMessageLite) -> Bool { if (lhs === rhs) { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = fieldCheck && (lhs.hasD == rhs.hasD) && (!lhs.hasD || lhs.d == rhs.d) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public fileprivate(set) var d:Int32 = Int32(0) public fileprivate(set) var hasD:Bool = false required public init() { super.init() } override public func isInitialized() -> Bool { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { if hasD { try codedOutputStream.writeInt32(fieldNumber: 1, value:d) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 if hasD { serialize_size += d.computeInt32Size(fieldNumber: 1) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func getBuilder() -> ProtobufUnittestImport.ImportMessageLite.Builder { return ProtobufUnittestImport.ImportMessageLite.classBuilder() as! ProtobufUnittestImport.ImportMessageLite.Builder } public func getBuilder() -> ProtobufUnittestImport.ImportMessageLite.Builder { return classBuilder() as! ProtobufUnittestImport.ImportMessageLite.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { return ProtobufUnittestImport.ImportMessageLite.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { return ProtobufUnittestImport.ImportMessageLite.Builder() } public func toBuilder() throws -> ProtobufUnittestImport.ImportMessageLite.Builder { return try ProtobufUnittestImport.ImportMessageLite.builderWithPrototype(prototype:self) } public class func builderWithPrototype(prototype:ProtobufUnittestImport.ImportMessageLite) throws -> ProtobufUnittestImport.ImportMessageLite.Builder { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary<String,Any> { guard isInitialized() else { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } var jsonMap:Dictionary<String,Any> = Dictionary<String,Any>() if hasD { jsonMap["d"] = Int(d) } return jsonMap } override class public func decode(jsonMap:Dictionary<String,Any>) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder.decodeToBuilder(jsonMap:jsonMap).build() } override class public func fromJSON(data:Data) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" if hasD { output += "\(indent) d: \(d) \n" } output += unknownFields.getDescription(indent: indent) return output } override public var hashValue:Int { get { var hashCode:Int = 7 if hasD { hashCode = (hashCode &* 31) &+ d.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "ProtobufUnittestImport.ImportMessageLite" } override public func className() -> String { return "ProtobufUnittestImport.ImportMessageLite" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { fileprivate var builderResult:ProtobufUnittestImport.ImportMessageLite = ProtobufUnittestImport.ImportMessageLite() public func getMessage() -> ProtobufUnittestImport.ImportMessageLite { return builderResult } required override public init () { super.init() } public var hasD:Bool { get { return builderResult.hasD } } public var d:Int32 { get { return builderResult.d } set (value) { builderResult.hasD = true builderResult.d = value } } @discardableResult public func setD(_ value:Int32) -> ProtobufUnittestImport.ImportMessageLite.Builder { self.d = value return self } @discardableResult public func clearD() -> ProtobufUnittestImport.ImportMessageLite.Builder{ builderResult.hasD = false builderResult.d = Int32(0) return self } override public var internalGetResult:GeneratedMessage { get { return builderResult } } @discardableResult override public func clear() -> ProtobufUnittestImport.ImportMessageLite.Builder { builderResult = ProtobufUnittestImport.ImportMessageLite() return self } override public func clone() throws -> ProtobufUnittestImport.ImportMessageLite.Builder { return try ProtobufUnittestImport.ImportMessageLite.builderWithPrototype(prototype:builderResult) } override public func build() throws -> ProtobufUnittestImport.ImportMessageLite { try checkInitialized() return buildPartial() } public func buildPartial() -> ProtobufUnittestImport.ImportMessageLite { let returnMe:ProtobufUnittestImport.ImportMessageLite = builderResult return returnMe } @discardableResult public func mergeFrom(other:ProtobufUnittestImport.ImportMessageLite) throws -> ProtobufUnittestImport.ImportMessageLite.Builder { if other == ProtobufUnittestImport.ImportMessageLite() { return self } if other.hasD { d = other.d } try merge(unknownField: other.unknownFields) return self } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream) throws -> ProtobufUnittestImport.ImportMessageLite.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittestImport.ImportMessageLite.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() switch protobufTag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self case 8: d = try codedInputStream.readInt32() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } class override public func decodeToBuilder(jsonMap:Dictionary<String,Any>) throws -> ProtobufUnittestImport.ImportMessageLite.Builder { let resultDecodedBuilder = ProtobufUnittestImport.ImportMessageLite.Builder() if let jsonValueD = jsonMap["d"] as? Int { resultDecodedBuilder.d = Int32(jsonValueD) } else if let jsonValueD = jsonMap["d"] as? String { resultDecodedBuilder.d = Int32(jsonValueD)! } return resultDecodedBuilder } override class public func fromJSONToBuilder(data:Data) throws -> ProtobufUnittestImport.ImportMessageLite.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary<String,Any> else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } return try ProtobufUnittestImport.ImportMessageLite.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } } extension ProtobufUnittestImport.ImportMessageLite: GeneratedMessageProtocol { public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array<ProtobufUnittestImport.ImportMessageLite> { var mergedArray = Array<ProtobufUnittestImport.ImportMessageLite>() while let value = try parseDelimitedFrom(inputStream: inputStream) { mergedArray.append(value) } return mergedArray } public class func parseDelimitedFrom(inputStream: InputStream) throws -> ProtobufUnittestImport.ImportMessageLite? { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build() } public class func parseFrom(data: Data) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeFrom(data: data, extensionRegistry:ProtobufUnittestImport.UnittestImportLiteRoot.default.extensionRegistry).build() } public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build() } public class func parseFrom(inputStream: InputStream) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeFrom(inputStream: inputStream).build() } public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build() } public class func parseFrom(codedInputStream: CodedInputStream) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeFrom(codedInputStream: codedInputStream).build() } public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> ProtobufUnittestImport.ImportMessageLite { return try ProtobufUnittestImport.ImportMessageLite.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build() } } // @@protoc_insertion_point(global_scope)
apache-2.0
darthpelo/TimerH2O
TimerH2O/TimerH2OTests/LocalDataTests.swift
1
1611
// // LocalDataTests.swift // TimerH2O // // Created by Alessio Roberto on 27/10/16. // Copyright © 2016 Alessio Roberto. All rights reserved. // import XCTest @testable import TimerH2O class LocalDataTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSessionInProgressTests() { SessionManagerImplementation().newSession(isStart: true) XCTAssertEqual(State.start, SessionManagerImplementation().state()) SessionManagerImplementation().newSession(isStart: false) XCTAssertEqual(State.end, SessionManagerImplementation().state()) } func testWaterSetupTests() { let water = 50.0 SessionManagerImplementation().newAmountOf(water: water) XCTAssertEqual(SessionManagerImplementation().amountOfWater(), water) } func testTimeIntervalTests() { let timer: Double = 15 // Second SessionManagerImplementation().newTimeInterval(second: timer) XCTAssertEqual(SessionManagerImplementation().timeInterval(), timer) } func testSaveDate() { let date = Date() SessionManagerImplementation().new(endTimer: date) let result = SessionManagerImplementation().endTimer() XCTAssertNotNil(result) XCTAssertEqual(result, date) } }
mit
kickstarter/ios-oss
KsApi/models/AccessTokenEnvelope.swift
1
348
public struct AccessTokenEnvelope { public let accessToken: String public let user: User public init(accessToken: String, user: User) { self.accessToken = accessToken self.user = user } } extension AccessTokenEnvelope: Decodable { enum CodingKeys: String, CodingKey { case accessToken = "access_token" case user } }
apache-2.0
noppoMan/Hexaville
Sources/HexavilleCore/Process/Proc.swift
1
1269
// // Proc.swift // Hexaville // // Created by Yuki Takei on 2017/05/16. // // import Foundation extension Process { public static func exec(_ cmd: String, _ args: [String], environment: [String: String] = ProcessInfo.processInfo.environment) -> Proc { var args = args args.insert(cmd, at: 0) return Proc.init("/usr/bin/env", args, environment: environment) } } public struct Proc { public let terminationStatus: Int32 public let stdout: Any? public let stderr: Any? public let pid: Int32? public init(_ exetutablePath: String, _ arguments: [String] = [], environment: [String: String] = ProcessInfo.processInfo.environment) { let process = Process() process.launchPath = exetutablePath process.arguments = arguments process.environment = environment process.launch() // handle SIGINT SignalEventEmitter.shared.once { sig in assert(sig == .int) process.interrupt() } process.waitUntilExit() terminationStatus = process.terminationStatus stdout = process.standardOutput stderr = process.standardError pid = process.processIdentifier } }
mit
AceWangLei/BYWeiBo
BYWeiBo/BYUserAccountViewModel.swift
1
3995
// // BYUserAccountViewModel.swift // BYWeiBo // // Created by wanglei on 16/1/25. // Copyright © 2016年 lit. All rights reserved. // import UIKit class BYUserAccountViewModel: NSObject { /** BYUserAccount 视图模型引用的Model */ var account: BYUserAccount? /** string accessToken */ var accessToken: String? { return account?.access_token } /** bool 以后,外界只需要调用这个属性就知道是否登陆 */ var isLogon: Bool { // account 不能为 nil && accessToken 不能过期 if account != nil && isExpiresIn == false { // 代表当前用户登陆 return true } return false } /** bool 代表当前账户是否过期, 为 true 代表过期 */ var isExpiresIn: Bool { // 当前时间比过期时间小,也就是还没有到过期时间,也就是没有过期 if NSDate().compare(account!.expiresDate!) == .OrderedAscending { return false } return true } /** BYUserAccountViewModel 全局访问对象 */ static let sharedViewModel:BYUserAccountViewModel = { let viewModel = BYUserAccountViewModel() // 会在第一次使用当前类的时候去归档文件里面读取当前用户的信息 viewModel.account = viewModel.userAccount() return viewModel }() /** string 归档&解档的路径 */ private var archivePath: String { return (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive") } /** 加载 accessToken - parameter code: code - parameter finished: 是否加载成功 */ func loadAccessToken(code: String, finished:(isSuccess: Bool)->()) { BYNetworkTools.sharedTools.loadAccessToken(code) { (response, error) -> () in if error != nil { finished(isSuccess: false) return } // 判断返回数据是否是字典 guard let dict = response as? [String: AnyObject] else { finished(isSuccess: false) return } // 字典转模型 let account = BYUserAccount(dict: dict) // 加载个人信息 self.loadUserInfo(account, finished: finished) } } /** 加载个人信息 - parameter account: BYUserAccount - parameter finished: 是否加载成功 */ private func loadUserInfo(account: BYUserAccount, finished: (isSuccess: Bool)->()) { BYNetworkTools.sharedTools.loadUserInfo(account.access_token!, uid: account.uid!) { (response, error) -> () in if error != nil { finished(isSuccess: false) return } guard let dict = response as? [String: AnyObject] else { finished(isSuccess: false) return } account.avatar_large = dict["avatar_large"] as? String account.screen_name = dict["screen_name"] as? String // 归档保存 self.saveUserAccount(account) // 给当前类的 account 赋值 self.account = account // 回调登陆成功 finished(isSuccess: true) } } } extension BYUserAccountViewModel { private func saveUserAccount(account: BYUserAccount) { // 1. 获取归档路径 print(archivePath) // 2. NSKeyedArchive NSKeyedArchiver.archiveRootObject(account, toFile: archivePath) } // 解档数据 func userAccount() -> BYUserAccount? { return NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? BYUserAccount } }
apache-2.0
Dhvl-Golakiya/ImageAdjusts
Example/ImageAdjusts/ViewController.swift
1
516
// // ViewController.swift // ImageAdjusts // // Created by Dhvl-Golakiya on 08/28/2017. // Copyright (c) 2017 Dhvl-Golakiya. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
onekiloparsec/SwiftAA
Tests/SwiftAATests/EarthTwilightsTests.swift
2
11493
// // EarthTests.swift // SwiftAA // // Created by Cédric Foellmi on 25/01/2017. // Copyright © 2017 onekiloparsec. All rights reserved. // import XCTest @testable import SwiftAA class EarthTwilightsTests: XCTestCase { func testValidTwilightNorthernHemisphereWestLongitude() { let paris = GeographicCoordinates(positivelyWestwardLongitude: Degree(.minus, 2, 21, 0.0), latitude: Degree(.plus, 48, 52, 0.0), altitude: Meter(30)) let earth = Earth(julianDay: JulianDay(year: 2017, month: 1, day: 30)) let twilights = earth.twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) XCTAssertNotNil(twilights.riseTime) XCTAssertNotNil(twilights.transitTime) XCTAssertNotNil(twilights.setTime) XCTAssertNil(twilights.transitError) XCTAssertTrue(twilights.riseTime! < twilights.setTime!) } func testValidTwilightSouthernHemisphereWestLongitude() { let parisSouth = GeographicCoordinates(positivelyWestwardLongitude: Degree(-2.3508333333), latitude: Degree(-48.8566666667), altitude: Meter(30)) let earth = Earth(julianDay: JulianDay(year: 2017, month: 1, day: 30)) let twilights = earth.twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: parisSouth) XCTAssertNotNil(twilights.riseTime) XCTAssertNotNil(twilights.transitTime) XCTAssertNotNil(twilights.setTime) XCTAssertNil(twilights.transitError) XCTAssertTrue(twilights.riseTime! < twilights.setTime!) } // func testPrintTwilights() { // var date = JulianDay(year: 2017, month: 1, day: 1).date // let paris = GeographicCoordinates(positivelyWestwardLongitude: Degree(.minus, 2, 21, 0.0), // latitude: Degree(.plus, 48, 52, 0.0), // altitude: Meter(30)) // // let gregorianCalendar = Calendar.gregorianGMT // // for _ in 1...365 { // // let sun = Sun(julianDay: JulianDay(date)) // // let riseTransitSetTimes = RiseTransitSetTimes(celestialBody: sun, geographicCoordinates: paris, riseSetAltitude: TwilightSunAltitude.astronomical.rawValue) // // print("dawn: \(riseTransitSetTimes.riseTime?.date) | dusk: \(riseTransitSetTimes.setTime?.date)") // // date = gregorianCalendar.date(byAdding: .day, value: 1, to: date)! // } // } // See http://aa.usno.navy.mil/cgi-bin/aa_rstablew.pl?ID=AA&year=2017&task=4&place=&lon_sign=1&lon_deg=2&lon_min=21&lat_sign=1&lat_deg=48&lat_min=52&tz=0&tz_sign=-1 // for a reference table for the 2017 year func testValidTwilightNorthernHemisphereWestLongitudeAgainstUSNOReference() { let paris = GeographicCoordinates(positivelyWestwardLongitude: Degree(.minus, 2, 21, 0.0), latitude: Degree(.plus, 48, 52, 0.0), altitude: Meter(30)) let accuracy1 = 1.0.minutes.inJulianDays let accuracy2 = 2.0.minutes.inJulianDays let accuracy5 = 5.0.minutes.inJulianDays let accuracy10 = 10.0.minutes.inJulianDays var date = JulianDay(year: 2017, month: 1, day: 1).date // january 1st var twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 1, day: 1, hour: 5, minute: 48), accuracy: accuracy2) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 1, day: 1, hour: 18, minute: 00), accuracy: accuracy5) date = JulianDay(year: 2017, month: 2, day: 1).date // february 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 2, day: 1, hour: 5, minute: 32), accuracy: accuracy2) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 2, day: 1, hour: 18, minute: 37), accuracy: accuracy10) date = JulianDay(year: 2017, month: 3, day: 1).date // march 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 3, day: 1, hour: 4, minute: 48), accuracy: accuracy2) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 3, day: 1, hour: 19, minute: 19), accuracy: accuracy10) date = JulianDay(year: 2017, month: 4, day: 1).date // april 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 4, day: 1, hour: 3, minute: 37), accuracy: accuracy1) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 4, day: 1, hour: 20, minute: 13), accuracy: accuracy10) date = JulianDay(year: 2017, month: 5, day: 1).date // may 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 5, day: 1, hour: 2, minute: 17), accuracy: accuracy2) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 5, day: 1, hour: 21, minute: 21), accuracy: accuracy10) date = JulianDay(year: 2017, month: 6, day: 1).date // june 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 6, day: 1, hour: 0, minute: 44), accuracy: accuracy2) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 6, day: 1, hour: 22, minute: 56), accuracy: accuracy10) date = JulianDay(year: 2017, month: 7, day: 1).date // july 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 7, day: 1, hour: 0, minute: 3), accuracy: accuracy1) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 7, day: 1, hour: 23, minute: 38), accuracy: accuracy5) date = JulianDay(year: 2017, month: 8, day: 1).date // august 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 8, day: 1, hour: 1, minute: 57), accuracy: accuracy2) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 8, day: 1, hour: 21, minute: 55), accuracy: accuracy5) date = JulianDay(year: 2017, month: 9, day: 1).date // september 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 9, day: 1, hour: 3, minute: 11), accuracy: accuracy2) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 9, day: 1, hour: 20, minute: 28), accuracy: accuracy5) date = JulianDay(year: 2017, month: 10, day: 1).date // october 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 10, day: 1, hour: 4, minute: 5), accuracy: accuracy5) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 10, day: 1, hour: 19, minute: 15), accuracy: accuracy5) date = JulianDay(year: 2017, month: 11, day: 1).date // november 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 11, day: 1, hour: 4, minute: 51), accuracy: accuracy5) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 11, day: 1, hour: 18, minute: 17), accuracy: accuracy5) date = JulianDay(year: 2017, month: 12, day: 1).date // december 1st twilights = Earth(julianDay: JulianDay(date)).twilights(forSunAltitude: TwilightSunAltitude.astronomical.rawValue, coordinates: paris) AssertEqual(twilights.riseTime!, JulianDay(year: 2017, month: 12, day: 1, hour: 5, minute: 29), accuracy: accuracy5) AssertEqual(twilights.setTime!, JulianDay(year: 2017, month: 12, day: 1, hour: 17, minute: 50), accuracy: accuracy5) } func testValidTwilightNorthernHemisphereAboveArticCircle() { // Latitude must be > 66º33'. let north = GeographicCoordinates(positivelyWestwardLongitude: Degree(.minus, 2, 21, 0.0), latitude: Degree(75.0), altitude: Meter(30)) // Winter var earth = Earth(julianDay: JulianDay(year: 2017, month: 1, day: 30)) var twilights = earth.twilights(forSunAltitude: TwilightSunAltitude.riseAndSet.rawValue, coordinates: north) XCTAssertNil(twilights.riseTime) XCTAssertNil(twilights.transitTime) XCTAssertNil(twilights.setTime) XCTAssertTrue(twilights.transitError == .alwaysBelowAltitude) // Summer earth = Earth(julianDay: JulianDay(year: 2017, month: 7, day: 30)) twilights = earth.twilights(forSunAltitude: TwilightSunAltitude.riseAndSet.rawValue, coordinates: north) XCTAssertNil(twilights.riseTime) XCTAssertNotNil(twilights.transitTime) XCTAssertNil(twilights.setTime) XCTAssertTrue(twilights.transitError == .alwaysAboveAltitude) } func testValidTwilightSouthernHemisphereBelowAntarcticCircle() { // Latitude must be < 66º33'. let north = GeographicCoordinates(positivelyWestwardLongitude: Degree(.minus, 2, 21, 0.0), latitude: Degree(-75.0), altitude: Meter(30)) // Summer var earth = Earth(julianDay: JulianDay(year: 2017, month: 1, day: 30)) var twilights = earth.twilights(forSunAltitude: TwilightSunAltitude.riseAndSet.rawValue, coordinates: north) XCTAssertNil(twilights.riseTime) XCTAssertNotNil(twilights.transitTime) XCTAssertNil(twilights.setTime) XCTAssertTrue(twilights.transitError == .alwaysAboveAltitude) // Winter earth = Earth(julianDay: JulianDay(year: 2017, month: 7, day: 30)) twilights = earth.twilights(forSunAltitude: TwilightSunAltitude.riseAndSet.rawValue, coordinates: north) XCTAssertNil(twilights.riseTime) XCTAssertNil(twilights.transitTime) XCTAssertNil(twilights.setTime) XCTAssertTrue(twilights.transitError == .alwaysBelowAltitude) } }
mit
AngryLi/note
iOS/Demos/Assignments_swift/assignment-1-calculator/Calculator_assignment/Calculator/StringExtension.swift
3
2148
// // StringExtension.swift // Calculator // // Created by 李亚洲 on 15/4/29. // Copyright (c) 2015年 liyazhou. All rights reserved. // import Foundation extension String{ //分割字符 func split(s:String)->[String]{ if s.isEmpty{ var x=[String]() for y in self{ x.append(String(y)) } return x } return self.componentsSeparatedByString(s) } //去掉左右空格 func trim()->String{ return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } //是否包含字符串 func has(s:String)->Bool{ if (self.rangeOfString(s) != nil) { return true }else{ return false } } //是否包含前缀 func hasBegin(s:String)->Bool{ if self.hasPrefix(s) { return true }else{ return false } } //是否包含后缀 func hasEnd(s:String)->Bool{ if self.hasSuffix(s) { return true }else{ return false } } //统计长度 func length()->Int{ return count(self) } //统计长度(别名) func size()->Int{ return count(self) } //截取字符串 func substringFromIndex(#startIndex: Int) -> String { return self.substringFromIndex(advance(self.startIndex, startIndex)) } func substringToIndex(#endIndex: Int) -> String { return self.substringToIndex(advance(self.startIndex, endIndex)) } func substringWithRange(#startIndex:Int, endIndex:Int) -> String { return self.substringWithRange(Range(start: advance(self.startIndex, startIndex), end: advance(self.startIndex, endIndex))) } //重复字符串 func repeat(#times: Int) -> String{ var result = "" for i in 0..<times { result += self } return result } //反转 func reverse()-> String{ var s=self.split("").reverse() var x="" for y in s{ x+=y } return x } }
mit
xuzhuoxi/SearchKit
Test/cs/wordscoding/PinyinCodingImplTest.swift
1
1553
// // PinyinCodingImplTest.swift // SearchKit // // Created by 许灼溪 on 15/12/31. // // import XCTest @testable import SearchKit class PinyinCodingImplTest: XCTestCase { // // override func setUp() { // super.setUp() // // Put setup code here. This method is called before the invocation of each test method in the class. // } // // override func tearDown() { // // Put teardown code here. This method is called after the invocation of each test method in the class. // super.tearDown() // } // // func testExample() { // // This is an example of a functional test case. // // Use XCTAssert and related functions to verify your tests produce the correct results. // } // // func testPerformanceExample() { // // This is an example of a performance test case. // self.measureBlock { // // Put the code you want to measure the time of here. // } // } func testCoding() { let impl = PinyinCodingImpl() let testAry = ["一", "丘", "之", "貉", "一丘之貉", "AA制"] let result = [["yi"],["qiu"],["zhi"],["hao","he","ma","mo"],["yi qiu zhi hao", "yi qiu zhi he", "yi qiu zhi ma", "yi qiu zhi mo"],["AA zhi"]] let cc = CachePool.instance.getCache(CacheNames.PINYIN_WORD) as! CharacterLibraryProtocol for (index, str) in testAry.enumerated() { let coded = impl.coding(cc, words: str) XCTAssertNotNil(coded) XCTAssertEqual(result[index], coded!) } } }
mit
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/Mixpanel.swift
2
6803
// // Mixpanel.swift // Mixpanel // // Created by Yarden Eitan on 6/1/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation #if !os(OSX) import UIKit #endif // os(OSX) /// The primary class for integrating Mixpanel with your app. open class Mixpanel { #if !os(OSX) /** Initializes an instance of the API with the given project token. Returns a new Mixpanel instance API object. This allows you to create more than one instance of the API object, which is convenient if you'd like to send data to more than one Mixpanel project from a single app. - parameter token: your project token - parameter launchOptions: Optional. App delegate launchOptions - parameter flushInterval: Optional. Interval to run background flushing - parameter instanceName: Optional. The name you want to call this instance - important: If you have more than one Mixpanel instance, it is beneficial to initialize the instances with an instanceName. Then they can be reached by calling getInstance with name. - returns: returns a mixpanel instance if needed to keep throughout the project. You can always get the instance by calling getInstance(name) */ @discardableResult open class func initialize(token apiToken: String, launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil, flushInterval: Double = 60, instanceName: String = UUID().uuidString) -> MixpanelInstance { return MixpanelManager.sharedInstance.initialize(token: apiToken, launchOptions: launchOptions, flushInterval: flushInterval, instanceName: instanceName) } #else /** Initializes an instance of the API with the given project token (MAC OS ONLY). Returns a new Mixpanel instance API object. This allows you to create more than one instance of the API object, which is convenient if you'd like to send data to more than one Mixpanel project from a single app. - parameter token: your project token - parameter flushInterval: Optional. Interval to run background flushing - parameter instanceName: Optional. The name you want to call this instance - important: If you have more than one Mixpanel instance, it is beneficial to initialize the instances with an instanceName. Then they can be reached by calling getInstance with name. - returns: returns a mixpanel instance if needed to keep throughout the project. You can always get the instance by calling getInstance(name) */ @discardableResult open class func initialize(token apiToken: String, flushInterval: Double = 60, instanceName: String = UUID().uuidString) -> MixpanelInstance { return MixpanelManager.sharedInstance.initialize(token: apiToken, flushInterval: flushInterval, instanceName: instanceName) } #endif // os(OSX) /** Gets the mixpanel instance with the given name - parameter name: the instance name - returns: returns the mixpanel instance */ open class func getInstance(name: String) -> MixpanelInstance? { return MixpanelManager.sharedInstance.getInstance(name: name) } /** Returns the main instance that was initialized. If not specified explicitly, the main instance is always the last instance added - returns: returns the main Mixpanel instance */ open class func mainInstance() -> MixpanelInstance { let instance = MixpanelManager.sharedInstance.getMainInstance() if instance == nil { fatalError("You have to call initialize(token:) before calling the main instance, " + "or define a new main instance if removing the main one") } return instance! } /** Sets the main instance based on the instance name - parameter name: the instance name */ open class func setMainInstance(name: String) { MixpanelManager.sharedInstance.setMainInstance(name: name) } /** Removes an unneeded Mixpanel instance based on its name - parameter name: the instance name */ open class func removeInstance(name: String) { MixpanelManager.sharedInstance.removeInstance(name: name) } } class MixpanelManager { static let sharedInstance = MixpanelManager() private var instances: [String: MixpanelInstance] private var mainInstance: MixpanelInstance? init() { instances = [String: MixpanelInstance]() Logger.addLogging(PrintLogging()) } #if !os(OSX) func initialize(token apiToken: String, launchOptions: [UIApplicationLaunchOptionsKey : Any]?, flushInterval: Double, instanceName: String) -> MixpanelInstance { let instance = MixpanelInstance(apiToken: apiToken, launchOptions: launchOptions, flushInterval: flushInterval, name: instanceName) mainInstance = instance instances[instanceName] = instance return instance } #else func initialize(token apiToken: String, flushInterval: Double, instanceName: String) -> MixpanelInstance { let instance = MixpanelInstance(apiToken: apiToken, flushInterval: flushInterval, name: instanceName) mainInstance = instance instances[instanceName] = instance return instance } #endif // os(OSX) func getInstance(name instanceName: String) -> MixpanelInstance? { guard let instance = instances[instanceName] else { Logger.warn(message: "no such instance: \(instanceName)") return nil } return instance } func getMainInstance() -> MixpanelInstance? { return mainInstance } func setMainInstance(name instanceName: String) { guard let instance = instances[instanceName] else { return } mainInstance = instance } func removeInstance(name instanceName: String) { if instances[instanceName] === mainInstance { mainInstance = nil } instances[instanceName] = nil } }
mit
crazypoo/PTools
Pods/CollectionViewPagingLayout/Lib/SwiftUI/PagingCollectionViewControllerBuilder.swift
1
2298
// // PagingCollectionViewControllerBuilder.swift // CollectionViewPagingLayout // // Created by Amir on 28/03/2021. // Copyright © 2021 Amir Khorsandi. All rights reserved. // import SwiftUI public class PagingCollectionViewControllerBuilder<ValueType: Identifiable, PageContent: View> { public typealias ViewController = PagingCollectionViewController<ValueType, PageContent> // MARK: Properties let data: [ValueType] let pageViewBuilder: (ValueType, CGFloat) -> PageContent let selection: Binding<ValueType.ID?>? var modifierData: PagingCollectionViewModifierData = .init() weak var viewController: ViewController? // MARK: Lifecycle public init( data: [ValueType], pageViewBuilder: @escaping (ValueType, CGFloat) -> PageContent, selection: Binding<ValueType.ID?>? ) { self.data = data self.pageViewBuilder = pageViewBuilder self.selection = selection } public init( data: [ValueType], pageViewBuilder: @escaping (ValueType) -> PageContent, selection: Binding<ValueType.ID?>? ) { self.data = data self.pageViewBuilder = { value, _ in pageViewBuilder(value) } self.selection = selection } // MARK: Public functions func make() -> ViewController { let viewController = ViewController() viewController.pageViewBuilder = pageViewBuilder viewController.modifierData = modifierData viewController.update(list: data, currentIndex: nil) setupOnCurrentPageChanged(viewController) return viewController } func update(viewController: ViewController) { let selectedIndex = data.enumerated().first { $0.element.id == selection?.wrappedValue }?.offset viewController.modifierData = modifierData viewController.update(list: data, currentIndex: selectedIndex) setupOnCurrentPageChanged(viewController) } // MARK: Private functions private func setupOnCurrentPageChanged(_ viewController: ViewController) { viewController.onCurrentPageChanged = { [data, selection] in guard $0 >= 0 && $0 < data.count else { return } selection?.wrappedValue = data[$0].id } } }
mit
IngmarStein/swift
stdlib/public/SDK/CoreGraphics/Private.swift
4
11354
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Redeclarations of all SwiftPrivate symbols with appropriate markup, // so that tools can help with migration // @available(*, unavailable, renamed:"DispatchQueue.init(label:attributes:target:)") @available(*, unavailable, message:"Use == instead") public func CGAffineTransformEqualToTransform(_ t1: CGAffineTransform, _ t2: CGAffineTransform) -> Bool { fatalError() } @available(*, unavailable, message:"Use class var white/black/clear instead") public func CGColorGetConstantColor(_ colorName: CFString?) -> CGColor? { fatalError() } @available(*, unavailable, message:"Use == instead") public func CGColorEqualToColor(_ color1: CGColor?, _ color2: CGColor?) -> Bool { fatalError() } @available(*, unavailable, renamed:"getter:CGColor.components(self:)") public func CGColorGetComponents(_ color: CGColor?) -> UnsafePointer<CGFloat> { fatalError() } @available(*, unavailable, message:"Use colorTable.count instead") public func CGColorSpaceGetColorTableCount(_ space: CGColorSpace?) -> Int { fatalError() } @available(*, unavailable, renamed:"CGColorSpace.colorTable(self:_:)") public func CGColorSpaceGetColorTable(_ space: CGColorSpace?, _ table: UnsafeMutablePointer<UInt8>) { fatalError() } @available(*, unavailable, message:"Use setLineDash(self:phase:lengths:)") public func CGContextSetLineDash(_ c: CGContext?, _ phase: CGFloat, _ lengths: UnsafePointer<CGFloat>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use move(to:) instead") public func CGContextMoveToPoint(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addLine(to:) instead") public func CGContextAddLineToPoint(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addCurve(to:control1:control2:) instead") public func CGContextAddCurveToPoint(_ c: CGContext?, _ cp1x: CGFloat, _ cp1y: CGFloat, _ cp2x: CGFloat, _ cp2y: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addQuadCurve(to:control:)") public func CGContextAddQuadCurveToPoint(_ c: CGContext?, _ cpx: CGFloat, _ cpy: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addRects(_:)") public func CGContextAddRects(_ c: CGContext?, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addLines(between:)") public func CGContextAddLines(_ c: CGContext?, _ points: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addArc(center:radius:startAngle:endAngle:clockwise:)") public func CGContextAddArc(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat, _ radius: CGFloat, _ startAngle: CGFloat, _ endAngle: CGFloat, _ clockwise: Int32) { fatalError() } @available(*, unavailable, message:"Use addArc(self:x1:y1:x2:y2:radius:)") public func CGContextAddArcToPoint(_ c: CGContext?, _ x1: CGFloat, _ y1: CGFloat, _ x2: CGFloat, _ y2: CGFloat, _ radius: CGFloat) { fatalError() } @available(*, unavailable, message:"Use fill(self:_:count:)") public func CGContextFillRects(_ c: CGContext?, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use strokeLineSegments(self:between:count:)") public func CGContextStrokeLineSegments(_ c: CGContext?, _ points: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use clip(to:)") public func CGContextClipToRects(_ c: CGContext?, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use draw(_:in:)") public func CGContextDrawImage(_ c: CGContext?, _ rect: CGRect, _ image: CGImage?) { fatalError() } @available(*, unavailable, message:"Use draw(_:in:byTiling:)") public func CGContextDrawTiledImage(_ c: CGContext?, _ rect: CGRect, _ image: CGImage?) { fatalError() } @available(*, unavailable, renamed:"getter:CGContext.textPosition(self:)") public func CGContextGetTextPosition(_ c: CGContext?) -> CGPoint { fatalError() } @available(*, unavailable, message:"Use var textPosition") public func CGContextSetTextPosition(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use showGlyphs(_:at:)") public func CGContextShowGlyphsAtPositions(_ c: CGContext?, _ glyphs: UnsafePointer<CGGlyph>, _ Lpositions: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, renamed:"CGContext.fillPath(self:)") public func CGContextFillPath(_ c: CGContext?) { fatalError() } @available(*, unavailable, message:"Use fillPath(using:)") public func CGContextEOFillPath(_ c: CGContext?) { fatalError() } @available(*, unavailable, renamed:"CGContext.clip(self:)") public func CGContextClip(_ c: CGContext?) { fatalError() } @available(*, unavailable, message:"Use clip(using:)") public func CGContextEOClip(_ c: CGContext?) { fatalError() } @available(*, unavailable, renamed:"CGGetLastMouseDelta") // different type public func CGGetLastMouseDelta(_ deltaX: UnsafeMutablePointer<Int32>?, _ deltaY: UnsafeMutablePointer<Int32>?) { fatalError() } @available(*, unavailable, message:"Use divided(atDistance:from:)") public func CGRectDivide(_ rect: CGRect, _ slice: UnsafeMutablePointer<CGRect>, _ remainder: UnsafeMutablePointer<CGRect>, _ amount: CGFloat, _ edge: CGRectEdge) { fatalError() } @available(*, unavailable, message:"Use CGPoint.init(dictionaryRepresentation:)") public func CGPointMakeWithDictionaryRepresentation(_ dict: CFDictionary?, _ point: UnsafeMutablePointer<CGPoint>) -> Bool { fatalError() } @available(*, unavailable, message:"Use CGSize.init(dictionaryRepresentation:)") public func CGSizeMakeWithDictionaryRepresentation(_ dict: CFDictionary?, _ size: UnsafeMutablePointer<CGSize>) -> Bool { fatalError() } @available(*, unavailable, message:"Use CGRect.init(dictionaryRepresentation:)") public func CGRectMakeWithDictionaryRepresentation(_ dict: CFDictionary?, _ rect: UnsafeMutablePointer<CGRect>) -> Bool { fatalError() } @available(*, unavailable, renamed:"CGImage.copy(self:maskingColorComponents:)") public func CGImageCreateWithMaskingColors(_ image: CGImage?, _ components: UnsafePointer<CGFloat>) -> CGImage? { fatalError() } @available(*, unavailable, message:"Use draw(_:in:)") public func CGContextDrawLayerInRect(_ context: CGContext?, _ rect: CGRect, _ layer: CGLayer?) { fatalError() } @available(*, unavailable, message:"Use draw(_:at:)") public func CGContextDrawLayerAtPoint(_ context: CGContext?, _ point: CGPoint, _ layer: CGLayer?) { fatalError() } @available(*, unavailable, message:"Use copy(byDashingWithPhase:lengths:transform:)") public func CGPathCreateCopyByDashingPath(_ path: CGPath?, _ transform: UnsafePointer<CGAffineTransform>, _ phase: CGFloat, _ lengths: UnsafePointer<CGFloat>, _ count: Int) -> CGPath? { fatalError() } @available(*, unavailable, message:"Use copy(byStroking:lineWidth:lineCap:lineJoin:miterLimit:transform:)") public func CGPathCreateCopyByStrokingPath(_ path: CGPath?, _ transform: UnsafePointer<CGAffineTransform>, _ lineWidth: CGFloat, _ lineCap: CGLineCap, _ lineJoin: CGLineJoin, _ miterLimit: CGFloat) -> CGPath? { fatalError() } @available(*, unavailable, message:"Use == instead") public func CGPathEqualToPath(_ path1: CGPath?, _ path2: CGPath?) -> Bool { fatalError() } @available(*, unavailable, message:"Use move(to:transform:)") public func CGPathMoveToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addLine(to:transform:)") public func CGPathAddLineToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addCurve(to:control1:control2:transform:)") public func CGPathAddCurveToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ cp1x: CGFloat, _ cp1y: CGFloat, _ cp2x: CGFloat, _ cp2y: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addQuadCurve(to:control:transform:)") public func CGPathAddQuadCurveToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ cpx: CGFloat, _ cpy: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addRect(_:transform:)") public func CGPathAddRect(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ rect: CGRect) { fatalError() } @available(*, unavailable, message:"Use addRects(_:transform:)") public func CGPathAddRects(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addLines(between:transform:)") public func CGPathAddLines(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ points: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addEllipse(rect:transform:)") public func CGPathAddEllipseInRect(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ rect: CGRect) { fatalError() } @available(*, unavailable, message:"Use addRelativeArc(center:radius:startAngle:delta:transform:)") public func CGPathAddRelativeArc(_ path: CGMutablePath?, _ matrix: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat, _ radius: CGFloat, _ startAngle: CGFloat, _ delta: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addArc(center:radius:startAngle:endAngle:clockwise:transform:)") public func CGPathAddArc(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat, _ radius: CGFloat, _ startAngle: CGFloat, _ endAngle: CGFloat, _ clockwise: Bool) { fatalError() } @available(*, unavailable, message:"Use addArc(tangent1End:tangent2End:radius:transform:)") public func CGPathAddArcToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x1: CGFloat, _ y1: CGFloat, _ x2: CGFloat, _ y2: CGFloat, _ radius: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addPath(_:transform:)") public func CGPathAddPath(_ path1: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ path2: CGPath?) { fatalError() } @available(*, unavailable, message:"Use CGColor.white") // retyped public var kCGColorWhite: CFString { fatalError() } @available(*, unavailable, message:"Use CGColor.black") // retyped public var kCGColorBlack: CFString { fatalError() } @available(*, unavailable, message:"Use CGColor.clear") // retyped public var kCGColorClear: CFString { fatalError() } // TODO: also add migration support from previous Swift3 betas?
apache-2.0
zhha/RPiProjects-iOS
RPiProject/DHT11ViewController.swift
1
878
// // DHT11ViewController.swift // RPiProject // // Created by wonderworld on 16/8/25. // Copyright © 2016年 haozhang. All rights reserved. // import UIKit class DHT11ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
tqtifnypmb/SwiftyImage
Framenderer/Sources/Filters/Color/ExplosureAdjust/ExplosureAdjustFilter.swift
2
806
// // ExplosureAdjustFilter.swift // Framenderer // // Created by tqtifnypmb on 15/12/2016. // Copyright © 2016 tqitfnypmb. All rights reserved. // import Foundation import OpenGLES.ES3.gl import OpenGLES.ES3.glext public class ExplosureAdjustFilter: BaseFilter { public init(value: Float = 0.25) { _ev = GLfloat(value) } private let _ev: GLfloat override func buildProgram() throws { _program = try Program.create(fragmentSourcePath: "ExplosureAdjustFragmentShader") } override func setUniformAttributs(context: Context) { super.setUniformAttributs(context: context) _program.setUniform(name: "ev", value: pow(2.0, _ev)) } override public var name: String { return "ExplosureAdjustFilter" } }
mit
iossocket/DBDemo
DBDemo/DetailViewController.swift
1
1125
// // DetailViewController.swift // DBDemo // // Created by Jianing Zheng on 12/27/16. // Copyright © 2016 ThoughtWorks. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! let bookDataService: BookDataService = RealmBookDataService(transform: RealmBookToBookTransform()) var bookDetailViewModel: BookDetailViewModel! override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { title = "Book Detail" nameLabel.text = bookDetailViewModel.name() authorLabel.text = bookDetailViewModel.author() statusLabel.text = bookDetailViewModel.status() } @IBAction func changeStatus(_ sender: Any) { bookDataService.changeBookStatus(bookDetailViewModel.bookID()) { [weak self] book in if let strongSelf = self { strongSelf.statusLabel.text = book.displayedStatus } } } }
mit
MrZoidberg/metapp
metapp/metapp/PeekPhotoViewController.swift
1
271
// // PeekPhotoViewController.swift // metapp // // Created by Mykhaylo Merkulov on 11/2/16. // Copyright © 2016 ZoidSoft. All rights reserved. // import Foundation import UIKit final class PeekPhotoViewController: UIViewController { var viewModel: MAPhoto? }
mpl-2.0
krevis/MIDIApps
Frameworks/SnoizeMIDI/VirtualInputStream.swift
1
3911
/* Copyright (c) 2001-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Foundation public class VirtualInputStream: InputStream { public override init(midiContext: MIDIContext) { virtualEndpointName = midiContext.name uniqueID = 0 // Let CoreMIDI assign a unique ID to the virtual endpoint when it is created singleSource = SingleInputStreamSource(name: virtualEndpointName) super.init(midiContext: midiContext) } deinit { isActive = false } public var uniqueID: MIDIUniqueID { didSet { if uniqueID != oldValue, let endpoint = endpoint { endpoint.uniqueID = uniqueID // that may or may not have worked uniqueID = endpoint.uniqueID } } } public var virtualEndpointName: String { didSet { if virtualEndpointName != oldValue { endpoint?.name = virtualEndpointName } } } public func setInputSourceName(_ name: String) { singleSource.name = name } public private(set) var endpoint: Destination? // MARK: InputStream subclass public override var parsers: [MessageParser] { if let parser = parser { return [parser] } else { return [] } } public override func parser(sourceConnectionRefCon refCon: UnsafeMutableRawPointer?) -> MessageParser? { // refCon is ignored, since it only applies to connections created with MIDIPortConnectSource() parser } public override func streamSource(parser: MessageParser) -> InputStreamSource? { singleSource.asInputStreamSource } public override var inputSources: [InputStreamSource] { [singleSource.asInputStreamSource] } public override var selectedInputSources: Set<InputStreamSource> { get { isActive ? [singleSource.asInputStreamSource] : [] } set { isActive = newValue.contains(singleSource.asInputStreamSource) } } // MARK: InputStream overrides public override var persistentSettings: Any? { isActive ? ["uniqueID": uniqueID] : nil } public override func takePersistentSettings(_ settings: Any) -> [String] { if let settings = settings as? [String: Any], let settingsUniqueID = settings["uniqueID"] as? MIDIUniqueID { uniqueID = settingsUniqueID isActive = true } else { isActive = false } return [] } // MARK: Private private let singleSource: SingleInputStreamSource private var parser: MessageParser? private var isActive: Bool { get { endpoint != nil } set { if newValue && endpoint == nil { createEndpoint() } else if !newValue && endpoint != nil { disposeEndpoint() } } } private func createEndpoint() { endpoint = midiContext.createVirtualDestination(name: virtualEndpointName, uniqueID: uniqueID, midiReadBlock: midiReadBlock) if let endpoint = endpoint { if parser == nil { parser = createParser(originatingEndpoint: endpoint) } else { parser!.originatingEndpoint = endpoint } // We requested a specific uniqueID, but we might not have gotten it. // Update our copy of it from the actual value in CoreMIDI. uniqueID = endpoint.uniqueID } } private func disposeEndpoint() { endpoint?.remove() endpoint = nil parser?.originatingEndpoint = nil } }
bsd-3-clause
wikimedia/wikipedia-ios
Wikipedia/Code/PreviewWebViewContainer.swift
1
1723
import Foundation import WebKit import WMF @objc protocol WMFPreviewAnchorTapAlertDelegate: AnyObject { func previewWebViewContainer(_ previewWebViewContainer: PreviewWebViewContainer, didTapLink url: URL) } class PreviewWebViewContainer: UIView, WKNavigationDelegate, Themeable { var theme: Theme = .standard @IBOutlet weak var previewAnchorTapAlertDelegate: WMFPreviewAnchorTapAlertDelegate! lazy var webView: WKWebView = { let controller = WKUserContentController() var earlyJSTransforms = "" let configuration = WKWebViewConfiguration() configuration.userContentController = controller configuration.applicationNameForUserAgent = "WikipediaApp" let newWebView = WKWebView(frame: CGRect.zero, configuration: configuration) newWebView.isOpaque = false newWebView.scrollView.backgroundColor = .clear wmf_addSubviewWithConstraintsToEdges(newWebView) newWebView.navigationDelegate = self return newWebView }() func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url, navigationAction.navigationType == .linkActivated else { decisionHandler(WKNavigationActionPolicy.allow) return } previewAnchorTapAlertDelegate.previewWebViewContainer(self, didTapLink: url) decisionHandler(WKNavigationActionPolicy.cancel) } func apply(theme: Theme) { self.theme = theme webView.backgroundColor = theme.colors.paperBackground backgroundColor = theme.colors.paperBackground } }
mit
mleiv/MEGameTracker
MEGameTracker/Models/CoreData/Game Rows/GameMaps.swift
1
7403
// // GameMaps.swift // MEGameTracker // // Created by Emily Ivie on 9/22/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import Foundation import CoreData extension Map: GameRowStorable { /// (CodableCoreDataStorable Protocol) /// Type of the core data entity. public typealias EntityType = GameMaps /// (GameRowStorable Protocol) /// Corresponding data entity for this game entity. public typealias DataRowType = DataMap /// (CodableCoreDataStorable Protocol) /// Sets core data values to match struct values (specific). public func setAdditionalColumnsOnSave( coreItem: EntityType ) { // only save searchable columns setDateModifiableColumnsOnSave(coreItem: coreItem) //TODO coreItem.id = id coreItem.gameSequenceUuid = gameSequenceUuid?.uuidString coreItem.isExplored = Map.gameValuesForIsExplored(isExploredPerGameVersion: isExploredPerGameVersion) coreItem.isSavedToCloud = isSavedToCloud ? 1 : 0 coreItem.dataParent = generalData.entity(context: coreItem.managedObjectContext) } /// (GameRowStorable X Eventsable Protocol) /// Create a new game entity value for the game uuid given using the data value given. public static func create( using data: DataRowType, with manager: CodableCoreDataManageable? ) -> Map { var item = Map(id: data.id, generalData: data) item.events = item.getEvents(gameSequenceUuid: item.gameSequenceUuid, with: manager) return item } /// (GameRowStorable Protocol) public mutating func migrateId(id newId: String) { id = newId generalData.migrateId(id: newId) } } extension Map { /// The closure type for editing fetch requests. /// (Duplicate these per file or use Whole Module Optimization, which is slow in dev) public typealias AlterFetchRequest<T: NSManagedObject> = ((NSFetchRequest<T>) -> Void) /// (OVERRIDE) /// Return all matching game values made from the data values. public static func getAllFromData( gameSequenceUuid: UUID?, with manager: CodableCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<DataRowType.EntityType> ) -> [Map] { let manager = manager ?? defaultManager let dataItems = DataRowType.getAll(gameVersion: nil, with: manager, alterFetchRequest: alterFetchRequest) let some: [Map] = dataItems.map { (dataItem: DataRowType) -> Map? in Map.getOrCreate(using: dataItem, gameSequenceUuid: gameSequenceUuid, with: manager) }.filter({ $0 != nil }).map({ $0! }) return some } // MARK: Methods customized with GameVersion /// Get a map by id and set it to specified game version. public static func get( id: String, gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> Map? { return getFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K == %@)", "id", id ) } } /// Get a map and set it to specified game version. public static func getFromData( gameVersion: GameVersion?, with manager: CodableCoreDataManageable? = nil, alterFetchRequest: @escaping AlterFetchRequest<DataRowType.EntityType> ) -> Map? { return getAllFromData(gameVersion: gameVersion, with: manager, alterFetchRequest: alterFetchRequest).first } /// Get a set of maps with the specified ids and set them to specified game version. public static func getAll( ids: [String], gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K in %@)", "id", ids ) } } /// Get a set of maps and set them to specified game version. public static func getAllFromData( gameVersion: GameVersion?, with manager: CodableCoreDataManageable? = nil, alterFetchRequest: @escaping AlterFetchRequest<DataRowType.EntityType> ) -> [Map] { let manager = manager ?? defaultManager let dataItems = DataRowType.getAll(gameVersion: gameVersion, with: manager, alterFetchRequest: alterFetchRequest) let some: [Map] = dataItems.map { (dataItem: DataRowType) -> Map? in Map.getOrCreate(using: dataItem, with: manager) }.filter({ $0 != nil }).map({ $0! }) return some } // MARK: Additional Convenience Methods /// Get all maps from the specified game version. public static func getAll( gameVersion: GameVersion, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { _ in } } /// Get all child maps of the specified map. public static func getAll( inMapId mapId: String, gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K == %@)", #keyPath(DataMaps.inMapId), mapId ) } } /// Get all main maps. public static func getAllMain( gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K == true)", #keyPath(DataMaps.isMain) ) } } /// Get all recently viewed maps. public static func getAllRecent( gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { var maps: [Map] = [] App.current.recentlyViewedMaps.contents.forEach { if var map = Map.get(id: $0.id, gameVersion: gameVersion, with: manager) { map.modifiedDate = $0.date // hijack for date - won't be saved anyway maps.append(map) } } return maps } /// Copy all the matching game values to a new GameSequence UUID. public static func copyAll( in gameVersions: [GameVersion], sourceUuid: UUID, destinationUuid: UUID, with manager: CodableCoreDataManageable? ) -> Bool { return copyAll(with: manager, alterFetchRequest: { fetchRequest in fetchRequest.predicate = NSPredicate( format: "gameSequenceUuid == %@", sourceUuid.uuidString) }, setChangedValues: { coreItem in coreItem.setValue(destinationUuid.uuidString, forKey: "gameSequenceUuid") var isExploredPerGameVersion = Map.gameValuesFromIsExplored(gameValues: coreItem.isExplored ?? "") for (gameVersion, _) in isExploredPerGameVersion { if !gameVersions.contains(gameVersion) { isExploredPerGameVersion[gameVersion] = false } } coreItem.isExplored = Map.gameValuesForIsExplored(isExploredPerGameVersion: isExploredPerGameVersion) if let data = coreItem.value(forKey: Map.serializedDataKey) as? Data, var json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { json["isExplored"] = coreItem.isExplored json["gameSequenceUuid"] = coreItem.gameSequenceUuid if let data2 = try? JSONSerialization.data(withJSONObject: json) { coreItem.setValue(data2, forKey: serializedDataKey) } } }) } }
mit
6ag/BaoKanIOS
BaoKanIOS/Classes/Module/News/Model/JFShareItemModel.swift
1
2228
// // JFShareItemModel.swift // WindSpeedVPN // // Created by zhoujianfeng on 2016/11/30. // Copyright © 2016年 zhoujianfeng. All rights reserved. // import UIKit enum JFShareType: Int { case qqFriend = 0 // qq好友 case qqQzone = 1 // qq空间 case weixinFriend = 2 // 微信好友 case friendCircle = 3 // 朋友圈 } class JFShareItemModel: NSObject { /// 名称 var title: String? /// 图标 var icon: String? /// 类型 var type: JFShareType = .qqFriend init(dict: [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} /// 加载分享item class func loadShareItems() -> [JFShareItemModel] { var shareItems = [JFShareItemModel]() // QQ if QQApiInterface.isQQInstalled() && QQApiInterface.isQQSupportApi() { let shareItemQQFriend = JFShareItemModel(dict: [ "title" : "QQ", "icon" : "share_qq" ]) shareItemQQFriend.type = JFShareType.qqFriend shareItems.append(shareItemQQFriend) let shareItemQQQzone = JFShareItemModel(dict: [ "title" : "QQ空间", "icon" : "share_qqkj" ]) shareItemQQFriend.type = JFShareType.qqQzone shareItems.append(shareItemQQQzone) } // 微信 if WXApi.isWXAppInstalled() && WXApi.isWXAppSupport() { let shareItemWeixinFriend = JFShareItemModel(dict: [ "title" : "微信好友", "icon" : "share_wechat" ]) shareItemWeixinFriend.type = JFShareType.weixinFriend shareItems.append(shareItemWeixinFriend) let shareItemFriendCircle = JFShareItemModel(dict: [ "title" : "朋友圈", "icon" : "share_friend" ]) shareItemFriendCircle.type = JFShareType.friendCircle shareItems.append(shareItemFriendCircle) } return shareItems } }
apache-2.0
sersoft-gmbh/XMLWrangler
Package.swift
1
989
// swift-tools-version:5.4 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "xmlwrangler", products: [ .library(name: "XMLWrangler", targets: ["XMLWrangler"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/sersoft-gmbh/semver.git", from: "3.1.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "XMLWrangler", dependencies: [ .product(name: "SemVer", package: "semver"), ]), .testTarget( name: "XMLWranglerTests", dependencies: ["XMLWrangler"]), ] )
apache-2.0
guipanizzon/ioscreator
IOS8SwiftActionsTableViewTutorial/IOS8SwiftActionsTableViewTutorialTests/IOS8SwiftActionsTableViewTutorialTests.swift
40
985
// // IOS8SwiftActionsTableViewTutorialTests.swift // IOS8SwiftActionsTableViewTutorialTests // // Created by Arthur Knopper on 18/11/14. // Copyright (c) 2014 Arthur Knopper. All rights reserved. // import UIKit import XCTest class IOS8SwiftActionsTableViewTutorialTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
P0ed/FireTek
Source/SpaceEngine/Components/UnitComponents.swift
1
1216
import Fx import PowerCore import SpriteKit struct ShipComponent { let sprite: ComponentIdx<SpriteComponent> let physics: ComponentIdx<PhysicsComponent> let hp: ComponentIdx<HPComponent> let input: ComponentIdx<ShipInputComponent> let stats: ComponentIdx<ShipStats> let primaryWpn: ComponentIdx<WeaponComponent> let secondaryWpn: ComponentIdx<WeaponComponent> } struct ShipStats { let speed: Float } struct TowerComponent { let sprite: ComponentIdx<SpriteComponent> let hp: ComponentIdx<HPComponent> let input: ComponentIdx<TowerInputComponent> } struct BuildingComponent { let sprite: ComponentIdx<SpriteComponent> let hp: ComponentIdx<HPComponent> } struct TargetComponent { var target: Entity? static let none = TargetComponent(target: nil) } enum Team { case blue case red } enum Crystal { case blue, red, purple, cyan, yellow, green, orange } struct CrystalComponent { let crystal: Crystal } struct LootComponent { let crystal: Crystal let count: Int8 } struct OwnerComponent { let entity: Entity } struct DeadComponent { let killedBy: Entity } struct MapItem { enum ItemType { case star case planet case ally case enemy } let type: ItemType let node: SKNode }
mit
NeoXant/rpn-swift
Tests/ConverterTests.swift
1
1190
// ConverterTests.swift // Convert infix notation to Reverse Polish Notation! // // Licensed under MIT License. See LICENSE for more info. // Copyright (c) 2017, Michał "NeoXant" Kolarczyk. import Cocoa import XCTest class ConverterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSimple() { let rpn = RPN(["23", "-", "5"]) XCTAssertEqual(rpn.rpnString, "23 5 -", "") } func testComplex() { let rpn = RPN(["(","(","5","-","2",")","^","(","3","+","1",")","/","(", "2","+","1",")","+","12",")","*","21"]) XCTAssertEqual(rpn.rpnString, "5 2 - 3 1 + ^ 2 1 + / 12 + 21 *", "") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
tonystone/geofeatures2
Sources/GeoFeatures/Precision.swift
1
1681
/// /// Precision.swift /// /// Copyright (c) 2016 Tony Stone /// /// 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. /// /// Created by Tony Stone on 2/11/2016. /// import Swift /// /// The precision model used for all `Geometry` types. /// public protocol Precision { /// /// Convert a double into `self` precision. /// /// - Returns: A double converted to `self` precision. /// func convert(_ value: Double) -> Double /// /// Convert an optional double into `self` precision. /// /// - Returns: A double converted to `self` precision if a value was passed, or nil otherwise. /// func convert(_ value: Double?) -> Double? /// /// Convert a Coordinate into `self` precision. /// /// - Returns: A Coordinate converted to `self` precision. /// func convert(_ coordinate: Coordinate) -> Coordinate } /// /// Compares to precision types for equality when both are Hashable. /// public func == <T1: Precision & Hashable, T2: Precision & Hashable>(lhs: T1, rhs: T2) -> Bool { if type(of: lhs) == type(of: rhs) { return lhs.hashValue == rhs.hashValue } return false }
apache-2.0
jigneshsheth/Datastructures
DataStructure/DataStructure/LongestSubstring.swift
1
1414
// // LongestSubstring.swift // DataStructure // // Created by Jigs Sheth on 11/2/21. // Copyright © 2021 jigneshsheth.com. All rights reserved. // /** Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Example 4: Input: s = "" Output: 0 Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces. **/ import Foundation class LongestSubstring { public static func lengthOfLongestSubstring(_ s: String) -> Int { var start = 0 var end = start+1 var counter = 0 var dict = [Character:Bool]() let charArray = Array(s) while start < charArray.count { dict[charArray[start]] = true while end < charArray.count { if dict[charArray[end]] != nil { break }else { dict[charArray[end]] = true end += 1 } } counter = max(dict.count,counter) dict.removeAll() start = start + 1 end = start + 1 } return counter } }
mit
matrix-org/matrix-ios-sdk
MatrixSDK/VoIP/MXiOSAudioOutputRouteType.swift
1
1478
// // Copyright 2021 The Matrix.org Foundation C.I.C // // 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 /// Audio output route type @objc public enum MXiOSAudioOutputRouteType: Int { /// the speakers at the top of the screen. case builtIn /// the speakers at the bottom of the phone case loudSpeakers /// external wired headphones case externalWired /// external Bluetooth device case externalBluetooth /// external CarPlay device case externalCar } extension MXiOSAudioOutputRouteType: CustomStringConvertible { public var description: String { switch self { case .builtIn: return "builtIn" case .loudSpeakers: return "loudSpeakers" case .externalWired: return "externalWired" case .externalBluetooth: return "externalBluetooth" case .externalCar: return "externalCar" } } }
apache-2.0
ministrycentered/onepassword-app-extension
Demos/App Demo for iOS Swift/App Demo for iOS Swift/AppDelegate.swift
2
2189
// // AppDelegate.swift // App Demo for iOS Swift // // Created by Rad Azzouz on 2015-05-14. // Copyright (c) 2015 Agilebits. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. } }
mit
jarocht/iOS-AlarmDJ
AlarmDJ/AlarmDJ/SettingsTableViewController.swift
1
4091
// // SettingsTableViewController.swift // AlarmDJ // // Created by X Code User on 7/22/15. // Copyright (c) 2015 Tim Jaroch, Morgan Heyboer, Andreas Plüss (TEAM E). All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var snoozeTimeTextField: UITextField! @IBOutlet weak var zipcodeTextField: UITextField! @IBOutlet weak var twentyFourHourSwitch: UISwitch! @IBOutlet weak var newsQueryTextField: UITextField! @IBOutlet weak var musicGenreDataPicker: UIPickerView! let ldm = LocalDataManager() var settings = SettingsContainer() var genres: [String] = ["Alternative","Blues","Country","Dance","Electronic","Hip-Hop/Rap","Jazz","Klassik","Pop","Rock", "Soundtracks"] override func viewDidLoad() { super.viewDidLoad() snoozeTimeTextField.delegate = self snoozeTimeTextField.tag = 0 zipcodeTextField.delegate = self zipcodeTextField.tag = 1 newsQueryTextField.delegate = self newsQueryTextField.tag = 2 musicGenreDataPicker.dataSource = self musicGenreDataPicker.delegate = self } override func viewWillAppear(animated: Bool) { settings = ldm.loadSettings() snoozeTimeTextField.text! = "\(settings.snoozeInterval)" zipcodeTextField.text! = settings.weatherZip twentyFourHourSwitch.on = settings.twentyFourHour newsQueryTextField.text! = settings.newsQuery var index = 0 for var i = 0; i < genres.count; i++ { if genres[i] == settings.musicGenre{ index = i } } musicGenreDataPicker.selectRow(index, inComponent: 0, animated: true) } override func viewWillDisappear(animated: Bool) { if count(zipcodeTextField.text!) == 5 { settings.weatherZip = zipcodeTextField.text! } if count(snoozeTimeTextField.text!) > 0 { var timeVal: Int = (snoozeTimeTextField.text!).toInt()! if timeVal > 0 { settings.snoozeInterval = timeVal //ldm.saveSettings(settingsContainer: settings) } } if count (newsQueryTextField.text!) > 0 { settings.newsQuery = newsQueryTextField.text! } ldm.saveSettings(settingsContainer: settings) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func twentyFourHourSwitchClicked(sender: AnyObject) { settings.twentyFourHour = twentyFourHourSwitch.on } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if textField.tag < 2 { if count(textField.text!) + count(string) <= 5 { return true; } return false } else { if count(textField.text!) + count(string) <= 25 { return true; } return false } } func textFieldDidBeginEditing(textField: UITextField) { } func textFieldShouldEndEditing(textField: UITextField) -> Bool { return true } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return genres.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return genres[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { settings.musicGenre = genres[row] } }
mit
johnsextro/cycschedule
cycschedule/SelectionViewController.swift
1
2664
import Foundation import UIKit class SelectionViewController: UITableViewController { var TableData:Array< String > = Array < String >() var lastSelectedIndexPath: NSIndexPath? override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return TableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell cell.accessoryType = .None cell.textLabel?.text = TableData[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.row != lastSelectedIndexPath?.row { if let lastSelectedIndexPath = lastSelectedIndexPath{ let oldCell = tableView.cellForRowAtIndexPath(lastSelectedIndexPath) oldCell?.accessoryType = .None } let newCell = tableView.cellForRowAtIndexPath(indexPath) newCell?.accessoryType = .Checkmark lastSelectedIndexPath = indexPath self.navigationItem.rightBarButtonItem?.enabled = true } } func extract_json(data:NSString) { var parseError: NSError? let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)! let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError) if (parseError == nil) { if let seasons_obj = json as? NSDictionary { if let seasons = seasons_obj["seasons"] as? NSArray { for (var i = 0; i < seasons.count ; i++ ) { if let season_obj = seasons[i] as? NSDictionary { if let season = season_obj["season"] as? String { TableData.append(season) } } } } } } do_table_refresh(); } func do_table_refresh() { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() return }) } }
gpl-2.0
jamfprofessionalservices/JamfMigrator
jamf-migrator/PrefsWindowController.swift
1
450
// // PrefsWindowController.swift // jamf-migrator // // Created by Leslie Helou on 11/25/18. // Copyright © 2018 jamf. All rights reserved. // import Cocoa class PrefsWindowController: NSWindowController, NSWindowDelegate { override func windowDidLoad() { super.windowDidLoad() } func windowShouldClose(_ sender: NSWindow) -> Bool { self.window?.orderOut(sender) return false } }
mit
alphatroya/hhkl-ios
HHKL/Classes/Business/Factories/ViewControllerFactory.swift
1
1564
// // Created by Alexey Korolev on 29.01.16. // Copyright (c) 2016 Heads and Hands. All rights reserved. // import Foundation enum ViewControllerType { case MatchesViewController case MatchViewController(match: Match) } protocol ViewControllerFactoryProtocol { func instantiateViewControllerWith(type: ViewControllerType, flowController: FlowControllerProtocol) -> ParentViewController } class ViewControllerFactory: ViewControllerFactoryProtocol { let accessoryFactory: ViewControllerAccessoryFactoryProtocol let viewModelFactory: ViewModelFactoryProtocol init(accessoryFactory: ViewControllerAccessoryFactoryProtocol, viewModelFactory: ViewModelFactoryProtocol) { self.accessoryFactory = accessoryFactory self.viewModelFactory = viewModelFactory } func instantiateViewControllerWith(type: ViewControllerType, flowController: FlowControllerProtocol) -> ParentViewController { switch type { case .MatchesViewController: return matchesViewController(viewModelFactory.matchesViewModel(flowController)) case .MatchViewController(let match): return matchViewController(viewModelFactory.matchViewModel(flowController, match: match)) } } func matchesViewController(viewModel: MatchesViewModelProtocol) -> ParentViewController { return MatchesViewController(viewModel: viewModel) } func matchViewController(viewModel: MatchViewModelProtocol) -> ParentViewController { return MatchViewController(viewModel: viewModel) } }
mit
toggl/superday
teferi/UI/Modules/Daily Summary/SummaryPageViewModel.swift
1
1910
import Foundation import RxSwift class SummaryPageViewModel { private var selectedDate = Variable<Date>(Date()) var currentlySelectedDate : Date { get { return self.selectedDate.value.ignoreTimeComponents() } set(value) { self.selectedDate.value = value self.canMoveForwardSubject.onNext(canScroll(toDate: selectedDate.value.add(days: 1))) self.canMoveBackwardSubject.onNext(canScroll(toDate: selectedDate.value.add(days: -1))) } } private let canMoveForwardSubject = PublishSubject<Bool>() private(set) lazy var canMoveForwardObservable : Observable<Bool> = { return self.canMoveForwardSubject.asObservable() }() private let canMoveBackwardSubject = PublishSubject<Bool>() private(set) lazy var canMoveBackwardObservable : Observable<Bool> = { return self.canMoveBackwardSubject.asObservable() }() private let settingsService: SettingsService private let timeService: TimeService var dateObservable : Observable<String> { return selectedDate .asObservable() .map { let dateformater = DateFormatter() dateformater.dateFormat = "EEE, dd MMM" return dateformater.string(from: $0) } } init(date: Date, timeService: TimeService, settingsService: SettingsService) { selectedDate.value = date self.settingsService = settingsService self.timeService = timeService } func canScroll(toDate date: Date) -> Bool { let minDate = settingsService.installDate!.ignoreTimeComponents() let maxDate = timeService.now.ignoreTimeComponents() let dateWithNoTime = date.ignoreTimeComponents() return dateWithNoTime >= minDate && dateWithNoTime <= maxDate } }
bsd-3-clause
crescentflare/ViewletCreator
ViewletCreatorIOS/Example/ViewletCreator/Viewlets/UITextFieldViewlet.swift
1
2257
// // UITextFieldViewlet.swift // Viewlet creator example // // Create a simple text input field // import UIKit import ViewletCreator class UITextFieldViewlet: Viewlet { func create() -> UIView { return UITextField() } func update(view: UIView, attributes: [String: Any], parent: UIView?, binder: ViewletBinder?) -> Bool { if let textField = view as? UITextField { // Prefilled text and placeholder textField.text = ViewletConvUtil.asString(value: attributes["text"]) textField.placeholder = NSLocalizedString(ViewletConvUtil.asString(value: attributes["placeholder"]) ?? "", comment: "") // Set keyboard mode textField.keyboardType = .default textField.autocapitalizationType = .sentences if let keyboardType = ViewletConvUtil.asString(value: attributes["keyboardType"]) { if keyboardType == "email" { textField.keyboardType = .emailAddress textField.autocapitalizationType = .none } else if keyboardType == "url" { textField.keyboardType = .URL textField.autocapitalizationType = .none } } // Text style let fontSize = ViewletConvUtil.asDimension(value: attributes["textSize"]) ?? 17 if let font = ViewletConvUtil.asString(value: attributes["font"]) { if font == "bold" { textField.font = UIFont.boldSystemFont(ofSize: fontSize) } else if font == "italics" { textField.font = UIFont.italicSystemFont(ofSize: fontSize) } else { textField.font = UIFont(name: font, size: fontSize) } } else { textField.font = UIFont.systemFont(ofSize: fontSize) } // Standard view attributes UIViewViewlet.applyDefaultAttributes(view: view, attributes: attributes) return true } return false } func canRecycle(view: UIView, attributes: [String : Any]) -> Bool { return view is UITextField } }
mit
devpunk/cartesian
cartesian/Model/DrawProject/Menu/Text/MDrawProjectMenuTextItemSize.swift
1
1393
import UIKit class MDrawProjectMenuTextItemSize:MDrawProjectMenuTextItem, MDrawProjectFontSizeDelegate { private weak var controller:CDrawProject? init() { let title:String = NSLocalizedString("MDrawProjectMenuTextItemSize_title", comment:"") super.init( title:title, image:#imageLiteral(resourceName: "assetGenericFontSize")) } override func selected(controller:CDrawProject) { self.controller = controller controller.modelState.stateStand(controller:controller) controller.viewProject.viewMenu.viewBar.modeNormal() controller.viewProject.showFontSize(delegate:self) } //MARK: fontSize delegate func fontSizeSelected(size:Int16) { let modelLabel:DLabel? = controller?.editingView?.viewSpatial.model as? DLabel controller?.endText() modelLabel?.fontSize = size modelLabel?.updateGenerated() DManager.sharedInstance?.save() modelLabel?.notifyDraw() } func fontCurrentSize() -> Int16? { guard let modelLabel:DLabel = controller?.editingView?.viewSpatial.model as? DLabel else { return nil } let currentSize:Int16 = modelLabel.fontSize return currentSize } }
mit
xeo-it/poggy
Pods/Eureka/Source/Core/HeaderFooterView.swift
2
5324
// HeaderFooterView.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.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 /** Enumeration used to generate views for the header and footer of a section. - Class: Will generate a view of the specified class. - Callback->ViewType: Will generate the view as a result of the given closure. - NibFile: Will load the view from a nib file. */ public enum HeaderFooterProvider<ViewType: UIView> { /** * Will generate a view of the specified class. */ case Class /** * Will generate the view as a result of the given closure. */ case Callback(()->ViewType) /** * Will load the view from a nib file. */ case NibFile(name: String, bundle: NSBundle?) internal func createView() -> ViewType { switch self { case .Class: return ViewType() case .Callback(let builder): return builder() case .NibFile(let nibName, let bundle): return (bundle ?? NSBundle(forClass: ViewType.self)).loadNibNamed(nibName, owner: nil, options: nil)![0] as! ViewType } } } /** * Represents headers and footers of sections */ public enum HeaderFooterType { case Header, Footer } /** * Struct used to generate headers and footers either from a view or a String. */ public struct HeaderFooterView<ViewType: UIView> : StringLiteralConvertible, HeaderFooterViewRepresentable { /// Holds the title of the view if it was set up with a String. public var title: String? /// Generates the view. public var viewProvider: HeaderFooterProvider<ViewType>? /// Closure called when the view is created. Useful to customize its appearance. public var onSetupView: ((view: ViewType, section: Section) -> ())? /// A closure that returns the height for the header or footer view. public var height: (()->CGFloat)? /** This method can be called to get the view corresponding to the header or footer of a section in a specific controller. - parameter section: The section from which to get the view. - parameter type: Either header or footer. - parameter controller: The controller from which to get that view. - returns: The header or footer of the specified section. */ public func viewForSection(section: Section, type: HeaderFooterType) -> UIView? { var view: ViewType? if type == .Header { view = section.headerView as? ViewType ?? { let result = viewProvider?.createView() section.headerView = result return result }() } else { view = section.footerView as? ViewType ?? { let result = viewProvider?.createView() section.footerView = result return result }() } guard let v = view else { return nil } onSetupView?(view: v, section: section) return v } /** Initiates the view with a String as title */ public init?(title: String?){ guard let t = title else { return nil } self.init(stringLiteral: t) } /** Initiates the view with a view provider, ideal for customized headers or footers */ public init(_ provider: HeaderFooterProvider<ViewType>){ viewProvider = provider } /** Initiates the view with a String as title */ public init(unicodeScalarLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(extendedGraphemeClusterLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(stringLiteral value: String) { self.title = value } } extension UIView { func eurekaInvalidate() { setNeedsUpdateConstraints() updateConstraintsIfNeeded() setNeedsLayout() } }
apache-2.0
jhabbbbb/ClassE
ClassE/AppDelegate.swift
1
2172
// // AppDelegate.swift // ClassE // // Created by JinHongxu on 2016/12/14. // Copyright © 2016年 JinHongxu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit