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 |
---|---|---|---|---|---|
lorentey/swift | stdlib/public/core/Policy.swift | 6 | 18095 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
// Swift Standard Prolog Library.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Standardized uninhabited type
//===----------------------------------------------------------------------===//
/// The return type of functions that do not return normally, that is, a type
/// with no values.
///
/// Use `Never` as the return type when declaring a closure, function, or
/// method that unconditionally throws an error, traps, or otherwise does
/// not terminate.
///
/// func crashAndBurn() -> Never {
/// fatalError("Something very, very bad happened")
/// }
@frozen
public enum Never {}
extension Never: Error {}
extension Never: Equatable {}
extension Never: Comparable {
public static func < (lhs: Never, rhs: Never) -> Bool {
}
}
extension Never: Hashable {}
//===----------------------------------------------------------------------===//
// Standardized aliases
//===----------------------------------------------------------------------===//
/// The return type of functions that don't explicitly specify a return type,
/// that is, an empty tuple `()`.
///
/// When declaring a function or method, you don't need to specify a return
/// type if no value will be returned. However, the type of a function,
/// method, or closure always includes a return type, which is `Void` if
/// otherwise unspecified.
///
/// Use `Void` or an empty tuple as the return type when declaring a closure,
/// function, or method that doesn't return a value.
///
/// // No return type declared:
/// func logMessage(_ s: String) {
/// print("Message: \(s)")
/// }
///
/// let logger: (String) -> Void = logMessage
/// logger("This is a void function")
/// // Prints "Message: This is a void function"
public typealias Void = ()
//===----------------------------------------------------------------------===//
// Aliases for floating point types
//===----------------------------------------------------------------------===//
// FIXME: it should be the other way round, Float = Float32, Double = Float64,
// but the type checker loses sugar currently, and ends up displaying 'FloatXX'
// in diagnostics.
/// A 32-bit floating point type.
public typealias Float32 = Float
/// A 64-bit floating point type.
public typealias Float64 = Double
//===----------------------------------------------------------------------===//
// Default types for unconstrained literals
//===----------------------------------------------------------------------===//
/// The default type for an otherwise-unconstrained integer literal.
public typealias IntegerLiteralType = Int
/// The default type for an otherwise-unconstrained floating point literal.
public typealias FloatLiteralType = Double
/// The default type for an otherwise-unconstrained Boolean literal.
///
/// When you create a constant or variable using one of the Boolean literals
/// `true` or `false`, the resulting type is determined by the
/// `BooleanLiteralType` alias. For example:
///
/// let isBool = true
/// print("isBool is a '\(type(of: isBool))'")
/// // Prints "isBool is a 'Bool'"
///
/// The type aliased by `BooleanLiteralType` must conform to the
/// `ExpressibleByBooleanLiteral` protocol.
public typealias BooleanLiteralType = Bool
/// The default type for an otherwise-unconstrained unicode scalar literal.
public typealias UnicodeScalarType = String
/// The default type for an otherwise-unconstrained Unicode extended
/// grapheme cluster literal.
public typealias ExtendedGraphemeClusterType = String
/// The default type for an otherwise-unconstrained string literal.
public typealias StringLiteralType = String
//===----------------------------------------------------------------------===//
// Default types for unconstrained number literals
//===----------------------------------------------------------------------===//
#if !os(Windows) && (arch(i386) || arch(x86_64))
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
#else
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
#endif
//===----------------------------------------------------------------------===//
// Standard protocols
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
/// The protocol to which all classes implicitly conform.
///
/// You use `AnyObject` when you need the flexibility of an untyped object or
/// when you use bridged Objective-C methods and properties that return an
/// untyped result. `AnyObject` can be used as the concrete type for an
/// instance of any class, class type, or class-only protocol. For example:
///
/// class FloatRef {
/// let value: Float
/// init(_ value: Float) {
/// self.value = value
/// }
/// }
///
/// let x = FloatRef(2.3)
/// let y: AnyObject = x
/// let z: AnyObject = FloatRef.self
///
/// `AnyObject` can also be used as the concrete type for an instance of a type
/// that bridges to an Objective-C class. Many value types in Swift bridge to
/// Objective-C counterparts, like `String` and `Int`.
///
/// let s: AnyObject = "This is a bridged string." as NSString
/// print(s is NSString)
/// // Prints "true"
///
/// let v: AnyObject = 100 as NSNumber
/// print(type(of: v))
/// // Prints "__NSCFNumber"
///
/// The flexible behavior of the `AnyObject` protocol is similar to
/// Objective-C's `id` type. For this reason, imported Objective-C types
/// frequently use `AnyObject` as the type for properties, method parameters,
/// and return values.
///
/// Casting AnyObject Instances to a Known Type
/// ===========================================
///
/// Objects with a concrete type of `AnyObject` maintain a specific dynamic
/// type and can be cast to that type using one of the type-cast operators
/// (`as`, `as?`, or `as!`).
///
/// This example uses the conditional downcast operator (`as?`) to
/// conditionally cast the `s` constant declared above to an instance of
/// Swift's `String` type.
///
/// if let message = s as? String {
/// print("Successful cast to String: \(message)")
/// }
/// // Prints "Successful cast to String: This is a bridged string."
///
/// If you have prior knowledge that an `AnyObject` instance has a particular
/// type, you can use the unconditional downcast operator (`as!`). Performing
/// an invalid cast triggers a runtime error.
///
/// let message = s as! String
/// print("Successful cast to String: \(message)")
/// // Prints "Successful cast to String: This is a bridged string."
///
/// let badCase = v as! String
/// // Runtime error
///
/// Casting is always safe in the context of a `switch` statement.
///
/// let mixedArray: [AnyObject] = [s, v]
/// for object in mixedArray {
/// switch object {
/// case let x as String:
/// print("'\(x)' is a String")
/// default:
/// print("'\(object)' is not a String")
/// }
/// }
/// // Prints "'This is a bridged string.' is a String"
/// // Prints "'100' is not a String"
///
/// Accessing Objective-C Methods and Properties
/// ============================================
///
/// When you use `AnyObject` as a concrete type, you have at your disposal
/// every `@objc` method and property---that is, methods and properties
/// imported from Objective-C or marked with the `@objc` attribute. Because
/// Swift can't guarantee at compile time that these methods and properties
/// are actually available on an `AnyObject` instance's underlying type, these
/// `@objc` symbols are available as implicitly unwrapped optional methods and
/// properties, respectively.
///
/// This example defines an `IntegerRef` type with an `@objc` method named
/// `getIntegerValue()`.
///
/// class IntegerRef {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
///
/// @objc func getIntegerValue() -> Int {
/// return value
/// }
/// }
///
/// func getObject() -> AnyObject {
/// return IntegerRef(100)
/// }
///
/// let obj: AnyObject = getObject()
///
/// In the example, `obj` has a static type of `AnyObject` and a dynamic type
/// of `IntegerRef`. You can use optional chaining to call the `@objc` method
/// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of
/// `obj`, you can call `getIntegerValue()` directly.
///
/// let possibleValue = obj.getIntegerValue?()
/// print(possibleValue)
/// // Prints "Optional(100)"
///
/// let certainValue = obj.getIntegerValue()
/// print(certainValue)
/// // Prints "100"
///
/// If the dynamic type of `obj` doesn't implement a `getIntegerValue()`
/// method, the system returns a runtime error when you initialize
/// `certainValue`.
///
/// Alternatively, if you need to test whether `obj.getIntegerValue()` exists,
/// use optional binding before calling the method.
///
/// if let f = obj.getIntegerValue {
/// print("The value of 'obj' is \(f())")
/// } else {
/// print("'obj' does not have a 'getIntegerValue()' method")
/// }
/// // Prints "The value of 'obj' is 100"
public typealias AnyObject = Builtin.AnyObject
#else
/// The protocol to which all classes implicitly conform.
public typealias AnyObject = Builtin.AnyObject
#endif
/// The protocol to which all class types implicitly conform.
///
/// You can use the `AnyClass` protocol as the concrete type for an instance of
/// any class. When you do, all known `@objc` class methods and properties are
/// available as implicitly unwrapped optional methods and properties,
/// respectively. For example:
///
/// class IntegerRef {
/// @objc class func getDefaultValue() -> Int {
/// return 42
/// }
/// }
///
/// func getDefaultValue(_ c: AnyClass) -> Int? {
/// return c.getDefaultValue?()
/// }
///
/// The `getDefaultValue(_:)` function uses optional chaining to safely call
/// the implicitly unwrapped class method on `c`. Calling the function with
/// different class types shows how the `getDefaultValue()` class method is
/// only conditionally available.
///
/// print(getDefaultValue(IntegerRef.self))
/// // Prints "Optional(42)"
///
/// print(getDefaultValue(NSString.self))
/// // Prints "nil"
public typealias AnyClass = AnyObject.Type
//===----------------------------------------------------------------------===//
// Standard pattern matching forms
//===----------------------------------------------------------------------===//
/// Returns a Boolean value indicating whether two arguments match by value
/// equality.
///
/// The pattern-matching operator (`~=`) is used internally in `case`
/// statements for pattern matching. When you match against an `Equatable`
/// value in a `case` statement, this operator is called behind the scenes.
///
/// let weekday = 3
/// let lunch: String
/// switch weekday {
/// case 3:
/// lunch = "Taco Tuesday!"
/// default:
/// lunch = "Pizza again."
/// }
/// // lunch == "Taco Tuesday!"
///
/// In this example, the `case 3` expression uses this pattern-matching
/// operator to test whether `weekday` is equal to the value `3`.
///
/// - Note: In most cases, you should use the equal-to operator (`==`) to test
/// whether two instances are equal. The pattern-matching operator is
/// primarily intended to enable `case` statement pattern matching.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@_transparent
public func ~= <T: Equatable>(a: T, b: T) -> Bool {
return a == b
}
//===----------------------------------------------------------------------===//
// Standard precedence groups
//===----------------------------------------------------------------------===//
precedencegroup AssignmentPrecedence {
assignment: true
associativity: right
}
precedencegroup FunctionArrowPrecedence {
associativity: right
higherThan: AssignmentPrecedence
}
precedencegroup TernaryPrecedence {
associativity: right
higherThan: FunctionArrowPrecedence
}
precedencegroup DefaultPrecedence {
higherThan: TernaryPrecedence
}
precedencegroup LogicalDisjunctionPrecedence {
associativity: left
higherThan: TernaryPrecedence
}
precedencegroup LogicalConjunctionPrecedence {
associativity: left
higherThan: LogicalDisjunctionPrecedence
}
precedencegroup ComparisonPrecedence {
higherThan: LogicalConjunctionPrecedence
}
precedencegroup NilCoalescingPrecedence {
associativity: right
higherThan: ComparisonPrecedence
}
precedencegroup CastingPrecedence {
higherThan: NilCoalescingPrecedence
}
precedencegroup RangeFormationPrecedence {
higherThan: CastingPrecedence
}
precedencegroup AdditionPrecedence {
associativity: left
higherThan: RangeFormationPrecedence
}
precedencegroup MultiplicationPrecedence {
associativity: left
higherThan: AdditionPrecedence
}
precedencegroup BitwiseShiftPrecedence {
higherThan: MultiplicationPrecedence
}
//===----------------------------------------------------------------------===//
// Standard operators
//===----------------------------------------------------------------------===//
// Standard postfix operators.
postfix operator ++
postfix operator --
postfix operator ...: Comparable
// Optional<T> unwrapping operator is built into the compiler as a part of
// postfix expression grammar.
//
// postfix operator !
// Standard prefix operators.
prefix operator ++
prefix operator --
prefix operator !: Bool
prefix operator ~: BinaryInteger
prefix operator +: AdditiveArithmetic
prefix operator -: SignedNumeric
prefix operator ...: Comparable
prefix operator ..<: Comparable
// Standard infix operators.
// "Exponentiative"
infix operator <<: BitwiseShiftPrecedence, BinaryInteger
infix operator &<<: BitwiseShiftPrecedence, FixedWidthInteger
infix operator >>: BitwiseShiftPrecedence, BinaryInteger
infix operator &>>: BitwiseShiftPrecedence, FixedWidthInteger
// "Multiplicative"
infix operator *: MultiplicationPrecedence, Numeric
infix operator &*: MultiplicationPrecedence, FixedWidthInteger
infix operator /: MultiplicationPrecedence, BinaryInteger, FloatingPoint
infix operator %: MultiplicationPrecedence, BinaryInteger
infix operator &: MultiplicationPrecedence, BinaryInteger
// "Additive"
infix operator +: AdditionPrecedence, AdditiveArithmetic, String, Array, Strideable
infix operator &+: AdditionPrecedence, FixedWidthInteger
infix operator -: AdditionPrecedence, AdditiveArithmetic, Strideable
infix operator &-: AdditionPrecedence, FixedWidthInteger
infix operator |: AdditionPrecedence, BinaryInteger
infix operator ^: AdditionPrecedence, BinaryInteger
// FIXME: is this the right precedence level for "..." ?
infix operator ...: RangeFormationPrecedence, Comparable
infix operator ..<: RangeFormationPrecedence, Comparable
// The cast operators 'as' and 'is' are hardcoded as if they had the
// following attributes:
// infix operator as: CastingPrecedence
// "Coalescing"
infix operator ??: NilCoalescingPrecedence
// "Comparative"
infix operator <: ComparisonPrecedence, Comparable
infix operator <=: ComparisonPrecedence, Comparable
infix operator >: ComparisonPrecedence, Comparable
infix operator >=: ComparisonPrecedence, Comparable
infix operator ==: ComparisonPrecedence, Equatable
infix operator !=: ComparisonPrecedence, Equatable
infix operator ===: ComparisonPrecedence
infix operator !==: ComparisonPrecedence
// FIXME: ~= will be built into the compiler.
infix operator ~=: ComparisonPrecedence
// "Conjunctive"
infix operator &&: LogicalConjunctionPrecedence, Bool
// "Disjunctive"
infix operator ||: LogicalDisjunctionPrecedence, Bool
// User-defined ternary operators are not supported. The ? : operator is
// hardcoded as if it had the following attributes:
// operator ternary ? : : TernaryPrecedence
// User-defined assignment operators are not supported. The = operator is
// hardcoded as if it had the following attributes:
// infix operator =: AssignmentPrecedence
// Compound
infix operator *=: AssignmentPrecedence, Numeric
infix operator &*=: AssignmentPrecedence, FixedWidthInteger
infix operator /=: AssignmentPrecedence, BinaryInteger
infix operator %=: AssignmentPrecedence, BinaryInteger
infix operator +=: AssignmentPrecedence, AdditiveArithmetic, String, Array, Strideable
infix operator &+=: AssignmentPrecedence, FixedWidthInteger
infix operator -=: AssignmentPrecedence, AdditiveArithmetic, Strideable
infix operator &-=: AssignmentPrecedence, FixedWidthInteger
infix operator <<=: AssignmentPrecedence, BinaryInteger
infix operator &<<=: AssignmentPrecedence, FixedWidthInteger
infix operator >>=: AssignmentPrecedence, BinaryInteger
infix operator &>>=: AssignmentPrecedence, FixedWidthInteger
infix operator &=: AssignmentPrecedence, BinaryInteger
infix operator ^=: AssignmentPrecedence, BinaryInteger
infix operator |=: AssignmentPrecedence, BinaryInteger
// Workaround for <rdar://problem/14011860> SubTLF: Default
// implementations in protocols. Library authors should ensure
// that this operator never needs to be seen by end-users. See
// test/Prototypes/GenericDispatch.swift for a fully documented
// example of how this operator is used, and how its use can be hidden
// from users.
infix operator ~>
| apache-2.0 |
vermont42/Conjugar | Conjugar/Quiz.swift | 1 | 18150 | //
// Quiz.swift
// Conjugar
//
// Created by Joshua Adams on 6/17/17.
// Copyright © 2017 Josh Adams. All rights reserved.
//
import Foundation
class Quiz {
private(set) var quizState: QuizState = .notStarted
private(set) var elapsedTime: Int = 0
private(set) var score: Int = 0
private(set) var currentQuestionIndex = 0
private(set) var lastRegion: Region = .spain
private(set) var lastDifficulty: Difficulty = .moderate
private(set) var proposedAnswers: [String] = []
private(set) var correctAnswers: [String] = []
private(set) var questions: [(String, Tense, PersonNumber)] = []
private var regularArVerbs = VerbFamilies.regularArVerbs
private var regularArVerbsIndex = 0
private var regularIrVerbs = VerbFamilies.regularIrVerbs
private var regularIrVerbsIndex = 0
private var regularErVerbs = VerbFamilies.regularErVerbs
private var regularErVerbsIndex = 0
private var allRegularVerbs = VerbFamilies.allRegularVerbs
private var allRegularVerbsIndex = 0
private var irregularPresenteDeIndicativoVerbs = VerbFamilies.irregularPresenteDeIndicativoVerbs
private var irregularPresenteDeIndicativoVerbsIndex = 0
private var irregularPreteritoVerbs = VerbFamilies.irregularPreteritoVerbs
private var irregularPreteritoVerbsIndex = 0
private var irregularRaizFuturaVerbs = VerbFamilies.irregularRaizFuturaVerbs
private var irregularRaizFuturaVerbsIndex = 0
private var irregularParticipioVerbs = VerbFamilies.irregularParticipioVerbs
private var irregularParticipioVerbsIndex = 0
private var irregularImperfectoVerbs = VerbFamilies.irregularImperfectivoVerbs
private var irregularImperfectoVerbsIndex = 0
private var irregularPresenteDeSubjuntivoVerbs = VerbFamilies.irregularPresenteDeSubjuntivoVerbs
private var irregularPresenteDeSubjuntivoVerbsIndex = 0
private var irregularGerundioVerbs = VerbFamilies.irregularGerundioVerbs
private var irregularGerundioVerbsIndex = 0
private var irregularTuImperativoVerbs = VerbFamilies.irregularTuImperativoVerbs
private var irregularTuImperativoVerbsIndex = 0
private var irregularVosImperativoVerbs = VerbFamilies.irregularVosImperativoVerbs
private var irregularVosImperativoVerbsIndex = 0
private var timer: Timer?
private var settings: Settings?
private var gameCenter: GameCenterable?
private var personNumbersWithTu: [PersonNumber] = [.firstSingular, .secondSingularTú, .thirdSingular, .firstPlural, .secondPlural, .thirdPlural]
private var personNumbersWithVos: [PersonNumber] = [.firstSingular, .secondSingularVos, .thirdSingular, .firstPlural, .secondPlural, .thirdPlural]
private var personNumbersIndex = 0
private var shouldShuffle = true
weak var delegate: QuizDelegate?
var questionCount: Int {
return questions.count
}
var verb: String {
if questions.count > 0 {
return questions[currentQuestionIndex].0
} else {
return ""
}
}
var tense: Tense {
if questions.count > 0 {
return questions[currentQuestionIndex].1
} else {
return .infinitivo
}
}
var currentPersonNumber: PersonNumber {
if questions.count > 0 {
return questions[currentQuestionIndex].2
} else {
return .none
}
}
init(settings: Settings, gameCenter: GameCenterable, shouldShuffle: Bool = true) {
self.settings = settings
self.gameCenter = gameCenter
self.shouldShuffle = shouldShuffle
}
func start() {
guard let settings = settings else {
fatalError("settings was nil.")
}
lastRegion = settings.region
lastDifficulty = settings.difficulty
questions.removeAll()
proposedAnswers.removeAll()
correctAnswers.removeAll()
if shouldShuffle {
regularArVerbs.shuffle()
regularIrVerbs.shuffle()
regularErVerbs.shuffle()
allRegularVerbs.shuffle()
irregularPresenteDeIndicativoVerbs.shuffle()
irregularPreteritoVerbs.shuffle()
irregularRaizFuturaVerbs.shuffle()
irregularParticipioVerbs.shuffle()
irregularImperfectoVerbs.shuffle()
irregularPresenteDeSubjuntivoVerbs.shuffle()
irregularGerundioVerbs.shuffle()
irregularTuImperativoVerbs.shuffle()
irregularVosImperativoVerbs.shuffle()
}
regularArVerbsIndex = 0
regularIrVerbsIndex = 0
regularErVerbsIndex = 0
allRegularVerbsIndex = 0
irregularPresenteDeIndicativoVerbsIndex = 0
irregularRaizFuturaVerbsIndex = 0
irregularParticipioVerbsIndex = 0
irregularImperfectoVerbsIndex = 0
irregularPresenteDeSubjuntivoVerbsIndex = 0
irregularGerundioVerbsIndex = 0
irregularTuImperativoVerbsIndex = 0
irregularVosImperativoVerbsIndex = 0
switch lastDifficulty {
case .easy:
// questions.append((allRegularVerb, .presenteDeIndicativo, personNumber())) // useful for testing
[regularArVerb, regularArVerb, regularArVerb, regularIrVerb, regularIrVerb, regularIrVerb, regularErVerb, regularErVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeIndicativo, personNumber()))
}
for _ in 0...8 {
questions.append((irregularPresenteDeIndicativoVerb, .presenteDeIndicativo, personNumber()))
}
for _ in 0...7 {
questions.append((irregularRaizFuturaVerb, .futuroDeIndicativo, personNumber()))
}
[regularArVerb, regularArVerb, regularArVerb, regularIrVerb, regularIrVerb, regularErVerb, regularErVerb].forEach {
questions.append(($0, .futuroDeIndicativo, personNumber()))
}
for _ in 0...7 {
questions.append((irregularPreteritoVerb, .pretérito, personNumber()))
}
for _ in 0...8 {
questions.append((allRegularVerb, .pretérito, personNumber()))
}
case .moderate:
[regularArVerb, regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeIndicativo, personNumber()))
}
for _ in 0...3 {
questions.append((irregularPresenteDeIndicativoVerb, .presenteDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularRaizFuturaVerb, .futuroDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .futuroDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularRaizFuturaVerb, .condicional, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .condicional, personNumber()))
}
for _ in 0...2 {
questions.append((irregularParticipioVerb, .perfectoDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .perfectoDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularImperfectoVerb, .imperfectoDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperfectoDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPreteritoVerb, .pretérito, personNumber()))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .pretérito, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPresenteDeSubjuntivoVerb, .presenteDeSubjuntivo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .presenteDeSubjuntivo, personNumber()))
}
for _ in 0...1 {
questions.append((irregularGerundioVerb, .gerundio, .none))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .gerundio, .none))
}
for _ in 0...1 {
if settings.secondSingularQuiz == .tu {
questions.append((irregularTuImperativoVerb, .imperativoPositivo, .secondSingularTú))
} else {
questions.append((irregularVosImperativoVerb, .imperativoPositivo, .secondSingularVos))
}
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperativoPositivo, personNumber(skipYo: true, skipTu: true)))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperativoNegativo, personNumber(skipYo: true, skipTu: true)))
}
case .difficult:
for _ in 0...1 {
questions.append((irregularGerundioVerb, .gerundio, .none))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .gerundio, .none))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPresenteDeIndicativoVerb, .presenteDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPreteritoVerb, .pretérito, personNumber()))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .pretérito, personNumber()))
}
for _ in 0...1 {
questions.append((irregularImperfectoVerb, .imperfectoDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperfectoDeIndicativo, personNumber()))
}
for _ in 0...1 {
questions.append((irregularRaizFuturaVerb, .futuroDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .futuroDeIndicativo, personNumber()))
}
for _ in 0...1 {
questions.append((allRegularVerb, .condicional, personNumber()))
}
questions.append((irregularRaizFuturaVerb, .condicional, personNumber()))
for _ in 0...2 {
questions.append((irregularPresenteDeSubjuntivoVerb, .presenteDeSubjuntivo, personNumber()))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeSubjuntivo, personNumber()))
}
questions.append((irregularPreteritoVerb, .imperfectoDeSubjuntivo1, personNumber()))
questions.append((allRegularVerb, .imperfectoDeSubjuntivo2, personNumber()))
questions.append((irregularPreteritoVerb, .futuroDeSubjuntivo, personNumber()))
questions.append((allRegularVerb, .futuroDeSubjuntivo, personNumber()))
if settings.secondSingularQuiz == .tu {
questions.append((irregularTuImperativoVerb, .imperativoPositivo, .secondSingularTú))
} else {
questions.append((irregularVosImperativoVerb, .imperativoPositivo, .secondSingularVos))
}
questions.append((allRegularVerb, .imperativoPositivo, personNumber(skipYo: true, skipTu: true)))
questions.append((allRegularVerb, .imperativoNegativo, personNumber(skipYo: true, skipTu: true)))
[.perfectoDeIndicativo, .pretéritoAnterior, .pluscuamperfectoDeIndicativo, .futuroPerfecto, .condicionalCompuesto, .perfectoDeSubjuntivo, .pluscuamperfectoDeSubjuntivo1, .pluscuamperfectoDeSubjuntivo2, .futuroPerfectoDeSubjuntivo].forEach {
questions.append((regularOrIrregularParticipioVerb, $0, personNumber()))
}
}
if shouldShuffle {
questions = questions.shuffled().shuffled()
}
score = 0
currentQuestionIndex = 0
elapsedTime = 0
quizState = .inProgress
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(Quiz.eachSecond), userInfo: nil, repeats: true)
delegate?.questionDidChange(verb: questions[0].0, tense: questions[0].1, personNumber: questions[0].2)
delegate?.scoreDidChange(newScore: 0)
delegate?.timeDidChange(newTime: 0)
delegate?.progressDidChange(current: 0, total: questions.count)
}
private var regularOrIrregularParticipioVerb: String {
let diceRoll: Int
if shouldShuffle {
diceRoll = Int.random(in: 0..<2)
} else {
diceRoll = questions.count % 2
}
if diceRoll == 0 {
return allRegularVerb
} else /* diceRoll == 1 */ {
return irregularParticipioVerb
}
}
func process(proposedAnswer: String) -> (ConjugationResult, String?) {
guard let gameCenter = gameCenter else {
fatalError("gameCenter was nil.")
}
let correctAnswerResult = Conjugator.shared.conjugate(infinitive: verb, tense: tense, personNumber: currentPersonNumber)
switch correctAnswerResult {
case let .success(correctAnswer):
let result = ConjugationResult.compare(lhs: proposedAnswer, rhs: correctAnswer)
proposedAnswers.append(proposedAnswer)
correctAnswers.append(correctAnswer)
if result != .noMatch {
score += result.rawValue
delegate?.scoreDidChange(newScore: score)
}
if currentQuestionIndex < questions.count - 1 {
currentQuestionIndex += 1
delegate?.progressDidChange(current: currentQuestionIndex, total: questions.count)
delegate?.questionDidChange(verb: questions[currentQuestionIndex].0, tense: questions[currentQuestionIndex].1, personNumber: questions[currentQuestionIndex].2)
} else {
score = Int(Double(score) * lastRegion.scoreModifier * lastDifficulty.scoreModifier)
timer?.invalidate()
quizState = .finished
delegate?.quizDidFinish()
gameCenter.reportScore(score)
}
if result == .totalMatch {
return (result, nil)
} else {
return (result, correctAnswer)
}
default:
fatalError()
}
}
func quit() {
timer?.invalidate()
quizState = .finished
}
@objc func eachSecond() {
elapsedTime += 1
delegate?.timeDidChange(newTime: elapsedTime)
}
private func personNumber(skipYo: Bool = false, skipTu: Bool = false) -> PersonNumber {
guard let settings = settings else {
fatalError("settings was nil.")
}
let personNumbers: [PersonNumber]
switch settings.secondSingularQuiz {
case .tu:
personNumbers = personNumbersWithTu
case .vos:
personNumbers = personNumbersWithVos
}
personNumbersIndex += 1
if personNumbersIndex == personNumbers.count {
personNumbersIndex = 0
} else if personNumbers[personNumbersIndex].pronoun == PersonNumber.secondPlural.pronoun && lastRegion == .latinAmerica {
personNumbersIndex += 1
}
if (personNumbers[personNumbersIndex].pronoun == PersonNumber.firstSingular.pronoun && skipYo) || (personNumbers[personNumbersIndex].pronoun == PersonNumber.secondSingularTú.pronoun && skipTu) {
return personNumber(skipYo: skipYo, skipTu: skipTu)
} else {
return personNumbers[personNumbersIndex]
}
}
private var regularArVerb: String {
regularArVerbsIndex += 1
if regularArVerbsIndex == regularArVerbs.count {
regularArVerbsIndex = 0
}
return regularArVerbs[regularArVerbsIndex]
}
private var regularIrVerb: String {
regularIrVerbsIndex += 1
if regularIrVerbsIndex == regularIrVerbs.count {
regularIrVerbsIndex = 0
}
return regularIrVerbs[regularIrVerbsIndex]
}
private var regularErVerb: String {
regularErVerbsIndex += 1
if regularErVerbsIndex == regularErVerbs.count {
regularErVerbsIndex = 0
}
return regularErVerbs[regularErVerbsIndex]
}
private var allRegularVerb: String {
allRegularVerbsIndex += 1
if allRegularVerbsIndex == allRegularVerbs.count {
allRegularVerbsIndex = 0
}
return allRegularVerbs[allRegularVerbsIndex]
}
private var irregularPresenteDeIndicativoVerb: String {
irregularPresenteDeIndicativoVerbsIndex += 1
if irregularPresenteDeIndicativoVerbsIndex == irregularPresenteDeIndicativoVerbs.count {
irregularPresenteDeIndicativoVerbsIndex = 0
}
return irregularPresenteDeIndicativoVerbs[irregularPresenteDeIndicativoVerbsIndex]
}
private var irregularRaizFuturaVerb: String {
irregularRaizFuturaVerbsIndex += 1
if irregularRaizFuturaVerbsIndex == irregularRaizFuturaVerbs.count {
irregularRaizFuturaVerbsIndex = 0
}
return irregularRaizFuturaVerbs[irregularRaizFuturaVerbsIndex]
}
private var irregularParticipioVerb: String {
irregularParticipioVerbsIndex += 1
if irregularParticipioVerbsIndex == irregularParticipioVerbs.count {
irregularParticipioVerbsIndex = 0
}
return irregularParticipioVerbs[irregularParticipioVerbsIndex]
}
private var irregularImperfectoVerb: String {
irregularImperfectoVerbsIndex += 1
if irregularImperfectoVerbsIndex == irregularImperfectoVerbs.count {
irregularImperfectoVerbsIndex = 0
}
return irregularImperfectoVerbs[irregularImperfectoVerbsIndex]
}
private var irregularPreteritoVerb: String {
irregularPreteritoVerbsIndex += 1
if irregularPreteritoVerbsIndex == irregularPreteritoVerbs.count {
irregularPreteritoVerbsIndex = 0
}
return irregularPreteritoVerbs[irregularPreteritoVerbsIndex]
}
private var irregularPresenteDeSubjuntivoVerb: String {
irregularPresenteDeSubjuntivoVerbsIndex += 1
if irregularPresenteDeSubjuntivoVerbsIndex == irregularPresenteDeSubjuntivoVerbs.count {
irregularPresenteDeSubjuntivoVerbsIndex = 0
}
return irregularPresenteDeSubjuntivoVerbs[irregularPresenteDeSubjuntivoVerbsIndex]
}
private var irregularGerundioVerb: String {
irregularGerundioVerbsIndex += 1
if irregularGerundioVerbsIndex == irregularGerundioVerbs.count {
irregularGerundioVerbsIndex = 0
}
return irregularGerundioVerbs[irregularGerundioVerbsIndex]
}
private var irregularTuImperativoVerb: String {
irregularTuImperativoVerbsIndex += 1
if irregularTuImperativoVerbsIndex == irregularTuImperativoVerbs.count {
irregularTuImperativoVerbsIndex = 0
}
return irregularTuImperativoVerbs[irregularTuImperativoVerbsIndex]
}
private var irregularVosImperativoVerb: String {
irregularVosImperativoVerbsIndex += 1
if irregularVosImperativoVerbsIndex == irregularVosImperativoVerbs.count {
irregularVosImperativoVerbsIndex = 0
}
return irregularVosImperativoVerbs[irregularVosImperativoVerbsIndex]
}
}
| agpl-3.0 |
firebase/quickstart-ios | performance/PerformanceExampleSwift/ViewController.swift | 1 | 3546 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebasePerformance
import AVKit
import AVFoundation
@objc(ViewController)
class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
// make a file name to write the data to using the documents directory
let fileName = "\(documentsDirectory)/perfsamplelog.txt"
// Start tracing
let trace = Performance.startTrace(name: "request_trace")
let contents: String
do {
contents = try String(contentsOfFile: fileName, encoding: .utf8)
} catch {
print("Log file doesn't exist yet")
contents = ""
}
let fileLength = contents.lengthOfBytes(using: .utf8)
trace?.incrementMetric("log_file_size", by: Int64(fileLength))
let target =
"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
guard let targetUrl = URL(string: target) else { return }
guard let metric = HTTPMetric(url: targetUrl, httpMethod: .get) else { return }
metric.start()
var request = URLRequest(url: targetUrl)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) {
data, response, error in
if let httpResponse = response as? HTTPURLResponse {
metric.responseCode = httpResponse.statusCode
}
metric.stop()
if let error = error {
print("error=\(error)")
return
}
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data!)
}
trace?.stop()
if let absoluteString = response?.url?.absoluteString {
let contentToWrite = contents + "\n" + absoluteString
do {
try contentToWrite.write(toFile: fileName, atomically: false, encoding: .utf8)
} catch {
print("Can't write to log file")
}
}
}
task.resume()
trace?.incrementMetric("request_sent", by: 1)
if #available(iOS 10, *) {
let asset =
AVURLAsset(
url: URL(
string: "https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/Two_red_dice_01.svg/220px-Two_red_dice_01.svg.png"
)!
)
let downloadSession =
AVAssetDownloadURLSession(
configuration: URLSessionConfiguration.background(withIdentifier: "avasset"),
assetDownloadDelegate: nil,
delegateQueue: OperationQueue.main
)
let task = downloadSession.makeAssetDownloadTask(asset: asset,
assetTitle: "something",
assetArtworkData: nil,
options: nil)!
task.resume()
trace?.incrementMetric("av_request_sent", by: 1)
}
}
}
| apache-2.0 |
mrdepth/EVEOnlineAPI | EVEAPI/EVEAPI/evecodegen/EVEGlobal.swift | 1 | 6089 | import Foundation
import Alamofire
public extension EVE {
class func loadClassess() {
_ = Corp.ContractItems.Item.classForCoder()
_ = Char.CharacterSheet.JumpClone.classForCoder()
_ = Char.UpcomingCalendarEvents.Event.classForCoder()
_ = Char.Bookmarks.Folder.classForCoder()
_ = Account.AccountStatus.classForCoder()
_ = Char.Research.classForCoder()
_ = Corp.KillMails.classForCoder()
_ = Char.CharacterSheet.Attributes.classForCoder()
_ = Char.AccountBalance.classForCoder()
_ = Char.WalletJournal.classForCoder()
_ = Char.AccountBalance.Account.classForCoder()
_ = Corp.ContactList.Contact.classForCoder()
_ = Char.ContactList.classForCoder()
_ = Char.MarketOrders.classForCoder()
_ = Corp.AssetList.classForCoder()
_ = Char.PlanetaryLinks.Link.classForCoder()
_ = Char.Contracts.Contract.classForCoder()
_ = Char.MailingLists.MailingList.classForCoder()
_ = Corp.Standings.classForCoder()
_ = Corp.Bookmarks.Folder.classForCoder()
_ = Api.CallList.Call.classForCoder()
_ = Char.CharacterSheet.Role.classForCoder()
_ = Char.MailingLists.classForCoder()
_ = Char.KillMails.Kill.classForCoder()
_ = Char.WalletTransactions.classForCoder()
_ = Char.WalletJournal.Transaction.classForCoder()
_ = Char.PlanetaryPins.Pin.classForCoder()
_ = Char.ContactNotifications.Notification.classForCoder()
_ = Corp.IndustryJobs.classForCoder()
_ = Char.MailBodies.Message.classForCoder()
_ = Corp.Medals.classForCoder()
_ = Corp.AccountBalance.Account.classForCoder()
_ = Char.ContractBids.classForCoder()
_ = Eve.RefTypes.classForCoder()
_ = Corp.WalletJournal.classForCoder()
_ = Char.CharacterSheet.Skill.classForCoder()
_ = Char.Clones.classForCoder()
_ = Char.CalendarEventAttendees.classForCoder()
_ = Char.Clones.JumpCloneImplant.classForCoder()
_ = Corp.ContractItems.classForCoder()
_ = Corp.AccountBalance.classForCoder()
_ = Char.MailBodies.classForCoder()
_ = Char.ChatChannels.Channel.classForCoder()
_ = Char.AssetList.Asset.classForCoder()
_ = Char.KillMails.Kill.Attacker.classForCoder()
_ = Char.NotificationTexts.Notification.classForCoder()
_ = Eve.RefTypes.RefType.classForCoder()
_ = Corp.Contracts.Contract.classForCoder()
_ = Corp.Blueprints.Blueprint.classForCoder()
_ = Char.FacWarStats.classForCoder()
_ = Char.ContactList.Label.classForCoder()
_ = Char.IndustryJobs.Job.classForCoder()
_ = Corp.Locations.Location.classForCoder()
_ = Corp.KillMails.Kill.Item.classForCoder()
_ = Char.PlanetaryRoutes.Route.classForCoder()
_ = Char.Messages.Message.classForCoder()
_ = Account.AccountStatus.MultiCharacterTraining.classForCoder()
_ = Char.ContractBids.Bid.classForCoder()
_ = Char.CharacterSheet.Certificate.classForCoder()
_ = Corp.MarketOrders.Order.classForCoder()
_ = Corp.Bookmarks.classForCoder()
_ = Char.Notifications.classForCoder()
_ = Char.ContactNotifications.classForCoder()
_ = Api.CallList.CallGroup.classForCoder()
_ = Char.Blueprints.classForCoder()
_ = Corp.Bookmarks.Folder.Bookmark.classForCoder()
_ = Char.ContractItems.Item.classForCoder()
_ = Char.Contracts.classForCoder()
_ = Char.ChatChannels.Channel.Accessor.classForCoder()
_ = Char.Clones.Attributes.classForCoder()
_ = Account.APIKeyInfo.APIKey.classForCoder()
_ = Corp.ContactList.classForCoder()
_ = Char.MarketOrders.Order.classForCoder()
_ = Char.Locations.classForCoder()
_ = Corp.WalletTransactions.classForCoder()
_ = Corp.WalletTransactions.Transaction.classForCoder()
_ = Char.Standings.Standing.classForCoder()
_ = Char.Messages.classForCoder()
_ = Corp.ContractBids.classForCoder()
_ = Account.Characters.Character.classForCoder()
_ = Char.CharacterSheet.classForCoder()
_ = Char.CalendarEventAttendees.Attendee.classForCoder()
_ = Char.PlanetaryColonies.Colony.classForCoder()
_ = Char.Standings.classForCoder()
_ = Char.Notifications.Notification.classForCoder()
_ = Corp.Medals.Medal.classForCoder()
_ = Char.Medals.Medal.classForCoder()
_ = Char.SkillQueue.Skill.classForCoder()
_ = Corp.Locations.classForCoder()
_ = Corp.KillMails.Kill.Attacker.classForCoder()
_ = Account.APIKeyInfo.classForCoder()
_ = Char.PlanetaryRoutes.classForCoder()
_ = Char.Locations.Location.classForCoder()
_ = Char.PlanetaryPins.classForCoder()
_ = Char.KillMails.Kill.Item.classForCoder()
_ = Char.Skills.Skill.classForCoder()
_ = Corp.KillMails.Kill.Victim.classForCoder()
_ = Account.APIKeyInfo.APIKey.Character.classForCoder()
_ = Char.PlanetaryLinks.classForCoder()
_ = Char.KillMails.classForCoder()
_ = Api.CallList.classForCoder()
_ = Char.WalletTransactions.Transaction.classForCoder()
_ = Char.SkillQueue.classForCoder()
_ = Corp.Blueprints.classForCoder()
_ = Char.CharacterSheet.Implant.classForCoder()
_ = Char.CharacterSheet.JumpCloneImplant.classForCoder()
_ = Char.ContactList.Contact.classForCoder()
_ = Corp.ContractBids.Bid.classForCoder()
_ = Char.Skills.classForCoder()
_ = Char.NotificationTexts.classForCoder()
_ = Corp.Standings.Standing.classForCoder()
_ = Corp.IndustryJobs.Job.classForCoder()
_ = Corp.FacWarStats.classForCoder()
_ = Corp.MarketOrders.classForCoder()
_ = Char.Clones.Implant.classForCoder()
_ = Char.Bookmarks.classForCoder()
_ = Char.UpcomingCalendarEvents.classForCoder()
_ = Char.IndustryJobs.classForCoder()
_ = Corp.Contracts.classForCoder()
_ = Char.PlanetaryColonies.classForCoder()
_ = Char.Clones.JumpClone.classForCoder()
_ = Account.Characters.classForCoder()
_ = Corp.AssetList.Asset.classForCoder()
_ = Char.Research.Research.classForCoder()
_ = Char.ContractItems.classForCoder()
_ = Char.Bookmarks.Folder.Bookmark.classForCoder()
_ = Corp.WalletJournal.Transaction.classForCoder()
_ = Char.Medals.classForCoder()
_ = Char.ChatChannels.classForCoder()
_ = Char.Blueprints.Blueprint.classForCoder()
_ = Char.AssetList.classForCoder()
_ = Corp.ContactList.Label.classForCoder()
_ = Corp.KillMails.Kill.classForCoder()
_ = Char.KillMails.Kill.Victim.classForCoder()
}
}
| mit |
KSMissQXC/KS_DYZB | KS_DYZB/KS_DYZB/Classes/Home/View/KSHomeRecommendCycleCell.swift | 1 | 797 | //
// KSHomeRecommendCycleCell.swift
// KS_DYZB
//
// Created by 耳动人王 on 2016/11/3.
// Copyright © 2016年 KS. All rights reserved.
//
import UIKit
import Kingfisher
class KSHomeRecommendCycleCell: UICollectionViewCell {
// MARK: 控件属性
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
// MARK: 定义模型属性
var cycleModel : KSHomeCycleModel? {
didSet {
titleLabel.text = cycleModel?.title
let iconURL = URL(string: cycleModel?.pic_url ?? "")!
iconImageView.kf.setImage(with: iconURL, placeholder: UIImage(named: "Img_default"))
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| mit |
kasketis/netfox | netfox/iOS/NFXHelper_iOS.swift | 1 | 7942 | //
// NFXHelper.swift
// netfox
//
// Copyright © 2016 netfox. All rights reserved.
//
#if os(iOS)
import UIKit
extension UIWindow {
override open func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if NFX.sharedInstance().getSelectedGesture() == .shake {
if (event!.type == .motion && event!.subtype == .motionShake) {
NFX.sharedInstance().motionDetected()
}
} else {
super.motionEnded(motion, with: event)
}
}
}
public extension UIDevice {
class func getNFXDeviceType() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
let mirror = Mirror(reflecting: machine)
var identifier = ""
for child in mirror.children {
if let value = child.value as? Int8 , value != 0 {
identifier.append(String(UnicodeScalar(UInt8(value))))
}
}
return parseDeviceType(identifier)
}
class func parseDeviceType(_ identifier: String) -> String {
switch identifier {
case "i386": return "iPhone Simulator"
case "x86_64": return "iPhone Simulator"
case "iPhone1,1": return "iPhone"
case "iPhone1,2": return "iPhone 3G"
case "iPhone2,1": return "iPhone 3GS"
case "iPhone3,1": return "iPhone 4"
case "iPhone3,2": return "iPhone 4 GSM Rev A"
case "iPhone3,3": return "iPhone 4 CDMA"
case "iPhone4,1": return "iPhone 4S"
case "iPhone5,1": return "iPhone 5 (GSM)"
case "iPhone5,2": return "iPhone 5 (GSM+CDMA)"
case "iPhone5,3": return "iPhone 5C (GSM)"
case "iPhone5,4": return "iPhone 5C (Global)"
case "iPhone6,1": return "iPhone 5S (GSM)"
case "iPhone6,2": return "iPhone 5S (Global)"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone7,2": return "iPhone 6"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE (GSM)"
case "iPhone9,1": return "iPhone 7"
case "iPhone9,2": return "iPhone 7 Plus"
case "iPhone9,3": return "iPhone 7"
case "iPhone9,4": return "iPhone 7 Plus"
case "iPhone10,1": return "iPhone 8"
case "iPhone10,2": return "iPhone 8 Plus"
case "iPhone10,3": return "iPhone X Global"
case "iPhone10,4": return "iPhone 8"
case "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,6": return "iPhone X GSM"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4": return "iPhone XS Max"
case "iPhone11,6": return "iPhone XS Max Global"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
case "iPhone12,8": return "iPhone SE 2nd Gen"
case "iPod1,1": return "1st Gen iPod"
case "iPod2,1": return "2nd Gen iPod"
case "iPod3,1": return "3rd Gen iPod"
case "iPod4,1": return "4th Gen iPod"
case "iPod5,1": return "5th Gen iPod"
case "iPod7,1": return "6th Gen iPod"
case "iPod9,1": return "7th Gen iPod"
case "iPad1,1": return "iPad"
case "iPad1,2": return "iPad 3G"
case "iPad2,1": return "2nd Gen iPad"
case "iPad2,2": return "2nd Gen iPad GSM"
case "iPad2,3": return "2nd Gen iPad CDMA"
case "iPad2,4": return "2nd Gen iPad New Revision"
case "iPad3,1": return "3rd Gen iPad"
case "iPad3,2": return "3rd Gen iPad CDMA"
case "iPad3,3": return "3rd Gen iPad GSM"
case "iPad2,5": return "iPad mini"
case "iPad2,6": return "iPad mini GSM+LTE"
case "iPad2,7": return "iPad mini CDMA+LTE"
case "iPad3,4": return "4th Gen iPad"
case "iPad3,5": return "4th Gen iPad GSM+LTE"
case "iPad3,6": return "4th Gen iPad CDMA+LTE"
case "iPad4,1": return "iPad Air (WiFi)"
case "iPad4,2": return "iPad Air (GSM+CDMA)"
case "iPad4,3": return "1st Gen iPad Air (China)"
case "iPad4,4": return "iPad mini Retina (WiFi)"
case "iPad4,5": return "iPad mini Retina (GSM+CDMA)"
case "iPad4,6": return "iPad mini Retina (China)"
case "iPad4,7": return "iPad mini 3 (WiFi)"
case "iPad4,8": return "iPad mini 3 (GSM+CDMA)"
case "iPad4,9": return "iPad Mini 3 (China)"
case "iPad5,1": return "iPad mini 4 (WiFi)"
case "iPad5,2": return "4th Gen iPad mini (WiFi+Cellular)"
case "iPad5,3": return "iPad Air 2 (WiFi)"
case "iPad5,4": return "iPad Air 2 (Cellular)"
case "iPad6,3": return "iPad Pro (9.7 inch, WiFi)"
case "iPad6,4": return "iPad Pro (9.7 inch, WiFi+LTE)"
case "iPad6,7": return "iPad Pro (12.9 inch, WiFi)"
case "iPad6,8": return "iPad Pro (12.9 inch, WiFi+LTE)"
case "iPad6,11": return "iPad (2017)"
case "iPad6,12": return "iPad (2017)"
case "iPad7,1": return "iPad Pro 2nd Gen (WiFi)"
case "iPad7,2": return "iPad Pro 2nd Gen (WiFi+Cellular)"
case "iPad7,3": return "iPad Pro 10.5-inch"
case "iPad7,4": return "iPad Pro 10.5-inch"
case "iPad7,5": return "iPad 6th Gen (WiFi)"
case "iPad7,6": return "iPad 6th Gen (WiFi+Cellular)"
case "iPad7,11": return "iPad 7th Gen 10.2-inch (WiFi)"
case "iPad7,12": return "iPad 7th Gen 10.2-inch (WiFi+Cellular)"
case "iPad8,1": return "iPad Pro 11 inch (WiFi)"
case "iPad8,2": return "iPad Pro 11 inch (1TB, WiFi)"
case "iPad8,3": return "iPad Pro 11 inch (WiFi+Cellular)"
case "iPad8,4": return "iPad Pro 11 inch (1TB, WiFi+Cellular)"
case "iPad8,5": return "iPad Pro 12.9 inch 3rd Gen (WiFi)"
case "iPad8,6": return "iPad Pro 12.9 inch 3rd Gen (1TB, WiFi)"
case "iPad8,7": return "iPad Pro 12.9 inch 3rd Gen (WiFi+Cellular)"
case "iPad8,8": return "iPad Pro 12.9 inch 3rd Gen (1TB, WiFi+Cellular)"
case "iPad8,9": return "iPad Pro 11 inch 2nd Gen (WiFi)"
case "iPad8,10": return "iPad Pro 11 inch 2nd Gen (WiFi+Cellular)"
case "iPad8,11": return "iPad Pro 12.9 inch 4th Gen (WiFi)"
case "iPad8,12": return "iPad Pro 12.9 inch 4th Gen (WiFi+Cellular)"
case "iPad11,1": return "iPad mini 5th Gen (WiFi)"
case "iPad11,2": return "iPad mini 5th Gen"
case "iPad11,3": return "iPad Air 3rd Gen (WiFi)"
case "iPad11,4": return "iPad Air 3rd Gen"
default: return "Not Available"
}
}
}
#endif
protocol DataCleaner {
func clearData(sourceView: UIView, originingIn sourceRect: CGRect?, then: @escaping () -> ())
}
extension DataCleaner where Self: UIViewController {
func clearData(sourceView: UIView, originingIn sourceRect: CGRect?, then: @escaping () -> ()) {
let actionSheetController: UIAlertController = UIAlertController(title: "Clear data?", message: "", preferredStyle: .actionSheet)
actionSheetController.popoverPresentationController?.sourceView = sourceView
if let sourceRect = sourceRect {
actionSheetController.popoverPresentationController?.sourceRect = sourceRect
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in }
actionSheetController.addAction(cancelAction)
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
NFX.sharedInstance().clearOldData()
then()
}
actionSheetController.addAction(yesAction)
let noAction = UIAlertAction(title: "No", style: .default) { _ in }
actionSheetController.addAction(noAction)
present(actionSheetController, animated: true, completion: nil)
}
}
| mit |
Urinx/SomeCodes | Swift/swiftDemo/demo.4/demo.4/AppDelegate.swift | 2 | 2158 | //
// AppDelegate.swift
// demo.3
//
// Created by Eular on 15-3-24.
// Copyright (c) 2015年 Eular. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> 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:.
}
}
| gpl-2.0 |
shial4/VaporDM | Sources/VaporDM/Controllers/DMController.swift | 1 | 13464 | //
// DMController.swift
// VaporDM
//
// Created by Shial on 19/04/2017.
//
//
import Foundation
import HTTP
import Vapor
import Fluent
public final class DMController<T:DMUser> {
/// Group under which endpoints are grouped
open var group: String = "chat"
/// VaporDM configuraton object
var configuration: DMConfiguration
/// VaporDM connection set
var connections: Set<DMConnection> = []
/// An Droplet instance under endpoint are handled
fileprivate weak var drop: Droplet?
/// Function which expose Models instance for Vapor Fluent to exten your database.
///
/// - Returns: Preparation reuired for VaporDM to work on database
fileprivate func models() -> [Preparation.Type] {
return [Pivot<T, DMRoom>.self,
DMRoom.self,
DMDirective.self,
]
}
/// DMController object which do provide endpoint to work with VaporDM
///
/// - Parameters:
/// - droplet: Droplet object required to correctly set up VaporDM
/// - configuration: DMConfiguration object required to configure VaporDM. Default value is DMDefaultConfiguration() object
public init(drop: Droplet, configuration: DMConfiguration) {
self.drop = drop
self.configuration = configuration
drop.preparations += models()
let chat = drop.grouped(group)
chat.socket("service", T.self, handler: chatService)
chat.post("room", handler: createRoom)
chat.post("room", String.self, handler: addUsersToRoom)
chat.post("room", String.self, "remove", handler: removeUsersFromRoom)
chat.get("room", String.self, handler: getRoom)
chat.get("room", String.self, "participant", handler: getRoomParticipants)
chat.get("participant", T.self, "rooms", handler: getParticipantRooms)
chat.get("history", String.self, handler: history)
}
/// Create chat room.
///```
/// POST: /chat/room
/// "Content-Type" = "application/json"
///```
/// In Body DMRoom object with minimum uniqueid and name parameters.
///```
/// {
/// "uniqueid":"",
/// "name":"RoomName"
/// }
///```
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: CHat room
/// - Throws: If room is not found or query do fail
public func createRoom(request: Request) throws -> ResponseRepresentable {
var room = try request.room()
try room.save()
if let users: [String] = try request.json?.extract("participants") {
for userId in users {
do {
if let user = try T.find(userId) {
_ = try Pivot<T, DMRoom>.getOrCreate(user, room)
}
} catch {
T.directMessage(log: DMLog(message: "Unable to find user with id: \(userId)\nError message: \(error)", type: .warning))
}
}
}
return try room.makeJSON()
}
/// Get chat room.
///
///```
/// GET: /chat/room/${room_uuid}
/// "Content-Type" = "application/json"
///```
///
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: Chat room
/// - Throws: If room is not found or query do fail
public func getRoom(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard let room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
return try room.makeJSON()
}
/// Add users to room.
///
///```
/// POST: /chat/room/${room_uuid}
/// "Content-Type" = "application/json"
///```
/// In Body Your Fluent Model or array of models which is associated with VaporDM.
///```
/// {
/// [
/// ${<User: Model, DMParticipant>},
/// ${<User: Model, DMParticipant>}
/// ]
/// }
///```
/// Or
///```
/// {
/// ${<User: Model, DMParticipant>}
/// }
///```
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: CHat room
/// - Throws: If room is not found or query do fail
public func addUsersToRoom(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard var room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
room.time.updated = Date()
try room.save()
for user: T in try request.users() {
_ = try Pivot<T, DMRoom>.getOrCreate(user, room)
}
return try room.makeJSON()
}
/// Remove users from room.
///
///```
/// POST: /chat/room/${room_uuid}/remove
/// "Content-Type" = "application/json"
///```
/// In Body Your Fluent Model or array of models which is associated with VaporDM.
///```
/// {
/// [
/// ${<User: Model, DMParticipant>},
/// ${<User: Model, DMParticipant>}
/// ]
/// }
///```
/// Or
///```
/// {
/// ${<User: Model, DMParticipant>}
/// }
///```
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: Chat room
/// - Throws: If room is not found or query do fail
public func removeUsersFromRoom(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard var room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
room.time.updated = Date()
try room.save()
for user: T in try request.users() {
try Pivot<T, DMRoom>.remove(user, room)
}
return try room.makeJSON()
}
/// Get DMRoom participants
///
///```
/// GET: /chat/room/${room_uuid}/participant
/// "Content-Type" = "application/json"
///```
///
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: Array of You Fluent object, which corresponds to DMParticipant and FLuent's Model Protocols
/// - Throws: If room is not found or query do fail
public func getRoomParticipants(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard let room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
let users: [T] = try room.participants()
return try users.makeJSON()
}
/// Get DMParticipant rooms. This request passes in url Your Fluent model `id` which is associated with VaporDM's
///
///```
/// GET: /chat/participant/${user_id}/rooms
/// "Content-Type" = "application/json"
///```
/// - Parameters:
/// - request: request object
/// - user: Your Fluent Associated model with VaporDM
/// - Returns: Array of DMRoom object which your User participate
/// - Throws: If query goes wrong
public func getParticipantRooms(request: Request, user: T) throws -> ResponseRepresentable {
let rooms: [DMRoom] = try user.rooms().all()
return try rooms.makeJSON()
}
/// Get chat room history. You can pass in request data `from` and `to` values which constrain query
///```
/// GET: /chat/history/${room_uuid}
/// "Content-Type" = "application/json"
///```
///
/// - Parameters:
/// - request: request object
/// - room: chat room UUID for which history will be retirned
/// - Returns: Array of DMDirective objects
/// - Throws: If room is not found or query will throw
public func history(request: Request, room: String) throws -> ResponseRepresentable {
guard let room = try DMRoom.find(room) else {
throw Abort.notFound
}
return try room.messages(from: request.data["from"]?.double, to: request.data["to"]?.double).makeJSON()
}
/// Called when a WebSocket client connects to the server
///```
/// ws: /chat/service/${user_id}
///```
///
/// - Parameters:
/// - request: WebSocket connection request
/// - ws: WebSocket
/// - user: User which did connect
public func chatService<T:DMUser>(request: Request, ws: WebSocket, user: T) {
let connectionIdentifier = UUID().uuidString
openConnection(from: user, ws: ws, identifier: connectionIdentifier)
ws.onText = {[weak self] ws, text in
self?.sendMessage(from: user, message:try? JSON(bytes: Array(text.utf8)))
}
ws.onClose = {[weak self] ws, _, _, _ in
guard let id = user.id?.string else {
T.directMessage(log: DMLog(message: "Unable to get user unigeId", type: .error))
return
}
self?.connections.remove(DMConnection(id: connectionIdentifier, user: id, socket: ws))
self?.sendMessage(from: user, message:JSON([DMKeys.type:String(DMType.disconnected.rawValue).makeNode()]))
}
}
}
extension DMController {
/// After user connect to WebSocket we are opening connection on VaporDM which means creating an connection object to identify user with this connection and being unique with different connection for the same user.
///
/// - Parameters:
/// - user: User which did connect
/// - ws: WebSocket object
/// - identifier: UUID to identify this connection
func openConnection<T:DMUser>(from user: T, ws: WebSocket, identifier: String) {
guard let id = user.id?.string else {
T.directMessage(log: DMLog(message: "Unable to get user unigeId", type: .error))
do {
try ws.close()
} catch {
T.directMessage(log: DMLog(message: "\(error)", type: .error))
}
return
}
T.directMessage(log: DMLog(message: "User: \(user.id ?? "") did connect", type: .info))
sendMessage(from: user, message:JSON([DMKeys.type:String(DMType.connected.rawValue).makeNode()]))
let connection = DMConnection(id: identifier, user: id, socket: ws)
applyConfiguration(for: connection)
self.connections.insert(connection)
}
/// Take message JSON object from sender and parse message with DMFlowCOntroller. After success sends message.
///
/// - Parameters:
/// - user: Sender of this message
/// - message: JSON containing message data
func sendMessage<T:DMUser>(from user: T, message: JSON?) {
guard let json = message else {
T.directMessage(log: DMLog(message: "JSON message is nil", type: .error))
return
}
do {
let flow = try DMFlowController(sender: user, message: json)
self.sendMessage(flow)
} catch {
T.directMessage(log: DMLog(message: "\(error)", type: .error))
}
}
/// Send message over the WebSocket thanks to DMFlowController `parseMessage` method result.
///
/// - Parameter message: DMFlowController instance
func sendMessage<T:DMUser>(_ message: DMFlowController<T>) {
do {
let response: (redirect: JSON?, receivers: [T]) = try message.parseMessage()
guard let redirect = response.redirect else { return }
var offline = response.receivers
var online: [T] = []
for connection in self.connections where response.receivers.contains(where: { reveiver -> Bool in
guard connection.userId == reveiver.id?.string else {
return false
}
return true
}) {
try connection.socket?.send(redirect)
if let removed = offline.remove(connection.userId) {
online.append(removed)
}
}
T.directMessage(event: DMEvent(online ,message: redirect))
T.directMessage(event: DMEvent(offline ,message: redirect, status: .failure))
} catch {
T.directMessage(log: DMLog(message: "\(error)", type: .error))
}
}
/// Apply DMConfiguration instance for current connection passed in argument.
///
/// - Parameter connection: Configuration which specify among others ping time interval.
func applyConfiguration(for connection: DMConnection) {
guard let interval = configuration.pingIterval else {
T.directMessage(log: DMLog(message: "Skipping ping sequence. DMConfiguration do not specify ping interval.", type: .info))
return
}
connection.ping(every: interval)
}
}
extension Request {
/// Parse Requesto JSON to chat room object
///
/// - Returns: chat room object
/// - Throws: Error if something goes wrong
func room() throws -> DMRoom {
guard let json = json else { throw Abort.badRequest }
return try DMRoom(node: json)
}
/// Parse Request JSON to your Fluent model
///
/// - Returns: Array of you Fluent models
/// - Throws: Error if something goes wrong
func users<T:DMUser>() throws -> [T] {
guard let json = json else { throw Abort.badRequest }
guard let array = json.pathIndexableArray else {
return [try T(node: json)]
}
return try array.map() { try T(node: $0)}
}
}
| mit |
WhereYat/whereyat-swift | WhereYat.swift | 1 | 1924 | //
// WhereYat.swift
// Flappy Flag
//
// Created by Zane Shannon on 2/1/15.
// Copyright (c) 2015 Where Y'at. All rights reserved.
//
import Foundation
public class WhereYat {
public class func locate(completionHandler: (WhereYatLocation?, NSError?) -> Void) -> Void {
let request = NSURLRequest(URL: NSURL(string: "https://ip.wherey.at/")!)
let urlSession = NSURLSession.sharedSession()
let dataTask = urlSession.dataTaskWithRequest(request) {
(var data, var response, var error) in
var location:WhereYatLocation? = nil
if (error == nil) {
var parseError : NSError?
let jsonResponse = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as Dictionary<String, AnyObject>
location = WhereYatLocation(api_response: jsonResponse)
} else {
println(error)
}
dispatch_async(dispatch_get_main_queue()) {
completionHandler(location, error)
}
}
dataTask.resume()
}
}
public class WhereYatLocation: NSObject {
var success:Bool = false
var city:String?
var metro_code:NSNumber?
var country:String?
var country_code:String?
var time_zone:String?
var longitude:NSNumber?
var latitude:NSNumber?
var ip:String?
var subdivisions:[Dictionary<String, String>]?
init(api_response: Dictionary<String, AnyObject>?) {
if let response = api_response {
if response["status"] as String? == "ok" {
self.success = true
self.city = response["city"] as String?
self.metro_code = response["metro_code"] as NSNumber?
self.country = response["country"] as String?
self.country_code = response["country_code"] as String?
self.time_zone = response["time_zone"] as String?
self.longitude = response["longitude"] as NSNumber?
self.latitude = response["latitude"] as NSNumber?
self.ip = response["ip"] as String?
self.subdivisions = response["subdivisions"] as [Dictionary<String, String>]?
}
}
}
} | mit |
proxpero/Endgame | Sources/Board+Sequence.swift | 1 | 762 | //
// Board+Sequence.swift
// Endgame
//
// Created by Todd Olsen on 3/15/17.
//
//
extension Board: Sequence {
/// Returns an iterator over the spaces of the board.
public func makeIterator() -> Iterator {
return Iterator(self)
}
/// An iterator for `Board`.
public struct Iterator: IteratorProtocol {
private let _board: Board
private var _index: Int
init(_ board: Board) {
self._board = board
self._index = 0
}
public mutating func next() -> Board.Space? {
guard let square = Square(rawValue: _index) else {
return nil
}
defer { _index += 1 }
return _board.space(at: square)
}
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/25720-swift-constraints-constraintsystem-simplifyconstraint.swift | 13 | 319 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a{
struct B
class B{func c<T{{
{
}
}
var _=c<T>{
}protocol g{
class a
class c<T where B:A class a:c
| apache-2.0 |
ngageoint/fog-machine | FogMachine/FogMachine/Models/FMTool.swift | 1 | 3633 | import Foundation
/**
This class provides the a simple lifecycle that your applicaiton can utilize. Extend this class and provide implementations for createWork, processWork and mergeResults, in order to make your custom tool. See the example projects and the README for more information.
*/
public class FMTool {
public init() {
}
/**
A unique identified for this tool. It should be consistent accross nodes, but it can be changed in order to version you tool.
- returns: unique identified for this tool
*/
public func id() -> UInt32 {
return 4229232399
}
/**
Description of your tool for logging
- returns: tool description. Ex: My Hello world tool
*/
public func name() -> String {
return "BASE FOGTOOL"
}
/**
This gets called n times by FogMachine on the initiator node, where n is the number of nodes in the network (including yourself). This function creates the information that will be sent to each node in the network. As a user of Fog Machine, you must provide an implmentation for this routine.
- parameter node: The FMNode in the network that will process this piece of work.
- parameter nodeNumber: An ordered nuber that indicates which node this is. Ex: 2.
- parameter numberOfNodes: The number of Nodes in the network for this lifecycle Ex: 3.
- returns: FMWork that contians the information that needs to get send to the node to run process work.
*/
public func createWork(node:FMNode, nodeNumber:UInt, numberOfNodes:UInt) -> FMWork {
return FMWork();
}
/**
This function will get called with one piece of work that was created in createWork. Each node will process its own work, and therefore this funtion will get called once on each device, each call with a different piece of work (excluding retry logic).
- parameter node: The node that is processing this piece of work.
- parameter fromNode: The initiator node.
- parameter work: The work to be processed by this node.
- returns: FMResult The information that needs to be returned to the initiator.
*/
public func processWork(node:FMNode, fromNode:FMNode, work: FMWork) -> FMResult {
return FMResult();
}
/**
This gets called only once by FogMachine on the initiator node. It is responsible for merging all the results from the nodes in the network.
- parameter node: The initiator node. This is you.
- parameter nodeToResult: All of the results matched to the node that create each result.
*/
public func mergeResults(node:FMNode, nodeToResult :[FMNode:FMResult]) -> Void {
}
/**
This is called when a peer connects to the network.
- parameter myNode: This is you.
- parameter connectedNode: The FMNode that connected
*/
public func onPeerConnect(myNode:FMNode, connectedNode:FMNode) {
}
/**
This is called when a peer disconnects from the network.
- parameter myNode: This is you.
- parameter disconnectedNode: The FMNode that disconnected
*/
public func onPeerDisconnect(myNode:FMNode, disconnectedNode:FMNode) {
}
/**
Called when FogMachine logs/sends messages
- parameter format: Stirng you want to log.
*/
public func onLog(format:String) {
}
} | mit |
StachkaConf/ios-app | StachkaIOS/StachkaIOS/Classes/User Stories/Favourites/Feed/ViewModel/FavouritesFeedViewModel.swift | 1 | 225 | //
// FavouritesFeedViewModel.swift
// StachkaIOS
//
// Created by m.rakhmanov on 26.03.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import Foundation
protocol FavouritesFeedViewModel: FeedViewModel {}
| mit |
robinmonjo/TFImagePickerController | Library/TFImageDownloader.swift | 1 | 965 | //
// TFImageDownloader.swift
// TFImagePickerController
//
// Created by Robin Monjo on 07/09/14.
// Copyright (c) 2014 Robin Monjo. All rights reserved.
//
import UIKit
class TFImageDownloader {
lazy var operationQueue: NSOperationQueue = {
return NSOperationQueue()
}()
func downloadImageAtUrl(url: String, completion: ( image: UIImage?, error: NSError? ) -> Void ) -> Void {
let request = NSURLRequest(URL: NSURL(string: url))
let requestOperation = AFHTTPRequestOperation(request: request)
requestOperation.responseSerializer = AFImageResponseSerializer()
requestOperation.setCompletionBlockWithSuccess({(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
completion(image: responseObject as? UIImage, error: nil)
}, failure: {(operation: AFHTTPRequestOperation!, error: NSError!) in
completion(image: nil, error: error)
})
self.operationQueue.addOperation(requestOperation)
}
}
| mit |
LittleRockInGitHub/LLAlgorithm | Project/LLAlgorithmTests/LLAlgorithmTests.swift | 1 | 594 | //
// LLAlgorithmTests.swift
// LLAlgorithmTests
//
// Created by Rock Young on 2017/6/26.
// Copyright © 2017年 Rock Young. All rights reserved.
//
import XCTest
@testable import LLAlgorithm
class LLAlgorithmTests: 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()
}
}
| apache-2.0 |
nathan-hekman/Chill | Chill/Chill/HomeViewController.swift | 1 | 13196 | //
// ViewController.swift
// Chill
//
// Created by Nathan Hekman on 12/7/15.
// Copyright © 2015 NTH. All rights reserved.
//
// Icons by PixelLove.com
import UIKit
import ChameleonFramework
import HealthKit
class HomeViewController: UIViewController {
@IBOutlet var healthKitView: UIView!
@IBOutlet weak var aboutButton: UIButton!
@IBOutlet weak var setupButton: UIButton!
@IBOutlet weak var lastHeartRateTextLabel: UILabel!
@IBOutlet weak var chillLogoLabel: UILabel!
@IBOutlet weak var heartRateView: UIView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var chillResultLabel: UILabel!
@IBOutlet weak var checkWatchLabel: UILabel!
@IBOutlet weak var chillLogoTopConstraint: NSLayoutConstraint!
@IBOutlet weak var heartrateLabel: UILabel!
@IBOutlet var healthKitRequestLabel: UILabel!
let app = UIApplication.sharedApplication()
var hasAnimated = false
override func viewDidLoad() {
super.viewDidLoad()
//temporary-- save a copy of this vc for updating views (need to refactor for MVVM)
PhoneSessionManager.sharedInstance.mainVC = self
//start WCSession to communicate to/from watch
PhoneSessionManager.sharedInstance.startSession()
setupView()
setupHeartRate()
}
override func viewDidAppear(animated: Bool) {
//tryToShowPopup()
if (hasAnimated == false) {
animateToShow()
}
else {
tryToShowPopup()
}
}
func setLabelBasedOnScreenSize() {
if UIDevice().userInterfaceIdiom == .Phone {
switch UIScreen.mainScreen().nativeBounds.height {
case 480:
print("iPhone Classic")
self.healthKitRequestLabel.text = "Tap the ••• button above to see Privacy Policy information."
case 960:
print("iPhone 4 or 4S")
self.healthKitRequestLabel.text = "\n\n\n\nCheck the Health app to grant heart rate permission."
// case 1136:
// print("iPhone 5 or 5S or 5C")
// case 1334:
// print("iPhone 6 or 6S")
// case 2208:
// print("iPhone 6+ or 6S+")
default:
print("normal")
self.healthKitRequestLabel.text = "\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app in order to check your heart rate and Chill status. Check the Health app to accept. Tap the ••• button above to see Privacy Policy information."
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// todo: watch spins but never measures if you press decline in the popup. if you accept then it works
func tryToShowPopup() {
// if let permission = Utils.retrieveHasRespondedToHealthKitFromUserDefaults() {
// if permission == 0 {
//}
//}
//else {
guard HKHealthStore.isHealthDataAvailable() == true else {
return
}
// guard let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else {
// return
// }
if let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) {
let dataTypes = Set(arrayLiteral: quantityType)
let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
if let healthStore = HealthKitManager.sharedInstance.healthStore {
let status = healthStore.authorizationStatusForType(quantityType!)
switch status {
case .SharingAuthorized:
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
self.healthKitView.hidden = true
case .SharingDenied:
dispatch_async(dispatch_get_main_queue()) {
self.setLabelBasedOnScreenSize()
self.healthKitView.hidden = false
self.showPopup("\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app in order to check your heart rate and Chill status. Check the Health app to accept.")
}
Utils.updateUserDefaultsHasRespondedToHealthKit(0) //update has responded now at this point
//}
case .NotDetermined:
dispatch_async(dispatch_get_main_queue()) {
self.setLabelBasedOnScreenSize()
//self.healthKitRequestButton.hidden = false
self.healthKitView.hidden = false
//self.tryToShowPopup()
}
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.requestAuthorizationToShareTypes(dataTypes, readTypes: dataTypes) { (success, error) -> Void in
if success == false { //this is if there is an error like running on simulator
Utils.updateUserDefaultsHasRespondedToHealthKit(0) //update has responded now at this point
}
else if success == true { //user has either confirmed or said not now
self.tryToShowPopup()
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
}
}
}
}
}
}
//showPopup("\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app. Open Chill on your Apple Watch to continue.")
//}
}
func showPopup(message: String!) {
let alert = UIAlertController(title: "Health Access", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Got it", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func setupView() {
//get color scheme
ColorUtil.sharedInstance.setupFlatColorPaletteWithFlatBaseColor(FlatBlueDark(), colorscheme: ColorScheme.Analogous)
//change colors
setStatusBarStyle(UIStatusBarStyleContrast)
//view.backgroundColor = FlatBlue()
checkWatchLabel.textColor = FlatWhite()
heartrateLabel.textColor = FlatWhite()
chillResultLabel.textColor = FlatWhite()
//checkWatchLabel.hidden = true
heartrateLabel.text = "--"
//chillResultLabel.text = "You're Chill."
//setup button targets
setupButton.addTarget(self, action: "showSetupVC", forControlEvents: .TouchUpInside)
aboutButton.addTarget(self, action: "showAboutVC", forControlEvents: .TouchUpInside)
}
func showSetupVC() {
let setupVC = ViewControllerUtils.vcWithNameFromStoryboardWithName("setup", storyboardName: "Main") as! SetupViewController
presentViewController(setupVC, animated: true, completion: { _ in
})
}
func showAboutVC() {
let aboutVC = ViewControllerUtils.vcWithNameFromStoryboardWithName("about", storyboardName: "Main") as! AboutViewController
presentViewController(aboutVC, animated: true, completion: { _ in
})
}
func animateToShow() {
//checkiPhoneSize()
UIView.animateWithDuration(0.5, delay: 0.5, options: .CurveLinear, animations: { _ in
self.chillLogoLabel.transform = CGAffineTransformScale(self.chillLogoLabel.transform, 1.2, 1.2)
}, completion: { _ in
//self.chillLogoLabel.font = UIFont(name: self.chillLogoLabel.font.fontName, size: 31)
UIView.animateWithDuration(0.7, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 15, options: .CurveEaseInOut, animations: {
self.chillLogoLabel.transform = CGAffineTransformScale(self.chillLogoLabel.transform, 0.3, 0.3)
}, completion: { _ in
//move logo up to top
self.chillLogoTopConstraint.constant = -1 * (UIScreen.mainScreen().bounds.height/2) + 50
UIView.animateWithDuration(0.7, delay: 0.0, options: .CurveEaseInOut, animations: { _ in
//let originalFrame = self.chillLogoLabel.frame
//self.chillLogoLabel.frame = CGRect(x: originalFrame.origin.x, y: originalFrame.origin.y/2, width: originalFrame.width, height: originalFrame.height)
self.view.layoutIfNeeded()
}, completion: { _ in
UIView.animateWithDuration(0.5, delay: 0.3, options: .CurveLinear, animations: { _ in
self.contentView.alpha = 1.0
self.heartRateView.alpha = 1.0
self.lastHeartRateTextLabel.alpha = 1.0
self.aboutButton.alpha = 1.0
self.setupButton.alpha = 1.0
}, completion: { _ in
UIView.animateWithDuration(0.5, delay: 0.3, options: .CurveLinear, animations: { _ in
self.checkWatchLabel.alpha = 1.0
self.chillResultLabel.alpha = 1.0
}, completion: { _ in
self.hasAnimated = true
self.tryToShowPopup()
})
})
})
})
})
}
func checkiPhoneSize() {
let oldConstant = self.chillLogoTopConstraint.constant
if UIDevice().userInterfaceIdiom == .Phone {
switch UIScreen.mainScreen().nativeBounds.height {
case 480:
print("iPhone Classic")
self.chillLogoTopConstraint.constant = oldConstant - 160
case 960:
print("iPhone 4 or 4S")
self.chillLogoTopConstraint.constant = oldConstant - 160
case 1136:
print("iPhone 5 or 5S or 5C")
self.chillLogoTopConstraint.constant = oldConstant - 160
case 1334:
print("iPhone 6 or 6S")
self.chillLogoTopConstraint.constant = oldConstant - 200
case 2208:
print("iPhone 6+ or 6S+")
self.chillLogoTopConstraint.constant = oldConstant - 220
default:
print("unknown")
self.chillLogoTopConstraint.constant = oldConstant - 220
}
}
}
func setupHeartRate() {
//initially tell apple watch what last heart rate was
if let lastHeartRate = Utils.retrieveLastHeartRateFromUserDefaults() {
heartrateLabel.text = "\(lastHeartRate)"
}
if let lastChillString = Utils.retrieveChillStringFromUserDefaults() {
checkWatchLabel.hidden = true
chillResultLabel.text = "\(lastChillString)"
}
}
func sendNotification() {
let alertTime = NSDate().dateByAddingTimeInterval(5)
let notifyAlarm = UILocalNotification()
notifyAlarm.fireDate = alertTime
notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()
notifyAlarm.soundName = UILocalNotificationDefaultSoundName
notifyAlarm.category = "CHILL_CATEGORY"
notifyAlarm.alertTitle = "Chill"
notifyAlarm.alertBody = "Yo, Chill!"
app.scheduleLocalNotification(notifyAlarm)
}
}
| mit |
nghiaphunguyen/NKit | NKit/Source/CustomViews/NKTextView.swift | 1 | 2662 | //
// NKTextView.swift
//
// Created by Nghia Nguyen on 2/6/16.
//
import UIKit
import RxSwift
import RxCocoa
open class NKTextView: UITextView, UITextViewDelegate {
private var _rx_didBeginEdit = Variable<Void>(())
private var _rx_didEndEdit = Variable<Void>(())
public var rx_didBeginEdit: Observable<Void> {
return self._rx_didBeginEdit.asObservable()
}
public var rx_didEndEdit: Observable<Void> {
return self._rx_didEndEdit.asObservable()
}
public var nk_text: String? = nil {
didSet {
self.updateText()
}
}
open var nk_placeholder: String? {
didSet {
self.updateText()
}
}
open var nk_placeholderColor: UIColor? {
didSet {
self.updateText()
}
}
open var nk_contentTextColor: UIColor? {
didSet {
self.updateText()
}
}
private var nk_isEditingMode: Bool = false
private var nk_isTurnOnPlaceholder: Bool {
return !self.nk_isEditingMode && self.nk_text?.isEmpty == true
}
open func updateText() {
if self.nk_isTurnOnPlaceholder {
self.text = self.nk_placeholder
self.textColor = self.nk_placeholderColor
} else {
if self.text != self.nk_text {
self.text = self.nk_text
}
self.textColor = self.nk_contentTextColor
}
}
convenience init() {
self.init(frame: CGRect.zero, textContainer: nil)
self.setupView()
}
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
self.setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
func setupView() {
self.delegate = self
self.rx.text.subscribe(onNext: { [unowned self] in
if self.nk_text != $0 && !self.nk_isTurnOnPlaceholder {
self.nk_text = $0
}
}).addDisposableTo(self.nk_disposeBag)
self.updateText()
}
//MARK: UITextViewDelegate
open func textViewDidBeginEditing(_ textView: UITextView) {
self.nk_isEditingMode = true
self.updateText()
self._rx_didBeginEdit.nk_reload()
}
open func textViewDidEndEditing(_ textView: UITextView) {
self.nk_isEditingMode = false
self.updateText()
self._rx_didEndEdit.nk_reload()
}
}
| mit |
trident10/TDMediaPicker | TDMediaPicker/Classes/Controller/ChildViewControllers/TDMediaPermissionViewController.swift | 1 | 3714 | //
// TDMediaPermissionViewController.swift
// ImagePicker
//
// Created by Abhimanu Jindal on 24/06/17.
// Copyright © 2017 Abhimanu Jindal. All rights reserved.
//
import UIKit
protocol TDMediaPermissionViewControllerDelegate:class{
func permissionControllerDidFinish(_ controller: TDMediaPermissionViewController)
func permissionControllerDidTapClose(_ controller: TDMediaPermissionViewController)
func permissionControllerDidRequestForConfig(_ controller: TDMediaPermissionViewController)-> TDConfigPermissionScreen?
}
class TDMediaPermissionViewController: UIViewController, TDMediaPermissionViewDelegate{
// MARK: - Variables
weak var delegate: TDMediaPermissionViewControllerDelegate?
private lazy var serviceManager = TDPermissionServiceManager()
private var permissionView: TDMediaPermissionView?
// MARK: - Init
public required init() {
super.init(nibName: "TDMediaPermission", bundle: TDMediaUtil.xibBundle())
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life cycle
public override func viewDidLoad() {
super.viewDidLoad()
permissionView = self.view as? TDMediaPermissionView
permissionView?.delegate = self
setupPermissionConfig()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
requestGalleryPermission()
}
//MARK: - Private Method(s)
private func setupPermissionConfig(){
let config = self.delegate?.permissionControllerDidRequestForConfig(self)
//1.
if let customView = config?.customView{
permissionView?.setupCustomView(view: customView)
return
}
//2.
var shouldDisplayDefaultScreen = true
if let standardView = config?.standardView{
permissionView?.setupStandardView(view: standardView)
shouldDisplayDefaultScreen = false
}
if let settingsButtonConfig = config?.settingButton{
permissionView?.setupSettingsButton(buttonConfig: settingsButtonConfig)
shouldDisplayDefaultScreen = false
}
if let cancelButtonConfig = config?.cancelButton{
permissionView?.setupCancelButton(buttonConfig: cancelButtonConfig)
shouldDisplayDefaultScreen = false
}
if let captionConfig = config?.caption{
permissionView?.setupCaptionLabel(captionConfig)
shouldDisplayDefaultScreen = false
}
//3.
if shouldDisplayDefaultScreen{
permissionView?.setupDefaultScreen()
}
}
private func requestGalleryPermission(){
TDMediaUtil.requestForHardwareAccess(accessType: .Gallery) { (isGranted) in
if isGranted{
self.delegate?.permissionControllerDidFinish(self)
}
}
}
//MARK:- View Delegate Method(s)
func permissionViewSettingsButtonTapped(_ view: TDMediaPermissionView) {
DispatchQueue.main.async {
if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
}
}
}
func permissionViewCloseButtonTapped(_ view: TDMediaPermissionView) {
self.delegate?.permissionControllerDidTapClose(self)
}
}
| mit |
diegosanchezr/Chatto | Chatto/Source/Chat Items/ChatItemProtocolDefinitions.swift | 1 | 2974 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
public typealias ChatItemType = String
public protocol ChatItemProtocol: class, UniqueIdentificable {
var type: ChatItemType { get }
}
public protocol ChatItemDecorationAttributesProtocol {
var bottomMargin: CGFloat { get }
}
public protocol ChatItemPresenterProtocol: class {
static func registerCells(collectionView: UICollectionView)
var canCalculateHeightInBackground: Bool { get } // Default is false
func heightForCell(maximumWidth width: CGFloat, decorationAttributes: ChatItemDecorationAttributesProtocol?) -> CGFloat
func dequeueCell(collectionView collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell
func configureCell(cell: UICollectionViewCell, decorationAttributes: ChatItemDecorationAttributesProtocol?)
func cellWillBeShown(cell: UICollectionViewCell) // optional
func cellWasHidden(cell: UICollectionViewCell) // optional
func shouldShowMenu() -> Bool // optional. Default is false
func canPerformMenuControllerAction(action: Selector) -> Bool // optional. Default is false
func performMenuControllerAction(action: Selector) // optional
}
public extension ChatItemPresenterProtocol { // Optionals
var canCalculateHeightInBackground: Bool { return false }
func cellWillBeShown(cell: UICollectionViewCell) {}
func cellWasHidden(cell: UICollectionViewCell) {}
func shouldShowMenu() -> Bool { return false }
func canPerformMenuControllerAction(action: Selector) -> Bool { return false }
func performMenuControllerAction(action: Selector) {}
}
public protocol ChatItemPresenterBuilderProtocol {
func canHandleChatItem(chatItem: ChatItemProtocol) -> Bool
func createPresenterWithChatItem(chatItem: ChatItemProtocol) -> ChatItemPresenterProtocol
var presenterType: ChatItemPresenterProtocol.Type { get }
}
| mit |
Johnykutty/SwiftLint | Tests/SwiftLintFrameworkTests/IntegrationTests.swift | 2 | 2464 | //
// IntegrationTests.swift
// SwiftLint
//
// Created by JP Simard on 5/28/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
import SwiftLintFramework
import XCTest
let config: Configuration = {
let directory = #file.bridge()
.deletingLastPathComponent.bridge()
.deletingLastPathComponent.bridge()
.deletingLastPathComponent
_ = FileManager.default.changeCurrentDirectoryPath(directory)
return Configuration(path: Configuration.fileName)
}()
class IntegrationTests: XCTestCase {
func testSwiftLintLints() {
// This is as close as we're ever going to get to a self-hosting linter.
let swiftFiles = config.lintableFiles(inPath: "")
XCTAssert(swiftFiles.map({ $0.path! }).contains(#file), "current file should be included")
let violations = swiftFiles.flatMap {
Linter(file: $0, configuration: config).styleViolations
}
violations.forEach { violation in
violation.location.file!.withStaticString {
XCTFail(violation.reason, file: $0, line: UInt(violation.location.line!))
}
}
}
func testSwiftLintAutoCorrects() {
let swiftFiles = config.lintableFiles(inPath: "")
let corrections = swiftFiles.flatMap { Linter(file: $0, configuration: config).correct() }
for correction in corrections {
correction.location.file!.withStaticString {
XCTFail(correction.ruleDescription.description,
file: $0, line: UInt(correction.location.line!))
}
}
}
}
extension String {
func withStaticString(_ closure: (StaticString) -> Void) {
withCString {
let rawPointer = $0._rawValue
let byteSize = lengthOfBytes(using: .utf8)._builtinWordValue
let isASCII = true._getBuiltinLogicValue()
let staticString = StaticString(_builtinStringLiteral: rawPointer,
utf8CodeUnitCount: byteSize,
isASCII: isASCII)
closure(staticString)
}
}
}
extension IntegrationTests {
static var allTests: [(String, (IntegrationTests) -> () throws -> Void)] {
return [
("testSwiftLintLints", testSwiftLintLints),
("testSwiftLintAutoCorrects", testSwiftLintAutoCorrects)
]
}
}
| mit |
wwq0327/iOS8Example | iOSFontList/iOSFontList/DetailViewController.swift | 1 | 863 | //
// DetailViewController.swift
// iOSFontList
//
// Created by wyatt on 15/6/10.
// Copyright (c) 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var indexPath = NSIndexPath()
let viewModel = MasterViewModel()
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var fontSize: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let fontName = viewModel.titleAtIndexPath(indexPath)
textView.font = UIFont(name: fontName, size: 12)
}
@IBAction func sliderFontSize(sender: UISlider) {
var size = Int(sender.value)
fontSize.text = "\(size)"
let fontName = viewModel.titleAtIndexPath(indexPath)
textView.font = UIFont(name: fontName, size: CGFloat(size))
}
}
| apache-2.0 |
timd/SwiftTable | SwiftTable/ViewController.swift | 1 | 2362 | //
// ViewController.swift
// SwiftTable
//
// Created by Tim on 20/07/14.
// Copyright (c) 2014 Charismatic Megafauna Ltd. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let cellIdentifier = "cellIdentifier"
var tableData = [String]()
@IBOutlet var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
// Register the UITableViewCell class with the tableView
self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
// Setup table data
for index in 0...100 {
self.tableData.append("Item \(index)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// UITableViewDataSource methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as UITableViewCell
cell.textLabel?.text = self.tableData[indexPath.row]
return cell
}
// UITableViewDelegate methods
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK",
style: UIAlertActionStyle.Default,
handler: {
(alert: UIAlertAction!) in println("An alert of type \(alert.style.hashValue) was tapped!")
self.tableView?.deselectRowAtIndexPath(indexPath, animated: true)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit |
gpancio/iOS-Prototypes | EdmundsAPI/EdmundsAPI/Classes/VehicleOptionSet.swift | 1 | 530 | //
// VehicleOption.swift
// EdmundsAPI
//
// Created by Graham Pancio on 2016-04-27.
// Copyright © 2016 Graham Pancio. All rights reserved.
//
import Foundation
import ObjectMapper
/**
Represents a set of vehicle options.
*/
public class VehicleOptionSet: Mappable {
public var category: String?
public var options: [VehicleOption]?
required public init?(_ map: Map) {
}
public func mapping(map: Map) {
category <- map["category"]
options <- map["options"]
}
} | mit |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Tests/EurofurenceModelTests/Sync/WhenPerformingSync_ApplicationShould.swift | 2 | 925 | import EurofurenceModel
import XCTest
class WhenPerformingSync_ApplicationShould: XCTestCase {
var context: EurofurenceSessionTestBuilder.Context!
override func setUp() {
super.setUp()
context = EurofurenceSessionTestBuilder().build()
}
func testTellRefreshServiceObserversRefreshStarted() {
context.refreshLocalStore()
XCTAssertEqual(context.refreshObserver.state, .refreshing)
}
func testTellRefreshServiceObserversWhenSyncFinishesSuccessfully() {
context.refreshLocalStore()
context.api.simulateSuccessfulSync(.randomWithoutDeletions)
XCTAssertEqual(context.refreshObserver.state, .finishedRefreshing)
}
func testTellRefreshServiceObserversWhenSyncFails() {
context.refreshLocalStore()
context.api.simulateUnsuccessfulSync()
XCTAssertEqual(context.refreshObserver.state, .finishedRefreshing)
}
}
| mit |
wilzh40/ShirPrize-Me | SwiftSkeleton/ThirdViewController.swift | 1 | 2174 | //
// ThirdViewController.swift
// SwiftSkeleton
//
// Created by Wilson Zhao on 8/17/14.
// Copyright (c) 2014 Wilson Zhao. All rights reserved.
//
import Foundation
import UIKit
class ThirdViewController: UIViewController {
let singleton:Singleton = Singleton.sharedInstance
@IBOutlet var stepper:UIStepper?
@IBOutlet var quantity: UILabel?
@IBOutlet var size: UIButton?
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.
}
@IBAction func changeSizeButton (sender:AnyObject) {
if size?.titleLabel.text == "med" {
size?.setTitle("lrg", forState: UIControlState.Normal)
}
if size?.titleLabel.text == "sma" {
size?.setTitle("med", forState: UIControlState.Normal)
}
if size?.titleLabel.text == "lrg" {
size?.setTitle("sma", forState: UIControlState.Normal)
}
singleton.quoteObject.product.size = size!.titleLabel.text!
}
@IBAction func oneStep (sender:AnyObject) {
quantity?.text = "\(Int(stepper!.value))"
singleton.quoteObject.product.quantity = Int(stepper!.value)
}
@IBAction func loading (sender:AnyObject) {
self.insertSpinner(YYSpinkitView(style:YYSpinKitViewStyle.Pulse,color:UIColor.whiteColor()),
atIndex:4,backgroundColor:UIColor(red:0.498,green:0.549,blue:0.553,alpha:1.0))
}
func insertSpinner(spinner:YYSpinkitView,atIndex index:Int,backgroundColor color:UIColor){
var screenBounds = UIScreen.mainScreen().bounds
var screenWidth = CGRectGetWidth(screenBounds)
var panel = UIView(frame:CGRectOffset(screenBounds, screenWidth * CGFloat(index), 0.0))
panel.backgroundColor = color
spinner.center = CGPointMake(CGRectGetMidX(screenBounds), CGRectGetMidY(screenBounds))
panel.addSubview(spinner)
self.view.addSubview(panel)
}
}
| mit |
sergiosilvajr/watchOS | MyWatchExample/MyWatchExample WatchKit Extension/ComplicationController.swift | 1 | 3058 | //
// ComplicationController.swift
// MyWatchExample WatchKit Extension
//
// Created by Luis Sergio da Silva Junior on 1/4/16.
// Copyright © 2016 Luis Sergio. All rights reserved.
//
import ClockKit
struct Dishes {
var name : String
var shortName : String?
var table: String
var startDate : NSDate
var length : NSTimeInterval
}
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler(.Forward)
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(NSDate())
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(NSDate(timeIntervalSinceNow: (60*60*24)))
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
// Call the handler with the current timeline entry
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
handler(nil);
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
let template = CLKComplicationTemplateModularLargeStandardBody()
template.headerTextProvider = CLKTimeIntervalTextProvider(startDate: NSDate(), endDate: NSDate(timeIntervalSinceNow: (60*60*24)))
template.body1TextProvider = CLKSimpleTextProvider(text:"Prato",shortText: nil)
template.body2TextProvider = CLKSimpleTextProvider(text:"Mesa",shortText: nil)
handler(template)
}
}
| apache-2.0 |
LuckyChen73/CW_WEIBO_SWIFT | WeiBo/WeiBo/Classes/View(视图)/Compose(发布)/CustomKeyboard(自定义键盘)/WBKeyboardToolbar.swift | 1 | 3175 | //
// WBKeyboardToolbar.swift
// WeiBo
//
// Created by chenWei on 2017/4/12.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
fileprivate let baseTag = 88
/// 协议
protocol WBKeyboardToolbarDelegate: NSObjectProtocol {
/// 代理方法
///
/// - Parameter section: <#section description#>
func toggleKeyboard(section: Int)
}
class WBKeyboardToolbar: UIStackView {
/// 代理
weak var delegate: WBKeyboardToolbarDelegate?
/// 记录选中的button
var selectedButton: UIButton?
var selectedIndex: Int = 0 {
didSet {
let selectedTag = selectedIndex + baseTag
let button = viewWithTag(selectedTag) as! UIButton
selectedButton?.isSelected = false
button.isSelected = true
selectedButton = button
}
}
override init(frame: CGRect) {
super.init(frame: frame)
//水平还是垂直分布
axis = .horizontal
//等距均匀分布
distribution = .fillEqually
setupUI()
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI 搭建
extension WBKeyboardToolbar {
func setupUI() {
//有关底部按钮信息的字典数组
let buttonDicArr: [[String: Any]] = [["title": "最近", "image": "left"],
["title": "默认", "image": "mid"],
["title": "emoji", "image": "mid"],
["title": "浪小花", "image": "right"]]
//遍历字典数组创建 button
for (index,dic) in buttonDicArr.enumerated() {
let title = dic["title"] as! String
let imageName = dic["image"] as! String
let normalImageName = "compose_emotion_table_\(imageName)_normal"
let selectedImage = UIImage(named: "compose_emotion_table_\(imageName)_selected")
let button = UIButton(title: title, titleColor: UIColor.white, fontSize: 16, target: self, selector: #selector(toggleKeyobard(button:)), bgImage: normalImageName)
//设置button的选中状态的文字和背景图片
button.setTitleColor(UIColor.darkGray, for: .selected)
button.setBackgroundImage(selectedImage, for: .selected)
button.tag = index + baseTag
//和addSubView的效果是一样的
addArrangedSubview(button)
//默认选中第一个按钮
if index == 0 {
button.isSelected = true
selectedButton = button
}
}
}
}
// MARK: - 点击事件的处理
extension WBKeyboardToolbar {
/// 切换键盘
func toggleKeyobard(button: UIButton) {
selectedButton?.isSelected = false
button.isSelected = true
selectedButton = button
//响应代理方法
delegate?.toggleKeyboard(section: button.tag - baseTag)
}
}
| mit |
felipecarreramo/R3LRackspace | Example/R3LRackspace/ViewController.swift | 1 | 1848 | //
// ViewController.swift
// R3LRackspace
//
// Created by Juan Felipe Carrera Moya on 12/18/2015.
// Copyright (c) 2015 Juan Felipe Carrera Moya. All rights reserved.
//
import UIKit
import R3LRackspace
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let cloud = CloudFiles(username: "##username##", apiKey: "##ApiKey##", region: .Chicago)
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("eye", ofType: "jpg")
if let path = path , let data = NSData(contentsOfFile: path) {
cloud.putObject(data, name: "eye.jpg", container: "##containerName##") { success in
if success {
cloud.getPublicURL("##containerName##", name: "eye.jpg") { urlObject in
if let urlObject = urlObject {
print("URL: \(urlObject)")
}
}
}
}
}
//cloud.createContainer("jugofresh-test-cdn")
//cloud.getPublicURL("jugofresh-test-cdn", name:"eye.jpg")
//cloud.getContainers()
//cloud.enableContainerForCDN("jugofresh-test-cdn")
//cloud.getPublicContainers()
// cloud.getPublicURL("jugofresh-JC", name: "testImage.jpg") { urlObject in
//
// if let urlObject = urlObject {
// print(urlObject)
// }
//
// }
//cloud.getContainer("jugofresh-JC")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
ResearchSuite/ResearchSuiteAppFramework-iOS | Source/Core/Classes/RSAFRootViewController.swift | 1 | 2395 | //
// RSAFRootViewController.swift
// Pods
//
// Created by James Kizer on 3/22/17.
//
//
import UIKit
import ReSwift
import ResearchSuiteTaskBuilder
import ResearchKit
open class RSAFRootViewController: UIViewController, RSAFRootViewControllerProtocol, StoreSubscriber {
public var presentedActivity: UUID?
private var state: RSAFCombinedState?
public var taskBuilder: RSTBTaskBuilder?
weak public var RSAFDelegate: RSAFRootViewControllerProtocolDelegate?
public var contentHidden = false {
didSet {
guard contentHidden != oldValue && isViewLoaded else { return }
if let vc = self.presentedViewController {
vc.view.isHidden = contentHidden
}
self.view.isHidden = contentHidden
}
}
override open func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.store?.subscribe(self)
}
deinit {
self.store?.unsubscribe(self)
}
open func newState(state: RSAFCombinedState) {
self.state = state
if self.presentedActivity == nil,
let coreState = state.coreState as? RSAFCoreState,
let (uuid, activityRun, taskBuilder) = coreState.activityQueue.first {
self.presentedActivity = uuid
self.runActivity(uuid: uuid, activityRun: activityRun, taskBuilder: taskBuilder, completion: { [weak self] in
self?.presentedActivity = nil
//potentially launch new activity
if let state = self?.state {
self?.newState(state: state)
}
self?.RSAFDelegate?.activityRunDidComplete(activityRun: activityRun)
})
}
}
open var store: Store<RSAFCombinedState>? {
guard let delegate = UIApplication.shared.delegate as? RSAFApplicationDelegate else {
return nil
}
return delegate.reduxStore
}
// open var taskBuilder: RSTBTaskBuilder? {
// guard let delegate = UIApplication.shared.delegate as? RSAFApplicationDelegate else {
// return nil
// }
//
// return delegate.taskBuilderManager?.rstb
// }
}
| apache-2.0 |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Common/Controllers/QDCommonViewController.swift | 1 | 987 | //
// QDCommonViewController.swift
// QMUI.swift
//
// Created by TonyHan on 2018/3/6.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
class QDCommonViewController: QMUICommonViewController, QDChangingThemeDelegate {
override func didInitialized() {
super.didInitialized()
NotificationCenter.default.addObserver(self, selector: #selector(handleThemeChanged(_:)), name: Notification.QD.ThemeChanged, object: nil)
}
@objc private func handleThemeChanged(_ notification: Notification) {
guard let userInfo = notification.userInfo else {
return
}
if let beforeChanged = userInfo[QDThemeNameKey.beforeChanged] as? QDThemeProtocol, let afterChanged = userInfo[QDThemeNameKey.afterChanged] as? QDThemeProtocol {
themeBeforeChanged(beforeChanged, afterChanged: afterChanged)
}
}
func themeBeforeChanged(_ beforeChanged: QDThemeProtocol, afterChanged: QDThemeProtocol) {
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1390-swift-typebase-gettypevariables.swift | 13 | 530 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b(self.d where f.B<d where l) {
protocol A where Optional<1 {
struct e = D> : b() -> {
}
class A, U, range.a<T) -> {
}
}
typealias A {
0)
}
func i: end: A, (b: A, object2: e : AnyObject, Any) -> T>(f, x in c {
class a<c()) -> Void>(".substringWithRange() -> Int {
protocol d {
typealias e : a {
("foo""
func a
| apache-2.0 |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/FernandoPreciado/Practica #5.swift | 1 | 327 | // Alumno: Fernando Preciado Salman
// Numero de Control: 12211415
// Patrones de diseño
// Practica: 1 capitulo 5
// Realizar un programa que simule el tiro de una moneda
import Foundation
let coinflip = Int(arc4random_uniform(UInt32(2)))
if (coinflip == 1)
{
print("Cara")
}
else
{
print("Cruz")
}
| gpl-3.0 |
TouchInstinct/LeadKit | TIFoundationUtils/TITimer/Sources/TITimer/TITimer.swift | 1 | 5774 | //
// Copyright (c) 2021 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import TISwiftUtils
public final class TITimer: ITimer {
private let mode: TimerRunMode
private let type: TimerType
private var sourceTimer: Invalidatable?
private var enterBackgroundDate: Date?
private var interval: TimeInterval = 0
public private(set) var elapsedTime: TimeInterval = 0
public var isRunning: Bool {
sourceTimer != nil
}
public var eventHandler: ParameterClosure<TimeInterval>?
// MARK: - Initialization
public init(type: TimerType, mode: TimerRunMode) {
self.mode = mode
self.type = type
if mode == .activeAndBackground {
addObserver()
}
}
deinit {
if mode == .activeAndBackground {
removeObserver()
}
invalidate()
}
// MARK: - Public
public func start(with interval: TimeInterval = 1) {
invalidate()
self.interval = interval
self.elapsedTime = 0
createTimer(with: interval)
eventHandler?(elapsedTime)
}
public func invalidate() {
sourceTimer?.invalidate()
sourceTimer = nil
}
public func pause() {
guard isRunning else {
return
}
invalidate()
}
public func resume() {
guard !isRunning else {
return
}
createTimer(with: interval)
}
// MARK: - Actions
@objc private func handleSourceUpdate() {
guard enterBackgroundDate == nil else {
return
}
elapsedTime += interval
eventHandler?(elapsedTime)
}
// MARK: - Private
private func createTimer(with interval: TimeInterval) {
switch type {
case let .dispatchSourceTimer(queue):
sourceTimer = startDispatchSourceTimer(interval: interval, queue: queue)
case let .runloopTimer(runloop, mode):
sourceTimer = startTimer(interval: interval, runloop: runloop, mode: mode)
case let .custom(timer):
sourceTimer = timer
timer.start(with: interval)
}
}
}
// MARK: - Factory
extension TITimer {
public convenience init(mode: TimerRunMode = .activeAndBackground) {
self.init(type: .runloopTimer(runloop: .main, mode: .common), mode: mode)
}
}
// MARK: - NotificationCenter
private extension TITimer {
func addObserver() {
NotificationCenter.default.addObserver(self,
selector: #selector(willEnterForegroundNotification),
name: UIApplication.willEnterForegroundNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(didEnterBackgroundNotification),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
func removeObserver() {
NotificationCenter.default.removeObserver(self)
}
@objc func willEnterForegroundNotification() {
guard let unwrappedEnterBackgroundDate = enterBackgroundDate else {
return
}
let timeInBackground = -unwrappedEnterBackgroundDate.timeIntervalSinceNow.rounded()
enterBackgroundDate = nil
elapsedTime += timeInBackground
eventHandler?(elapsedTime)
}
@objc func didEnterBackgroundNotification() {
enterBackgroundDate = Date()
}
}
// MARK: - DispatchSourceTimer
private extension TITimer {
func startDispatchSourceTimer(interval: TimeInterval, queue: DispatchQueue) -> Invalidatable? {
let timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
timer.schedule(deadline: .now() + interval, repeating: interval)
timer.setEventHandler() { [weak self] in
self?.handleSourceUpdate()
}
return timer as? DispatchSource
}
}
// MARK: - Timer
private extension TITimer {
func startTimer(interval: TimeInterval, runloop: RunLoop, mode: RunLoop.Mode) -> Invalidatable {
let timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
self?.handleSourceUpdate()
}
runloop.add(timer, forMode: mode)
return timer
}
}
| apache-2.0 |
peaks-cc/iOS11_samplecode | chapter_11/MyQRCode/MyQRCodeKit/Me.swift | 1 | 4678 | //
// Me.swift
// MyQRCodeKit
//
// Created by Kishikawa Katsumi on 2017/09/04.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import Foundation
import CoreImage
public struct Me: Codable {
public let firstname: String?
public let lastname: String?
public let company: String?
public let street: String?
public let city: String?
public let zipcode: String?
public let country: String?
public let phone: String?
public let email: String?
public let website: String?
public let birthday: String?
private static var userDefaults: UserDefaults {
get {
return UserDefaults(suiteName: "group.com.kishikawakatsumi.myqrcode")!
}
}
let key = "me"
public init(firstname: String?, lastname: String?, company: String?,
street: String?, city: String?, zipcode: String?, country: String?,
phone: String?, email: String?, website: String?,
birthday: String?) {
self.firstname = firstname
self.lastname = lastname
self.company = company
self.street = street
self.city = city
self.zipcode = zipcode
self.country = country
self.phone = phone
self.email = email
self.website = website
self.birthday = birthday
}
public func generateVisualCode() -> UIImage? {
let parameters: [String : Any] = [
"inputMessage": vCardRepresentation(),
"inputCorrectionLevel": "L"
]
let filter = CIFilter(name: "CIQRCodeGenerator", withInputParameters: parameters)
guard let outputImage = filter?.outputImage else {
return nil
}
let scaledImage = outputImage.transformed(by: CGAffineTransform(scaleX: 6, y: 6))
guard let cgImage = CIContext().createCGImage(scaledImage, from: scaledImage.extent) else {
return nil
}
return UIImage(cgImage: cgImage)
}
private func vCardRepresentation() -> Data! {
var vCard = [String]()
vCard += ["BEGIN:VCARD"]
vCard += ["VERSION:3.0"]
switch (firstname, lastname) {
case let (firstname?, lastname?):
vCard += ["N:\(lastname);\(firstname);"]
case let (firstname?, nil):
vCard += ["N:\(firstname);"]
case let (nil, lastname?):
vCard += ["N:\(lastname);"]
case (nil, nil):
break
}
if let company = company {
vCard += ["ORG:\(company)"]
}
switch (street, city, zipcode, country) {
case let (street?, city?, zipcode?, country?):
vCard += ["ADR:;;\(street);\(city);;\(zipcode);\(country)"]
case let (nil, city?, zipcode?, country?):
vCard += ["ADR:;;;\(city);;\(zipcode);\(country)"]
case let (street?, nil, zipcode?, country?):
vCard += ["ADR:;;\(street);;;\(zipcode);\(country)"]
case let (street?, city?, nil, country?):
vCard += ["ADR:;;\(street);\(city);;;\(country)"]
case let (street?, city?, zipcode?, nil):
vCard += ["ADR:;;\(street);\(city);;\(zipcode);"]
case let (nil, nil, zipcode?, country?):
vCard += ["ADR:;;;;;\(zipcode);\(country)"]
case let (street?, nil, nil, country?):
vCard += ["ADR:;;\(street);;;;\(country)"]
case let (street?, city?, nil, nil):
vCard += ["ADR:;;\(street);\(city);;;"]
case let (nil, city?, nil, country?):
vCard += ["ADR:;;;\(city);;;\(country)"]
case let (street?, nil, zipcode?, nil):
vCard += ["ADR:;;\(street);;;\(zipcode);"]
case let (nil, city?, zipcode?, nil):
vCard += ["ADR:;;;\(city);;\(zipcode);"]
case let (nil, nil, nil, country?):
vCard += ["ADR:;;;;;;\(country)"]
case let (street?, nil, nil, nil):
vCard += ["ADR:;;\(street);;;;"]
case let (nil, city?, nil, nil):
vCard += ["ADR:;;;\(city);;;"]
case let (nil, nil, zipcode?, nil):
vCard += ["ADR:;;;;;\(zipcode);"]
case (nil, nil, nil, nil):
break
}
if let phone = phone {
vCard += ["TEL:\(phone)"]
}
if let email = email {
vCard += ["EMAIL:\(email)"]
}
if let website = website {
vCard += ["URL:\(website)"]
}
if let birthday = birthday {
vCard += ["BDAY:\(birthday)"]
}
vCard += ["END:VCARD"]
return vCard.joined(separator: "\n").data(using: .utf8)
}
}
| mit |
pablot/HardRider | HardRider/GameScene.swift | 1 | 2156 | //
// GameScene.swift
// HardRider
//
// Created by Paweł Tymura on 03.03.2016.
// Copyright (c) 2016 Paweł Tymura. All rights reserved.
//
import SpriteKit
import CoreMotion
import UIKit
class GameScene: SKScene {
var mainscreen = UIScreen()
var spaceShip = MainGameObject(imageNamed: "Spaceship")
var sand = SKSpriteNode(imageNamed: "piasek")
var motionManager = CMMotionManager()
var dest = CGPoint(x: 0, y:0)
override func didMoveToView(view:SKView) {
self.backgroundColor = UIColor.yellowColor()
sand.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
sand.size = CGSize(width: 1024, height: 768)
self.addChild(sand)
spaceShip.position = CGPoint(x: 674 /*CGRectGetMidX(self.frame)*/, y:700)
spaceShip.size = CGSize(width: 100.0, height: 150.0)
self.addChild(spaceShip)
if motionManager.accelerometerAvailable == true {
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler:{
data, error in
let currentX = self.spaceShip.position.x
let currentY = self.spaceShip.position.y
var change: CGFloat = 0
if data!.acceleration.x != 0
{
change = currentX + CGFloat(data!.acceleration.x * 100)
if self.mainscreen.bounds.contains(CGPoint(x: change, y: currentY)) {
self.dest.x = change
}
}
if data!.acceleration.y != 0
{
change = currentY + CGFloat(data!.acceleration.y * 100)
if self.mainscreen.bounds.contains(CGPoint(x: currentX, y: change)) {
self.dest.y = change
}
}
})
}
}
override func update(currentTime: CFTimeInterval) {
let action = SKAction.moveTo(dest, duration: 1)
self.spaceShip.runAction(action)
}
}
| mit |
FranDepascuali/ProyectoAlimentar | ProyectoAlimentar/Domain/Model/User.swift | 1 | 292 | //
// User.swift
// ProyectoAlimentar
//
// Created by Francisco Depascuali on 10/28/16.
// Copyright © 2016 Alimentar. All rights reserved.
//
import Foundation
public struct User {
public let email: String
public let userName: String
public let name: String
}
| apache-2.0 |
sodascourse/swift-introduction | Swift-Introduction.playground/Pages/Type Casting.xcplaygroundpage/Contents.swift | 1 | 3046 | /*:
# Type Check and Casting
Type casting is a way to check the type of an instance, or to treat that
instance as a different superclass or subclass from somewhere
else in its own class hierarchy.
Type casting in Swift is implemented with the `is` and `as` operators.
These two operators provide a simple and expressive way to
check the type of a value or cast a value to a different type.
*/
protocol Animal {}
protocol FourLegsAnimal: Animal {}
struct Cat: FourLegsAnimal {
func asMaster() -> String {
return "Meow, I'm your master."
}
}
class Dog: FourLegsAnimal {}
class Duck: Animal {}
let zoo: [Animal] = [Cat(), Dog(), Duck(), Dog(), Cat(), Cat()]
//: Use `is` to test whether this variable is an instance of Class/Struct or Protocol conformance
var catsCount = 0, dogsCount = 0, fourLegsCount = 0
for animal in zoo {
if animal is Cat {
catsCount += 1
}
if animal is Dog {
dogsCount += 1
}
if animal is FourLegsAnimal {
fourLegsCount += 1
}
}
"We have \(catsCount) cats in the zoo."
"We have \(dogsCount) dogs in the zoo."
"We have \(fourLegsCount) four-leg animals."
//: Use `as` to cast type of instance
for animal in zoo {
if let cat = animal as? Cat {
cat.asMaster()
}
}
//: The Swift compiler would help you to check the casting between types.
let cat = Cat()
//cat is Animal // Uncomment to see the warning Xcode yields.
//cat is Dog // Uncomment to see the warning Xcode yields.
let animal = cat as Animal // Up-casting. Use `option+click` to see the type of `animal`
//let dog = cat as? Dog // Check the warning and the value of `dog`
//let someDog = cat as Dog // Uncomment to see the error Xcode yields.
//let someDog2 = cat as! Dog // Uncomment to see the error Xcode yields.
let someCat = animal as? Cat // // Down-casting. Use `option+click` to see the type of `someCat`
let someDog3 = animal as? Dog // Down-casting. Check the value and the type of `someDog3`
/*:
## `Any` and `AnyObject`
Swift provides two special types for working with nonspecific types:
- `Any` can represent an instance of any type at all, including function types.
- `AnyObject` can represent an instance of any class type.
Use `Any` and `AnyObject` only when you explicitly need the behavior and capabilities they provide.
It is always better to be specific about the types you expect to work with in your code.
By making the type context clear, Swift could keep your code safe to execute.
*/
var anything: [Any] = [-1, "XD", ["yo"], ["answer": 42], true, 57, "Hello"]
var stringCount = 0, sumOfAllInt = 0
for item in anything {
// Here we uses "Pattern Matching" (google 'Swift Pattern Matching')
// But anyway, you can still use `if-else` to implement this.
switch item {
case is String:
stringCount += 1
case let integer as Int:
sumOfAllInt += integer
default: () // Do nothing
}
}
stringCount
sumOfAllInt
//: ---
//:
//: [<- Previous](@previous) | [Next ->](@next)
//:
| apache-2.0 |
breadwallet/breadwallet-ios | breadwallet/src/ViewControllers/ManageWalletsViewController.swift | 1 | 6320 | //
// ManageWalletsViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2019-07-30.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import UIKit
private let addWalletButtonHeight: CGFloat = 72.0
class ManageWalletsViewController: UITableViewController {
private let assetCollection: AssetCollection
private let coreSystem: CoreSystem
private var displayData = [CurrencyMetaData]()
init(assetCollection: AssetCollection, coreSystem: CoreSystem) {
self.assetCollection = assetCollection
self.coreSystem = coreSystem
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
tableView.backgroundColor = .darkBackground
tableView.rowHeight = 66.0
tableView.separatorStyle = .none
title = S.TokenList.manageTitle
tableView.register(ManageCurrencyCell.self, forCellReuseIdentifier: ManageCurrencyCell.cellIdentifier)
tableView.setEditing(true, animated: true)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(pushAddWallets))
//If we are first in the nav controller stack, we need a close button
if navigationController?.viewControllers.first == self {
let button = UIButton.close
button.tintColor = .white
button.tap = {
self.dismiss(animated: true, completion: nil)
}
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
displayData = assetCollection.enabledAssets
tableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
assetCollection.saveChanges()
}
override func viewDidLayoutSubviews() {
setupAddButton()
}
private func removeCurrency(_ identifier: CurrencyId) {
guard let index = displayData.firstIndex(where: { $0.uid == identifier }) else { return }
displayData.remove(at: index)
assetCollection.removeAsset(at: index)
tableView.performBatchUpdates({
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .left)
}, completion: { [unowned self] _ in
self.tableView.reloadData() // to update isRemovable
})
}
private func setupAddButton() {
guard tableView.tableFooterView == nil else { return }
let topInset: CGFloat = C.padding[1]
let leftRightInset: CGFloat = C.padding[2]
let width = tableView.frame.width - tableView.contentInset.left - tableView.contentInset.right
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: addWalletButtonHeight))
let addButton = UIButton()
addButton.tintColor = .disabledWhiteText
addButton.setTitleColor(Theme.tertiaryText, for: .normal)
addButton.setTitleColor(.transparentWhite, for: .highlighted)
addButton.titleLabel?.font = Theme.body1
addButton.imageView?.contentMode = .scaleAspectFit
addButton.setBackgroundImage(UIImage(named: "add"), for: .normal)
addButton.contentHorizontalAlignment = .center
addButton.contentVerticalAlignment = .center
addButton.setTitle("+ " + S.TokenList.addTitle, for: .normal)
addButton.tap = { [weak self] in
guard let `self` = self else { return }
self.pushAddWallets()
}
addButton.frame = CGRect(x: leftRightInset, y: topInset,
width: footerView.frame.width - (2 * leftRightInset),
height: addWalletButtonHeight)
footerView.addSubview(addButton)
footerView.backgroundColor = Theme.primaryBackground
tableView.tableFooterView = footerView
}
@objc private func pushAddWallets() {
let vc = AddWalletsViewController(assetCollection: assetCollection, coreSystem: coreSystem)
navigationController?.pushViewController(vc, animated: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ManageWalletsViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ManageCurrencyCell.cellIdentifier, for: indexPath) as? ManageCurrencyCell else {
return UITableViewCell()
}
let metaData = displayData[indexPath.row]
// cannot remove a native currency if its tokens are enabled, or remove the last currency
let currencyIsRemovable = !coreSystem.isWalletRequired(for: metaData.uid) && assetCollection.enabledAssets.count > 1
cell.set(currency: metaData,
balance: nil,
listType: .manage,
isHidden: false,
isRemovable: currencyIsRemovable)
cell.didRemoveIdentifier = { [unowned self] identifier in
self.removeCurrency(identifier)
}
return cell
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = displayData[sourceIndexPath.row]
displayData.remove(at: sourceIndexPath.row)
displayData.insert(movedObject, at: destinationIndexPath.row)
assetCollection.moveAsset(from: sourceIndexPath.row, to: destinationIndexPath.row)
}
}
| mit |
austinzheng/swift | validation-test/compiler_crashers_fixed/26638-bool.swift | 65 | 457 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func d{
class B{
struct B{let s={:{{}
}}
{var:{class
case,
| apache-2.0 |
itsbriany/Sudoku | Sudoku/SudokuButtonCollectionViewCell.swift | 1 | 273 | //
// SudokuButtonCollectionViewCell.swift
// Sudoku
//
// Created by Brian Yip on 2016-02-01.
// Copyright © 2016 Brian Yip. All rights reserved.
//
import UIKit
class SudokuButtonCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var value: UIButton!
}
| apache-2.0 |
zhou9734/Warm | Warm/Classes/Home/Controller/SubjectViewController.swift | 1 | 7055 | //
// SubjectViewController.swift
// Warm
//
// Created by zhoucj on 16/9/22.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
import SVProgressHUD
let SubjectSalonTableReuseIdentifier = "SubjectSalonTableReuseIdentifier"
let SubjectClassesTableReuseIdentifier = "SubjectClassesTableReuseIdentifier"
class SubjectViewController: UIViewController {
let homeViewModel = HomeViewModel()
var rdata: WRdata?
var subid: Int64?{
didSet{
guard let _subid = subid else{
SVProgressHUD.showErrorWithStatus("参数传递错误")
return
}
view.addSubview(progressBar)
view.bringSubviewToFront(progressBar)
unowned let tmpSelf = self
tmpSelf.progressBar.progress = 0.7
UIView.animateWithDuration(1) { () -> Void in
tmpSelf.view.layoutIfNeeded()
}
homeViewModel.loadSubjectDetail(_subid) { (data, error) -> () in
guard let _rdata = data as? WRdata else {
return
}
tmpSelf.rdata = _rdata
tmpSelf.tmpWebView.loadRequest(NSURLRequest(URL: NSURL(string: _rdata.content!)!))
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//隐藏navigationBar
navigationController?.navigationBarHidden = false
}
private func setupUI(){
view.backgroundColor = UIColor.whiteColor()
navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: shareBtn), UIBarButtonItem(customView: loveBtn)]
view.addSubview(tableView)
}
private lazy var loveBtn: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "navigationLoveNormal_22x20_"), forState: .Normal)
btn.addTarget(self, action: Selector("loveBtnClick:"), forControlEvents: .TouchUpInside)
btn.setBackgroundImage(UIImage(named: "navigation_liked_22x22_"), forState: .Selected)
btn.sizeToFit()
return btn
}()
private lazy var shareBtn: UIButton = UIButton(target: self, backgroundImage: "navigationShare_20x20_", action: Selector("shareBtnClick"))
private lazy var tableView: UITableView = {
let tv = UITableView(frame: ScreenBounds, style: .Plain)
tv.registerClass(SubjectSalonTableViewCell.self, forCellReuseIdentifier: SubjectSalonTableReuseIdentifier)
tv.registerClass(SubjectClassesTableViewCell.self, forCellReuseIdentifier: SubjectClassesTableReuseIdentifier)
tv.dataSource = self
tv.delegate = self
tv.separatorStyle = .None
return tv
}()
private lazy var tableHeadView: SubjectHeadView = SubjectHeadView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 2))
private lazy var tmpWebView: UIWebView = {
let wv = UIWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, 2))
wv.alpha = 0
wv.delegate = self
wv.sizeToFit()
return wv
}()
//进度条
private lazy var progressBar: UIProgressView = {
let pb = UIProgressView()
pb.frame = CGRect(x: 0, y: 64, width: ScreenWidth, height: 1)
pb.backgroundColor = UIColor.whiteColor()
pb.progressTintColor = UIColor(red: 116.0/255.0, green: 213.0/255.0, blue: 53.0/255.0, alpha: 1.0)
return pb
}()
@objc func loveBtnClick(btn: UIButton){
btn.selected = !btn.selected
}
@objc func shareBtnClick(){
ShareTools.shareApp(self, shareText: nil)
}
deinit{
tmpWebView.delegate = nil
tmpWebView.stopLoading()
SVProgressHUD.dismiss()
}
}
//MARK: - UITableViewDataSource代理
extension SubjectViewController: UITableViewDataSource{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rdata?.itmes?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = rdata?.itmes![indexPath.row]
if item?.type == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier(SubjectClassesTableReuseIdentifier, forIndexPath: indexPath) as! SubjectClassesTableViewCell
cell.item = item
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier(SubjectSalonTableReuseIdentifier, forIndexPath: indexPath) as! SubjectSalonTableViewCell
cell.item = item
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 140
}
}
//MARK: - UITableViewDelegate代理
extension SubjectViewController: UITableViewDelegate{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
//释放选中效果
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let item = rdata?.itmes![indexPath.row]
if item?.type == 1{
guard let id = item?.classes?.id else{
alert("数据错误!")
return
}
let classesVC = ClassesViewController()
classesVC.classesId = id
navigationController?.pushViewController(classesVC, animated: true)
}else if item?.type == 2{
guard let id = item?.salon?.id else{
alert("数据错误!")
return
}
let salonVC = SalonViewController()
salonVC.salonId = id
navigationController?.pushViewController(salonVC, animated: true)
}
}
}
extension SubjectViewController: UIWebViewDelegate{
//为了解决UIWebView高度自适应
func webViewDidFinishLoad(webView: UIWebView) {
//客户端高度
let str = "document.body.offsetHeight"
let clientheightStr = webView.stringByEvaluatingJavaScriptFromString(str)
let height = CGFloat((clientheightStr! as NSString).floatValue) + 80
//移除多余的webView
tmpWebView.removeFromSuperview()
unowned let tmpSelf = self
tmpSelf.progressBar.progress = 1.0
UIView.animateWithDuration(1.3, animations: { () -> Void in
tmpSelf.view.layoutIfNeeded()
}) { (_) -> Void in
tmpSelf.progressBar.removeFromSuperview()
}
tableHeadView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: height)
guard let data = rdata else{
SVProgressHUD.dismiss()
alert("获取数据失败")
return
}
tableHeadView.titleStrng = data.title
tableHeadView.urlString = data.content
tableView.tableHeaderView = tableHeadView
tableView.reloadData()
// SVProgressHUD.dismiss()
}
}
| mit |
Eonil/Monolith.Swift | Standards/Sources/RFC1866+RFC4627.swift | 3 | 633 | //
// RFC1866+RFC4627.swift
// Standards
//
// Created by Hoon H. on 11/21/14.
//
//
import Foundation
/// MARK:
/// Move to `RFC1866+RFC4627.swift` when compiler bug to be fixed.
public extension RFC1866.Form.URLEncoded {
/// Supports only string -> string flat JSON object.
public static func encode(parameters:JSON.Object) -> String? {
var ps2 = [:] as [String:String]
for p1 in parameters {
if p1.1.string == nil {
return Error.trap("Input string contains non-string (possibly complex) value, and it cannot be used to form a query-string.")
}
ps2[p1.0] = p1.1.string!
}
return encode(ps2)
}
}
| mit |
tardieu/swift | validation-test/compiler_crashers_fixed/01016-swift-genericsignature-get.swift | 65 | 530 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
A<d
class A<l : T) -> Bool {
struct X<B {
func b> String {
protocol c == {
}
class a {
}
}
protocol a {
typealias d: d = [c: String
| apache-2.0 |
ZeeQL/ZeeQL3 | Tests/ZeeQLTests/SQLite3OGoAdaptorTests.swift | 1 | 5076 | //
// SQLite3OGoAdaptorTests.swift
// ZeeQL
//
// Created by Helge Hess on 06/03/2017.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
import Foundation
import XCTest
@testable import ZeeQL
class SQLite3OGoAdaptorTests: AdaptorOGoTestCase {
override var adaptor : Adaptor! {
XCTAssertNotNil(_adaptor)
return _adaptor
}
var _adaptor : SQLite3Adaptor = {
var pathToTestDB : String = {
#if ZEE_BUNDLE_RESOURCES
let bundle = Bundle(for: type(of: self) as! AnyClass)
let url = bundle.url(forResource: "OGo", withExtension: "sqlite3")
guard let path = url?.path else { return "OGo.sqlite3" }
return path
#else
let dataPath = lookupTestDataPath()
return "\(dataPath)/OGo.sqlite3"
#endif
}()
return SQLite3Adaptor(pathToTestDB)
}()
func testCount() throws {
let db = Database(adaptor: adaptor)
class OGoObject : ActiveRecord {
// TODO: actually add KVC to store the key in this var
var id : Int { return value(forKey: "id") as! Int }
}
class OGoCodeEntity<T: OGoObject> : CodeEntity<T> {
// add common attributes, and support them in reflection
let objectVersion = Info.Int(column: "object_version")
}
class Person : OGoObject, EntityType {
class Entity : OGoCodeEntity<Person> {
let table = "person"
let id = Info.Int(column: "company_id")
let isPerson = Info.Int(column: "is_person")
let login = Info.OptString(width: 50)
let isLocked = Info.Int(column: "is_locked")
let number = Info.String(width: 100)
let lastname = Info.OptString(column: "name")
let firstname : String? = nil
let middlename : String? = nil
}
static let fields = Entity()
static let entity : ZeeQL.Entity = fields
}
let persons = ActiveDataSource<Person>(database: db)
persons.fetchSpecification = Person
.where(Person.fields.login.like("*"))
.limit(4)
.order(by: Person.fields.login)
do {
let count = try persons.fetchCount()
if printResults {
print("got person count: #\(count)")
}
XCTAssert(count > 2)
}
catch {
XCTAssertNil(error, "catched error: \(error)")
}
}
func testFetchGlobalIDs() throws {
let db = Database(adaptor: adaptor)
class OGoObject : ActiveRecord {
// TODO: actually add KVC to store the key in this var
var id : Int { return value(forKey: "id") as! Int }
}
class OGoCodeEntity<T: OGoObject> : CodeEntity<T> {
// add common attributes, and support them in reflection
let objectVersion = Info.Int(column: "object_version")
}
class Person : OGoObject, EntityType {
class Entity : OGoCodeEntity<Person> {
let table = "person"
let id = Info.Int(column: "company_id")
let isPerson = Info.Int(column: "is_person")
let login = Info.OptString(width: 50)
let isLocked = Info.Int(column: "is_locked")
let number = Info.String(width: 100)
let lastname = Info.OptString(column: "name")
let firstname : String? = nil
let middlename : String? = nil
}
static let fields = Entity()
static let entity : ZeeQL.Entity = fields
}
let persons = ActiveDataSource<Person>(database: db)
persons.fetchSpecification = Person
.where(Person.fields.login.like("*"))
.limit(4)
.order(by: Person.fields.login)
do {
let gids = try persons.fetchGlobalIDs()
if printResults {
print("got person count: \(gids)")
}
XCTAssert(gids.count > 2)
// and now lets fetch the GIDs
let objects = try persons.fetchObjects(with: gids)
if printResults {
print("got persons: #\(objects.count)")
}
XCTAssertEqual(objects.count, gids.count)
}
catch {
XCTAssertNil(error, "catched error: \(error)")
}
}
// MARK: - Non-ObjC Swift Support
static var allTests = [
// super
( "testRawAdaptorChannelQuery", testRawAdaptorChannelQuery ),
( "testEvaluateQueryExpression", testEvaluateQueryExpression ),
( "testRawTypeSafeQuery", testRawTypeSafeQuery ),
( "testSimpleTX", testSimpleTX ),
( "testAdaptorDataSourceFindByID", testAdaptorDataSourceFindByID ),
( "testBasicReflection", testBasicReflection ),
( "testTableReflection", testTableReflection ),
( "testCodeSchema", testCodeSchema ),
( "testCodeSchemaWithJoinQualifier", testCodeSchemaWithJoinQualifier ),
( "testCodeSchemaWithRelshipPrefetch", testCodeSchemaWithRelshipPrefetch ),
( "testCodeSchemaWithTypedFetchSpec", testCodeSchemaWithTypedFetchSpec ),
// own
( "testCount", testCount ),
]
}
| apache-2.0 |
ingresse/ios-sdk | IngresseSDKTests/Model/UserTests.swift | 1 | 1878 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
import XCTest
@testable import IngresseSDK
class UserTests: XCTestCase {
func testDecode() {
// Given
var json = [String: Any]()
json["id"] = 1
json["name"] = "name"
json["email"] = "email"
json["type"] = "type"
json["username"] = "username"
json["phone"] = "phone"
json["cellphone"] = "cellphone"
json["pictures"] = [:]
json["social"] = [
[
"network": "facebook",
"id": "facebookId"
], [
"network": "twitter",
"id": "twitterId"
]
]
// When
let obj = JSONDecoder().decodeDict(of: User.self, from: json)
// Then
XCTAssertNotNil(obj)
XCTAssertEqual(obj?.id, 1)
XCTAssertEqual(obj?.name, "name")
XCTAssertEqual(obj?.email, "email")
XCTAssertEqual(obj?.type, "type")
XCTAssertEqual(obj?.username, "username")
XCTAssertEqual(obj?.phone, "phone")
XCTAssertEqual(obj?.cellphone, "cellphone")
XCTAssertEqual(obj?.pictures, [:])
let social = obj!.social
XCTAssertEqual(social[0].network, "facebook")
XCTAssertEqual(social[1].network, "twitter")
XCTAssertEqual(social[0].id, "facebookId")
XCTAssertEqual(social[1].id, "twitterId")
}
func testEmptyInit() {
// When
let obj = User()
// Then
XCTAssertEqual(obj.id, 0)
XCTAssertEqual(obj.name, "")
XCTAssertEqual(obj.email, "")
XCTAssertEqual(obj.type, "")
XCTAssertEqual(obj.username, "")
XCTAssertEqual(obj.phone, "")
XCTAssertEqual(obj.cellphone, "")
XCTAssertEqual(obj.pictures, [:])
XCTAssertEqual(obj.social, [])
}
}
| mit |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/AppContextBridge.swift | 1 | 5076 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for context management purposes
Auto-generated implementation of IAppContext specification.
*/
public class AppContextBridge : IAppContext {
/**
Group of API.
*/
private var apiGroup : IAdaptiveRPGroup = IAdaptiveRPGroup.Kernel
public func getAPIGroup() -> IAdaptiveRPGroup? {
return self.apiGroup
}
/**
API Delegate.
*/
private var delegate : IAppContext? = nil
/**
Constructor with delegate.
@param delegate The delegate implementing platform specific functions.
*/
public init(delegate : IAppContext?) {
self.delegate = delegate
}
/**
Get the delegate implementation.
@return IAppContext delegate that manages platform specific functions..
*/
public final func getDelegate() -> IAppContext? {
return self.delegate
}
/**
Set the delegate implementation.
@param delegate The delegate implementing platform specific functions.
*/
public final func setDelegate(delegate : IAppContext) {
self.delegate = delegate;
}
/**
The main application context. This should be cast to the platform specific implementation.
@return Object representing the specific singleton application context provided by the OS.
@since v2.0
*/
public func getContext() -> AnyObject? {
// Start logging elapsed time.
let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executing getContext...")
}
var result : AnyObject? = nil
if (self.delegate != nil) {
result = self.delegate!.getContext()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executed 'getContext' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.")
}
} else {
if (logger != nil) {
logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextBridge no delegate for 'getContext'.")
}
}
return result
}
/**
The type of context provided by the getContext method.
@return Type of platform context.
@since v2.0
*/
public func getContextType() -> IOSType? {
// Start logging elapsed time.
let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executing getContextType...")
}
var result : IOSType? = nil
if (self.delegate != nil) {
result = self.delegate!.getContextType()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executed 'getContextType' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.")
}
} else {
if (logger != nil) {
logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextBridge no delegate for 'getContextType'.")
}
}
return result
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 |
uasys/swift | test/SourceKit/Demangle/demangle.swift | 18 | 733 | // RUN: %sourcekitd-test -req=demangle unmangled _TtBf80_ _TtP3foo3bar_ | %FileCheck %s
// CHECK: START DEMANGLE
// CHECK-NEXT: <empty>
// CHECK-NEXT: Builtin.Float80
// CHECK-NEXT: foo.bar
// CHECK-NEXT: END DEMANGLE
// RUN: %sourcekitd-test -req=demangle unmangled _TtBf80_ _TtP3foo3bar_ -simplified-demangling | %FileCheck %s -check-prefix=SIMPLIFIED
// SIMPLIFIED: START DEMANGLE
// SIMPLIFIED-NEXT: <empty>
// SIMPLIFIED-NEXT: Builtin.Float80
// SIMPLIFIED-NEXT: bar
// SIMPLIFIED-NEXT: END DEMANGLE
// RUN: %sourcekitd-test -req=mangle Foo.Baru Swift.Beer | %FileCheck %s -check-prefix=MANGLED
// MANGLED: START MANGLE
// MANGLED-NEXT: _T03Foo4BaruCD
// MANGLED-NEXT: _T0s4BeerCD
// MANGLED-NEXT: END MANGLE
| apache-2.0 |
colbylwilliams/bugtrap | iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/Common/Domain/CellData.swift | 1 | 474 | //
// CellData.swift
// bugTrap
//
// Created by Colby L Williams on 11/14/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
class CellData {
var CellType : BugCellTypes = BugCellTypes.Display
var Selected : Bool = false
var Data = [DataKeys : String]()
func Set(key: DataKeys, value: String) {
Data[key] = value
}
func Get(key: DataKeys) -> String? {
return Data[key]
}
} | mit |
lorentey/swift | test/ClangImporter/enum-anon.swift | 26 | 791 | // RUN: %target-swift-frontend -typecheck %s -enable-objc-interop -import-objc-header %S/Inputs/enum-anon.h -DDIAGS -verify
func testDiags() {
#if _runtime(_ObjC)
let us2 = USConstant2
#else
let us2: UInt16 = 0
#endif
let _: String = us2 // expected-error {{cannot convert value of type 'UInt16' to specified type 'String'}}
#if _runtime(_ObjC)
let usVar2 = USVarConstant2
#else
let usVar2: UInt16 = 0
#endif
let _: String = usVar2 // expected-error {{cannot convert value of type 'UInt16' to specified type 'String'}}
// The nested anonymous enum value should still have top-level scope, because
// that's how C works. It should also have the same type as the field (above).
let _: String = SR2511.SR2511B // expected-error {{type 'SR2511' has no member 'SR2511B'}}
}
| apache-2.0 |
marcelobusico/reddit-ios-app | Reddit-App/Reddit-App/ListReddits/Presenter/ListRedditsPresenter.swift | 1 | 3570 | //
// ListRedditsPresenter.swift
// Reddit-App
//
// Created by Marcelo Busico on 13/2/17.
// Copyright © 2017 Busico. All rights reserved.
//
import UIKit
class ListRedditsPresenter {
// MARK: - Constants
private let pageSize = 50
// MARK: - Properties
private weak var view: ListRedditsViewProtocol?
private let serviceAdapter: RedditServiceAdapterProtocol
private var redditsList = [RedditModel]()
// MARK: - Initialization
init(view: ListRedditsViewProtocol, serviceAdapter: RedditServiceAdapterProtocol) {
self.view = view
self.serviceAdapter = serviceAdapter
}
// MARK: - Internal Methods
func start() {
if redditsList.isEmpty {
loadRedditsAsync(appendToCurrentRedditsList: false)
}
}
func refresh() {
loadRedditsAsync(appendToCurrentRedditsList: false)
}
func saveState(coder: NSCoder) {
coder.encode(redditsList, forKey: "redditsList")
}
func restoreState(coder: NSCoder) {
if let redditsList = coder.decodeObject(forKey: "redditsList") as? [RedditModel] {
self.redditsList = redditsList
}
}
func numberOfElements() -> Int {
return redditsList.count
}
func elementModel(forPosition position: Int) -> RedditModel? {
if position >= redditsList.count {
return nil
}
if position == (redditsList.count - 1) {
loadRedditsAsync(appendToCurrentRedditsList: true)
}
return redditsList[position]
}
func elementPosition(forName name: String) -> Int? {
return redditsList.index { (redditModel) -> Bool in
return redditModel.name == name
}
}
func loadThumbnailForModel(model: RedditModel,
onComplete: @escaping (UIImage?) -> Void) {
guard let thumbnailURL = model.thumbnailURL else {
onComplete(nil)
return
}
DispatchQueue.global().async {
self.serviceAdapter.downloadImage(withURL: thumbnailURL,
onComplete: { image in
DispatchQueue.main.async {
onComplete(image)
}
},
onError: { error in
DispatchQueue.main.async {
onComplete(nil)
}
}
)
}
}
func elementSelected(atPosition position: Int) {
guard let redditModel = elementModel(forPosition: position),
redditModel.imageURL != nil else {
return
}
view?.showDetailsScreen(forModel: redditModel)
}
// MARK: - Private Methods
private func loadRedditsAsync(appendToCurrentRedditsList: Bool) {
var afterName: String? = nil
if appendToCurrentRedditsList,
let lastReddit = redditsList.last {
afterName = lastReddit.name
}
self.view?.showLoading()
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
self.serviceAdapter.loadTopReddits(amount: self.pageSize, afterName: afterName,
onComplete: { redditsList in
if appendToCurrentRedditsList {
self.redditsList.append(contentsOf: redditsList)
} else {
self.redditsList = redditsList
}
DispatchQueue.main.async {
if let view = self.view {
view.hideLoading()
view.refreshRedditsList()
}
}
},
onError: { error in
print(error)
DispatchQueue.main.async {
if let view = self.view {
view.hideLoading()
view.displayMessage(title: "Error", message: "Error loading reddits. Please try again later.")
}
}
}
)
}
}
}
| apache-2.0 |
SandcastleApps/partyup | PartyUP/PartyRootController.swift | 1 | 15178 | //
// PartyRootController.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2015-11-07.
// Copyright © 2015 Sandcastle Application Development. All rights reserved.
//
import UIKit
import LocationPickerViewController
import INTULocationManager
import CoreLocation
import SCLAlertView
import Flurry_iOS_SDK
import SCLAlertView
class PartyRootController: UIViewController {
@IBOutlet weak var ackButton: UIButton!
@IBOutlet weak var cameraButton: UIButton! {
didSet {
cameraButton?.enabled = here != nil
}
}
@IBOutlet weak var reminderButton: UIButton!
private var partyPicker: PartyPickerController!
private var here: PartyPlace? {
didSet {
cameraButton?.enabled = here != nil
}
}
private var there: PartyPlace?
private var adRefreshTimer: NSTimer?
private var locationRequestId: INTULocationRequestID = 0
private var favoriting: SCLAlertViewResponder?
private lazy var stickyTowns: [Address] = {
let raw = NSUserDefaults.standardUserDefaults().arrayForKey(PartyUpPreferences.StickyTowns)
let plist = raw as? [[NSObject:AnyObject]]
return plist?.flatMap { Address(plist: $0) } ?? [Address]()
}()
override func viewDidLoad() {
super.viewDidLoad()
refreshReminderButton()
resolveLocalPlacemark()
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: #selector(PartyRootController.observeApplicationBecameActive), name: UIApplicationDidBecomeActiveNotification, object: nil)
nc.addObserver(self, selector: #selector(PartyRootController.refreshSelectedRegion), name: PartyPickerController.VenueRefreshRequest, object: nil)
nc.addObserver(self, selector: #selector(PartyRootController.observeCityUpdateNotification(_:)), name: PartyPlace.CityUpdateNotification, object: nil)
nc.addObserver(self, selector: #selector(PartyRootController.refreshReminderButton), name: NSUserDefaultsDidChangeNotification, object: nil)
nc.addObserverForName(PartyUpConstants.RecordVideoNotification, object: nil, queue: nil) {_ in
if self.shouldPerformSegueWithIdentifier("Bake Sample Segue", sender: nil) {
self.performSegueWithIdentifier("Bake Sample Segue", sender: nil)
}
}
nc.addObserver(self, selector: #selector(PartyRootController.bookmarkLocation), name: PartyUpConstants.FavoriteLocationNotification, object: nil)
nc.addObserverForName(AuthenticationManager.AuthenticationStatusChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { note in
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey(PartyUpPreferences.PromptAuthentication) {
if let new = AuthenticationState(rawValue: note.userInfo?["new"] as! Int), let old = AuthenticationState(rawValue: note.userInfo?["old"] as! Int) where new == .Unauthenticated && old == .Transitioning {
let flow = AuthenticationFlow.shared
let allowPutoff = defaults.boolForKey(PartyUpPreferences.AllowAuthenticationPutoff)
flow.setPutoffs( allowPutoff ?
[NSLocalizedString("Miss out on Facebook Posts", comment: "First ignore Facebook button")] : [])
flow.addAction { [weak self] manager, cancelled in
if let me = self {
if allowPutoff { defaults.setBool(false, forKey: PartyUpPreferences.PromptAuthentication) }
me.presentTutorial()
}
}
flow.startOnController(self)
}
}
}
adRefreshTimer = NSTimer.scheduledTimerWithTimeInterval(3600, target: self, selector: #selector(PartyRootController.refreshAdvertising), userInfo: nil, repeats: true)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
presentTutorial()
}
func presentTutorial() {
if !NSUserDefaults.standardUserDefaults().boolForKey(PartyUpPreferences.PromptAuthentication) {
tutorial.start(self)
}
}
func refreshSelectedRegion(note: NSNotification) {
if let adjust = note.userInfo?["adjustLocation"] as? Bool where adjust {
chooseLocation()
} else {
let force = (note.userInfo?["forceUpdate"] as? Bool) ?? false
if there == nil {
resolveLocalPlacemark()
} else {
fetchPlaceVenues(there, force: force)
}
}
}
func refreshAdvertising() {
let cities = [here,there].flatMap { $0?.location }
Advertisement.refresh(cities)
}
func resolveLocalPlacemark() {
partyPicker.isFetching = true
locationRequestId = INTULocationManager.sharedInstance().requestLocationWithDesiredAccuracy(.City, timeout: 60) { (location, accuracy, status) in
self.locationRequestId = 0
if status == .Success {
Address.addressForCoordinates(location.coordinate) { address, error in
if let address = address where error == nil {
self.here = PartyPlace(location: address)
if self.there == nil {
self.there = self.here
}
self.fetchPlaceVenues(self.here)
Flurry.setLatitude(location!.coordinate.latitude, longitude: location!.coordinate.longitude, horizontalAccuracy: Float(location!.horizontalAccuracy), verticalAccuracy: Float(location!.verticalAccuracy))
} else {
self.cancelLocationLookup()
alertFailureWithTitle(NSLocalizedString("Failed to find you", comment: "Location determination failure hud title"), andDetail: NSLocalizedString("Failed to lookup your city.", comment: "Hud message for failed locality lookup"))
Flurry.logError("City_Locality_Failed", message: error?.localizedDescription, error: error)
}
}
} else {
self.cancelLocationLookup()
alertFailureWithLocationServicesStatus(status)
Flurry.logError("City_Determination_Failed", message: "Reason \(status.rawValue)", error: nil)
}
}
}
func cancelLocationLookup() {
here = nil
partyPicker.parties = self.there
partyPicker.isFetching = false
}
func fetchPlaceVenues(place: PartyPlace?, force: Bool = false) {
if let place = place {
partyPicker.isFetching = true
if let categories = NSUserDefaults.standardUserDefaults().stringForKey(PartyUpPreferences.VenueCategories) {
let radius = NSUserDefaults.standardUserDefaults().integerForKey(PartyUpPreferences.ListingRadius)
place.fetch(radius, categories: categories, force: force)
}
}
}
func refreshReminderButton() {
if let settings = UIApplication.sharedApplication().currentUserNotificationSettings() where settings.types != .None {
let defaults = NSUserDefaults.standardUserDefaults()
reminderButton.hidden = !defaults.boolForKey(PartyUpPreferences.RemindersInterface)
switch defaults.integerForKey(PartyUpPreferences.RemindersInterval) {
case 60:
reminderButton.setTitle("60m 🔔", forState: .Normal)
case 30:
reminderButton.setTitle("30m 🔔", forState: .Normal)
default:
reminderButton.setTitle("Off 🔕", forState: .Normal)
}
}
}
func observeCityUpdateNotification(note: NSNotification) {
if let city = note.object as? PartyPlace {
partyPicker.isFetching = city.isFetching
if city.lastFetchStatus.error == nil {
self.partyPicker.parties = self.there
} else {
alertFailureWithTitle(NSLocalizedString("Venue Query Failed", comment: "Hud title failed to fetch venues from google"),
andDetail: NSLocalizedString("The venue query failed.", comment: "Hud detail failed to fetch venues from google"))
}
}
}
deinit {
adRefreshTimer?.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Navigation
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if (tutorial.tutoring || presentedViewController != nil || navigationController?.topViewController != self) && identifier != "Party Embed Segue" {
return false
}
if identifier == "Bake Sample Segue" {
if !AuthenticationManager.shared.isLoggedIn {
AuthenticationFlow.shared.startOnController(self).addAction { manager, cancelled in
if manager.isLoggedIn {
if self.shouldPerformSegueWithIdentifier("Bake Sample Segue", sender: nil) {
self.performSegueWithIdentifier("Bake Sample Segue", sender: nil)
}
}
}
return false
}
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Party Embed Segue" {
partyPicker = segue.destinationViewController as! PartyPickerController
partyPicker.parties = nil
}
if segue.identifier == "Bake Sample Segue" {
let bakerVC = segue.destinationViewController as! BakeRootController
bakerVC.venues = here?.venues.flatMap{ $0 } ?? [Venue]()
bakerVC.pregame = here?.pregame
}
}
@IBAction func favoriteLocation(sender: UILongPressGestureRecognizer) {
bookmarkLocation()
}
func bookmarkLocation() {
if var place = there?.location where favoriting == nil {
let alert = SCLAlertView()
let nameField = alert.addTextField(NSLocalizedString("Location Name", comment: "Favorite location text title"))
alert.addButton(NSLocalizedString("Add Favorite", comment: "Add favorite location button")) {
place.identifier = nameField.text
self.stickyTowns.append(place)
NSUserDefaults.standardUserDefaults().setObject(self.stickyTowns.map { $0.plist }, forKey: PartyUpPreferences.StickyTowns)
self.there?.name = place.identifier
self.partyPicker.locationFavorited()
}
favoriting = alert.showEdit(NSLocalizedString("Favorite Location", comment: "Favorite location title"),
subTitle: NSLocalizedString("Add selected location as a favorite.", comment: "Favorite location subtitle"),
closeButtonTitle: NSLocalizedString("Cancel", comment: "Favorite location cancel"),
colorStyle: 0xF45E63)
favoriting?.setDismissBlock { self.favoriting = nil }
}
}
@IBAction func chooseLocation() {
partyPicker.defocusSearch()
let locationPicker = LocationPicker()
let locationNavigator = UINavigationController(rootViewController: locationPicker)
locationPicker.title = NSLocalizedString("Popular Party Places", comment: "Location picker title")
locationPicker.searchBarPlaceholder = NSLocalizedString("Search for place or address", comment: "Location picker search bar")
locationPicker.setColors(UIColor(r: 247, g: 126, b: 86, alpha: 255))
locationPicker.locationDeniedHandler = { _ in
var status: INTULocationStatus
switch INTULocationManager.locationServicesState() {
case .Denied:
status = .ServicesDenied
case .Restricted:
status = .ServicesRestricted
case .Disabled:
status = .ServicesDisabled
case .NotDetermined:
status = .ServicesNotDetermined
case .Available:
status = .Error
}
alertFailureWithLocationServicesStatus(status)
}
locationPicker.pickCompletion = { [weak locationPicker] picked in
let name : String? = picked.mapItem.phoneNumber == "Yep" ? picked.name : nil
let address = Address(coordinate: picked.mapItem.placemark.coordinate, mapkitAddress: picked.addressDictionary!, name: name)
self.there = PartyPlace(location: address)
if picked.mapItem.name == "No matter where you go, there you are!" {
self.here = self.there
}
self.partyPicker.parties = self.there
self.fetchPlaceVenues(self.there)
Flurry.logEvent("Selected_Town", withParameters: ["town" : address.debugDescription])
locationPicker?.dismissViewControllerAnimated(true, completion: nil)
}
locationPicker.selectCompletion = locationPicker.pickCompletion
locationPicker.alternativeLocationEditable = true
locationPicker.deleteCompletion = { picked in
if let index = self.stickyTowns.indexOf({ $0.name == picked.name && ($0.coordinate.latitude == picked.coordinate?.latitude && $0.coordinate.longitude == picked.coordinate?.longitude)}) {
self.stickyTowns.removeAtIndex(index)
NSUserDefaults.standardUserDefaults().setObject(self.stickyTowns.map { $0.plist }, forKey: PartyUpPreferences.StickyTowns)
}
}
locationPicker.addBarButtons(UIBarButtonItem(title: "", style: .Done, target: nil, action: nil))
locationPicker.alternativeLocations = stickyTowns.map {
let item = LocationItem(coordinate: (latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude), addressDictionary: $0.appleAddressDictionary)
item.mapItem.phoneNumber = "Yep"
return item
}
presentViewController(locationNavigator, animated: true, completion: nil)
}
@IBAction func setReminders(sender: UIButton) {
let defaults = NSUserDefaults.standardUserDefaults()
var interval = defaults.integerForKey(PartyUpPreferences.RemindersInterval)
interval = (interval + 30) % 90
defaults.setInteger(interval, forKey: PartyUpPreferences.RemindersInterval)
refreshReminderButton()
if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {
delegate.scheduleReminders()
}
}
@IBAction func sequeFromBaking(segue: UIStoryboardSegue) {
}
@IBAction func segueFromAcknowledgements(segue: UIStoryboardSegue) {
}
func observeApplicationBecameActive() {
let defaults = NSUserDefaults.standardUserDefaults()
presentTutorial()
if here == nil {
if INTULocationManager.locationServicesState() == .Available && locationRequestId == 0 {
resolveLocalPlacemark()
}
} else if defaults.boolForKey(PartyUpPreferences.CameraJump) && AuthenticationManager.shared.isLoggedIn {
if shouldPerformSegueWithIdentifier("Bake Sample Segue", sender: nil) {
performSegueWithIdentifier("Bake Sample Segue", sender: nil)
}
}
}
//MARK: - Tutorial
private enum CoachIdentifier: Int {
case Greeting = -1000, City = 1001, About, Camera, Reminder
}
private static let availableCoachMarks = [
TutorialMark(identifier: CoachIdentifier.Greeting.rawValue, hint: NSLocalizedString("Welcome to the PartyUP City Hub!\nThis is where you find the parties.\nTap a place to see what is going on!", comment: "City hub welcome coachmark")),
TutorialMark(identifier: CoachIdentifier.Camera.rawValue, hint: NSLocalizedString("Take video of your\nnightlife adventures!", comment: "City hub camera coachmark")),
TutorialMark(identifier: CoachIdentifier.City.rawValue, hint: NSLocalizedString("See what is going on in\nother party cities.", comment: "City hub location selector coachmark")),
TutorialMark(identifier: CoachIdentifier.Reminder.rawValue, hint: NSLocalizedString("You want to remember to PartyUP?\nSet reminders here.", comment: "City hub reminder button coachmark")),
TutorialMark(identifier: CoachIdentifier.About.rawValue, hint: NSLocalizedString("Learn more about PartyUP!", comment: "City hub acknowledgements coachmark"))]
private let tutorial = TutorialOverlayManager(marks: PartyRootController.availableCoachMarks)
}
| mit |
pksprojects/ElasticSwift | Tests/ElasticSwiftTests/Serialization/SerializationTests.swift | 1 | 5172 | //
// SerializationTests.swift
// ElasticSwiftTests
//
// Created by Prafull Kumar Soni on 7/12/19.
//
import Logging
import UnitTestSettings
import XCTest
@testable import ElasticSwift
@testable import ElasticSwiftCore
class SerializationTests: XCTestCase {
let logger = Logger(label: "org.pksprojects.ElasticSwiftTests.Serialization.SerializationTests", factory: logFactory)
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
super.setUp()
XCTAssert(isLoggingConfigured)
logger.info("====================TEST=START===============================")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
logger.info("====================TEST=END===============================")
}
func test_01_encode() throws {
let serializer = DefaultSerializer()
let myclass = MyClass("value")
let result = serializer.encode(myclass)
switch result {
case let .success(data):
let str = String(data: data, encoding: .utf8)
logger.info("Encoded: \(String(describing: str))")
XCTAssertNotNil(str, "Encoded value can't be nil")
XCTAssert(str! == "{\"value\":\"value\"}", "Validation on Encoded Value Failed")
case let .failure(error):
logger.error("Error: \(error)")
XCTAssert(false, "Encoding Failed!")
}
}
func test_02_encode_fail() throws {
let serializer = DefaultSerializer()
let myclass = MyFailureClass("value")
let result = serializer.encode(myclass)
switch result {
case let .success(data):
let str = String(data: data, encoding: .utf8)
logger.info("Encoded: \(String(describing: str))")
XCTAssert(false, "Encoding Failure Failed!")
case let .failure(error):
logger.error("Expected Error: \(error)")
XCTAssert(type(of: error) == EncodingError.self, "Unexpected Error observed: \(error)")
XCTAssert(type(of: error.value) == MyFailureClass.self, "Unexpected input value \(error.value)")
XCTAssert(type(of: error.error) == MyError.self, "Unexpected internal Error: \(error.error.self)")
let err = error.error as! MyError
XCTAssert(err.localizedDescription == "Error", "Error description validation failed \(err.localizedDescription)")
}
}
func test_03_decode() throws {
let serializer = DefaultSerializer()
let data = "{\"value\":\"value\"}".data(using: .utf8)
let result: Result<MyClass, DecodingError> = serializer.decode(data: data!)
switch result {
case let .success(myclass):
logger.info("Decoded: \(myclass.description)")
XCTAssert(myclass.description == "MyClass[value: value]", "Validation on Decoded Value Failed")
case let .failure(error):
logger.info("Unexpected Error: \(error.localizedDescription)")
XCTAssert(false, "Encoding Failed!")
}
}
func test_04_decode_fail() throws {
let serializer = DefaultSerializer()
let data = "badJson".data(using: .utf8)
let result: Result<MyClass, DecodingError> = serializer.decode(data: data!)
switch result {
case let .success(myclass):
logger.info("Decoded: \(String(describing: myclass))")
XCTAssert(false, "Decoding Failure Failed!")
case let .failure(error):
logger.error("Expected Error: \(error)")
XCTAssert(type(of: error) == DecodingError.self, "Unexpected Error observed: \(error)")
XCTAssert(error.data == data!, "Unexpected input value \(error.data)")
XCTAssert(error.type == MyClass.self, "Unexpected Type")
XCTAssert(type(of: error.error) == Swift.DecodingError.self, "Unexpected internal Error: \(error.type)")
}
}
}
class MyClass: Codable, CustomStringConvertible, CustomDebugStringConvertible {
public let value: String
public init(_ value: String) {
self.value = value
}
var description: String {
return "MyClass[value: \(value.description)]"
}
var debugDescription: String {
return "MyClass[value: \(value.debugDescription)]"
}
}
final class MyFailureClass: CustomStringConvertible, CustomDebugStringConvertible {
public let value: String
public init(_ value: String) {
self.value = value
}
var description: String {
return "MyClass[value: \(value.description)]"
}
var debugDescription: String {
return "MyClass[value: \(value.debugDescription)]"
}
}
extension MyFailureClass: Encodable {
public func encode(to _: Encoder) throws {
throw MyError("Error")
}
}
struct MyError: Error {
private let msg: String
public init(_ msg: String) {
self.msg = msg
}
public var localizedDescription: String {
return msg
}
}
| mit |
thatseeyou/SpriteKitExamples.playground | Pages/SKEmitterNode.xcplaygroundpage/Contents.swift | 1 | 1255 | /*:
### Particle file을 Xcode를 통해서 생성한 후에 읽을 수 있다.
- Fire.sks 생성하기 : File/New/File에서 Resource/Particle File 선택에서 생성 후 끌어서 Resources 폴더에 놓으면 된다.
*/
import UIKit
import SpriteKit
class GameScene: SKScene {
var contentCreated = false
override func didMove(to view: SKView) {
if self.contentCreated != true {
let fireNode = SKEmitterNode(fileNamed: "Fire.sks")!
fireNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
addChild(fireNode)
self.contentCreated = true
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add SKView
do {
let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480))
skView.showsFPS = true
//skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
let scene = GameScene(size: CGSize(width: 320, height: 480))
scene.scaleMode = .aspectFit
skView.presentScene(scene)
self.view.addSubview(skView)
}
}
}
PlaygroundHelper.showViewController(ViewController())
| isc |
AndrewBennet/readinglist | ReadingList_Foundation/UI/TextBoxAlert.swift | 1 | 1657 | import Foundation
import UIKit
/**
A UIAlertController with a single text field input, and an OK and Cancel action. The OK button is disabled
when the text box is empty or whitespace.
*/
public class TextBoxAlert: UIAlertController {
var textValidator: ((String?) -> Bool)?
public convenience init(title: String, message: String? = nil, initialValue: String? = nil, placeholder: String? = nil,
keyboardAppearance: UIKeyboardAppearance = .default, keyboardType: UIKeyboardType = .default, textValidator: ((String?) -> Bool)? = nil, onCancel: (() -> Void)? = nil, onOK: @escaping (String?) -> Void) {
self.init(title: title, message: message, preferredStyle: .alert)
self.textValidator = textValidator
addTextField { [unowned self] textField in
textField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
textField.autocapitalizationType = .words
textField.keyboardType = keyboardType
textField.keyboardAppearance = keyboardAppearance
textField.placeholder = placeholder
textField.text = initialValue
}
addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
onCancel?()
})
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
onOK(self.textFields![0].text)
}
okAction.isEnabled = textValidator?(initialValue) ?? true
addAction(okAction)
}
@objc func textFieldDidChange(_ textField: UITextField) {
actions[1].isEnabled = textValidator?(textField.text) ?? true
}
}
| gpl-3.0 |
kickstarter/ios-oss | Kickstarter-iOS/SharedViews/UIView+ShimmerLoading.swift | 1 | 3305 | import Foundation
import Library
import ObjectiveC
import UIKit
private enum ShimmerConstants {
enum Locations {
static let start: [NSNumber] = [-1.0, -0.5, 0.0]
static let end: [NSNumber] = [1.0, 1.5, 2.0]
}
enum Animation {
static let movingAnimationDuration: CFTimeInterval = 1.25
static let delayBetweenAnimationLoops: CFTimeInterval = 0.3
}
}
private struct AssociatedKeys {
static var shimmerLayers = "shimmerLayers"
}
protocol ShimmerLoading: AnyObject {
func shimmerViews() -> [UIView]
func startLoading()
func stopLoading()
}
extension ShimmerLoading where Self: UIView {
private var shimmerLayers: [CAGradientLayer] {
get {
guard
let value = objc_getAssociatedObject(self, &AssociatedKeys.shimmerLayers) as? [CAGradientLayer]
else { return [] }
return value
}
set(newValue) {
objc_setAssociatedObject(
self,
&AssociatedKeys.shimmerLayers,
newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
// MARK: - Accessors
func startLoading() {
self.shimmerViews()
.forEach { view in
let gradientLayer = shimmerGradientLayer(with: view.bounds)
let animation = shimmerAnimation()
let animationGroup = shimmerAnimationGroup(with: animation)
gradientLayer.add(animationGroup, forKey: animation.keyPath)
view.layer.addSublayer(gradientLayer)
self.shimmerLayers.append(gradientLayer)
}
}
func stopLoading() {
self.shimmerLayers.forEach { $0.removeFromSuperlayer() }
}
func layoutGradientLayers() {
self.layoutIfNeeded()
self.shimmerLayers.forEach { layer in
layer.frame = layer.superlayer?.bounds ?? .zero
layer.setNeedsLayout()
}
}
}
private func shimmerGradientLayer(with frame: CGRect) -> CAGradientLayer {
let gradientBackgroundColor: CGColor = UIColor(white: 0.85, alpha: 1.0).cgColor
let gradientMovingColor: CGColor = UIColor(white: 0.75, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = frame
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.colors = [
gradientBackgroundColor,
gradientMovingColor,
gradientBackgroundColor
]
gradientLayer.locations = ShimmerConstants.Locations.start
return gradientLayer
}
private func shimmerAnimation() -> CABasicAnimation {
let locationsKeyPath = \CAGradientLayer.locations
let animation = CABasicAnimation(keyPath: locationsKeyPath._kvcKeyPathString)
animation.fromValue = ShimmerConstants.Locations.start
animation.toValue = ShimmerConstants.Locations.end
animation.duration = ShimmerConstants.Animation.movingAnimationDuration
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
return animation
}
private func shimmerAnimationGroup(with animation: CABasicAnimation) -> CAAnimationGroup {
let animationGroup = CAAnimationGroup()
animationGroup.duration = ShimmerConstants.Animation.movingAnimationDuration
+ ShimmerConstants.Animation.delayBetweenAnimationLoops
animationGroup.animations = [animation]
animationGroup.repeatCount = .infinity
animationGroup.beginTime = CACurrentMediaTime()
return animationGroup
}
| apache-2.0 |
uasys/swift | test/SILGen/writeback.swift | 2 | 5798 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
struct Foo {
mutating // used to test writeback.
func foo() {}
subscript(x: Int) -> Foo {
get {
return Foo()
}
set {}
}
}
var x: Foo {
get {
return Foo()
}
set {}
}
var y: Foo {
get {
return Foo()
}
set {}
}
var z: Foo {
get {
return Foo()
}
set {}
}
var readonly: Foo {
get {
return Foo()
}
}
func bar(x x: inout Foo) {}
// Writeback to value type 'self' argument
x.foo()
// CHECK: [[FOO:%.*]] = function_ref @_T09writeback3FooV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]]
// CHECK: apply [[FOO]]([[X_TEMP]]) : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
// Writeback to inout argument
bar(x: &x)
// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]] : $*Foo
// CHECK: apply [[BAR]]([[X_TEMP]]) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
func zang(x x: Foo) {}
// No writeback for pass-by-value argument
zang(x: x)
// CHECK: function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_T09writeback1xAA3FooVvs
zang(x: readonly)
// CHECK: function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_T09writeback8readonlyAA3FooVvs
func zung() -> Int { return 0 }
// Ensure that subscripts are only evaluated once.
bar(x: &x[zung()])
// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[ZUNG:%.*]] = function_ref @_T09writeback4zungSiyF : $@convention(thin) () -> Int
// CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV{{[_0-9a-zA-Z]*}}ig : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV{{[_0-9a-zA-Z]*}}is : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: function_ref @_T09writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
protocol Fungible {}
extension Foo : Fungible {}
var addressOnly: Fungible {
get {
return Foo()
}
set {}
}
func funge(x x: inout Fungible) {}
funge(x: &addressOnly)
// CHECK: [[FUNGE:%.*]] = function_ref @_T09writeback5fungeyAA8Fungible_pz1x_tF : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[TEMP:%.*]] = alloc_stack $Fungible
// CHECK: [[GET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pvg : $@convention(thin) () -> @out Fungible
// CHECK: apply [[GET]]([[TEMP]]) : $@convention(thin) () -> @out Fungible
// CHECK: apply [[FUNGE]]([[TEMP]]) : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[SET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pvs : $@convention(thin) (@in Fungible) -> ()
// CHECK: apply [[SET]]([[TEMP]]) : $@convention(thin) (@in Fungible) -> ()
// CHECK: dealloc_stack [[TEMP]] : $*Fungible
// Test that writeback occurs with generic properties.
// <rdar://problem/16525257>
protocol Runcible {
associatedtype Frob: Frobable
var frob: Frob { get set }
}
protocol Frobable {
associatedtype Anse
var anse: Anse { get set }
}
// CHECK-LABEL: sil hidden @_T09writeback12test_generic{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce.Frob, #Frobable.anse!setter.1
// CHECK: witness_method $Runce, #Runcible.frob!materializeForSet.1
func test_generic<Runce: Runcible>(runce runce: inout Runce, anse: Runce.Frob.Anse) {
runce.frob.anse = anse
}
// We should *not* write back when referencing decls or members as rvalues.
// <rdar://problem/16530235>
// CHECK-LABEL: sil hidden @_T09writeback15loadAddressOnlyAA8Fungible_pyF : $@convention(thin) () -> @out Fungible {
func loadAddressOnly() -> Fungible {
// CHECK: function_ref writeback.addressOnly.getter
// CHECK-NOT: function_ref writeback.addressOnly.setter
return addressOnly
}
// CHECK-LABEL: sil hidden @_T09writeback10loadMember{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!getter.1
// CHECK: witness_method $Runce.Frob, #Frobable.anse!getter.1
// CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter.1
// CHECK-NOT: witness_method $Runce, #Runcible.frob!setter.1
func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse {
return runce.frob.anse
}
| apache-2.0 |
PeterWang0124/iOS-LearningSamples | SwiftTutorialLearning/SwiftTutorialLearning/AppDelegate.swift | 1 | 2153 | //
// AppDelegate.swift
// SwiftTutorialLearning
//
// Created by PeterWang on 3/10/15.
// Copyright (c) 2015 PeterWang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:.
}
}
| mit |
northwind/Swift-Observable | Demo/SwiftObservableDemo/SwiftObservableDemo/AppDelegate.swift | 1 | 2180 | //
// AppDelegate.swift
// SwiftObservableDemo
//
// Created by Norris Tong on 8/27/14.
// Copyright (c) 2014 Norris Tong. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> 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:.
}
}
| mit |
jackpal/smallpt-swift | smallpt.swift | 1 | 8358 | #!/usr/bin/env xcrun swift -O
// Smallpt in swift
// Based on http://www.kevinbeason.com/smallpt/
import Foundation
class OutputStream : OutputStreamType {
let handle : NSFileHandle
init(handle : NSFileHandle) {
self.handle = handle
}
func write(string: String) {
if let asUTF8 = string.dataUsingEncoding(NSUTF8StringEncoding) {
handle.writeData(asUTF8)
}
}
}
class StandardErrorOutputStream: OutputStream {
init() {
let stderr = NSFileHandle.fileHandleWithStandardError()
super.init(handle:stderr)
}
}
class FileStream : OutputStream {
init(path : String) {
let d = NSFileManager.defaultManager()
d.createFileAtPath(path, contents: nil, attributes: nil)
let h = NSFileHandle(forWritingAtPath: path)
super.init(handle:h!)
}
}
let stderr = StandardErrorOutputStream()
struct Vec {
let x, y, z : Double
init() { self.init(x:0, y:0, z:0) }
init(x : Double, y : Double, z: Double){ self.x=x; self.y=y; self.z=z; }
func length() -> Double { return sqrt(x*x+y*y+z*z) }
func norm() -> Vec { return self * (1/self.length()) }
func dot(b : Vec) -> Double { return x*b.x+y*b.y+z*b.z }
};
func +(a :Vec, b:Vec) -> Vec { return Vec(x:a.x+b.x, y:a.y+b.y, z:a.z+b.z) }
func -(a :Vec, b:Vec) -> Vec { return Vec(x:a.x-b.x, y:a.y-b.y, z:a.z-b.z) }
func *(a :Vec, b : Double) -> Vec { return Vec(x:a.x*b, y:a.y*b, z:a.z*b) }
func *(a :Vec, b : Vec) -> Vec { return Vec(x:a.x*b.x, y:a.y*b.y, z:a.z*b.z) }
// cross product:
func %(a :Vec, b : Vec) -> Vec{
return Vec(x:a.y*b.z-a.z*b.y, y:a.z*b.x-a.x*b.z, z:a.x*b.y-a.y*b.x)
}
struct Ray { let o, d : Vec; init(o : Vec, d : Vec) {self.o = o; self.d = d}}
enum Refl_t { case DIFF; case SPEC; case REFR } // material types, used in radiance()
struct Sphere {
let rad : Double // radius
let p, e, c : Vec // position, emission, color
let refl : Refl_t // reflection type (DIFFuse, SPECular, REFRactive)
init(rad :Double, p: Vec, e: Vec, c: Vec, refl: Refl_t) {
self.rad = rad; self.p = p; self.e = e; self.c = c; self.refl = refl; }
func intersect(r: Ray) -> Double { // returns distance, 0 if nohit
let op = p-r.o // Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0
let eps = 1e-4
let b = op.dot(r.d)
let det = b*b-op.dot(op)+rad*rad
if (det<0) {
return 0
}
let det2=sqrt(det)
let t=b-det2
if t > eps {
return t
}
let t2 = b+det2
if t2 > eps {return t2}
return 0
}
}
let spheres :[Sphere] = [//Scene: radius, position, emission, color, material
Sphere(rad:1e5, p:Vec(x: 1e5+1,y:40.8,z:81.6), e:Vec(), c:Vec(x:0.75,y:0.25,z:0.25), refl:Refl_t.DIFF),//Left
Sphere(rad:1e5, p:Vec(x:-1e5+99,y:40.8,z:81.6),e:Vec(), c:Vec(x:0.25,y:0.25,z:0.75), refl:Refl_t.DIFF),//Rght
Sphere(rad:1e5, p:Vec(x:50,y:40.8,z: 1e5), e:Vec(), c:Vec(x:0.75,y:0.75,z:0.75), refl:Refl_t.DIFF),//Back
Sphere(rad:1e5, p:Vec(x:50,y:40.8,z:-1e5+170), e:Vec(), c:Vec(), refl:Refl_t.DIFF),//Frnt
Sphere(rad:1e5, p:Vec(x:50,y: 1e5,z: 81.6), e:Vec(), c:Vec(x:0.75,y:0.75,z:0.75), refl:Refl_t.DIFF),//Botm
Sphere(rad:1e5, p:Vec(x:50,y:-1e5+81.6,z:81.6),e:Vec(), c:Vec(x:0.75,y:0.75,z:0.75), refl:Refl_t.DIFF),//Top
Sphere(rad:16.5,p:Vec(x:27,y:16.5,z:47), e:Vec(), c:Vec(x:1,y:1,z:1)*0.999, refl:Refl_t.SPEC),//Mirr
Sphere(rad:16.5,p:Vec(x:73,y:16.5,z:78), e:Vec(), c:Vec(x:1,y:1,z:1)*0.999, refl:Refl_t.REFR),//Glas
Sphere(rad:600, p:Vec(x:50,y:681.6-0.27,z:81.6),e:Vec(x:12,y:12,z:12), c:Vec(), refl:Refl_t.DIFF) //Lite
]
func clamp(x : Double) -> Double { return x < 0 ? 0 : x > 1 ? 1 : x; }
func toInt(x : Double) -> Int { return Int(pow(clamp(x),1/2.2)*255+0.5); }
func intersect(r : Ray, inout t: Double, inout id: Int) -> Bool {
let n = spheres.count
let inf = 1e20
t = inf
for (var i = n-1; i >= 0; i--) {
let d = spheres[i].intersect(r)
if (d != 0.0 && d<t){
t=d
id=i
}
}
return t<inf
}
struct drand {
let pbuffer = UnsafeMutablePointer<UInt16>.alloc(3)
init(a : UInt16) {
pbuffer[2] = a
}
func next() -> Double { return erand48(pbuffer) }
}
func radiance(r: Ray, depthIn: Int, Xi : drand) -> Vec {
var t : Double = 0 // distance to intersection
var id : Int = 0 // id of intersected object
if (!intersect(r, &t, &id)) {return Vec() } // if miss, return black
let obj = spheres[id] // the hit object
let x=r.o+r.d*t
let n=(x-obj.p).norm()
let nl = (n.dot(r.d) < 0) ? n : n * -1
var f=obj.c
let p = f.x > f.y && f.x > f.z ? f.x : f.y > f.z ? f.y : f.z; // max refl
let depth = depthIn+1
// Russian Roulette:
if (depth>5) {
// Limit depth to 150 to avoid stack overflow.
if (depth < 150 && Xi.next()<p) {
f=f*(1/p)
} else {
return obj.e
}
}
switch (obj.refl) {
case Refl_t.DIFF: // Ideal DIFFUSE reflection
let r1=2*M_PI*Xi.next(), r2=Xi.next(), r2s=sqrt(r2);
let w = nl
let u = ((fabs(w.x)>0.1 ? Vec(x:0, y:1, z:0) : Vec(x:1, y:0, z:0)) % w).norm()
let v = w % u
let d = (u*cos(r1)*r2s + v*sin(r1)*r2s + w*sqrt(1-r2)).norm()
return obj.e + f * radiance(Ray(o: x, d:d), depth, Xi)
case Refl_t.SPEC: // Ideal SPECULAR reflection
return obj.e + f * (radiance(Ray(o:x, d:r.d-n*2*n.dot(r.d)), depth, Xi))
case Refl_t.REFR:
let reflRay = Ray(o:x, d:r.d-n*2*n.dot(r.d)) // Ideal dielectric REFRACTION
let into = n.dot(nl)>0 // Ray from outside going in?
let nc = 1, nt=1.5
let nnt = into ? Double(nc) / nt : nt / Double(nc)
let ddn = r.d.dot(nl)
let cos2t=1-nnt*nnt*(1-ddn*ddn)
if (cos2t<0) { // Total internal reflection
return obj.e + f * radiance(reflRay, depth, Xi)
}
let tdir = (r.d * nnt - n * ((into ? 1 : -1)*(ddn*nnt+sqrt(cos2t)))).norm()
let a = nt-Double(nc), b = nt+Double(nc), R0 = a*a/(b*b), c = 1-(into ? -ddn : tdir.dot(n))
let Re=R0+(1-R0)*c*c*c*c*c,Tr=1-Re,P=0.25+0.5*Re,RP=Re/P,TP=Tr/(1-P)
return obj.e + f * (depth>2 ? (Xi.next()<P ? // Russian roulette
radiance(reflRay,depth,Xi) * RP : radiance(Ray(o: x, d: tdir),depth,Xi)*TP) :
radiance(reflRay,depth,Xi) * Re + radiance(Ray(o: x, d: tdir),depth,Xi)*Tr);
}
}
func main() {
let mainQueue = dispatch_get_main_queue()
dispatch_async(mainQueue) {
let argc = C_ARGC, argv = C_ARGV
let w=1024, h=768
// let w = 160, h = 120
let samps = argc==2 ? Int(atoi(argv[1])/4) : 1 // # samples
let cam = Ray(o:Vec(x:50,y:52,z:295.6), d:Vec(x:0,y:-0.042612,z:-1).norm()) // cam pos, dir
let cx = Vec(x:Double(w) * 0.5135 / Double(h), y:0, z:0)
let cy = (cx % cam.d).norm()*0.5135
var c = Array<Vec>(count:w*h, repeatedValue:Vec())
let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_apply(UInt(h), globalQueue) {
let y = Int($0)
let Xi = drand(a:UInt16(0xffff & (y * y * y)))
let spp = samps*4
let percent = 100.0 * Double(y)/Double(h-1)
stderr.write(String(format:"\rRendering (%d spp) %.2f%%", spp, percent))
for (var x = 0; x < w; x++) { // Loop cols
let i=(h-y-1)*w+x
var r = Vec()
for (var sy=0; sy<2; sy++) { // 2x2 subpixel rows
for (var sx=0; sx<2; sx++) { // 2x2 subpixel cols
for (var s=0; s < samps; s++) {
let r1=2*Xi.next(), dx=r1<1 ? sqrt(r1)-1: 1-sqrt(2-r1)
let r2=2*Xi.next(), dy=r2<1 ? sqrt(r2)-1: 1-sqrt(2-r2)
let part1 = ( ( (Double(sx)+0.5 + Double(dx))/2 + Double(x))/Double(w) - 0.5)
let part2 = ( ( (Double(sy)+0.5 + Double(dy))/2 + Double(y))/Double(h) - 0.5)
let d = cx * part1
+ cy * part2
+ cam.d
let rr = radiance(Ray(o:cam.o+d*140, d:d.norm()), 0, Xi)
r = r + rr * (1.0 / Double(samps))
} // Camera rays are pushed ^^^^^ forward to start in interior
}
}
let result = r*0.25
c[i] = result
}
}
let f = FileStream(path: "image.ppm") // Write image to PPM file.
f.write("P3\n\(w) \(h)\n\(255)\n")
for (var i=0; i<w*h; i++) {
f.write("\(toInt(c[i].x)) \(toInt(c[i].y)) \(toInt(c[i].z)) ")
}
exit(0)
}
dispatch_main();
}
main()
| mit |
ngageoint/mage-ios | Mage/SingleUserMapView.swift | 1 | 1464 | //
// SingleUserMap.swift
// MAGE
//
// Created by Daniel Barela on 2/10/22.
// Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
class SingleUserMapView: MageMapView, FilteredUsersMap, FilteredObservationsMap, FollowUser {
var filteredObservationsMapMixin: FilteredObservationsMapMixin?
var filteredUsersMapMixin: FilteredUsersMapMixin?
var followUserMapMixin: FollowUserMapMixin?
var user: User?
public init(user: User?, scheme: MDCContainerScheming?) {
self.user = user
super.init(scheme: scheme)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutView() {
super.layoutView()
filteredUsersMapMixin = FilteredUsersMapMixin(filteredUsersMap: self, user: user, scheme: scheme)
filteredObservationsMapMixin = FilteredObservationsMapMixin(filteredObservationsMap: self, user: user)
followUserMapMixin = FollowUserMapMixin(followUser: self, user: user, scheme: scheme)
mapMixins.append(filteredObservationsMapMixin!)
mapMixins.append(filteredUsersMapMixin!)
mapMixins.append(followUserMapMixin!)
initiateMapMixins()
}
override func removeFromSuperview() {
filteredUsersMapMixin = nil
filteredObservationsMapMixin = nil
followUserMapMixin = nil
}
}
| apache-2.0 |
cbrentharris/swift | validation-test/compiler_crashers/28069-swift-nominaltypedecl-classifyasoptionaltype.swift | 1 | 297 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b{struct S{struct d{struct B{class A{enum B<T{func c{if{func f<e:T.A
| apache-2.0 |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/Views/Protocol/KeyboardProcessProtocol.swift | 1 | 360 | //
// KeyboardProcessProtocol.swift
// travelMapMvvm
//
// Created by green on 15/9/1.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import Foundation
/**
* 键盘处理(通常给viewcontroller实现)
*/
protocol KeyboardProcessProtocol {
var scrollView : UIScrollView { get }
var activeField : UITextField? { get set}
} | apache-2.0 |
MTTHWBSH/Short-Daily-Devotions | Short Daily Devotions/View Models/PageViewModel.swift | 1 | 1103 | //
// PageViewModel.swift
// Short Daily Devotions
//
// Created by Matthew Bush on 12/21/16.
// Copyright © 2016 Matt Bush. All rights reserved.
//
import Alamofire
class PageViewModel: ViewModel {
private var pageID: String
private var page: Post?
init(pageID: String) {
self.pageID = pageID
super.init()
loadPage(id: pageID, completion: nil)
}
private func loadPage(id: String, completion: ((Void) -> Void)?) {
Alamofire.request(Constants.kPageBaseURL + pageID)
.responseJSON { [weak self] response in
guard let data = response.data,
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let dict = json as? NSDictionary,
let page = Post.from(dict) else { return }
self?.page = page
self?.render?()
completion?()
}
}
func titleForPage() -> String { return page?.title ?? "" }
func pageContent() -> String { return page?.content ?? "" }
}
| mit |
AirChen/ACSwiftDemoes | Target15-TransitionViewControllers/AppDelegate.swift | 1 | 2198 | //
// AppDelegate.swift
// Target15-TransitionViewControllers
//
// Created by Air_chen on 2016/11/12.
// Copyright © 2016年 Air_chen. 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 |
marcdown/tagifai | TagifaiUITests/TagifaiUITests.swift | 1 | 1245 | //
// TagifaiUITests.swift
// TagifaiUITests
//
// Created by Marc Brown on 9/27/15.
// Copyright © 2015 creative mess. All rights reserved.
//
import XCTest
class TagifaiUITests: 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 |
noahprince22/StrollSafe_iOS | Stroll SafeUITests/TutorialUtil.swift | 1 | 632 | //
// TutorialUtil.swift
// Stroll Safe
//
// Created by Noah Prince on 8/22/15.
// Copyright © 2015 Stroll Safe. All rights reserved.
//
import Foundation
import XCTest
class TutorialUtil {
var app: XCUIApplication
init(app: XCUIApplication) {
self.app = app
}
func finishTutorial() {
let element = app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element
element.swipeLeft()
element.swipeLeft()
element.swipeLeft()
element.swipeLeft()
app.buttons["Got it!"].tap()
}
} | apache-2.0 |
kylebshr/ALTextInputBar | ALTextInputBarTests/ALTextInputBarTests.swift | 2 | 921 | //
// ALTextInputBarTests.swift
// ALTextInputBarTests
//
// Created by Alex Littlejohn on 2015/04/24.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import XCTest
class ALTextInputBarTests: 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 |
SwiftAndroid/swift | validation-test/stdlib/Dictionary.swift | 1 | 117930 | // RUN: rm -rf %t
// RUN: mkdir -p %t
//
// RUN: %S/../../utils/gyb %s -o %t/main.swift
// RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o
// RUN: %S/../../utils/line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Dictionary -Xfrontend -disable-access-control
//
// RUN: %S/../../utils/line-directive %t/main.swift -- %target-run %t/Dictionary
// REQUIRES: executable_test
// XFAIL: linux
import Darwin
import StdlibUnittest
import StdlibCollectionUnittest
import Foundation
import StdlibUnittestFoundationExtras
// Check that the generic parameters are called 'Key' and 'Value'.
protocol TestProtocol1 {}
extension Dictionary where Key : TestProtocol1, Value : TestProtocol1 {
var _keyValueAreTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension DictionaryIndex where Key : TestProtocol1, Value : TestProtocol1 {
var _keyValueAreTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension DictionaryIterator
where Key : TestProtocol1, Value : TestProtocol1 {
var _keyValueAreTestProtocol1: Bool {
fatalError("not implemented")
}
}
var DictionaryTestSuite = TestSuite("Dictionary")
DictionaryTestSuite.test("sizeof") {
var dict = [ 1: "meow", 2: "meow" ]
#if arch(i386) || arch(arm)
expectEqual(4, sizeofValue(dict))
#else
expectEqual(8, sizeofValue(dict))
#endif
}
DictionaryTestSuite.test("valueDestruction") {
var d1 = Dictionary<Int, TestValueTy>()
for i in 100...110 {
d1[i] = TestValueTy(i)
}
var d2 = Dictionary<TestKeyTy, TestValueTy>()
for i in 100...110 {
d2[TestKeyTy(i)] = TestValueTy(i)
}
}
DictionaryTestSuite.test("COW.Smoke") {
var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10)
var identity1 = unsafeBitCast(d1, to: Int.self)
d1[TestKeyTy(10)] = TestValueTy(1010)
d1[TestKeyTy(20)] = TestValueTy(1020)
d1[TestKeyTy(30)] = TestValueTy(1030)
var d2 = d1
_fixLifetime(d2)
assert(identity1 == unsafeBitCast(d2, to: Int.self))
d2[TestKeyTy(40)] = TestValueTy(2040)
assert(identity1 != unsafeBitCast(d2, to: Int.self))
d1[TestKeyTy(50)] = TestValueTy(1050)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
func getCOWFastDictionary() -> Dictionary<Int, Int> {
var d = Dictionary<Int, Int>(minimumCapacity: 10)
d[10] = 1010
d[20] = 1020
d[30] = 1030
return d
}
func getCOWSlowDictionary() -> Dictionary<TestKeyTy, TestValueTy> {
var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10)
d[TestKeyTy(10)] = TestValueTy(1010)
d[TestKeyTy(20)] = TestValueTy(1020)
d[TestKeyTy(30)] = TestValueTy(1030)
return d
}
func getCOWSlowEquatableDictionary()
-> Dictionary<TestKeyTy, TestEquatableValueTy> {
var d = Dictionary<TestKeyTy, TestEquatableValueTy>(minimumCapacity: 10)
d[TestKeyTy(10)] = TestEquatableValueTy(1010)
d[TestKeyTy(20)] = TestEquatableValueTy(1020)
d[TestKeyTy(30)] = TestEquatableValueTy(1030)
return d
}
DictionaryTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
var startIndex = d.startIndex
var endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
d[40] = 2040
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
var startIndex = d.startIndex
var endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
d[TestKeyTy(40)] = TestValueTy(2040)
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
var startIndex = d.startIndex
let empty = startIndex == d.endIndex
assert((d.startIndex < d.endIndex) == !empty)
assert(d.startIndex <= d.endIndex)
assert((d.startIndex >= d.endIndex) == empty)
assert(!(d.startIndex > d.endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d[startIndex].1 != 0)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
var startIndex = d.startIndex
let empty = startIndex == d.endIndex
assert((d.startIndex < d.endIndex) == !empty)
assert(d.startIndex <= d.endIndex)
assert((d.startIndex >= d.endIndex) == empty)
assert(!(d.startIndex > d.endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d[startIndex].1.value != 0)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("COW.Fast.SubscriptWithKeyDoesNotReallocate") {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(d[10]! == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Insert a new key-value pair.
d[40] = 2040
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 4)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
// Overwrite a value in existing binding.
d[10] = 2010
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 4)
assert(d[10]! == 2010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
// Delete an existing key.
d[10] = nil
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 3)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
// Try to delete a key that does not exist.
d[42] = nil
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 3)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
do {
var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:]
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashValueWasCalled = 0
expectEmpty(d2[MinimalHashableValue(42)])
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashValueWasCalled)
}
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeyDoesNotReallocate") {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(d[TestKeyTy(10)]!.value == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Insert a new key-value pair.
d[TestKeyTy(40)] = TestValueTy(2040)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 4)
assert(d[TestKeyTy(10)]!.value == 1010)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
// Overwrite a value in existing binding.
d[TestKeyTy(10)] = TestValueTy(2010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 4)
assert(d[TestKeyTy(10)]!.value == 2010)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
// Delete an existing key.
d[TestKeyTy(10)] = nil
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 3)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
// Try to delete a key that does not exist.
d[TestKeyTy(42)] = nil
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 3)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
do {
var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:]
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashValueWasCalled = 0
expectEmpty(d2[MinimalHashableClass(42)])
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashValueWasCalled)
}
}
DictionaryTestSuite.test("COW.Fast.UpdateValueForKeyDoesNotReallocate") {
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
// Insert a new key-value pair.
assert(d1.updateValue(2040, forKey: 40) == .none)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(d1[40]! == 2040)
// Overwrite a value in existing binding.
assert(d1.updateValue(2010, forKey: 10)! == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(d1[10]! == 2010)
}
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
// Insert a new key-value pair.
d2.updateValue(2040, forKey: 40)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d1[40] == .none)
assert(d2.count == 4)
assert(d2[10]! == 1010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
assert(d2[40]! == 2040)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
// Overwrite a value in existing binding.
d2.updateValue(2010, forKey: 10)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d2.count == 3)
assert(d2[10]! == 2010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Slow.AddDoesNotReallocate") {
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
// Insert a new key-value pair.
assert(d1.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) == nil)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(d1.count == 4)
assert(d1[TestKeyTy(40)]!.value == 2040)
// Overwrite a value in existing binding.
assert(d1.updateValue(TestValueTy(2010), forKey: TestKeyTy(10))!.value == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(d1.count == 4)
assert(d1[TestKeyTy(10)]!.value == 2010)
}
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
// Insert a new key-value pair.
d2.updateValue(TestValueTy(2040), forKey: TestKeyTy(40))
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d1[TestKeyTy(20)]!.value == 1020)
assert(d1[TestKeyTy(30)]!.value == 1030)
assert(d1[TestKeyTy(40)] == nil)
assert(d2.count == 4)
assert(d2[TestKeyTy(10)]!.value == 1010)
assert(d2[TestKeyTy(20)]!.value == 1020)
assert(d2[TestKeyTy(30)]!.value == 1030)
assert(d2[TestKeyTy(40)]!.value == 2040)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
// Overwrite a value in existing binding.
d2.updateValue(TestValueTy(2010), forKey: TestKeyTy(10))
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d1[TestKeyTy(20)]!.value == 1020)
assert(d1[TestKeyTy(30)]!.value == 1030)
assert(d2.count == 3)
assert(d2[TestKeyTy(10)]!.value == 2010)
assert(d2[TestKeyTy(20)]!.value == 1020)
assert(d2[TestKeyTy(30)]!.value == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.IndexForKeyDoesNotReallocate") {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
// Find an existing key.
do {
var foundIndex1 = d.index(forKey: 10)!
assert(identity1 == unsafeBitCast(d, to: Int.self))
var foundIndex2 = d.index(forKey: 10)!
assert(foundIndex1 == foundIndex2)
assert(d[foundIndex1].0 == 10)
assert(d[foundIndex1].1 == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
// Try to find a key that is not present.
do {
var foundIndex1 = d.index(forKey: 1111)
assert(foundIndex1 == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
do {
var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:]
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashValueWasCalled = 0
expectEmpty(d2.index(forKey: MinimalHashableValue(42)))
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashValueWasCalled)
}
}
DictionaryTestSuite.test("COW.Slow.IndexForKeyDoesNotReallocate") {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
// Find an existing key.
do {
var foundIndex1 = d.index(forKey: TestKeyTy(10))!
assert(identity1 == unsafeBitCast(d, to: Int.self))
var foundIndex2 = d.index(forKey: TestKeyTy(10))!
assert(foundIndex1 == foundIndex2)
assert(d[foundIndex1].0 == TestKeyTy(10))
assert(d[foundIndex1].1.value == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
// Try to find a key that is not present.
do {
var foundIndex1 = d.index(forKey: TestKeyTy(1111))
assert(foundIndex1 == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
do {
var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:]
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashValueWasCalled = 0
expectEmpty(d2.index(forKey: MinimalHashableClass(42)))
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashValueWasCalled)
}
}
DictionaryTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") {
do {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
let foundIndex1 = d.index(forKey: 10)!
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d[foundIndex1].0 == 10)
assert(d[foundIndex1].1 == 1010)
let removed = d.remove(at: foundIndex1)
assert(removed.0 == 10)
assert(removed.1 == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.index(forKey: 10) == nil)
}
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
var foundIndex1 = d2.index(forKey: 10)!
assert(d2[foundIndex1].0 == 10)
assert(d2[foundIndex1].1 == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
let removed = d2.remove(at: foundIndex1)
assert(removed.0 == 10)
assert(removed.1 == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
assert(d2.index(forKey: 10) == nil)
}
}
DictionaryTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") {
do {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
var foundIndex1 = d.index(forKey: TestKeyTy(10))!
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d[foundIndex1].0 == TestKeyTy(10))
assert(d[foundIndex1].1.value == 1010)
let removed = d.remove(at: foundIndex1)
assert(removed.0 == TestKeyTy(10))
assert(removed.1.value == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.index(forKey: TestKeyTy(10)) == nil)
}
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
var foundIndex1 = d2.index(forKey: TestKeyTy(10))!
assert(d2[foundIndex1].0 == TestKeyTy(10))
assert(d2[foundIndex1].1.value == 1010)
let removed = d2.remove(at: foundIndex1)
assert(removed.0 == TestKeyTy(10))
assert(removed.1.value == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
assert(d2.index(forKey: TestKeyTy(10)) == nil)
}
}
DictionaryTestSuite.test("COW.Fast.RemoveValueForKeyDoesNotReallocate") {
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var deleted = d1.removeValue(forKey: 0)
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
deleted = d1.removeValue(forKey: 10)
assert(deleted! == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
// Keep variables alive.
_fixLifetime(d1)
}
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
var deleted = d2.removeValue(forKey: 0)
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
deleted = d2.removeValue(forKey: 10)
assert(deleted! == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Slow.RemoveValueForKeyDoesNotReallocate") {
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var deleted = d1.removeValue(forKey: TestKeyTy(0))
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
deleted = d1.removeValue(forKey: TestKeyTy(10))
assert(deleted!.value == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
// Keep variables alive.
_fixLifetime(d1)
}
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
var deleted = d2.removeValue(forKey: TestKeyTy(0))
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
deleted = d2.removeValue(forKey: TestKeyTy(10))
assert(deleted!.value == 1010)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 != unsafeBitCast(d2, to: Int.self))
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") {
do {
var d = getCOWFastDictionary()
let originalCapacity = d._variantStorage.asNative.capacity
assert(d.count == 3)
assert(d[10]! == 1010)
d.removeAll()
// We cannot assert that identity changed, since the new buffer of smaller
// size can be allocated at the same address as the old one.
var identity1 = unsafeBitCast(d, to: Int.self)
assert(d._variantStorage.asNative.capacity < originalCapacity)
assert(d.count == 0)
assert(d[10] == nil)
d.removeAll()
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 0)
assert(d[10] == nil)
}
do {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
let originalCapacity = d._variantStorage.asNative.capacity
assert(d.count == 3)
assert(d[10]! == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity == originalCapacity)
assert(d.count == 0)
assert(d[10] == nil)
d.removeAll(keepingCapacity: true)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity == originalCapacity)
assert(d.count == 0)
assert(d[10] == nil)
}
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(d1.count == 3)
assert(d1[10]! == 1010)
var d2 = d1
d2.removeAll()
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d2.count == 0)
assert(d2[10] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
let originalCapacity = d1._variantStorage.asNative.capacity
assert(d1.count == 3)
assert(d1[10] == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d2._variantStorage.asNative.capacity == originalCapacity)
assert(d2.count == 0)
assert(d2[10] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") {
do {
var d = getCOWSlowDictionary()
let originalCapacity = d._variantStorage.asNative.capacity
assert(d.count == 3)
assert(d[TestKeyTy(10)]!.value == 1010)
d.removeAll()
// We cannot assert that identity changed, since the new buffer of smaller
// size can be allocated at the same address as the old one.
var identity1 = unsafeBitCast(d, to: Int.self)
assert(d._variantStorage.asNative.capacity < originalCapacity)
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
d.removeAll()
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
}
do {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
let originalCapacity = d._variantStorage.asNative.capacity
assert(d.count == 3)
assert(d[TestKeyTy(10)]!.value == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity == originalCapacity)
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
d.removeAll(keepingCapacity: true)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity == originalCapacity)
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
}
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll()
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d2.count == 0)
assert(d2[TestKeyTy(10)] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
let originalCapacity = d1._variantStorage.asNative.capacity
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d2._variantStorage.asNative.capacity == originalCapacity)
assert(d2.count == 0)
assert(d2[TestKeyTy(10)] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.CountDoesNotReallocate") {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(d.count == 3)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("COW.Slow.CountDoesNotReallocate") {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(d.count == 3)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("COW.Fast.GenerateDoesNotReallocate") {
var d = getCOWFastDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
pairs += [(key, value)]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("COW.Slow.GenerateDoesNotReallocate") {
var d = getCOWSlowDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
// FIXME: This doesn't work (<rdar://problem/17751308> Can't +=
// with array literal of pairs)
// pairs += [(key.value, value.value)]
// FIXME: This doesn't work (<rdar://problem/17750582> generics over tuples)
// pairs.append((key.value, value.value))
// FIXME: This doesn't work (<rdar://problem/17751359>)
// pairs.append(key.value, value.value)
let kv = (key.value, value.value)
pairs += [kv]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") {
var d1 = getCOWFastDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = getCOWFastDictionary()
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(d1 == d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
d2[40] = 2040
assert(d1 != d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
}
DictionaryTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") {
var d1 = getCOWSlowEquatableDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = getCOWSlowEquatableDictionary()
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(d1 == d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
d2[TestKeyTy(40)] = TestEquatableValueTy(2040)
assert(d1 != d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
}
//===---
// Native dictionary tests.
//===---
func helperDeleteThree(_ k1: TestKeyTy, _ k2: TestKeyTy, _ k3: TestKeyTy) {
var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10)
d1[k1] = TestValueTy(1010)
d1[k2] = TestValueTy(1020)
d1[k3] = TestValueTy(1030)
assert(d1[k1]!.value == 1010)
assert(d1[k2]!.value == 1020)
assert(d1[k3]!.value == 1030)
d1[k1] = nil
assert(d1[k2]!.value == 1020)
assert(d1[k3]!.value == 1030)
d1[k2] = nil
assert(d1[k3]!.value == 1030)
d1[k3] = nil
assert(d1.count == 0)
}
DictionaryTestSuite.test("deleteChainCollision") {
var k1 = TestKeyTy(value: 10, hashValue: 0)
var k2 = TestKeyTy(value: 20, hashValue: 0)
var k3 = TestKeyTy(value: 30, hashValue: 0)
helperDeleteThree(k1, k2, k3)
}
DictionaryTestSuite.test("deleteChainNoCollision") {
var k1 = TestKeyTy(value: 10, hashValue: 0)
var k2 = TestKeyTy(value: 20, hashValue: 1)
var k3 = TestKeyTy(value: 30, hashValue: 2)
helperDeleteThree(k1, k2, k3)
}
DictionaryTestSuite.test("deleteChainCollision2") {
var k1_0 = TestKeyTy(value: 10, hashValue: 0)
var k2_0 = TestKeyTy(value: 20, hashValue: 0)
var k3_2 = TestKeyTy(value: 30, hashValue: 2)
var k4_0 = TestKeyTy(value: 40, hashValue: 0)
var k5_2 = TestKeyTy(value: 50, hashValue: 2)
var k6_0 = TestKeyTy(value: 60, hashValue: 0)
var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10)
d[k1_0] = TestValueTy(1010) // in bucket 0
d[k2_0] = TestValueTy(1020) // in bucket 1
d[k3_2] = TestValueTy(1030) // in bucket 2
d[k4_0] = TestValueTy(1040) // in bucket 3
d[k5_2] = TestValueTy(1050) // in bucket 4
d[k6_0] = TestValueTy(1060) // in bucket 5
d[k3_2] = nil
assert(d[k1_0]!.value == 1010)
assert(d[k2_0]!.value == 1020)
assert(d[k3_2] == nil)
assert(d[k4_0]!.value == 1040)
assert(d[k5_2]!.value == 1050)
assert(d[k6_0]!.value == 1060)
}
func uniformRandom(_ max: Int) -> Int {
// FIXME: this is not uniform.
return random() % max
}
func pickRandom<T>(_ a: [T]) -> T {
return a[uniformRandom(a.count)]
}
DictionaryTestSuite.test("deleteChainCollisionRandomized") {
let timeNow = CUnsignedInt(time(nil))
print("time is \(timeNow)")
srandom(timeNow)
func check(_ d: Dictionary<TestKeyTy, TestValueTy>) {
var keys = Array(d.keys)
for i in 0..<keys.count {
for j in 0..<i {
assert(keys[i] != keys[j])
}
}
for k in keys {
assert(d[k] != nil)
}
}
var collisionChainsChoices = Array(1...8)
var chainOverlapChoices = Array(0...5)
var collisionChains = pickRandom(collisionChainsChoices)
var chainOverlap = pickRandom(chainOverlapChoices)
print("chose parameters: collisionChains=\(collisionChains) chainLength=\(chainOverlap)")
let chainLength = 7
var knownKeys: [TestKeyTy] = []
func getKey(_ value: Int) -> TestKeyTy {
for k in knownKeys {
if k.value == value {
return k
}
}
let hashValue = uniformRandom(chainLength - chainOverlap) * collisionChains
let k = TestKeyTy(value: value, hashValue: hashValue)
knownKeys += [k]
return k
}
var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 30)
for i in 1..<300 {
let key = getKey(uniformRandom(collisionChains * chainLength))
if uniformRandom(chainLength * 2) == 0 {
d[key] = nil
} else {
d[key] = TestValueTy(key.value * 10)
}
check(d)
}
}
DictionaryTestSuite.test("init(dictionaryLiteral:)") {
do {
var empty = Dictionary<Int, Int>()
assert(empty.count == 0)
assert(empty[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral: (10, 1010))
assert(d.count == 1)
assert(d[10]! == 1010)
assert(d[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020))
assert(d.count == 2)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020), (30, 1030))
assert(d.count == 3)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020), (30, 1030), (40, 1040))
assert(d.count == 4)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 1040)
assert(d[1111] == nil)
}
do {
var d: Dictionary<Int, Int> = [ 10: 1010, 20: 1020, 30: 1030 ]
assert(d.count == 3)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
}
}
//===---
// NSDictionary -> Dictionary bridging tests.
//===---
func getAsNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary {
let keys = Array(d.keys.map { TestObjCKeyTy($0) })
let values = Array(d.values.map { TestObjCValueTy($0) })
// Return an `NSMutableDictionary` to make sure that it has a unique
// pointer identity.
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getAsEquatableNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary {
let keys = Array(d.keys.map { TestObjCKeyTy($0) })
let values = Array(d.values.map { TestObjCEquatableValueTy($0) })
// Return an `NSMutableDictionary` to make sure that it has a unique
// pointer identity.
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getAsNSMutableDictionary(_ d: Dictionary<Int, Int>) -> NSMutableDictionary {
let keys = Array(d.keys.map { TestObjCKeyTy($0) })
let values = Array(d.values.map { TestObjCValueTy($0) })
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> {
let nsd = getAsNSDictionary([ 10: 1010, 20: 1020, 30: 1030 ])
return convertNSDictionaryToDictionary(nsd)
}
func getBridgedVerbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, AnyObject> {
let nsd = getAsNSDictionary(d)
return convertNSDictionaryToDictionary(nsd)
}
func getBridgedVerbatimDictionaryAndNSMutableDictionary()
-> (Dictionary<NSObject, AnyObject>, NSMutableDictionary) {
let nsd = getAsNSMutableDictionary([ 10: 1010, 20: 1020, 30: 1030 ])
return (convertNSDictionaryToDictionary(nsd), nsd)
}
func getBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd = getAsNSDictionary([ 10: 1010, 20: 1020, 30: 1030 ])
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
func getBridgedNonverbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd = getAsNSDictionary(d)
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
func getBridgedNonverbatimDictionaryAndNSMutableDictionary()
-> (Dictionary<TestBridgedKeyTy, TestBridgedValueTy>, NSMutableDictionary) {
let nsd = getAsNSMutableDictionary([ 10: 1010, 20: 1020, 30: 1030 ])
return (Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self), nsd)
}
func getBridgedVerbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, TestObjCEquatableValueTy> {
let nsd = getAsEquatableNSDictionary(d)
return convertNSDictionaryToDictionary(nsd)
}
func getBridgedNonverbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedEquatableValueTy> {
let nsd = getAsEquatableNSDictionary(d)
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
func getHugeBridgedVerbatimDictionaryHelper() -> NSDictionary {
let keys = (1...32).map { TestObjCKeyTy($0) }
let values = (1...32).map { TestObjCValueTy(1000 + $0) }
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getHugeBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> {
let nsd = getHugeBridgedVerbatimDictionaryHelper()
return convertNSDictionaryToDictionary(nsd)
}
func getHugeBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd = getHugeBridgedVerbatimDictionaryHelper()
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
/// A mock dictionary that stores its keys and values in parallel arrays, which
/// allows it to return inner pointers to the keys array in fast enumeration.
@objc
class ParallelArrayDictionary : NSDictionary {
struct Keys {
var key0: AnyObject = TestObjCKeyTy(10)
var key1: AnyObject = TestObjCKeyTy(20)
var key2: AnyObject = TestObjCKeyTy(30)
var key3: AnyObject = TestObjCKeyTy(40)
}
var keys = [ Keys() ]
var value: AnyObject = TestObjCValueTy(1111)
override init() {
super.init()
}
override init(
objects: UnsafePointer<AnyObject>,
forKeys keys: UnsafePointer<NSCopying>,
count: Int) {
super.init(objects: objects, forKeys: keys, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by ParallelArrayDictionary")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> AnyObject {
// Ensure that copying this dictionary does not produce a CoreFoundation
// object.
return self
}
override func countByEnumerating(
with state: UnsafeMutablePointer<NSFastEnumerationState>,
objects: AutoreleasingUnsafeMutablePointer<AnyObject>, count: Int) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(keys._baseAddressIfContiguous)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
state.pointee = theState
return 4
}
return 0
}
override func object(forKey aKey: AnyObject) -> AnyObject? {
return value
}
override var count: Int {
return 4
}
}
func getParallelArrayBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> {
let nsd: NSDictionary = ParallelArrayDictionary()
return convertNSDictionaryToDictionary(nsd)
}
func getParallelArrayBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd: NSDictionary = ParallelArrayDictionary()
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
@objc
class CustomImmutableNSDictionary : NSDictionary {
init(_privateInit: ()) {
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(
objects: UnsafePointer<AnyObject>,
forKeys keys: UnsafePointer<NSCopying>,
count: Int) {
expectUnreachable()
super.init(objects: objects, forKeys: keys, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by CustomImmutableNSDictionary")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> AnyObject {
CustomImmutableNSDictionary.timesCopyWithZoneWasCalled += 1
return self
}
override func object(forKey aKey: AnyObject) -> AnyObject? {
CustomImmutableNSDictionary.timesObjectForKeyWasCalled += 1
return getAsNSDictionary([ 10: 1010, 20: 1020, 30: 1030 ]).object(forKey: aKey)
}
override func keyEnumerator() -> NSEnumerator {
CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled += 1
return getAsNSDictionary([ 10: 1010, 20: 1020, 30: 1030 ]).keyEnumerator()
}
override var count: Int {
CustomImmutableNSDictionary.timesCountWasCalled += 1
return 3
}
static var timesCopyWithZoneWasCalled = 0
static var timesObjectForKeyWasCalled = 0
static var timesKeyEnumeratorWasCalled = 0
static var timesCountWasCalled = 0
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.DictionaryIsCopied") {
var (d, nsd) = getBridgedVerbatimDictionaryAndNSMutableDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
// Find an existing key.
do {
var kv = d[d.index(forKey: TestObjCKeyTy(10))!]
assert(kv.0 == TestObjCKeyTy(10))
assert((kv.1 as! TestObjCValueTy).value == 1010)
}
// Delete the key from the NSMutableDictionary.
assert(nsd[TestObjCKeyTy(10)] != nil)
nsd.removeObject(forKey: TestObjCKeyTy(10))
assert(nsd[TestObjCKeyTy(10)] == nil)
// Find an existing key, again.
do {
var kv = d[d.index(forKey: TestObjCKeyTy(10))!]
assert(kv.0 == TestObjCKeyTy(10))
assert((kv.1 as! TestObjCValueTy).value == 1010)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.DictionaryIsCopied") {
var (d, nsd) = getBridgedNonverbatimDictionaryAndNSMutableDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
// Find an existing key.
do {
var kv = d[d.index(forKey: TestBridgedKeyTy(10))!]
assert(kv.0 == TestBridgedKeyTy(10))
assert(kv.1.value == 1010)
}
// Delete the key from the NSMutableDictionary.
assert(nsd[TestBridgedKeyTy(10)] != nil)
nsd.removeObject(forKey: TestBridgedKeyTy(10))
assert(nsd[TestBridgedKeyTy(10)] == nil)
// Find an existing key, again.
do {
var kv = d[d.index(forKey: TestBridgedKeyTy(10))!]
assert(kv.0 == TestBridgedKeyTy(10))
assert(kv.1.value == 1010)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.NSDictionaryIsRetained") {
var nsd: NSDictionary = NSDictionary(dictionary:
getAsNSDictionary([ 10: 1010, 20: 1020, 30: 1030 ]))
var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd)
var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.NSDictionaryIsCopied") {
var nsd: NSDictionary = NSDictionary(dictionary:
getAsNSDictionary([ 10: 1010, 20: 1020, 30: 1030 ]))
var d: [TestBridgedKeyTy : TestBridgedValueTy] =
convertNSDictionaryToDictionary(nsd)
var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectNotEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ImmutableDictionaryIsRetained") {
var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ())
CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0
CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0
CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0
CustomImmutableNSDictionary.timesCountWasCalled = 0
var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd)
expectEqual(1, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled)
expectEqual(0, CustomImmutableNSDictionary.timesObjectForKeyWasCalled)
expectEqual(0, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled)
expectEqual(0, CustomImmutableNSDictionary.timesCountWasCalled)
var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableDictionaryIsCopied") {
var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ())
CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0
CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0
CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0
CustomImmutableNSDictionary.timesCountWasCalled = 0
TestBridgedValueTy.bridgeOperations = 0
var d: [TestBridgedKeyTy : TestBridgedValueTy] =
convertNSDictionaryToDictionary(nsd)
expectEqual(0, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled)
expectEqual(3, CustomImmutableNSDictionary.timesObjectForKeyWasCalled)
expectEqual(1, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled)
expectNotEqual(0, CustomImmutableNSDictionary.timesCountWasCalled)
expectEqual(3, TestBridgedValueTy.bridgeOperations)
var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectNotEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.IndexForKey") {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
// Find an existing key.
do {
var kv = d[d.index(forKey: TestObjCKeyTy(10))!]
assert(kv.0 == TestObjCKeyTy(10))
assert((kv.1 as! TestObjCValueTy).value == 1010)
kv = d[d.index(forKey: TestObjCKeyTy(20))!]
assert(kv.0 == TestObjCKeyTy(20))
assert((kv.1 as! TestObjCValueTy).value == 1020)
kv = d[d.index(forKey: TestObjCKeyTy(30))!]
assert(kv.0 == TestObjCKeyTy(30))
assert((kv.1 as! TestObjCValueTy).value == 1030)
}
// Try to find a key that does not exist.
assert(d.index(forKey: TestObjCKeyTy(40)) == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForKey") {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
// Find an existing key.
do {
var kv = d[d.index(forKey: TestBridgedKeyTy(10))!]
assert(kv.0 == TestBridgedKeyTy(10))
assert(kv.1.value == 1010)
kv = d[d.index(forKey: TestBridgedKeyTy(20))!]
assert(kv.0 == TestBridgedKeyTy(20))
assert(kv.1.value == 1020)
kv = d[d.index(forKey: TestBridgedKeyTy(30))!]
assert(kv.0 == TestBridgedKeyTy(30))
assert(kv.1.value == 1030)
}
// Try to find a key that does not exist.
assert(d.index(forKey: TestBridgedKeyTy(40)) == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var startIndex = d.startIndex
var endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
var pairs = Array<(Int, Int)>()
for i in startIndex..<endIndex {
var (key, value) = d[i]
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs += [kv]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var startIndex = d.startIndex
var endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
var pairs = Array<(Int, Int)>()
for i in startIndex..<endIndex {
var (key, value) = d[i]
let kv = (key.value, value.value)
pairs += [kv]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") {
var d = getBridgedVerbatimDictionary([:])
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var startIndex = d.startIndex
var endIndex = d.endIndex
assert(startIndex == endIndex)
assert(!(startIndex < endIndex))
assert(startIndex <= endIndex)
assert(startIndex >= endIndex)
assert(!(startIndex > endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") {
var d = getBridgedNonverbatimDictionary([:])
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var startIndex = d.startIndex
var endIndex = d.endIndex
assert(startIndex == endIndex)
assert(!(startIndex < endIndex))
assert(startIndex <= endIndex)
assert(startIndex >= endIndex)
assert(!(startIndex > endIndex))
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithKey") {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
// Read existing key-value pairs.
var v = d[TestObjCKeyTy(10)] as! TestObjCValueTy
assert(v.value == 1010)
v = d[TestObjCKeyTy(20)] as! TestObjCValueTy
assert(v.value == 1020)
v = d[TestObjCKeyTy(30)] as! TestObjCValueTy
assert(v.value == 1030)
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Insert a new key-value pair.
d[TestObjCKeyTy(40)] = TestObjCValueTy(2040)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestObjCKeyTy(10)] as! TestObjCValueTy
assert(v.value == 1010)
v = d[TestObjCKeyTy(20)] as! TestObjCValueTy
assert(v.value == 1020)
v = d[TestObjCKeyTy(30)] as! TestObjCValueTy
assert(v.value == 1030)
v = d[TestObjCKeyTy(40)] as! TestObjCValueTy
assert(v.value == 2040)
// Overwrite value in existing binding.
d[TestObjCKeyTy(10)] = TestObjCValueTy(2010)
assert(identity2 == unsafeBitCast(d, to: Int.self))
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestObjCKeyTy(10)] as! TestObjCValueTy
assert(v.value == 2010)
v = d[TestObjCKeyTy(20)] as! TestObjCValueTy
assert(v.value == 1020)
v = d[TestObjCKeyTy(30)] as! TestObjCValueTy
assert(v.value == 1030)
v = d[TestObjCKeyTy(40)] as! TestObjCValueTy
assert(v.value == 2040)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithKey") {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
// Read existing key-value pairs.
var v = d[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = d[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = d[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
assert(identity1 == unsafeBitCast(d, to: Int.self))
// Insert a new key-value pair.
d[TestBridgedKeyTy(40)] = TestBridgedValueTy(2040)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = d[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = d[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
v = d[TestBridgedKeyTy(40)]
assert(v!.value == 2040)
// Overwrite value in existing binding.
d[TestBridgedKeyTy(10)] = TestBridgedValueTy(2010)
assert(identity2 == unsafeBitCast(d, to: Int.self))
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestBridgedKeyTy(10)]
assert(v!.value == 2010)
v = d[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = d[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
v = d[TestBridgedKeyTy(40)]
assert(v!.value == 2040)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.UpdateValueForKey") {
// Insert a new key-value pair.
do {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var oldValue: AnyObject? =
d.updateValue(TestObjCValueTy(2040), forKey: TestObjCKeyTy(40))
assert(oldValue == nil)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert((d[TestObjCKeyTy(40)] as! TestObjCValueTy).value == 2040)
}
// Overwrite a value in existing binding.
do {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var oldValue: AnyObject? =
d.updateValue(TestObjCValueTy(2010), forKey: TestObjCKeyTy(10))
assert((oldValue as! TestObjCValueTy).value == 1010)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 3)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 2010)
assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.UpdateValueForKey") {
// Insert a new key-value pair.
do {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var oldValue =
d.updateValue(TestBridgedValueTy(2040), forKey: TestBridgedKeyTy(40))
assert(oldValue == nil)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
assert(d[TestBridgedKeyTy(10)]!.value == 1010)
assert(d[TestBridgedKeyTy(20)]!.value == 1020)
assert(d[TestBridgedKeyTy(30)]!.value == 1030)
assert(d[TestBridgedKeyTy(40)]!.value == 2040)
}
// Overwrite a value in existing binding.
do {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var oldValue =
d.updateValue(TestBridgedValueTy(2010), forKey: TestBridgedKeyTy(10))!
assert(oldValue.value == 1010)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 == identity2)
assert(isNativeDictionary(d))
assert(d.count == 3)
assert(d[TestBridgedKeyTy(10)]!.value == 2010)
assert(d[TestBridgedKeyTy(20)]!.value == 1020)
assert(d[TestBridgedKeyTy(30)]!.value == 1030)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
let foundIndex1 = d.index(forKey: TestObjCKeyTy(10))!
assert(d[foundIndex1].0 == TestObjCKeyTy(10))
assert((d[foundIndex1].1 as! TestObjCValueTy).value == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
let removedElement = d.remove(at: foundIndex1)
assert(identity1 != unsafeBitCast(d, to: Int.self))
assert(isNativeDictionary(d))
assert(removedElement.0 == TestObjCKeyTy(10))
assert((removedElement.1 as! TestObjCValueTy).value == 1010)
assert(d.count == 2)
assert(d.index(forKey: TestObjCKeyTy(10)) == nil)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
let foundIndex1 = d.index(forKey: TestBridgedKeyTy(10))!
assert(d[foundIndex1].0 == TestBridgedKeyTy(10))
assert(d[foundIndex1].1.value == 1010)
assert(identity1 == unsafeBitCast(d, to: Int.self))
let removedElement = d.remove(at: foundIndex1)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(isNativeDictionary(d))
assert(removedElement.0 == TestObjCKeyTy(10))
assert(removedElement.1.value == 1010)
assert(d.count == 2)
assert(d.index(forKey: TestBridgedKeyTy(10)) == nil)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveValueForKey") {
do {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var deleted: AnyObject? = d.removeValue(forKey: TestObjCKeyTy(0))
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(isCocoaDictionary(d))
deleted = d.removeValue(forKey: TestObjCKeyTy(10))
assert((deleted as! TestObjCValueTy).value == 1010)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 2)
assert(d[TestObjCKeyTy(10)] == nil)
assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert(identity2 == unsafeBitCast(d, to: Int.self))
}
do {
var d1 = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(isCocoaDictionary(d1))
assert(isCocoaDictionary(d2))
var deleted: AnyObject? = d2.removeValue(forKey: TestObjCKeyTy(0))
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
assert(isCocoaDictionary(d1))
assert(isCocoaDictionary(d2))
deleted = d2.removeValue(forKey: TestObjCKeyTy(10))
assert((deleted as! TestObjCValueTy).value == 1010)
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 != identity2)
assert(isCocoaDictionary(d1))
assert(isNativeDictionary(d2))
assert(d2.count == 2)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert((d1[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d1[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(d2[TestObjCKeyTy(10)] == nil)
assert((d2[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d2[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert(identity2 == unsafeBitCast(d2, to: Int.self))
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveValueForKey") {
do {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var deleted = d.removeValue(forKey: TestBridgedKeyTy(0))
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(isNativeDictionary(d))
deleted = d.removeValue(forKey: TestBridgedKeyTy(10))
assert(deleted!.value == 1010)
var identity2 = unsafeBitCast(d, to: Int.self)
assert(identity1 == identity2)
assert(isNativeDictionary(d))
assert(d.count == 2)
assert(d[TestBridgedKeyTy(10)] == nil)
assert(d[TestBridgedKeyTy(20)]!.value == 1020)
assert(d[TestBridgedKeyTy(30)]!.value == 1030)
assert(identity2 == unsafeBitCast(d, to: Int.self))
}
do {
var d1 = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
var d2 = d1
assert(isNativeDictionary(d1))
assert(isNativeDictionary(d2))
var deleted = d2.removeValue(forKey: TestBridgedKeyTy(0))
assert(deleted == nil)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity1 == unsafeBitCast(d2, to: Int.self))
assert(isNativeDictionary(d1))
assert(isNativeDictionary(d2))
deleted = d2.removeValue(forKey: TestBridgedKeyTy(10))
assert(deleted!.value == 1010)
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 != identity2)
assert(isNativeDictionary(d1))
assert(isNativeDictionary(d2))
assert(d2.count == 2)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
assert(d1[TestBridgedKeyTy(20)]!.value == 1020)
assert(d1[TestBridgedKeyTy(30)]!.value == 1030)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(d2[TestBridgedKeyTy(10)] == nil)
assert(d2[TestBridgedKeyTy(20)]!.value == 1020)
assert(d2[TestBridgedKeyTy(30)]!.value == 1030)
assert(identity2 == unsafeBitCast(d2, to: Int.self))
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") {
do {
var d = getBridgedVerbatimDictionary([:])
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
assert(d.count == 0)
d.removeAll()
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 0)
}
do {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
d.removeAll()
assert(identity1 != unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity < originalCapacity)
assert(d.count == 0)
assert(d[TestObjCKeyTy(10)] == nil)
}
do {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 != unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity >= originalCapacity)
assert(d.count == 0)
assert(d[TestObjCKeyTy(10)] == nil)
}
do {
var d1 = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(isCocoaDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
var d2 = d1
d2.removeAll()
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert(d2._variantStorage.asNative.capacity < originalCapacity)
assert(d2.count == 0)
assert(d2[TestObjCKeyTy(10)] == nil)
}
do {
var d1 = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(isCocoaDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert(d2._variantStorage.asNative.capacity >= originalCapacity)
assert(d2.count == 0)
assert(d2[TestObjCKeyTy(10)] == nil)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") {
do {
var d = getBridgedNonverbatimDictionary([:])
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
assert(d.count == 0)
d.removeAll()
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d.count == 0)
}
do {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert(d[TestBridgedKeyTy(10)]!.value == 1010)
d.removeAll()
assert(identity1 != unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity < originalCapacity)
assert(d.count == 0)
assert(d[TestBridgedKeyTy(10)] == nil)
}
do {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert(d[TestBridgedKeyTy(10)]!.value == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 == unsafeBitCast(d, to: Int.self))
assert(d._variantStorage.asNative.capacity >= originalCapacity)
assert(d.count == 0)
assert(d[TestBridgedKeyTy(10)] == nil)
}
do {
var d1 = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(isNativeDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll()
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
assert(d2._variantStorage.asNative.capacity < originalCapacity)
assert(d2.count == 0)
assert(d2[TestBridgedKeyTy(10)] == nil)
}
do {
var d1 = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(isNativeDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
assert(d2._variantStorage.asNative.capacity >= originalCapacity)
assert(d2.count == 0)
assert(d2[TestBridgedKeyTy(10)] == nil)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Count") {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
assert(d.count == 3)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Count") {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
assert(d.count == 3)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate") {
var d = getBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") {
var d = getBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") {
var d = getBridgedVerbatimDictionary([:])
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
// Cannot write code below because of
// <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison
// assert(iter.next() == .none)
assert(iter.next() == nil)
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") {
var d = getBridgedNonverbatimDictionary([:])
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var iter = d.makeIterator()
// Cannot write code below because of
// <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison
// assert(iter.next() == .none)
assert(iter.next() == nil)
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") {
var d = getHugeBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
var expectedPairs = Array<(Int, Int)>()
for i in 1...32 {
expectedPairs += [(i, 1000 + i)]
}
assert(equalsUnordered(pairs, expectedPairs))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") {
var d = getHugeBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
var expectedPairs = Array<(Int, Int)>()
for i in 1...32 {
expectedPairs += [(i, 1000 + i)]
}
assert(equalsUnordered(pairs, expectedPairs))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_ParallelArray") {
autoreleasepoolIfUnoptimizedReturnAutoreleased {
// Add an autorelease pool because ParallelArrayDictionary autoreleases
// values in objectForKey.
var d = getParallelArrayBridgedVerbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
var expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ]
assert(equalsUnordered(pairs, expectedPairs))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_ParallelArray") {
autoreleasepoolIfUnoptimizedReturnAutoreleased {
// Add an autorelease pool because ParallelArrayDictionary autoreleases
// values in objectForKey.
var d = getParallelArrayBridgedNonverbatimDictionary()
var identity1 = unsafeBitCast(d, to: Int.self)
assert(isNativeDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
var expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ]
assert(equalsUnordered(pairs, expectedPairs))
// The following is not required by the IteratorProtocol protocol, but
// it is a nice QoI.
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == unsafeBitCast(d, to: Int.self))
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") {
var d1 = getBridgedVerbatimEquatableDictionary([:])
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(isCocoaDictionary(d1))
var d2 = getBridgedVerbatimEquatableDictionary([:])
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(isCocoaDictionary(d2))
// We can't check that `identity1 != identity2` because Foundation might be
// returning the same singleton NSDictionary for empty dictionaries.
assert(d1 == d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
d2[TestObjCKeyTy(10)] = TestObjCEquatableValueTy(2010)
assert(isNativeDictionary(d2))
assert(identity2 != unsafeBitCast(d2, to: Int.self))
identity2 = unsafeBitCast(d2, to: Int.self)
assert(d1 != d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") {
var d1 = getBridgedNonverbatimEquatableDictionary([:])
var identity1 = unsafeBitCast(d1, to: Int.self)
assert(isNativeDictionary(d1))
var d2 = getBridgedNonverbatimEquatableDictionary([:])
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(isNativeDictionary(d2))
assert(identity1 != identity2)
assert(d1 == d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
d2[TestBridgedKeyTy(10)] = TestBridgedEquatableValueTy(2010)
assert(isNativeDictionary(d2))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
assert(d1 != d2)
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") {
func helper(_ nd1: Dictionary<Int, Int>, _ nd2: Dictionary<Int, Int>, _ expectedEq: Bool) {
let d1 = getBridgedVerbatimEquatableDictionary(nd1)
let identity1 = unsafeBitCast(d1, to: Int.self)
assert(isCocoaDictionary(d1))
var d2 = getBridgedVerbatimEquatableDictionary(nd2)
var identity2 = unsafeBitCast(d2, to: Int.self)
assert(isCocoaDictionary(d2))
do {
let eq1 = (d1 == d2)
assert(eq1 == expectedEq)
let eq2 = (d2 == d1)
assert(eq2 == expectedEq)
let neq1 = (d1 != d2)
assert(neq1 != expectedEq)
let neq2 = (d2 != d1)
assert(neq2 != expectedEq)
}
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
d2[TestObjCKeyTy(1111)] = TestObjCEquatableValueTy(1111)
d2[TestObjCKeyTy(1111)] = nil
assert(isNativeDictionary(d2))
assert(identity2 != unsafeBitCast(d2, to: Int.self))
identity2 = unsafeBitCast(d2, to: Int.self)
do {
let eq1 = (d1 == d2)
assert(eq1 == expectedEq)
let eq2 = (d2 == d1)
assert(eq2 == expectedEq)
let neq1 = (d1 != d2)
assert(neq1 != expectedEq)
let neq2 = (d2 != d1)
assert(neq2 != expectedEq)
}
assert(identity1 == unsafeBitCast(d1, to: Int.self))
assert(identity2 == unsafeBitCast(d2, to: Int.self))
}
helper([:], [:], true)
helper([ 10: 1010 ],
[ 10: 1010 ],
true)
helper([ 10: 1010, 20: 1020 ],
[ 10: 1010, 20: 1020 ],
true)
helper([ 10: 1010, 20: 1020, 30: 1030 ],
[ 10: 1010, 20: 1020, 30: 1030 ],
true)
helper([ 10: 1010, 20: 1020, 30: 1030 ],
[ 10: 1010, 20: 1020, 1111: 1030 ],
false)
helper([ 10: 1010, 20: 1020, 30: 1030 ],
[ 10: 1010, 20: 1020, 30: 1111 ],
false)
helper([ 10: 1010, 20: 1020, 30: 1030 ],
[ 10: 1010, 20: 1020 ],
false)
helper([ 10: 1010, 20: 1020, 30: 1030 ],
[ 10: 1010 ],
false)
helper([ 10: 1010, 20: 1020, 30: 1030 ],
[:],
false)
helper([ 10: 1010, 20: 1020, 30: 1030 ],
[ 10: 1010, 20: 1020, 30: 1030, 40: 1040 ],
false)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfDictionaries") {
var nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSDictionary([ 10: 1010 + i, 20: 1020 + i, 30: 1030 + i ]))
}
var a = nsa as [AnyObject] as! [Dictionary<NSObject, AnyObject>]
for i in 0..<3 {
var d = a[i]
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
var expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ]
assert(equalsUnordered(pairs, expectedPairs))
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfDictionaries") {
var nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSDictionary([ 10: 1010 + i, 20: 1020 + i, 30: 1030 + i ]))
}
var a = nsa as [AnyObject] as! [Dictionary<TestBridgedKeyTy, TestBridgedValueTy>]
for i in 0..<3 {
var d = a[i]
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
var expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ]
assert(equalsUnordered(pairs, expectedPairs))
}
}
//===---
// Dictionary -> NSDictionary bridging tests.
//
// Key and Value are bridged verbatim.
//===---
DictionaryTestSuite.test("BridgedToObjC.Verbatim.Count") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
assert(d.count == 3)
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.ObjectForKey") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
var v: AnyObject? = d.object(forKey: TestObjCKeyTy(10))
expectEqual(1010, (v as! TestObjCValueTy).value)
let idValue10 = unsafeBitCast(v, to: UInt.self)
v = d.object(forKey: TestObjCKeyTy(20))
expectEqual(1020, (v as! TestObjCValueTy).value)
let idValue20 = unsafeBitCast(v, to: UInt.self)
v = d.object(forKey: TestObjCKeyTy(30))
expectEqual(1030, (v as! TestObjCValueTy).value)
let idValue30 = unsafeBitCast(v, to: UInt.self)
expectEmpty(d.object(forKey: TestObjCKeyTy(40)))
for i in 0..<3 {
expectEqual(idValue10, unsafeBitCast(
d.object(forKey: TestObjCKeyTy(10)), to: UInt.self))
expectEqual(idValue20, unsafeBitCast(
d.object(forKey: TestObjCKeyTy(20)), to: UInt.self))
expectEqual(idValue30, unsafeBitCast(
d.object(forKey: TestObjCKeyTy(30)), to: UInt.self))
}
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
var capturedIdentityPairs = Array<(UInt, UInt)>()
for i in 0..<3 {
let enumerator = d.keyEnumerator()
var dataPairs = Array<(Int, Int)>()
var identityPairs = Array<(UInt, UInt)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)!
let dataPair =
((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
dataPairs.append(dataPair)
let identityPair =
(unsafeBitCast(key, to: UInt.self),
unsafeBitCast(value, to: UInt.self))
identityPairs.append(identityPair)
}
expectTrue(
equalsUnordered(dataPairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
if capturedIdentityPairs.isEmpty {
capturedIdentityPairs = identityPairs
} else {
expectTrue(equalsUnordered(capturedIdentityPairs, identityPairs))
}
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
}
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject_Empty") {
let d = getBridgedEmptyNSDictionary()
let enumerator = d.keyEnumerator()
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration_Empty") {
let d = getBridgedEmptyNSDictionary()
checkDictionaryFastEnumerationFromSwift(
[], d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
checkDictionaryFastEnumerationFromObjC(
[], d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") {
let d = getBridgedEmptyNSDictionary()
checkDictionaryFastEnumerationFromSwift(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
checkDictionaryFastEnumerationFromObjC(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
}
//===---
// Dictionary -> NSDictionary bridging tests.
//
// Key type and value type are bridged non-verbatim.
//===---
DictionaryTestSuite.test("BridgedToObjC.KeyValue_ValueTypesCustomBridged") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
let enumerator = d.keyEnumerator()
var pairs = Array<(Int, Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)!
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift.Partial") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged(
numElements: 9)
checkDictionaryEnumeratorPartialFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030), (40, 1040), (50, 1050),
(60, 1060), (70, 1070), (80, 1080), (90, 1090) ],
d, maxFastEnumerationItems: 5,
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (9, 9))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged(
numElements: 0)
checkDictionaryFastEnumerationFromSwift(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
checkDictionaryFastEnumerationFromObjC(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
}
func getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() -> NSDictionary {
assert(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self))
assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self))
var d = Dictionary<TestBridgedKeyTy, TestObjCValueTy>()
d[TestBridgedKeyTy(10)] = TestObjCValueTy(1010)
d[TestBridgedKeyTy(20)] = TestObjCValueTy(1020)
d[TestBridgedKeyTy(30)] = TestObjCValueTy(1030)
let bridged = convertDictionaryToNSDictionary(d)
assert(isNativeNSDictionary(bridged))
return bridged
}
DictionaryTestSuite.test("BridgedToObjC.Key_ValueTypeCustomBridged") {
let d = getBridgedNSDictionaryOfKey_ValueTypeCustomBridged()
let enumerator = d.keyEnumerator()
var pairs = Array<(Int, Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)!
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
func getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() -> NSDictionary {
assert(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self))
assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self))
var d = Dictionary<TestObjCKeyTy, TestBridgedValueTy>()
d[TestObjCKeyTy(10)] = TestBridgedValueTy(1010)
d[TestObjCKeyTy(20)] = TestBridgedValueTy(1020)
d[TestObjCKeyTy(30)] = TestBridgedValueTy(1030)
let bridged = convertDictionaryToNSDictionary(d)
assert(isNativeNSDictionary(bridged))
return bridged
}
DictionaryTestSuite.test("BridgedToObjC.Value_ValueTypeCustomBridged") {
let d = getBridgedNSDictionaryOfValue_ValueTypeCustomBridged()
let enumerator = d.keyEnumerator()
var pairs = Array<(Int, Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)!
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
//===---
// NSDictionary -> Dictionary -> NSDictionary bridging tests.
//===---
func getRoundtripBridgedNSDictionary() -> NSDictionary {
let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) }
let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) }
let nsd = NSDictionary(objects: values, forKeys: keys)
let d: Dictionary<NSObject, AnyObject> = convertNSDictionaryToDictionary(nsd)
let bridgedBack = convertDictionaryToNSDictionary(d)
assert(isCocoaNSDictionary(bridgedBack))
// FIXME: this should be true.
//assert(unsafeBitCast(nsd, Int.self) == unsafeBitCast(bridgedBack, Int.self))
return bridgedBack
}
DictionaryTestSuite.test("BridgingRoundtrip") {
let d = getRoundtripBridgedNSDictionary()
let enumerator = d.keyEnumerator()
var pairs = Array<(key: Int, value: Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)!
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
expectEqualsUnordered([ (10, 1010), (20, 1020), (30, 1030) ], pairs)
}
//===---
// NSDictionary -> Dictionary implicit conversion.
//===---
DictionaryTestSuite.test("NSDictionaryToDictionaryConversion") {
let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) }
let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) }
let nsd = NSDictionary(objects: values, forKeys: keys)
let d: Dictionary = nsd as Dictionary
var pairs = Array<(Int, Int)>()
for (key, value) in d {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
}
DictionaryTestSuite.test("DictionaryToNSDictionaryConversion") {
var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
let nsd: NSDictionary = d
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
//===---
// Dictionary upcasts
//===---
DictionaryTestSuite.test("DictionaryUpcastEntryPoint") {
var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
var dAsAnyObject: Dictionary<NSObject, AnyObject> = _dictionaryUpCast(d)
assert(dAsAnyObject.count == 3)
var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)]
assert((v! as! TestObjCValueTy).value == 1010)
v = dAsAnyObject[TestObjCKeyTy(20)]
assert((v! as! TestObjCValueTy).value == 1020)
v = dAsAnyObject[TestObjCKeyTy(30)]
assert((v! as! TestObjCValueTy).value == 1030)
}
DictionaryTestSuite.test("DictionaryUpcast") {
var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
var dAsAnyObject: Dictionary<NSObject, AnyObject> = d
assert(dAsAnyObject.count == 3)
var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)]
assert((v! as! TestObjCValueTy).value == 1010)
v = dAsAnyObject[TestObjCKeyTy(20)]
assert((v! as! TestObjCValueTy).value == 1020)
v = dAsAnyObject[TestObjCKeyTy(30)]
assert((v! as! TestObjCValueTy).value == 1030)
}
DictionaryTestSuite.test("DictionaryUpcastBridgedEntryPoint") {
var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32)
d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010)
d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020)
d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030)
do {
var dOO: Dictionary<NSObject, AnyObject> = _dictionaryBridgeToObjectiveC(d)
assert(dOO.count == 3)
var v: AnyObject? = dOO[TestObjCKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dOO[TestObjCKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dOO[TestObjCKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
do {
var dOV: Dictionary<NSObject, TestBridgedValueTy>
= _dictionaryBridgeToObjectiveC(d)
assert(dOV.count == 3)
var v = dOV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dOV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dOV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
do {
var dVO: Dictionary<TestBridgedKeyTy, AnyObject>
= _dictionaryBridgeToObjectiveC(d)
assert(dVO.count == 3)
var v: AnyObject? = dVO[TestBridgedKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dVO[TestBridgedKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dVO[TestBridgedKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
}
DictionaryTestSuite.test("DictionaryUpcastBridged") {
var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32)
d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010)
d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020)
d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030)
do {
var dOO: Dictionary<NSObject, AnyObject> = d
assert(dOO.count == 3)
var v: AnyObject? = dOO[TestObjCKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dOO[TestObjCKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dOO[TestObjCKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
do {
var dOV: Dictionary<NSObject, TestBridgedValueTy> = d
assert(dOV.count == 3)
var v = dOV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dOV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dOV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
do {
var dVO: Dictionary<TestBridgedKeyTy, AnyObject> = d
assert(dVO.count == 3)
var v: AnyObject? = dVO[TestBridgedKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dVO[TestBridgedKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dVO[TestBridgedKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
}
//===---
// Dictionary downcasts
//===---
DictionaryTestSuite.test("DictionaryDowncastEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCC: Dictionary<TestObjCKeyTy, TestObjCValueTy> = _dictionaryDownCast(d)
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("DictionaryDowncast") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCC = d as! Dictionary<TestObjCKeyTy, TestObjCValueTy>
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("DictionaryDowncastConditionalEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCC
= _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? {
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcast
d["hello"] = 17
if let dCC
= _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? {
assert(false)
}
}
DictionaryTestSuite.test("DictionaryDowncastConditional") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> {
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcast
d["hello"] = 17
if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> {
assert(false)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCV: Dictionary<TestObjCKeyTy, TestBridgedValueTy>
= _dictionaryBridgeFromObjectiveC(d)
do {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVC: Dictionary<TestBridgedKeyTy, TestObjCValueTy>
= _dictionaryBridgeFromObjectiveC(d)
do {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVV: Dictionary<TestBridgedKeyTy, TestBridgedValueTy>
= _dictionaryBridgeFromObjectiveC(d)
do {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveC") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCV = d as! Dictionary<TestObjCKeyTy, TestBridgedValueTy>
do {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVC = d as! Dictionary<TestBridgedKeyTy, TestObjCValueTy>
do {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVV = d as! Dictionary<TestBridgedKeyTy, TestBridgedValueTy>
do {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditionalEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCV
= _dictionaryBridgeFromObjectiveCConditional(d) as
Dictionary<TestObjCKeyTy, TestBridgedValueTy>? {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVC
= _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>? {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVV
= _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>? {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcasts
d["hello"] = 17
if let dCV
= _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>?{
assert(false)
}
if let dVC
= _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>?{
assert(false)
}
if let dVV
= _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>?{
assert(false)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditional") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcasts
d["hello"] = 17
if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> {
assert(false)
}
if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> {
assert(false)
}
if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
assert(false)
}
}
//===---
// Tests for APIs implemented strictly based on public interface. We only need
// to test them once, not for every storage type.
//===---
func getDerivedAPIsDictionary() -> Dictionary<Int, Int> {
var d = Dictionary<Int, Int>(minimumCapacity: 10)
d[10] = 1010
d[20] = 1020
d[30] = 1030
return d
}
var DictionaryDerivedAPIs = TestSuite("DictionaryDerivedAPIs")
@objc
class MockDictionaryWithCustomCount : NSDictionary {
init(count: Int) {
self._count = count
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(
objects: UnsafePointer<AnyObject>,
forKeys keys: UnsafePointer<NSCopying>,
count: Int) {
expectUnreachable()
super.init(objects: objects, forKeys: keys, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by MockDictionaryWithCustomCount")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> AnyObject {
// Ensure that copying this dictionary produces an object of the same
// dynamic type.
return self
}
override func object(forKey aKey: AnyObject) -> AnyObject? {
expectUnreachable()
return NSObject()
}
override var count: Int {
MockDictionaryWithCustomCount.timesCountWasCalled += 1
return _count
}
var _count: Int = 0
static var timesCountWasCalled = 0
}
func getMockDictionaryWithCustomCount(count count: Int)
-> Dictionary<NSObject, AnyObject> {
return MockDictionaryWithCustomCount(count: count) as Dictionary
}
DictionaryDerivedAPIs.test("isEmpty") {
do {
var empty = Dictionary<Int, Int>()
expectTrue(empty.isEmpty)
}
do {
var d = getDerivedAPIsDictionary()
expectFalse(d.isEmpty)
}
}
func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool {
return collection.isEmpty
}
DictionaryDerivedAPIs.test("isEmpty/ImplementationIsCustomized") {
do {
var d = getMockDictionaryWithCustomCount(count: 0)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectTrue(d.isEmpty)
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockDictionaryWithCustomCount(count: 0)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectTrue(callGenericIsEmpty(d))
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockDictionaryWithCustomCount(count: 4)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectFalse(d.isEmpty)
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
do {
var d = getMockDictionaryWithCustomCount(count: 4)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectFalse(callGenericIsEmpty(d))
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
}
DictionaryDerivedAPIs.test("keys") {
do {
var empty = Dictionary<Int, Int>()
var keys = Array(empty.keys)
expectTrue(equalsUnordered(keys, []))
}
do {
var d = getDerivedAPIsDictionary()
var keys = Array(d.keys)
expectTrue(equalsUnordered(keys, [ 10, 20, 30 ]))
}
}
DictionaryDerivedAPIs.test("values") {
do {
var empty = Dictionary<Int, Int>()
var values = Array(empty.values)
expectTrue(equalsUnordered(values, []))
}
do {
var d = getDerivedAPIsDictionary()
var values = Array(d.values)
expectTrue(equalsUnordered(values, [ 1010, 1020, 1030 ]))
d[11] = 1010
values = Array(d.values)
expectTrue(equalsUnordered(values, [ 1010, 1010, 1020, 1030 ]))
}
}
var ObjCThunks = TestSuite("ObjCThunks")
class ObjCThunksHelper : NSObject {
dynamic func acceptArrayBridgedVerbatim(_ array: [TestObjCValueTy]) {
expectEqual(10, array[0].value)
expectEqual(20, array[1].value)
expectEqual(30, array[2].value)
}
dynamic func acceptArrayBridgedNonverbatim(_ array: [TestBridgedValueTy]) {
// Cannot check elements because doing so would bridge them.
expectEqual(3, array.count)
}
dynamic func returnArrayBridgedVerbatim() -> [TestObjCValueTy] {
return [ TestObjCValueTy(10), TestObjCValueTy(20),
TestObjCValueTy(30) ]
}
dynamic func returnArrayBridgedNonverbatim() -> [TestBridgedValueTy] {
return [ TestBridgedValueTy(10), TestBridgedValueTy(20),
TestBridgedValueTy(30) ]
}
dynamic func acceptDictionaryBridgedVerbatim(
_ d: [TestObjCKeyTy : TestObjCValueTy]) {
expectEqual(3, d.count)
expectEqual(1010, d[TestObjCKeyTy(10)]!.value)
expectEqual(1020, d[TestObjCKeyTy(20)]!.value)
expectEqual(1030, d[TestObjCKeyTy(30)]!.value)
}
dynamic func acceptDictionaryBridgedNonverbatim(
_ d: [TestBridgedKeyTy : TestBridgedValueTy]) {
expectEqual(3, d.count)
// Cannot check elements because doing so would bridge them.
}
dynamic func returnDictionaryBridgedVerbatim() ->
[TestObjCKeyTy : TestObjCValueTy] {
return [
TestObjCKeyTy(10): TestObjCValueTy(1010),
TestObjCKeyTy(20): TestObjCValueTy(1020),
TestObjCKeyTy(30): TestObjCValueTy(1030),
]
}
dynamic func returnDictionaryBridgedNonverbatim() ->
[TestBridgedKeyTy : TestBridgedValueTy] {
return [
TestBridgedKeyTy(10): TestBridgedValueTy(1010),
TestBridgedKeyTy(20): TestBridgedValueTy(1020),
TestBridgedKeyTy(30): TestBridgedValueTy(1030),
]
}
}
ObjCThunks.test("Array/Accept") {
var helper = ObjCThunksHelper()
do {
helper.acceptArrayBridgedVerbatim(
[ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ])
}
do {
TestBridgedValueTy.bridgeOperations = 0
helper.acceptArrayBridgedNonverbatim(
[ TestBridgedValueTy(10), TestBridgedValueTy(20),
TestBridgedValueTy(30) ])
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
ObjCThunks.test("Array/Return") {
var helper = ObjCThunksHelper()
do {
let a = helper.returnArrayBridgedVerbatim()
expectEqual(10, a[0].value)
expectEqual(20, a[1].value)
expectEqual(30, a[2].value)
}
do {
TestBridgedValueTy.bridgeOperations = 0
let a = helper.returnArrayBridgedNonverbatim()
expectEqual(0, TestBridgedValueTy.bridgeOperations)
TestBridgedValueTy.bridgeOperations = 0
expectEqual(10, a[0].value)
expectEqual(20, a[1].value)
expectEqual(30, a[2].value)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
ObjCThunks.test("Dictionary/Accept") {
var helper = ObjCThunksHelper()
do {
helper.acceptDictionaryBridgedVerbatim(
[ TestObjCKeyTy(10): TestObjCValueTy(1010),
TestObjCKeyTy(20): TestObjCValueTy(1020),
TestObjCKeyTy(30): TestObjCValueTy(1030) ])
}
do {
TestBridgedKeyTy.bridgeOperations = 0
TestBridgedValueTy.bridgeOperations = 0
helper.acceptDictionaryBridgedNonverbatim(
[ TestBridgedKeyTy(10): TestBridgedValueTy(1010),
TestBridgedKeyTy(20): TestBridgedValueTy(1020),
TestBridgedKeyTy(30): TestBridgedValueTy(1030) ])
expectEqual(0, TestBridgedKeyTy.bridgeOperations)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
ObjCThunks.test("Dictionary/Return") {
var helper = ObjCThunksHelper()
do {
let d = helper.returnDictionaryBridgedVerbatim()
expectEqual(3, d.count)
expectEqual(1010, d[TestObjCKeyTy(10)]!.value)
expectEqual(1020, d[TestObjCKeyTy(20)]!.value)
expectEqual(1030, d[TestObjCKeyTy(30)]!.value)
}
do {
TestBridgedKeyTy.bridgeOperations = 0
TestBridgedValueTy.bridgeOperations = 0
let d = helper.returnDictionaryBridgedNonverbatim()
expectEqual(0, TestBridgedKeyTy.bridgeOperations)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
TestBridgedKeyTy.bridgeOperations = 0
TestBridgedValueTy.bridgeOperations = 0
expectEqual(3, d.count)
expectEqual(1010, d[TestBridgedKeyTy(10)]!.value)
expectEqual(1020, d[TestBridgedKeyTy(20)]!.value)
expectEqual(1030, d[TestBridgedKeyTy(30)]!.value)
expectEqual(0, TestBridgedKeyTy.bridgeOperations)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
//===---
// Check that iterators traverse a snapshot of the collection.
//===---
DictionaryTestSuite.test("mutationDoesNotAffectIterator/subscript/store") {
var dict = getDerivedAPIsDictionary()
var iter = dict.makeIterator()
dict[10] = 1011
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,1") {
var dict = getDerivedAPIsDictionary()
var iter = dict.makeIterator()
expectOptionalEqual(1010, dict.removeValue(forKey: 10))
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,all") {
var dict = getDerivedAPIsDictionary()
var iter = dict.makeIterator()
expectOptionalEqual(1010, dict.removeValue(forKey: 10))
expectOptionalEqual(1020, dict.removeValue(forKey: 20))
expectOptionalEqual(1030, dict.removeValue(forKey: 30))
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test(
"mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") {
var dict = getDerivedAPIsDictionary()
var iter = dict.makeIterator()
dict.removeAll(keepingCapacity: false)
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test(
"mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") {
var dict = getDerivedAPIsDictionary()
var iter = dict.makeIterator()
dict.removeAll(keepingCapacity: true)
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
//===---
// Misc tests.
//===---
DictionaryTestSuite.test("misc") {
do {
// Dictionary literal
var dict = [ "Hello": 1, "World": 2 ]
// Insertion
dict["Swift"] = 3
// Access
expectOptionalEqual(1, dict["Hello"])
expectOptionalEqual(2, dict["World"])
expectOptionalEqual(3, dict["Swift"])
expectEmpty(dict["Universe"])
// Overwriting existing value
dict["Hello"] = 0
expectOptionalEqual(0, dict["Hello"])
expectOptionalEqual(2, dict["World"])
expectOptionalEqual(3, dict["Swift"])
expectEmpty(dict["Universe"])
}
do {
// Dictionaries with other types
var d = [ 1.2: 1, 2.6: 2 ]
d[3.3] = 3
expectOptionalEqual(1, d[1.2])
expectOptionalEqual(2, d[2.6])
expectOptionalEqual(3, d[3.3])
}
do {
var d = Dictionary<String, Int>(minimumCapacity: 13)
d["one"] = 1
d["two"] = 2
d["three"] = 3
d["four"] = 4
d["five"] = 5
expectOptionalEqual(1, d["one"])
expectOptionalEqual(2, d["two"])
expectOptionalEqual(3, d["three"])
expectOptionalEqual(4, d["four"])
expectOptionalEqual(5, d["five"])
// Iterate over (key, value) tuples as a silly copy
var d3 = Dictionary<String,Int>(minimumCapacity: 13)
for (k, v) in d {
d3[k] = v
}
expectOptionalEqual(1, d3["one"])
expectOptionalEqual(2, d3["two"])
expectOptionalEqual(3, d3["three"])
expectOptionalEqual(4, d3["four"])
expectOptionalEqual(5, d3["five"])
expectEqual(3, d.values[d.keys.index(of: "three")!])
expectEqual(4, d.values[d.keys.index(of: "four")!])
expectEqual(3, d3.values[d.keys.index(of: "three")!])
expectEqual(4, d3.values[d.keys.index(of: "four")!])
}
}
DictionaryTestSuite.test("dropsBridgedCache") {
// rdar://problem/18544533
// Previously this code would segfault due to a double free in the Dictionary
// implementation.
// This test will only fail in address sanitizer.
var dict = [0:10]
do {
var bridged: NSDictionary = dict
expectEqual(10, bridged[0] as! Int)
}
dict[0] = 11
do {
var bridged: NSDictionary = dict
expectEqual(11, bridged[0] as! Int)
}
}
DictionaryTestSuite.test("getObjects:andKeys:") {
let d = ([1: "one", 2: "two"] as Dictionary<Int, String>) as NSDictionary
var keys = UnsafeMutableBufferPointer(
start: UnsafeMutablePointer<NSNumber>(allocatingCapacity: 2), count: 2)
var values = UnsafeMutableBufferPointer(
start: UnsafeMutablePointer<NSString>(allocatingCapacity: 2), count: 2)
var kp = AutoreleasingUnsafeMutablePointer<AnyObject>(keys.baseAddress!)
var vp = AutoreleasingUnsafeMutablePointer<AnyObject>(values.baseAddress!)
d.getObjects(nil, andKeys: nil) // don't segfault
d.getObjects(nil, andKeys: kp)
expectEqual([2, 1] as [NSNumber], Array(keys))
d.getObjects(vp, andKeys: nil)
expectEqual(["two", "one"] as [NSString], Array(values))
d.getObjects(vp, andKeys: kp)
expectEqual([2, 1] as [NSNumber], Array(keys))
expectEqual(["two", "one"] as [NSString], Array(values))
}
DictionaryTestSuite.test("popFirst") {
// Empty
do {
var d = [Int: Int]()
let popped = d.popFirst()
expectEmpty(popped)
}
do {
var popped = [(Int, Int)]()
var d: [Int: Int] = [
1010: 1010,
2020: 2020,
3030: 3030,
]
let expected = Array(d.map{($0.0, $0.1)})
while let element = d.popFirst() {
popped.append(element)
}
expectEqualSequence(expected, Array(popped)) {
(lhs: (Int, Int), rhs: (Int, Int)) -> Bool in
lhs.0 == rhs.0 && lhs.1 == rhs.1
}
expectTrue(d.isEmpty)
}
}
DictionaryTestSuite.test("removeAt") {
// Test removing from the startIndex, the middle, and the end of a dictionary.
for i in 1...3 {
var d: [Int: Int] = [
10: 1010,
20: 2020,
30: 3030,
]
let removed = d.remove(at: d.index(forKey: i*10)!)
expectEqual(i*10, removed.0)
expectEqual(i*1010, removed.1)
expectEqual(2, d.count)
expectEmpty(d.index(forKey: i))
let origKeys: [Int] = [10, 20, 30]
expectEqual(origKeys.filter { $0 != (i*10) }, d.keys.sorted())
}
}
DictionaryTestSuite.setUp {
resetLeaksOfDictionaryKeysValues()
resetLeaksOfObjCDictionaryKeysValues()
}
DictionaryTestSuite.tearDown {
expectNoLeaksOfDictionaryKeysValues()
expectNoLeaksOfObjCDictionaryKeysValues()
}
runAllTests()
| apache-2.0 |
drewag/agnostic-router | Tests/AgnosticRouterTests/RouterTests.swift | 1 | 11645 | //
// RouterTests.swift
// RouterTests
//
// Created by Andrew J Wagner on 4/9/16.
// Copyright © 2016 Drewag. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import XCTest
import AgnosticRouter
struct StandardRouteType: InputOutput {
typealias InputType = Int
typealias OutputType = String
}
struct TestParameterizedRouter: ParameterizedRouter {
var routes: [ParameterizedRoute<StandardRouteType, String>] {
return [
.Variable(router: NestedParameterizedRouter()),
.Static("parrot", handler: self.parrot),
.Variable(handler: self.parrotDoublePlusInput),
.Static("sub", router: TestParameterizedRouter()),
.Static("sub2", subRoutes: [
.Static("parrot", handler: self.parrot),
.Variable(handler: self.parrotDoublePlusInput),
])
]
}
func parrot(input: Int, param: String) throws -> RouterResponse<String> {
return .Handled("Hello \(input)-\(param)")
}
func parrotDoublePlusInput(input: Int, param: (String, Double)) throws -> RouterResponse<String> {
return .Handled("Hello \(input + Int(param.1))-\(param.0)")
}
}
struct TestRouter: Router {
var routes: [Route<StandardRouteType>] {
return [
.Static("hello", handler: self.hello),
.Variable(handler: self.helloDoublePlusInput),
.Static("sub", router: TestRouter()),
.Static("sub2", subRoutes: [
.Static("hello", handler: self.hello),
.Variable(handler: self.helloDoublePlusInput),
])
]
}
func hello(input: Int) throws -> RouterResponse<String> {
return .Handled("Hello \(input)")
}
func helloDoublePlusInput(input: Int, param: Double) throws -> RouterResponse<String> {
return .Handled("Hello \(param + Double(input))")
}
}
struct TestRouter2: Router {
var routes: [Route<StandardRouteType>] {
return [
.Variable(handleSubPaths: true, router: TestParameterizedRouter()),
]
}
}
struct NestedParameterizedRouter: ParameterizedRouter {
var routes: [ParameterizedRoute<StandardRouteType, (String, Int)>] {
return [
.Static("parrot", handler: self.parrot),
]
}
func parrot(input: Int, param: (String, Int)) throws -> RouterResponse<String> {
return .Handled("Nested \(input)-\(param.0)-\(param.1)")
}
}
struct AllRouter: Router {
var routes: [Route<StandardRouteType>] {
return [
.All(handler: self.all),
.Static("hello", handler: self.hello),
]
}
func all(input: Int) throws -> RouterResponse<String> {
if input == 0 {
return .Unhandled
}
else {
return .Handled("ALL \(input)")
}
}
func hello(input: Int) throws -> RouterResponse<String> {
return .Handled("Hello \(input)")
}
}
class RouterTests: XCTestCase {
func testClosureRouter() {
let router = TestRouter()
XCTAssertEqual(try router.route(input: 1, path: "hello").value, "Hello 1")
XCTAssertEqual(try router.route(input: 2, path: "hello/").value, "Hello 2")
XCTAssertEqual(try router.route(input: 3, path: "/hello/").value, "Hello 3")
XCTAssertNil(try router.route(input: 2, path: "helloX").value)
XCTAssertNil(try router.route(input: 2, path: "Xhello").value)
XCTAssertNil(try router.route(input: 2, path: "hello/X").value)
}
func testVariableRouter() {
let router = TestRouter()
XCTAssertEqual(try router.route(input: 1, path: "2.2").value, "Hello 3.2")
XCTAssertEqual(try router.route(input: 2, path: "3.3/").value, "Hello 5.3")
XCTAssertEqual(try router.route(input: 3, path: "/4.4").value, "Hello 7.4")
XCTAssertNil(try router.route(input: 2, path: "2.2X").value)
XCTAssertNil(try router.route(input: 2, path: "2.2/X").value)
}
func testSubStaticRouter() {
let router = TestRouter()
XCTAssertEqual(try router.route(input: 1, path: "sub/hello").value, "Hello 1")
XCTAssertEqual(try router.route(input: 2, path: "/sub/hello").value, "Hello 2")
XCTAssertEqual(try router.route(input: 3, path: "/sub/hello/").value, "Hello 3")
XCTAssertEqual(try router.route(input: 1, path: "sub/2.2").value, "Hello 3.2")
XCTAssertEqual(try router.route(input: 2, path: "sub/3.3").value, "Hello 5.3")
XCTAssertNil(try router.route(input: 2, path: "Xsub/hello").value)
XCTAssertNil(try router.route(input: 2, path: "subX/hello").value)
XCTAssertNil(try router.route(input: 2, path: "sub/helloX").value)
XCTAssertNil(try router.route(input: 2, path: "sub/Xhello").value)
XCTAssertNil(try router.route(input: 2, path: "sub/hello/X").value)
XCTAssertNil(try router.route(input: 2, path: "sub/2.2X").value)
XCTAssertNil(try router.route(input: 2, path: "sub/2.2/X").value)
}
func testSubRoutes() {
let router = TestRouter()
XCTAssertEqual(try router.route(input: 1, path: "sub2/hello").value, "Hello 1")
XCTAssertEqual(try router.route(input: 2, path: "sub2/hello").value, "Hello 2")
XCTAssertEqual(try router.route(input: 1, path: "sub2/2.2").value, "Hello 3.2")
XCTAssertEqual(try router.route(input: 2, path: "sub2/3.3").value, "Hello 5.3")
XCTAssertNil(try router.route(input: 2, path: "Xsub2/hello").value)
XCTAssertNil(try router.route(input: 2, path: "sub2X/hello").value)
XCTAssertNil(try router.route(input: 2, path: "sub2/helloX").value)
XCTAssertNil(try router.route(input: 2, path: "sub2/Xhello").value)
XCTAssertNil(try router.route(input: 2, path: "sub2/hello/X").value)
XCTAssertNil(try router.route(input: 2, path: "sub2/2.2X").value)
XCTAssertNil(try router.route(input: 2, path: "sub2/2.2/X").value)
}
func testVariableSubRouter() {
let router = TestRouter2()
XCTAssertEqual(try router.route(input: 1, path: "captured/parrot").value, "Hello 1-captured")
XCTAssertEqual(try router.route(input: 2, path: "other/parrot/").value, "Hello 2-other")
XCTAssertNil(try router.route(input: 2, path: "something/parrotX").value)
XCTAssertNil(try router.route(input: 2, path: "something/Xparrot").value)
XCTAssertNil(try router.route(input: 2, path: "something/parrot/X").value)
}
func testVariableInVariableSubRouter() {
let router = TestRouter2()
XCTAssertEqual(try router.route(input: 1, path: "captured/2.2").value, "Hello 3-captured")
XCTAssertEqual(try router.route(input: 2, path: "captured/3").value, "Hello 5-captured")
XCTAssertNil(try router.route(input: 2, path: "captured/2.2x").value)
XCTAssertNil(try router.route(input: 2, path: "captured/2.2/X").value)
}
func testSubRouterInVariableSubRouter() {
let router = TestRouter2()
XCTAssertEqual(try router.route(input: 1, path: "captured/sub/parrot").value, "Hello 1-captured")
XCTAssertEqual(try router.route(input: 2, path: "other/sub/parrot/").value, "Hello 2-other")
XCTAssertEqual(try router.route(input: 1, path: "captured/sub/2.2").value, "Hello 3-captured")
XCTAssertEqual(try router.route(input: 2, path: "captured/sub/3").value, "Hello 5-captured")
XCTAssertNil(try router.route(input: 1, path: "captured/subX/parrot").value)
XCTAssertNil(try router.route(input: 2, path: "other/subX/parrot/").value)
XCTAssertNil(try router.route(input: 1, path: "captured/subX/2.2").value)
XCTAssertNil(try router.route(input: 2, path: "captured/subX/3").value)
XCTAssertNil(try router.route(input: 2, path: "something/sub/parrotX").value)
XCTAssertNil(try router.route(input: 2, path: "something/sub/Xparrot").value)
XCTAssertNil(try router.route(input: 2, path: "something/sub/parrot/X").value)
XCTAssertNil(try router.route(input: 2, path: "captured/sub/2.2x").value)
XCTAssertNil(try router.route(input: 2, path: "captured/sub/2.2/X").value)
}
func testSubRoutesInVariableSubRouter() {
let router = TestRouter2()
XCTAssertEqual(try router.route(input: 1, path: "captured/sub2/parrot").value, "Hello 1-captured")
XCTAssertEqual(try router.route(input: 2, path: "other/sub2/parrot/").value, "Hello 2-other")
XCTAssertEqual(try router.route(input: 1, path: "captured/sub2/2.2").value, "Hello 3-captured")
XCTAssertEqual(try router.route(input: 2, path: "captured/sub2/3").value, "Hello 5-captured")
XCTAssertNil(try router.route(input: 1, path: "captured/sub2X/parrot").value)
XCTAssertNil(try router.route(input: 2, path: "other/sub2X/parrot/").value)
XCTAssertNil(try router.route(input: 1, path: "captured/sub2X/2.2").value)
XCTAssertNil(try router.route(input: 2, path: "captured/sub2X/3").value)
XCTAssertNil(try router.route(input: 2, path: "something/sub2/parrotX").value)
XCTAssertNil(try router.route(input: 2, path: "something/sub2/Xparrot").value)
XCTAssertNil(try router.route(input: 2, path: "something/sub2/parrot/X").value)
XCTAssertNil(try router.route(input: 2, path: "captured/sub2/2.2x").value)
XCTAssertNil(try router.route(input: 2, path: "captured/sub2/2.2/X").value)
}
func testNestedParameterizedRouters() {
let router = TestRouter2()
XCTAssertEqual(try router.route(input: 1, path: "captured/2/parrot").value, "Nested 1-captured-2")
XCTAssertEqual(try router.route(input: 5, path: "captured/60/parrot/").value, "Nested 5-captured-60")
XCTAssertNil(try router.route(input: 1, path: "captured/2/parrotX").value)
XCTAssertNil(try router.route(input: 1, path: "captured/2/Xparrot").value)
XCTAssertNil(try router.route(input: 1, path: "captured/2/Xparrot/X").value)
}
func testAllRouter() {
let router = AllRouter()
XCTAssertEqual(try router.route(input: 1, path: "hello").value, "ALL 1")
XCTAssertEqual(try router.route(input: 2, path: "").value, "ALL 2")
XCTAssertEqual(try router.route(input: 3, path: "something/with/sub/route").value, "ALL 3")
// Should be unhandled by all router
XCTAssertEqual(try router.route(input: 0, path: "hello").value, "Hello 0")
XCTAssertNil(try router.route(input: 0, path: "helloX").value)
}
}
| mit |
exercism/xswift | exercises/trinary/Tests/TrinaryTests/TrinaryTests.swift | 3 | 1624 | import XCTest
@testable import Trinary
class TrinaryTests: XCTestCase {
func testTrinary1IsDecimal1() {
XCTAssertEqual(1, Int(Trinary("1")))
}
func testTrinary2IsDecimal2() {
XCTAssertEqual(2, Int(Trinary("2")))
}
func testTrinary10IsDecimal3() {
XCTAssertEqual(3, Int(Trinary("10")))
}
func testTrinary11IsDecimal4() {
XCTAssertEqual(4, Int(Trinary("11")))
}
func testTrinary100IsDecimal9() {
XCTAssertEqual(9, Int(Trinary("100")))
}
func testTrinary112IsDecimal14() {
XCTAssertEqual(14, Int(Trinary("112")))
}
func testTrinary222Is26() {
XCTAssertEqual(26, Int(Trinary("222")))
}
func testTrinary1122000120Is32091() {
XCTAssertEqual(32091, Int(Trinary("1122000120")))
}
func testInvalidTrinaryIsDecimal0() {
XCTAssertEqual(0, Int(Trinary("carrot")))
}
static var allTests: [(String, (TrinaryTests) -> () throws -> Void)] {
return [
("testTrinary1IsDecimal1", testTrinary1IsDecimal1),
("testTrinary2IsDecimal2", testTrinary2IsDecimal2),
("testTrinary10IsDecimal3", testTrinary10IsDecimal3),
("testTrinary11IsDecimal4", testTrinary11IsDecimal4),
("testTrinary100IsDecimal9", testTrinary100IsDecimal9),
("testTrinary112IsDecimal14", testTrinary112IsDecimal14),
("testTrinary222Is26", testTrinary222Is26),
("testTrinary1122000120Is32091", testTrinary1122000120Is32091),
("testInvalidTrinaryIsDecimal0", testInvalidTrinaryIsDecimal0),
]
}
}
| mit |
summermk/dw17-bdd-workshop | bdd-workshop/AppDelegate.swift | 1 | 2171 | //
// AppDelegate.swift
// bdd-workshop
//
// Created by Mira Kim on 20/08/17.
// Copyright © 2017 Mira Kim. 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 |
JakeLin/IBAnimatable | IBAnimatableApp/IBAnimatableApp/Playground/Transitions/TransitionTableViewController.swift | 2 | 11031 | //
// Created by Jake Lin on 2/29/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
import IBAnimatable
final class TransitionTableViewController: UITableViewController {
fileprivate var transitionAnimationsHeaders = [String]()
fileprivate var transitionAnimations = [[String]]()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
populateTransitionTypeData()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let toNavigationController = segue.destination as? AnimatableNavigationController, let indexPath = tableView.indexPathForSelectedRow else {
return
}
let transitionString = transitionAnimations[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
let transitionAnimationType = TransitionAnimationType(string: transitionString)
// Set the transition animation type for `AnimatableNavigationController`, used for Push/Pop transitions
toNavigationController.transitionAnimationType = transitionAnimationType
toNavigationController.navigationBar.topItem?.title = transitionString
// Set the transition animation type for `AnimatableViewController`, used for Present/Dismiss transitions
if let toViewController = toNavigationController.topViewController as? TransitionViewController {
toViewController.transitionAnimationType = transitionAnimationType
}
}
}
// MARK: - Factory
private extension TransitionTableViewController {
func populateTransitionTypeData() {
transitionAnimationsHeaders.append("Fade")
let fadeAnimations: [TransitionAnimationType] = [.fade(direction: .in),
.fade(direction: .out),
.fade(direction: .cross)]
transitionAnimations.append(toString(animations: fadeAnimations))
transitionAnimationsHeaders.append("SystemCube")
let cubeAnimations: [TransitionAnimationType] = [.systemCube(from: .left),
.systemCube(from: .right),
.systemCube(from: .top),
.systemCube(from: .bottom)]
transitionAnimations.append(toString(animations: cubeAnimations))
transitionAnimationsHeaders.append("SystemFlip")
let flipSystemAnimations: [TransitionAnimationType] = [.systemFlip(from: .left),
.systemFlip(from: .right),
.systemFlip(from: .top),
.systemFlip(from: .bottom)]
transitionAnimations.append(toString(animations: flipSystemAnimations))
transitionAnimationsHeaders.append("SystemMoveIn")
let moveAnimations: [TransitionAnimationType] = [.systemMoveIn(from: .left),
.systemMoveIn(from: .right),
.systemMoveIn(from: .top),
.systemMoveIn(from: .bottom)]
transitionAnimations.append(toString(animations: moveAnimations))
transitionAnimationsHeaders.append("SystemPush")
let pushAnimations: [TransitionAnimationType] = [.systemPush(from: .left),
.systemPush(from: .right),
.systemMoveIn(from: .top),
.systemMoveIn(from: .bottom)]
transitionAnimations.append(toString(animations: pushAnimations))
transitionAnimationsHeaders.append("SystemReveal")
let revealAnimations: [TransitionAnimationType] = [.systemReveal(from: .left),
.systemReveal(from: .right),
.systemReveal(from: .top),
.systemReveal(from: .bottom)]
transitionAnimations.append(toString(animations: revealAnimations))
transitionAnimationsHeaders.append("SystemPage")
let pageAnimations: [TransitionAnimationType] = [.systemPage(type: .curl), .systemPage(type: .unCurl)]
transitionAnimations.append(toString(animations: pageAnimations))
transitionAnimationsHeaders.append("SystemCameraIris")
let cameraAnimations: [TransitionAnimationType] = [.systemCameraIris(hollowState: .none),
.systemCameraIris(hollowState: .open),
.systemCameraIris(hollowState: .close)]
transitionAnimations.append(toString(animations: cameraAnimations))
transitionAnimationsHeaders.append("Fold")
let foldAnimations: [TransitionAnimationType] = [.fold(from: .left, folds: nil),
.fold(from: .right, folds: nil),
.fold(from: .top, folds: nil),
.fold(from: .bottom, folds: nil)]
transitionAnimations.append(toString(animations: foldAnimations))
transitionAnimationsHeaders.append("Portal")
let portalAnimations: [TransitionAnimationType] = [.portal(direction: .forward, zoomScale: 0.3),
.portal(direction: .backward, zoomScale: nil)]
transitionAnimations.append(toString(animations: portalAnimations))
transitionAnimationsHeaders.append("NatGeo")
let natGeoAnimations: [TransitionAnimationType] = [.natGeo(to: .left), .natGeo(to: .right)]
transitionAnimations.append(toString(animations: natGeoAnimations))
transitionAnimationsHeaders.append("Turn")
let turnAnimations: [TransitionAnimationType] = [.turn(from: .left),
.turn(from: .right),
.turn(from: .top),
.turn(from: .bottom)]
transitionAnimations.append(toString(animations: turnAnimations))
transitionAnimationsHeaders.append("Cards")
let cardAnimations: [TransitionAnimationType] = [.cards(direction: .forward), .cards(direction: .backward)]
transitionAnimations.append(toString(animations: cardAnimations))
transitionAnimationsHeaders.append("Flip")
let flipAnimations: [TransitionAnimationType] = [.flip(from: .left), .flip(from: .right)]
transitionAnimations.append(toString(animations: flipAnimations))
transitionAnimationsHeaders.append("Slide")
let slideAnimations: [TransitionAnimationType] = [.slide(to: .left, isFade: true),
.slide(to: .right, isFade: false),
.slide(to: .top, isFade: true),
.slide(to: .bottom, isFade: false)]
transitionAnimations.append(toString(animations: slideAnimations))
transitionAnimationsHeaders.append("Others")
let otherAnimations: [TransitionAnimationType] = [.systemRotate,
.systemRippleEffect,
.explode(xFactor: nil, minAngle: nil, maxAngle: nil),
.explode(xFactor: 10, minAngle: -20, maxAngle: 20)]
transitionAnimations.append(toString(animations: otherAnimations))
}
private func toString(animations: [TransitionAnimationType]) -> [String] {
return animations.map { $0.asString }
}
}
fileprivate extension TransitionAnimationType {
var asString: String {
switch self {
case .fade(let direction):
return "fade" + "(\(direction.rawValue))"
case .systemCube(let direction):
return "systemCube" + "(\(direction.rawValue))"
case .systemFlip(let direction):
return "systemFlip" + "(\(direction.rawValue))"
case .systemMoveIn(let direction):
return "systemMoveIn" + "(\(direction.rawValue))"
case .systemPush(let direction):
return "systemPush" + "(\(direction.rawValue))"
case .systemReveal(let direction):
return "systemReveal" + "(\(direction.rawValue))"
case .systemPage(let type):
return "systemPage(\(type.rawValue))"
case .systemCameraIris(let hollowState):
return "systemCameraIris" + (hollowState == .none ? "" : "(\(hollowState.rawValue))")
case .fold(let direction, _):
return "fold" + "(\(direction.rawValue))"
case let .portal(direction, zoomScale):
return "portal" + (zoomScale == nil ? "(\(direction.rawValue))" : "(\(direction.rawValue),\(zoomScale!))")
case .natGeo(let direction):
return "natGeo" + "(\(direction.rawValue))"
case .turn(let direction):
return "turn" + "(\(direction.rawValue))"
case .cards(let direction):
return "cards" + "(\(direction.rawValue))"
case .flip(let direction):
return "flip" + "(\(direction.rawValue))"
case let .slide(direction, isFade):
return "slide" + (isFade ? "(\(direction.rawValue), fade)" : "slide" + "(\(direction.rawValue))")
case .systemRotate:
return "systemRotate"
case .systemRippleEffect:
return "systemRippleEffect"
case .systemSuckEffect:
return "systemSuckEffect"
case let .explode(.some(x), .some(min), .some(max)):
return "explode" + "(\(x),\(min),\(max))"
case .explode:
return "explode"
case .none:
return "none"
}
}
}
// MARK: - UITableViewDataSource / UITableViewDelegate
extension TransitionTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return transitionAnimations.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transitionAnimations[section].count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return transitionAnimationsHeaders[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "transitionCell", for: indexPath) as UITableViewCell
cell.textLabel?.text = transitionAnimations[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
}
// MARK: - reset the group header font color and size
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel?.textColor = .white
header.textLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.light)
}
}
}
| mit |
telldus/telldus-live-mobile-v3 | ios/HomescreenWidget/UIViews/NotLoggedInView.swift | 1 | 852 | //
// NotLoggedInView.swift
// TelldusLiveApp
//
// Created by Rimnesh Fernandez on 14/10/20.
// Copyright © 2020 Telldus Technologies AB. All rights reserved.
//
import SwiftUI
struct NotLoggedInView: View {
@available(iOS 13.0.0, *)
var body: some View {
let text = String(format: "widget_ios_pre_login_info")
VStack (alignment: .center, spacing: 0) {
Text("\u{e92e}")
.foregroundColor(Color("widgetTextColorOne"))
.font(.custom("telldusicons", size: 32))
Text(LocalizedStringKey(text))
.foregroundColor(Color("widgetTextColorOne"))
.font(.system(size: 16))
.padding(.top, 5)
.multilineTextAlignment(.center)
}
.padding(.all, 8)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color("widgetTopBGC"))
}
}
| gpl-3.0 |
jozsef-vesza/ExpandableTableView | ExpandableTableView/Photo.swift | 1 | 457 | //
// Photo.swift
// ExpandableTableView
//
// Created by Vesza Jozsef on 26/05/15.
// Copyright (c) 2015 Vesza Jozsef. All rights reserved.
//
import UIKit
class Photo: NSObject {
var title: String
var author: String
var image: UIImage?
init(title: String, withAuthor author: String, withImage image: UIImage?) {
self.title = title
self.author = author
self.image = image
super.init()
}
} | mit |
BennyKJohnson/OpenCloudKit | Sources/CKQuery.swift | 1 | 2370 | //
// CKQuery.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 6/07/2016.
//
//
import Foundation
struct CKQueryDictionary {
static let recordType = "recordType"
static let filterBy = "filterBy"
static let sortBy = "sortBy"
}
struct CKSortDescriptorDictionary {
static let fieldName = "fieldName"
static let ascending = "ascending"
static let relativeLocation = "relativeLocation"
}
public class CKQuery: CKCodable {
public var recordType: String
public var predicate: NSPredicate
let filters: [CKQueryFilter]
public init(recordType: String, predicate: NSPredicate) {
self.recordType = recordType
self.predicate = predicate
self.filters = CKPredicate(predicate: predicate).filters()
}
public init(recordType: String, filters: [CKQueryFilter]) {
self.recordType = recordType
self.filters = filters
self.predicate = NSPredicate(value: true)
}
public var sortDescriptors: [NSSortDescriptor] = []
// Returns a Dictionary Representation of a Query Dictionary
var dictionary: [String: Any] {
var queryDictionary: [String: Any] = ["recordType": recordType.bridge()]
queryDictionary["filterBy"] = filters.map({ (filter) -> [String: Any] in
return filter.dictionary
}).bridge()
// Create Sort Descriptor Dictionaries
queryDictionary["sortBy"] = sortDescriptors.flatMap { (sortDescriptor) -> [String: Any]? in
if let fieldName = sortDescriptor.key {
var sortDescriptionDictionary: [String: Any] = [CKSortDescriptorDictionary.fieldName: fieldName.bridge(),
CKSortDescriptorDictionary.ascending: NSNumber(value: sortDescriptor.ascending)]
if let locationSortDescriptor = sortDescriptor as? CKLocationSortDescriptor {
sortDescriptionDictionary[CKSortDescriptorDictionary.relativeLocation] = locationSortDescriptor.relativeLocation.recordFieldDictionary.bridge()
}
return sortDescriptionDictionary
} else {
return nil
}
}.bridge()
return queryDictionary
}
}
| mit |
iException/garage | Garage/Sources/VehicleListViewController.swift | 1 | 8808 | //
// VehicleListViewController.swift
// Garage
//
// Created by Xiang Li on 28/10/2017.
// Copyright © 2017 Baixing. All rights reserved.
import UIKit
import RealmSwift
import SKPhotoBrowser
import Photos
class VehicleListViewController: UIViewController {
private static let collectionViewInset: CGFloat = 5.0
private static let numberOfColumns = 2
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let collectionViewInset = VehicleListViewController.collectionViewInset
layout.minimumInteritemSpacing = collectionViewInset
layout.minimumLineSpacing = collectionViewInset
layout.sectionInset = UIEdgeInsetsMake(collectionViewInset, collectionViewInset, collectionViewInset, collectionViewInset)
var collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(VehicleCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: VehicleCollectionViewCell.self))
return collectionView
}()
lazy var realm: Realm = {
return try! Realm()
}()
var vehicles: [VehicleViewModel]?
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// forgeData()
// removeAllVehicle()
setUpViews()
setUpNavigationItems()
configurePhotoBrowserOptions()
reload()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.collectionView.frame = view.bounds
}
// MARK: - Private -
private func setUpNavigationItems() {
let buttonItem = UIBarButtonItem(title: "scan", style: .plain, target: self, action: #selector(scanButtonPressed(_:)))
self.navigationItem.rightBarButtonItems = [ buttonItem ]
}
private func reload() {
loadVehicle()
reloadCollectionView()
}
// MARK: - Event Handler
@objc private func scanButtonPressed(_ sender : Any) {
let viewController = ViewController()
viewController.delegate = self
self.present(viewController, animated: true, completion: nil)
}
// MARK: - Realm
private func forgeData() {
for index in 0...5 {
let imageName = "image\(index)"
let image = UIImage(named:imageName)!
let aVehicle = Vehicle(image: image)
saveVehicle(vehicle: aVehicle, realm: realm)
printVehicleCount(realm)
}
}
private func printVehicleCount(_ realm: Realm) {
print("Vehicle count is \(realm.objects(Vehicle.self).count)")
}
private func saveVehicle(vehicle: Vehicle, realm: Realm) {
realm.beginWrite()
realm.add(vehicle)
try! realm.commitWrite()
}
private func deleteVehicle(vehicle: Vehicle, realm: Realm) {
try! realm.write {
realm.delete(vehicle)
}
}
private func loadVehicle() {
self.vehicles = realm.objects(Vehicle.self).map { (vehicle) -> VehicleViewModel in
guard let image = vehicle.image else { return VehicleViewModel(image: UIImage(), model: vehicle) }
let viewModel = VehicleViewModel(image: image, model: vehicle)
return viewModel
}
}
private func removeAllVehicle() {
try! realm.write {
realm.deleteAll()
}
}
// MARK: - Photo Browser
private func configurePhotoBrowserOptions() {
SKPhotoBrowserOptions.displayStatusbar = true
SKPhotoBrowserOptions.displayDeleteButton = true
SKPhotoBrowserOptions.enableSingleTapDismiss = true
}
// MARK: - CollectionView
private func setUpViews() {
view.addSubview(collectionView)
}
private func reloadCollectionView() {
collectionView.reloadData()
}
// MARK: - Wrapper
private func viewModelAtIndex(index: Int) -> VehicleViewModel? {
guard let vehicles = vehicles else { return nil }
return vehicles[safe: index]
}
private func imageAtIndex(index: Int) -> UIImage? {
guard let vehicle = viewModelAtIndex(index: index) else { return nil }
return vehicle.image
}
}
extension VehicleListViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let vehicles = vehicles else { return 0 }
return vehicles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: VehicleCollectionViewCell.self), for: indexPath) as? VehicleCollectionViewCell else {
return UICollectionViewCell()
}
cell.imageView.image = imageAtIndex(index: indexPath.item)
return cell
}
}
extension VehicleListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfColumns = Double(VehicleListViewController.numberOfColumns)
let collectionViewWidth = Double(collectionView.frame.size.width)
let collectionViewInset = Double(VehicleListViewController.collectionViewInset)
let width = (collectionViewWidth - (numberOfColumns + 1) * collectionViewInset) / numberOfColumns
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? VehicleCollectionViewCell else {
return
}
guard let image = imageAtIndex(index: indexPath.item) else {
return
}
showPhotoBrowser(image: image, photos: vehicles!, sourceView: cell, index: indexPath.item)
}
private func showPhotoBrowser(image: UIImage, photos: [SKPhotoProtocol], sourceView: UIView, index: Int) {
let browser = SKPhotoBrowser(originImage: image, photos: photos, animatedFromView: sourceView)
browser.initializePageIndex(index)
browser.delegate = self
browser.showDeleteButton(bool: true)
present(browser, animated: true, completion: {})
}
}
extension VehicleListViewController: SKPhotoBrowserDelegate {
func removePhoto(_ browser: SKPhotoBrowser, index: Int, reload: @escaping (() -> Void)) {
guard let vehicle = viewModelAtIndex(index: index) else { return }
deleteVehicle(vehicle: vehicle.model, realm: realm)
self.reload()
reload()
}
func viewForPhoto(_ browser: SKPhotoBrowser, index: Int) -> UIView? {
return collectionView.cellForItem(at: IndexPath(item: index, section: 0))
}
}
extension VehicleListViewController: ViewControllerDelegate {
func viewControllerFinishClassifying(_ viewController: ViewController, assets: [PHAsset]) {
viewController.dismiss(animated: true, completion: nil)
saveAssetsToDatabase(assets)
deleteAssets(assets)
}
}
extension VehicleListViewController {
private func saveAssetsToDatabase(_ assets: [PHAsset]) {
let dispatchGroup = DispatchGroup()
for (index, asset) in assets.enumerated() {
let size = CGSize(width: 500, height: 500)
dispatchGroup.enter()
let options = PHImageRequestOptions()
options.isSynchronous = true
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options, resultHandler: { (image, info) in
defer {
dispatchGroup.leave()
}
guard let image = image else {
return
}
let vehicle = Vehicle(image: image)
if vehicle.imageData != nil {
self.saveVehicle(vehicle: vehicle, realm: self.realm)
}
})
}
dispatchGroup.notify(queue: .main) {
self.reload()
}
}
private func deleteAssets(_ assets: [PHAsset]) {
// TODO:
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets(NSArray(array: assets))
}) { (result, error) in
}
}
}
| mit |
BPerlakiH/Swift4Cart | SwiftCartTests/FXTests.swift | 1 | 1569 | //
// FXTests.swift
// SwiftCartTests
//
// Created by Balazs Perlaki-Horvath on 07/07/2017.
// Copyright © 2017 perlakidigital. All rights reserved.
//
import XCTest
class FXTests: XCTestCase {
func testConfiguration() {
let fx = FX()
XCTAssertNotNil(fx.apiKey)
XCTAssertTrue(30 < fx.apiKey.count)
XCTAssertNotNil(fx.activeCurrencies)
XCTAssertFalse(fx.activeCurrencies.isEmpty)
for currency:String in fx.activeCurrencies {
XCTAssertEqual(currency.count, 3, "currency: \(currency) should have a 3 letter key")
}
}
func testDownloadRates() {
let fx = FX()
XCTAssertNil(fx.all())
fx.refresh()
XCTAssertNotNil(fx.all())
XCTAssertEqualWithAccuracy(fx.priceOf(price: 1.0, inCurrency: "CHF"), 0.9, accuracy: 0.1)
XCTAssertEqualWithAccuracy(fx.priceOf(price: 1.0, inCurrency: "EUR"), 0.8, accuracy: 0.1)
XCTAssertEqualWithAccuracy(fx.priceOf(price: 1.0, inCurrency: "GBP"), 0.7, accuracy: 0.1)
XCTAssertEqualWithAccuracy(fx.priceOf(price: 1.0, inCurrency: "PLN"), 3.7, accuracy: 0.1)
XCTAssertEqualWithAccuracy(fx.priceOf(price: 1.0, inCurrency: "HUF"), 260, accuracy: 20)
XCTAssertEqualWithAccuracy(fx.priceOf(price: 4.0, inCurrency: "EUR"), 3.2, accuracy: 0.4)
XCTAssertEqualWithAccuracy(fx.priceOf(price: 10.0, inCurrency: "GBP"), 7.0, accuracy: 1)
}
func testAvailableCurrencies() {
let fx = FX()
fx.refresh()
XCTAssertNotNil(fx.all()![""])
}
}
| mit |
chamander/Sampling-Reactive | Source/WeatherContent/WeatherViewModel.swift | 2 | 611 | // Copyright © 2016 Gavan Chan. All rights reserved.
struct WeatherViewModel {
private let data: Weather
init(with data: Weather) {
self.data = data
}
var location: City.Name { return data.city.name }
var information: String { return String(format: "Current: %.1fºC", data.current) }
var theme: WeatherView.Theme! {
switch data.current {
case let x where x >= 35.0: return .blistering
case 25.0 ..< 35.0: return .hot
case 18.0 ..< 25.0: return .neutral
case let x where x < 18.0: return .cold
default: return nil // This case should not be reached.
}
}
}
| mit |
takeo-asai/math-puzzle | problems/06.swift | 1 | 439 | // 2m-1: 3n+1
// 2m: n/2
// 初期値はともに3n+1する
func collatzx(n: Int) -> (Int, [Int]) {
func collatz(n: Int, _ history: [Int]) -> (Int, [Int]) {
let m: Int = n % 2 == 0 ? n/2 : 3*n + 1
if history.contains(m) {
return (m, history+[m])
}
return collatz(m, history+[m])
}
return collatz(3*n+1, [n, 3*n+1])
}
var count = 0
for i in 1 ... 5000 {
if collatzx(2*i).0 == 2*i {
count++
}
}
print("Count: \(count)")
| mit |
bitjammer/swift | test/SILGen/mangling_private.swift | 1 | 2720 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/mangling_private_helper.swift
// RUN: %target-swift-frontend -emit-silgen %S/Inputs/mangling_private_helper.swift | %FileCheck %s -check-prefix=CHECK-BASE
// RUN: %target-swift-frontend %s -I %t -emit-silgen | %FileCheck %s
// RUN: cp %s %t
// RUN: %target-swift-frontend %t/mangling_private.swift -I %t -emit-silgen | %FileCheck %s
// RUN: cp %s %t/other_name.swift
// RUN: %target-swift-frontend %t/other_name.swift -I %t -emit-silgen -module-name mangling_private | %FileCheck %s -check-prefix=OTHER-NAME
import mangling_private_helper
// CHECK-LABEL: sil private @_T016mangling_private0B4Func33_A3CCBB841DB59E79A4AD4EE458655068LLSiyF
// OTHER-NAME-LABEL: sil private @_T016mangling_private0B4Func33_CF726049E48876D30EA29D63CF139F1DLLSiyF
private func privateFunc() -> Int {
return 0
}
public struct PublicStruct {
// CHECK-LABEL: sil private @_T016mangling_private12PublicStructV0B6Method33_A3CCBB841DB59E79A4AD4EE458655068LLyyFZ
private static func privateMethod() {}
}
public struct InternalStruct {
// CHECK-LABEL: sil private @_T016mangling_private14InternalStructV0B6Method33_A3CCBB841DB59E79A4AD4EE458655068LLyyFZ
private static func privateMethod() {}
}
private struct PrivateStruct {
// CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV0B6MethodyyFZ
private static func privateMethod() {}
struct Inner {
// CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV5InnerV0B6MethodyyFZ
private static func privateMethod() {}
}
}
func localTypes() {
struct LocalStruct {
private static func privateMethod() {}
}
}
extension PublicStruct {
// CHECK-LABEL: sil private @_T016mangling_private12PublicStructV16extPrivateMethod33_A3CCBB841DB59E79A4AD4EE458655068LLyyF
private func extPrivateMethod() {}
}
extension PrivateStruct {
// CHECK-LABEL: sil private @_T016mangling_private13PrivateStruct33_A3CCBB841DB59E79A4AD4EE458655068LLV03extC6MethodyyF
private func extPrivateMethod() {}
}
// CHECK-LABEL: sil shared @_T016mangling_private10localTypesyyF11LocalStructL_V0B6MethodyyFZ
// CHECK-LABEL: sil_vtable Sub {
class Sub : Base {
// CHECK-BASE: #Base.privateMethod!1: {{.*}} : _T023mangling_private_helper4BaseC0B6Method33_0E108371B0D5773E608A345AC52C7674LLyyF
// CHECK-DAG: #Base.privateMethod!1: {{.*}} : _T023mangling_private_helper4BaseC0B6Method33_0E108371B0D5773E608A345AC52C7674LLyyF
// CHECK-DAG: #Sub.subMethod!1: {{.*}} : _T016mangling_private3SubC9subMethod33_A3CCBB841DB59E79A4AD4EE458655068LLyyF
private func subMethod() {}
} // CHECK: {{^[}]$}}
| apache-2.0 |
scottkawai/sendgrid-swift | Sources/SendGrid/Structs/Page.swift | 1 | 872 | import Foundation
/// This struct is used to represent a page via the `limit` and `offset`
/// parameters found in various API calls.
public struct Page {
// MARK: - Properties
/// The limit value for each page of results.
public let limit: Int
/// The offset value for the page.
public let offset: Int
// MARK: - Initialization
/// Initializes the struct with a limit and offset.
///
/// - Parameters:
/// - limit: The number of results per page.
/// - offset: The index to start the page on.
public init(limit: Int, offset: Int) {
self.limit = limit
self.offset = offset
}
}
extension Page: Equatable {
/// :nodoc:
/// Equatable conformance.
public static func ==(lhs: Page, rhs: Page) -> Bool {
lhs.limit == rhs.limit && lhs.offset == rhs.offset
}
}
| mit |
sharplet/five-day-plan | Sources/FiveDayPlan/ViewControllers/PlanOutlineViewController.swift | 1 | 3651 | import CircleProgressView
import CoreData
import UIKit
private let sectionHeaderLabelAdjustment = 18 as CGFloat
final class PlanOutlineViewController: UITableViewController {
let viewModel = PlanOutlineViewModel(plan: .year2017, store: .shared)
private var isFirstLoad = true
override func viewDidLoad() {
super.viewDidLoad()
viewModel.fetchController.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
initialise()
performFetch()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
defer { isFirstLoad = false }
if isFirstLoad, let indexPath = viewModel.indexPathForCurrentWeek() {
tableView.scrollToRow(at: indexPath, at: .top, animated: false)
tableView.contentOffset.y -= sectionHeaderLabelAdjustment
}
}
private func initialise() {
viewModel.initialise { error in
if let error = error {
self.show(error)
}
}
}
private func performFetch() {
do {
try viewModel.performFetch()
} catch {
show(error)
}
}
override func numberOfSections(in _: UITableView) -> Int {
return viewModel.numberOfSections
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows(inSection: section)
}
override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.titleForHeader(inSection: section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let day = viewModel[indexPath]
let cell = tableView.dequeueReusableCell(withIdentifier: "Day Summary", for: indexPath) as! DaySummaryCell
cell.textLabel?.text = day.name
cell.textLabel?.textColor = day.isComplete ? .lightGray : nil
cell.detailTextLabel?.textColor = day.isComplete ? .lightGray : nil
cell.detailTextLabel?.text = day.formattedSummary
cell.progressView?.isHidden = !day.isInProgress
cell.progressView?.progress = day.percentageRead
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let weekTitle = viewModel.titleForHeader(inSection: indexPath.section)
navigationItem.backBarButtonItem = UIBarButtonItem(title: weekTitle, style: .plain, target: nil, action: nil)
perform(.showDayDetail) {
$0.details = self.viewModel.dayDetails(at: indexPath)
}
}
}
extension PlanOutlineViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_: NSFetchedResultsController<NSFetchRequestResult>, didChange _: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .update:
tableView.reloadRows(at: [indexPath!], with: .none)
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
default:
fatalError("unexpected row change type: \(type.rawValue)")
}
}
func controller(_: NSFetchedResultsController<NSFetchRequestResult>, didChange _: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
tableView.insertSections([sectionIndex], with: .fade)
default:
fatalError("unexpected section change type: \(type.rawValue)")
}
}
func controllerDidChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
| mit |
syoung-smallwisdom/BridgeAppSDK | BridgeAppSDK/SBARegistrationStep.swift | 1 | 5657 | //
// SBARegistrationStep.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
open class SBARegistrationStep: ORKFormStep, SBAProfileInfoForm {
static let confirmationIdentifier = "confirmation"
static let defaultPasswordMinLength = 4
static let defaultPasswordMaxLength = 16
open var surveyItemType: SBASurveyItemType {
return .account(.registration)
}
open func defaultOptions(_ inputItem: SBASurveyItem?) -> [SBAProfileInfoOption] {
return [.name, .email, .password]
}
public override required init(identifier: String) {
super.init(identifier: identifier)
commonInit(nil)
}
public init(inputItem: SBASurveyItem) {
super.init(identifier: inputItem.identifier)
commonInit(inputItem)
}
open override func validateParameters() {
super.validateParameters()
try! validate(options: self.options)
}
open func validate(options: [SBAProfileInfoOption]?) throws {
guard let options = options else {
throw SBAProfileInfoOptionsError.missingRequiredOptions
}
guard options.contains(.email) && options.contains(.password) else {
throw SBAProfileInfoOptionsError.missingEmail
}
}
open override var isOptional: Bool {
get { return false }
set {}
}
open var passwordAnswerFormat: ORKTextAnswerFormat? {
return self.formItemForIdentifier(SBAProfileInfoOption.password.rawValue)?.answerFormat as? ORKTextAnswerFormat
}
open override func stepViewControllerClass() -> AnyClass {
return SBARegistrationStepViewController.classForCoder()
}
// MARK: NSCoding
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
open class SBARegistrationStepViewController: ORKFormStepViewController, SBAUserRegistrationController {
/**
If there are data groups that were set in a previous step or via a custom onboarding manager,
set them on the view controller using this property.
*/
open var dataGroups: [String]?
// MARK: SBASharedInfoController
lazy open var sharedAppDelegate: SBAAppInfoDelegate = {
return UIApplication.shared.delegate as! SBAAppInfoDelegate
}()
// MARK: SBAUserRegistrationController
open var failedValidationMessage = Localization.localizedString("SBA_REGISTRATION_UNKNOWN_FAILED")
open var failedRegistrationTitle = Localization.localizedString("SBA_REGISTRATION_FAILED_TITLE")
// MARK: Navigation overrides - cannot go back and override go forward to register
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// set the back and cancel buttons to empty items
self.cancelButtonItem = UIBarButtonItem()
self.backButtonItem = UIBarButtonItem()
}
// Override the default method for goForward and attempt user registration. Do not allow subclasses
// to override this method
final public override func goForward() {
showLoadingView()
sharedUser.registerUser(email: email!, password: password!, externalId: externalID, dataGroups: dataGroups) { [weak self] error in
if let error = error {
self?.handleFailedRegistration(error)
}
else {
self?.goNext()
}
}
}
func goNext() {
// successfully registered. Set the other values from this form.
if let gender = self.gender {
sharedUser.gender = gender
}
if let birthdate = self.birthdate {
sharedUser.birthdate = birthdate
}
// Then call super to go forward
super.goForward()
}
override open func goBackward() {
// Do nothing
}
}
| bsd-3-clause |
wupingzj/YangRepoApple | QiuTuiJian/QiuTuiJian/MapPopoverVC.swift | 1 | 1614 | //
// MapPopoverVC.swift
// QiuTuiJian
//
// Created by Ping on 24/09/2014.
// Copyright (c) 2014 Yang Ltd. All rights reserved.
//
import UIKit
class MapPopoverVC: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
// 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.
}
*/
}
| gpl-2.0 |
mikina/Right-Direction | RightDirection/RightDirection/Tools/Constants.swift | 1 | 203 | //
// Constants.swift
// RightDirection
//
// Created by Mike Mikina on 3/10/16.
// Copyright © 2016 FDT. All rights reserved.
//
import Foundation
let kPointsPositive = 1
let kPointsNegative = 5
| mit |
erlandranvinge/swift-mini-json | Json.swift | 1 | 1416 | import Foundation
class Json: Sequence {
private let data:AnyObject?
init(data:AnyObject?) {
if (data is NSData) {
self.data = try? JSONSerialization.jsonObject(
with: (data as! NSData) as Data,
options: .allowFragments) as AnyObject
} else {
self.data = data
}
}
func string() -> String { return data as? String ?? "" }
func int() -> Int { return data as? Int ?? 0 }
func float() -> Float { return data as? Float ?? 0.0 }
func double() -> Double { return data as? Double ?? 0.0 }
func bool() -> Bool { return data as? Bool ?? false }
subscript(name:String) -> Json {
let hash = data as? NSDictionary
return Json(data: hash?.value(forKey: name) as AnyObject)
}
subscript(index:Int) -> Json {
guard let items = data as? [AnyObject] else { return Json(data: nil) }
guard index >= 0 && index < items.count else { return Json(data: nil) }
return Json(data: items[index])
}
func makeIterator() -> AnyIterator<Json> {
guard let items = data as? [AnyObject] else {
return AnyIterator { return .none }
}
var current = -1
return AnyIterator {
current = current + 1
return current < items.count ? Json(data: items[current]) : .none
}
}
}
| mit |
wtrumler/FluentSwiftAssertions | FluentSwiftAssertions/OptionalExtension.swift | 1 | 3232 | //
// OptionalExtension.swift
// FluentSwiftAssertions
//
// Created by Wolfgang Trumler on 19.03.17.
// Copyright © 2017 Wolfgang Trumler. All rights reserved.
//
import Foundation
import XCTest
extension Optional {
public var should: Optional {
return self
}
public func beNil(_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNil) {
assertionFunction(self, message, file, line)
}
public func notBeNil(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotNil)
{
assertionFunction(self, message, file, line)
}
public func notBeNilToExecute(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotNil,
_ block: () -> Void) {
if self != nil {
block()
}
else {
// "Optional expected to be non nil."
assertionFunction(self, message, file, line)
}
}
//
// compare optional with other (non)optional
//
public func beEqualTo<T : Equatable>(_ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertEqual)
{
do {
let result = try expression2()
assertionFunction(self as! Optional<T>, result, message, file, line)
} catch {
// if the evaluation fails an exception is thrown anyway.
// so no need to do something here
}
}
public func notBeEqualTo<T : Equatable>(_ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotEqual)
{
do {
let result = try expression2()
assertionFunction(self as! Optional<T>, result, message, file, line)
} catch {
// if the evaluation fails an exception is thrown anyway.
// so no need to do something here
}
}
}
| mit |
ashfurrow/Moya | Tests/MoyaTests/SignalProducer+MoyaSpec.swift | 1 | 25062 | import Quick
import Moya
import ReactiveSwift
import Nimble
import Foundation
private func signalSendingData(_ data: Data, statusCode: Int = 200) -> SignalProducer<Response, MoyaError> {
return SignalProducer(value: Response(statusCode: statusCode, data: data as Data, response: nil))
}
final class SignalProducerMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes closed range upperbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filter(statusCodes: 0...9).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes closed range lowerbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: -1)
var errored = false
signal.filter(statusCodes: 0...9).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes range upperbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filter(statusCodes: 0..<10).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes range lowerbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: -1)
var errored = false
signal.filter(statusCodes: 0..<10).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusCodes().startWithResult { result in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusCodes().startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { result in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 304)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("knows how to filter individual status codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 42)
var called = false
signal.filter(statusCode: 42).startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = Data()
let signal = signalSendingData(data, statusCode: 43)
var errored = false
signal.filter(statusCode: 42).startWithResult { result in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testImage
let data = image.asJPEGRepresentation(0.75)
let signal = signalSendingData(data!)
var size: CGSize?
signal.mapImage().startWithResult { _ in
size = image.size
}
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = Data()
let signal = signalSendingData(data)
var receivedError: MoyaError?
signal.mapImage().startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let signal = signalSendingData(data)
var receivedJSON: [String: String]?
signal.mapJSON().startWithResult { result in
if case .success(let response) = result,
let json = response as? [String: String] {
receivedJSON = json
}
}
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
let data = json.data(using: String.Encoding.utf8)
let signal = signalSendingData(data!)
var receivedError: MoyaError?
signal.mapJSON().startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
switch receivedError {
case .some(.jsonMapping):
break
default:
fail("expected NSError with \(NSCocoaErrorDomain) domain")
}
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
let data = string.data(using: String.Encoding.utf8)
let signal = signalSendingData(data!)
var receivedString: String?
signal.mapString().startWithResult { result in
receivedString = try? result.get()
}
expect(receivedString).to(equal(string))
}
it("maps data representing a string at a key path to a string") {
let string = "You have the rights to the remains of a silent attorney."
let json = ["words_to_live_by": string]
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let signal = signalSendingData(data)
var receivedString: String?
signal.mapString(atKeyPath: "words_to_live_by").startWithResult { result in
receivedString = try? result.get()
}
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8
let signal = signalSendingData(data as Data)
var receivedError: MoyaError?
signal.mapString().startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("object mapping") {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let json: [String: Any] = [
"title": "Hello, Moya!",
"createdAt": "1995-01-14T12:34:56"
]
it("maps data representing a json to a decodable object") {
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObject: Issue?
_ = signal.map(Issue.self, using: decoder).startWithResult { result in
receivedObject = try? result.get()
}
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to an array of decodable objects") {
let jsonArray = [json, json, json]
guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObjects: [Issue]?
_ = signal.map([Issue].self, using: decoder).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 3
expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"]
}
it("maps empty data to a decodable object with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: OptionalIssue?
_ = signal.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: [OptionalIssue]?
_ = signal.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
context("when using key path mapping") {
it("maps data representing a json to a decodable object") {
let json: [String: Any] = ["issue": json] // nested json
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObject: Issue?
_ = signal.map(Issue.self, atKeyPath: "issue", using: decoder).startWithResult { result in
receivedObject = try? result.get()
}
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to a decodable object (#1311)") {
let json: [String: Any] = ["issues": [json]] // nested json array
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObjects: [Issue]?
_ = signal.map([Issue].self, atKeyPath: "issues", using: decoder).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title) == "Hello, Moya!"
expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps empty data to a decodable object with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: OptionalIssue?
_ = signal.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: [OptionalIssue]?
_ = signal.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
it("map Int data to an Int value") {
let json: [String: Any] = ["count": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var count: Int?
_ = signal.map(Int.self, atKeyPath: "count", using: decoder).startWithResult { result in
count = try? result.get()
}
expect(count).notTo(beNil())
expect(count) == 1
}
it("map Bool data to a Bool value") {
let json: [String: Any] = ["isNew": true]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var isNew: Bool?
_ = signal.map(Bool.self, atKeyPath: "isNew", using: decoder).startWithResult { result in
isNew = try? result.get()
}
expect(isNew).notTo(beNil())
expect(isNew) == true
}
it("map String data to a String value") {
let json: [String: Any] = ["description": "Something interesting"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var description: String?
_ = signal.map(String.self, atKeyPath: "description", using: decoder).startWithResult { result in
description = try? result.get()
}
expect(description).notTo(beNil())
expect(description) == "Something interesting"
}
it("map String data to a URL value") {
let json: [String: Any] = ["url": "http://www.example.com/test"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var url: URL?
_ = signal.map(URL.self, atKeyPath: "url", using: decoder).startWithResult { result in
url = try? result.get()
}
expect(url).notTo(beNil())
expect(url) == URL(string: "http://www.example.com/test")
}
it("shouldn't map Int data to a Bool value") {
let json: [String: Any] = ["isNew": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var isNew: Bool?
_ = signal.map(Bool.self, atKeyPath: "isNew", using: decoder).startWithResult { result in
isNew = try? result.get()
}
expect(isNew).to(beNil())
}
it("shouldn't map String data to an Int value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var test: Int?
_ = signal.map(Int.self, atKeyPath: "test", using: decoder).startWithResult { result in
test = try? result.get()
}
expect(test).to(beNil())
}
it("shouldn't map Array<String> data to an String value") {
let json: [String: Any] = ["test": ["123", "456"]]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var test: String?
_ = signal.map(String.self, atKeyPath: "test", using: decoder).startWithResult { result in
test = try? result.get()
}
expect(test).to(beNil())
}
it("shouldn't map String data to an Array<String> value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var test: [String]?
_ = signal.map([String].self, atKeyPath: "test", using: decoder).startWithResult { result in
test = try? result.get()
}
expect(test).to(beNil())
}
}
it("ignores invalid data") {
var json = json
json["createdAt"] = "Hahaha" // invalid date string
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedError: Error?
_ = signal.map(Issue.self, using: decoder).startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
if case let MoyaError.objectMapping(nestedError, _)? = receivedError {
expect(nestedError).to(beAKindOf(DecodingError.self))
} else {
fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>")
}
}
}
}
}
| mit |
ozgur/TestApp | TestApp/i18n/Internationalization.swift | 1 | 1737 | //
// Internationalization.swift
// TestApp
//
// Created by Ozgur Vatansever on 11/18/16.
// Copyright © 2017 Ozgur. All rights reserved.
//
import Swifternalization
/**
Returns a localized string, using the main bundle if one is not specified.
Calls `NSLocalizedString:comment` with empty `comment` value internally.
- parameter key: A key to which localized string is assigned
- returns: localized string if found, otherwise `key` is returned.
*/
public func NSLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
// Alias for NSLocalizedString(_ key:) function.
public func localize(_ key: String) -> String {
return NSLocalizedString(key)
}
/**
Returns a localized string, using the main bundle if one is not specified.
- parameter key: A key to which localized string is assigned
- parameter args: Variable arguments
- returns: localized string if found, otherwise `key` is returned.
*/
func NSLocalizedFormatString(_ key: String, _ args: CVarArg...) -> String {
return withVaList(args) { (arguments) -> String in
return NSString(format: NSLocalizedString(key), arguments: arguments) as String
}
}
/**
Returns the localized version of the given string with respect to pluralization value.
Calls `Swifternalization.localizedString:intValue` internally.
- parameter key: A key to which localized string is assigned
- parameter intValue: A int for determining pluralized version of the string
- returns: localized string if found, otherwise `key` is returned.
*/
public func NSLocalizedString(_ key: String, intValue: Int) -> String {
return String(format: Swifternalization.localizedString(key, intValue: intValue), intValue)
}
| gpl-3.0 |
rbukovansky/Gloss | Tests/Comparators.swift | 2 | 277 | //
// Comparators.swift
// Gloss
//
// Created by Maciej Kołek on 10/18/16.
// Copyright © 2016 Harlan Kellaway. All rights reserved.
//
import Foundation
import Gloss
func ==(lhs: JSON, rhs: JSON ) -> Bool {
return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
| mit |
jmelberg/acmehealth-swift | AcmeHealth/AppDelegate.swift | 1 | 2840 | /** Author: Jordan Melberg **/
/** Copyright © 2016, Okta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import OktaAuth
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
return OktaAuth.resume(url, options: options)
}
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:.
}
}
| apache-2.0 |
OscarSwanros/swift | stdlib/public/core/UnsafeBitMap.swift | 2 | 2683 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A wrapper around a bitmap storage with room for at least `bitCount` bits.
@_fixed_layout // FIXME(sil-serialize-all)
public // @testable
struct _UnsafeBitMap {
public // @testable
let values: UnsafeMutablePointer<UInt>
public // @testable
let bitCount: Int
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func wordIndex(_ i: Int) -> Int {
// Note: We perform the operation on UInts to get faster unsigned math
// (shifts).
return Int(bitPattern: UInt(bitPattern: i) / UInt(UInt.bitWidth))
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func bitIndex(_ i: Int) -> UInt {
// Note: We perform the operation on UInts to get faster unsigned math
// (shifts).
return UInt(bitPattern: i) % UInt(UInt.bitWidth)
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
static func sizeInWords(forSizeInBits bitCount: Int) -> Int {
return (bitCount + Int.bitWidth - 1) / Int.bitWidth
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
init(storage: UnsafeMutablePointer<UInt>, bitCount: Int) {
self.bitCount = bitCount
self.values = storage
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
var numberOfWords: Int {
return _UnsafeBitMap.sizeInWords(forSizeInBits: bitCount)
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
func initializeToZero() {
values.initialize(to: 0, count: numberOfWords)
}
@_inlineable // FIXME(sil-serialize-all)
public // @testable
subscript(i: Int) -> Bool {
get {
_sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds")
let word = values[_UnsafeBitMap.wordIndex(i)]
let bit = word & (1 << _UnsafeBitMap.bitIndex(i))
return bit != 0
}
nonmutating set {
_sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds")
let wordIdx = _UnsafeBitMap.wordIndex(i)
let bitMask = (1 as UInt) &<< _UnsafeBitMap.bitIndex(i)
if newValue {
values[wordIdx] = values[wordIdx] | bitMask
} else {
values[wordIdx] = values[wordIdx] & ~bitMask
}
}
}
}
| apache-2.0 |
iceman201/NZAirQuality | Pods/ScrollableGraphView/Classes/Drawing/LineDrawingLayer.swift | 3 | 6008 |
import UIKit
internal class LineDrawingLayer : ScrollableGraphViewDrawingLayer {
private var currentLinePath = UIBezierPath()
private var lineStyle: ScrollableGraphViewLineStyle
private var shouldFill: Bool
private var lineCurviness: CGFloat
init(frame: CGRect, lineWidth: CGFloat, lineColor: UIColor, lineStyle: ScrollableGraphViewLineStyle, lineJoin: String, lineCap: String, shouldFill: Bool, lineCurviness: CGFloat) {
self.lineStyle = lineStyle
self.shouldFill = shouldFill
self.lineCurviness = lineCurviness
super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height)
self.lineWidth = lineWidth
self.strokeColor = lineColor.cgColor
self.lineJoin = convertToCAShapeLayerLineJoin(lineJoin)
self.lineCap = convertToCAShapeLayerLineCap(lineCap)
// Setup
self.fillColor = UIColor.clear.cgColor // This is handled by the fill drawing layer.
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func createLinePath() -> UIBezierPath {
guard let owner = owner else {
return UIBezierPath()
}
// Can't really do anything without the delegate.
guard let delegate = self.owner?.graphViewDrawingDelegate else {
return currentLinePath
}
currentLinePath.removeAllPoints()
let pathSegmentAdder = lineStyle == .straight ? addStraightLineSegment : addCurvedLineSegment
let activePointsInterval = delegate.intervalForActivePoints()
let pointPadding = delegate.paddingForPoints()
let min = delegate.rangeForActivePoints().min
zeroYPosition = delegate.calculatePosition(atIndex: 0, value: min).y
let viewport = delegate.currentViewport()
let viewportWidth = viewport.width
let viewportHeight = viewport.height
// Connect the line to the starting edge if we are filling it.
if(shouldFill) {
// Add a line from the base of the graph to the first data point.
let firstDataPoint = owner.graphPoint(forIndex: activePointsInterval.lowerBound)
let viewportLeftZero = CGPoint(x: firstDataPoint.location.x - (pointPadding.leftmostPointPadding), y: zeroYPosition)
let leftFarEdgeTop = CGPoint(x: firstDataPoint.location.x - (pointPadding.leftmostPointPadding + viewportWidth), y: zeroYPosition)
let leftFarEdgeBottom = CGPoint(x: firstDataPoint.location.x - (pointPadding.leftmostPointPadding + viewportWidth), y: viewportHeight)
currentLinePath.move(to: leftFarEdgeBottom)
pathSegmentAdder(leftFarEdgeBottom, leftFarEdgeTop, currentLinePath)
pathSegmentAdder(leftFarEdgeTop, viewportLeftZero, currentLinePath)
pathSegmentAdder(viewportLeftZero, CGPoint(x: firstDataPoint.location.x, y: firstDataPoint.location.y), currentLinePath)
}
else {
let firstDataPoint = owner.graphPoint(forIndex: activePointsInterval.lowerBound)
currentLinePath.move(to: firstDataPoint.location)
}
// Connect each point on the graph with a segment.
for i in activePointsInterval.lowerBound ..< activePointsInterval.upperBound - 1 {
let startPoint = owner.graphPoint(forIndex: i).location
let endPoint = owner.graphPoint(forIndex: i+1).location
pathSegmentAdder(startPoint, endPoint, currentLinePath)
}
// Connect the line to the ending edge if we are filling it.
if(shouldFill) {
// Add a line from the last data point to the base of the graph.
let lastDataPoint = owner.graphPoint(forIndex: activePointsInterval.upperBound - 1).location
let viewportRightZero = CGPoint(x: lastDataPoint.x + (pointPadding.rightmostPointPadding), y: zeroYPosition)
let rightFarEdgeTop = CGPoint(x: lastDataPoint.x + (pointPadding.rightmostPointPadding + viewportWidth), y: zeroYPosition)
let rightFarEdgeBottom = CGPoint(x: lastDataPoint.x + (pointPadding.rightmostPointPadding + viewportWidth), y: viewportHeight)
pathSegmentAdder(lastDataPoint, viewportRightZero, currentLinePath)
pathSegmentAdder(viewportRightZero, rightFarEdgeTop, currentLinePath)
pathSegmentAdder(rightFarEdgeTop, rightFarEdgeBottom, currentLinePath)
}
return currentLinePath
}
private func addStraightLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
path.addLine(to: endPoint)
}
private func addCurvedLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
// calculate control points
let difference = endPoint.x - startPoint.x
var x = startPoint.x + (difference * lineCurviness)
var y = startPoint.y
let controlPointOne = CGPoint(x: x, y: y)
x = endPoint.x - (difference * lineCurviness)
y = endPoint.y
let controlPointTwo = CGPoint(x: x, y: y)
// add curve from start to end
currentLinePath.addCurve(to: endPoint, controlPoint1: controlPointOne, controlPoint2: controlPointTwo)
}
override func updatePath() {
self.path = createLinePath().cgPath
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToCAShapeLayerLineJoin(_ input: String) -> CAShapeLayerLineJoin {
return CAShapeLayerLineJoin(rawValue: input)
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToCAShapeLayerLineCap(_ input: String) -> CAShapeLayerLineCap {
return CAShapeLayerLineCap(rawValue: input)
}
| mit |
robertofrontado/RxGcm-iOS | iOS/Pods/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift | 43 | 6438 | import Foundation
#if _runtime(_ObjC)
public struct AsyncDefaults {
public static var Timeout: TimeInterval = 1
public static var PollInterval: TimeInterval = 0.01
}
internal struct AsyncMatcherWrapper<T, U>: Matcher
where U: Matcher, U.ValueType == T
{
let fullMatcher: U
let timeoutInterval: TimeInterval
let pollInterval: TimeInterval
init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) {
self.fullMatcher = fullMatcher
self.timeoutInterval = timeoutInterval
self.pollInterval = pollInterval
}
func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).toEventually(...)"
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: "expect(...).toEventuallyNot(...)") {
try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventuallyNot(...).")
}
}
}
private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function")
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionMatches(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
to: "to eventually",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionDoesNotMatch(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
toNot: "to eventually not",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
#endif
| apache-2.0 |
natecook1000/swift-compiler-crashes | crashes-duplicates/24603-swift-astcontext-getidentifier.swift | 9 | 220 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T where B:a{var:B{}class B{}struct S<T:a}
| mit |
AndreMuis/Algorithms | StairClimbing.playground/Contents.swift | 1 | 700 | //
// A child can climb a set of stairs by takinbg 1, 2 or 3 steps at a time.
// How man ways can the child climb the stairs?
//
func countPaths(stair stair : Int, stairs : Int) -> Int
{
var paths : Int
if stair > stairs
{
paths = 0
}
else if stair == stairs
{
paths = 1
}
else
{
paths = countPaths(stair: stair + 1, stairs: stairs) +
countPaths(stair: stair + 2, stairs: stairs) +
countPaths(stair: stair + 3, stairs: stairs)
}
return paths
}
let startStair : Int = 1
countPaths(stair: startStair, stairs: 2)
countPaths(stair: startStair, stairs: 3)
countPaths(stair: startStair, stairs: 4)
| mit |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModelTests/EurofurenceSessionTestBuilder.swift | 1 | 13205 | import EurofurenceModel
import EurofurenceModelTestDoubles
import Foundation
class EurofurenceSessionTestBuilder {
class Context {
var session: EurofurenceSession
var clock: StubClock
var notificationTokenRegistration: CapturingRemoteNotificationsTokenRegistration
var credentialStore: CapturingCredentialStore
var api: FakeAPI
var dataStore: InMemoryDataStore
var conventionStartDateRepository: StubConventionStartDateRepository
var imageRepository: CapturingImageRepository
var significantTimeChangeAdapter: CapturingSignificantTimeChangeAdapter
var urlOpener: CapturingURLOpener
var longRunningTaskManager: FakeLongRunningTaskManager
var mapCoordinateRender: CapturingMapCoordinateRender
var refreshObserver: CapturingRefreshServiceObserver
private(set) var lastRefreshError: RefreshServiceError?
fileprivate init(session: EurofurenceSession,
clock: StubClock,
notificationTokenRegistration: CapturingRemoteNotificationsTokenRegistration,
credentialStore: CapturingCredentialStore,
api: FakeAPI,
dataStore: InMemoryDataStore,
conventionStartDateRepository: StubConventionStartDateRepository,
imageRepository: CapturingImageRepository,
significantTimeChangeAdapter: CapturingSignificantTimeChangeAdapter,
urlOpener: CapturingURLOpener,
longRunningTaskManager: FakeLongRunningTaskManager,
mapCoordinateRender: CapturingMapCoordinateRender,
refreshObserver: CapturingRefreshServiceObserver) {
self.session = session
self.clock = clock
self.notificationTokenRegistration = notificationTokenRegistration
self.credentialStore = credentialStore
self.api = api
self.dataStore = dataStore
self.conventionStartDateRepository = conventionStartDateRepository
self.imageRepository = imageRepository
self.significantTimeChangeAdapter = significantTimeChangeAdapter
self.urlOpener = urlOpener
self.longRunningTaskManager = longRunningTaskManager
self.mapCoordinateRender = mapCoordinateRender
self.refreshObserver = refreshObserver
}
var services: Services {
return session.services
}
var additionalServicesRepository: AdditionalServicesRepository {
return session.repositories.additionalServices
}
var notificationsService: NotificationService {
return services.notifications
}
var refreshService: RefreshService {
return services.refresh
}
var announcementsService: AnnouncementsService {
return services.announcements
}
var authenticationService: AuthenticationService {
return services.authentication
}
var eventsService: EventsService {
return services.events
}
var dealersService: DealersService {
return services.dealers
}
var knowledgeService: KnowledgeService {
return services.knowledge
}
var contentLinksService: ContentLinksService {
return services.contentLinks
}
var conventionCountdownService: ConventionCountdownService {
return services.conventionCountdown
}
var collectThemAllService: CollectThemAllService {
return services.collectThemAll
}
var mapsService: MapsService {
return services.maps
}
var sessionStateService: SessionStateService {
return services.sessionState
}
var privateMessagesService: PrivateMessagesService {
return services.privateMessages
}
var authenticationToken: String? {
return credentialStore.persistedCredential?.authenticationToken
}
func tickTime(to time: Date) {
clock.tickTime(to: time)
}
func registerForRemoteNotifications(_ deviceToken: Data = Data()) {
notificationsService.storeRemoteNotificationsToken(deviceToken)
}
func login(registrationNumber: Int = 0,
username: String = "",
password: String = "",
completionHandler: @escaping (LoginResult) -> Void = { _ in }) {
let arguments = LoginArguments(registrationNumber: registrationNumber, username: username, password: password)
authenticationService.login(arguments, completionHandler: completionHandler)
}
func loginSuccessfully() {
login()
api.simulateLoginResponse(LoginResponse(userIdentifier: .random, username: .random, token: .random, tokenValidUntil: Date(timeIntervalSinceNow: 1)))
}
func logoutSuccessfully() {
authenticationService.logout(completionHandler: { (_) in })
notificationTokenRegistration.succeedLastRequest()
}
@discardableResult
func refreshLocalStore(completionHandler: ((RefreshServiceError?) -> Void)? = nil) -> Progress {
return session.services.refresh.refreshLocalStore { (error) in
self.lastRefreshError = error
completionHandler?(error)
}
}
func performSuccessfulSync(response: ModelCharacteristics) {
refreshLocalStore()
simulateSyncSuccess(response)
}
func simulateSyncSuccess(_ response: ModelCharacteristics) {
api.simulateSuccessfulSync(response)
}
func simulateSyncAPIError() {
api.simulateUnsuccessfulSync()
}
func simulateSignificantTimeChange() {
significantTimeChangeAdapter.simulateSignificantTimeChange()
}
}
private var api = FakeAPI()
private var credentialStore = CapturingCredentialStore()
private var clock = StubClock()
private var dataStore = InMemoryDataStore()
private var userPreferences: UserPreferences = StubUserPreferences()
private var timeIntervalForUpcomingEventsSinceNow: TimeInterval = .greatestFiniteMagnitude
private var imageRepository = CapturingImageRepository()
private var urlOpener: CapturingURLOpener = CapturingURLOpener()
private var collectThemAllRequestFactory: CollectThemAllRequestFactory = StubCollectThemAllRequestFactory()
private var companionAppURLRequestFactory: CompanionAppURLRequestFactory = StubCompanionAppURLRequestFactory()
private var forceUpgradeRequired: ForceRefreshRequired = StubForceRefreshRequired(isForceRefreshRequired: false)
private var longRunningTaskManager: FakeLongRunningTaskManager = FakeLongRunningTaskManager()
private var conventionStartDateRepository = StubConventionStartDateRepository()
private var refreshCollaboration: RefreshCollaboration?
func with(_ currentDate: Date) -> EurofurenceSessionTestBuilder {
clock = StubClock(currentDate: currentDate)
return self
}
func with(_ persistedCredential: Credential?) -> EurofurenceSessionTestBuilder {
credentialStore = CapturingCredentialStore(persistedCredential: persistedCredential)
return self
}
@discardableResult
func with(_ dataStore: InMemoryDataStore) -> EurofurenceSessionTestBuilder {
self.dataStore = dataStore
return self
}
@discardableResult
func with(_ userPreferences: UserPreferences) -> EurofurenceSessionTestBuilder {
self.userPreferences = userPreferences
return self
}
@discardableResult
func with(timeIntervalForUpcomingEventsSinceNow: TimeInterval) -> EurofurenceSessionTestBuilder {
self.timeIntervalForUpcomingEventsSinceNow = timeIntervalForUpcomingEventsSinceNow
return self
}
@discardableResult
func with(_ api: FakeAPI) -> EurofurenceSessionTestBuilder {
self.api = api
return self
}
@discardableResult
func with(_ imageRepository: CapturingImageRepository) -> EurofurenceSessionTestBuilder {
self.imageRepository = imageRepository
return self
}
@discardableResult
func with(_ urlOpener: CapturingURLOpener) -> EurofurenceSessionTestBuilder {
self.urlOpener = urlOpener
return self
}
@discardableResult
func with(_ collectThemAllRequestFactory: CollectThemAllRequestFactory) -> EurofurenceSessionTestBuilder {
self.collectThemAllRequestFactory = collectThemAllRequestFactory
return self
}
@discardableResult
func with(_ companionAppURLRequestFactory: CompanionAppURLRequestFactory) -> EurofurenceSessionTestBuilder {
self.companionAppURLRequestFactory = companionAppURLRequestFactory
return self
}
@discardableResult
func with(_ longRunningTaskManager: FakeLongRunningTaskManager) -> EurofurenceSessionTestBuilder {
self.longRunningTaskManager = longRunningTaskManager
return self
}
func loggedInWithValidCredential() -> EurofurenceSessionTestBuilder {
let credential = Credential(username: "User",
registrationNumber: 42,
authenticationToken: "Token",
tokenExpiryDate: .distantFuture)
return with(credential)
}
@discardableResult
func with(_ forceUpgradeRequired: ForceRefreshRequired) -> EurofurenceSessionTestBuilder {
self.forceUpgradeRequired = forceUpgradeRequired
return self
}
@discardableResult
func with(_ conventionStartDateRepository: StubConventionStartDateRepository) -> EurofurenceSessionTestBuilder {
self.conventionStartDateRepository = conventionStartDateRepository
return self
}
@discardableResult
func with(_ refreshCollaboration: RefreshCollaboration) -> EurofurenceSessionTestBuilder {
self.refreshCollaboration = refreshCollaboration
return self
}
@discardableResult
func build() -> Context {
let notificationTokenRegistration = CapturingRemoteNotificationsTokenRegistration()
let significantTimeChangeAdapter = CapturingSignificantTimeChangeAdapter()
let mapCoordinateRender = CapturingMapCoordinateRender()
let builder = makeSessionBuilder()
.with(timeIntervalForUpcomingEventsSinceNow: timeIntervalForUpcomingEventsSinceNow)
.with(significantTimeChangeAdapter)
.with(mapCoordinateRender)
.with(notificationTokenRegistration)
includeRefreshCollaboration(builder)
let session = builder.build()
let refreshObserver = CapturingRefreshServiceObserver()
session.services.refresh.add(refreshObserver)
return Context(session: session,
clock: clock,
notificationTokenRegistration: notificationTokenRegistration,
credentialStore: credentialStore,
api: api,
dataStore: dataStore,
conventionStartDateRepository: conventionStartDateRepository,
imageRepository: imageRepository,
significantTimeChangeAdapter: significantTimeChangeAdapter,
urlOpener: urlOpener,
longRunningTaskManager: longRunningTaskManager,
mapCoordinateRender: mapCoordinateRender,
refreshObserver: refreshObserver)
}
private func makeSessionBuilder() -> EurofurenceSessionBuilder {
let conventionIdentifier = ConventionIdentifier(identifier: ModelCharacteristics.testConventionIdentifier)
let mandatory = EurofurenceSessionBuilder.Mandatory(
conventionIdentifier: conventionIdentifier,
conventionStartDateRepository: conventionStartDateRepository,
shareableURLFactory: FakeShareableURLFactory()
)
return EurofurenceSessionBuilder(mandatory: mandatory)
.with(api)
.with(clock)
.with(credentialStore)
.with(StubDataStoreFactory(conventionIdentifier: conventionIdentifier, dataStore: dataStore))
.with(userPreferences)
.with(imageRepository)
.with(urlOpener)
.with(collectThemAllRequestFactory)
.with(longRunningTaskManager)
.with(forceUpgradeRequired)
.with(companionAppURLRequestFactory)
}
private func includeRefreshCollaboration(_ builder: EurofurenceSessionBuilder) {
if let refreshCollaboration = refreshCollaboration {
builder.with(refreshCollaboration)
}
}
}
| mit |
xmartlabs/Swift-Project-Template | Project-iOS/XLProjectName/XLProjectName/Helpers/Opera/Pagination/PaginationRequestType+Rx.swift | 1 | 3056 | //
// PaginationRequestType+Rx.swift
// Opera
//
// Copyright (c) 2019 Xmartlabs SRL ( 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
import RxSwift
import Alamofire
extension Reactive where Base: PaginationRequestType {
/**
Returns a `Observable` of [Response] for the PaginationRequestType instance.
If something goes wrong a Opera.Error error is propagated through the result sequence.
- returns: An instance of `Observable<Response>`
*/
var collection: Single<Base.Response> {
let myPage = base.page
return Single<Base.Response>.create { single in
let req = NetworkManager.singleton.response(route: self.base) { (response: DataResponse<Base.Response, XLProjectNameError>) in
switch response.result {
case .failure(let error):
single(.error(error))
case .success(let value):
let previousPage = response.response?.linkPagePrameter((self as? WebLinkingSettings)?.prevRelationName ?? Default.prevRelationName,
pageParameterName: (self as? WebLinkingSettings)?
.relationPageParamName ?? Default.relationPageParamName)
let nextPage = response.response?.linkPagePrameter((self as? WebLinkingSettings)?.nextRelationName ?? Default.nextRelationName,
pageParameterName: (self as? WebLinkingSettings)?
.relationPageParamName ?? Default.relationPageParamName)
let baseResponse = Base.Response(elements: value.elements, previousPage: previousPage, nextPage: nextPage, page: myPage)
single(.success(baseResponse))
}
}
return Disposables.create {
req.cancel()
}
}
}
}
| mit |
r4phab/ECAB | ECAB/TestsTableViewController.swift | 1 | 3586 | //
// GamesTableViewController.swift
// ECAB
//
// Created by Boris Yurkevich on 3/9/15.
// Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import UIKit
class TestsTableViewController: UITableViewController {
let model = Model.sharedInstance
private let reuseIdentifier = "Games Table Cell"
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return model.games.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SubtestCell
cell.title.text = model.games[indexPath.row].rawValue
switch model.games[indexPath.row].rawValue {
case Game.AuditorySustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_auditory.rawValue)
cell.subtitle.text = "Touch when the animal is heared"
case Game.VisualSearch.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_visualSearch.rawValue)
cell.subtitle.text = "Touch the red apples"
case Game.VisualSustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_visualSustain.rawValue)
cell.subtitle.text = "Touch when the animal is seen"
case Game.BalloonSorting.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_balloonSorting.rawValue)
cell.subtitle.text = "Work out the balloons"
case Game.DualSustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_dualTask.rawValue)
cell.subtitle.text = "Touch when animal heard or seen"
case Game.Flanker.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_flanker.rawValue)
cell.subtitle.text = "Touch the side the fish is facing"
case Game.VerbalOpposites.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_verbalOpposites.rawValue)
cell.subtitle.text = "Speak the animal name"
case Game.Counterpointing.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_counterpointing.rawValue)
cell.subtitle.text = "Touch the side of the dog"
default:
cell.icon.image = UIImage(named: Picture.Icon_auditory.rawValue)
}
return cell
}
// Select correct test row when the view is displayed
override func viewWillAppear(animated: Bool) {
if(model.data != nil){
selectRow(model.data.selectedGame.integerValue)
}
}
// MARK: — Table View delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
model.data.selectedGame = indexPath.row
model.save()
let navVC = splitViewController!.viewControllers.last as! UINavigationController
let detailVC = navVC.topViewController as! TestViewController
detailVC.showTheGame(model.data.selectedGame.integerValue)
}
func selectRow(index:Int) {
let rowToSelect:NSIndexPath = NSIndexPath(forRow: index, inSection: 0)
self.tableView.selectRowAtIndexPath(rowToSelect, animated: false, scrollPosition:UITableViewScrollPosition.None)
}
}
| mit |
Swiftodon/Leviathan | Leviathan/Sources/Application/LeviathanError.swift | 1 | 1076 | //
// LeviathanError.swift
// Leviathan
//
// Created by Thomas Bonk on 17.11.22.
// Copyright 2022 The Swiftodon Team
//
// 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
enum LeviathanError: Error {
case noUserLoggedOn
}
extension LeviathanError: LocalizedError {
public var errorDescription: String? {
switch self {
case .noUserLoggedOn:
return NSLocalizedString(
"You are not logged in to a Mastodon instance.", comment: "Localized error message")
}
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.