repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
JGiola/swift
test/Sema/availability_versions.swift
1
73225
// RUN: %target-typecheck-verify-swift -target %target-cpu-apple-macosx10.50 -disable-objc-attr-requires-foundation-module // RUN: not %target-swift-frontend -target %target-cpu-apple-macosx10.50 -disable-objc-attr-requires-foundation-module -typecheck %s 2>&1 | %FileCheck %s '--implicit-check-not=<unknown>:0' // Make sure we do not emit availability errors or warnings when -disable-availability-checking is passed // RUN: not %target-swift-frontend -target %target-cpu-apple-macosx10.50 -typecheck -disable-objc-attr-requires-foundation-module -disable-availability-checking %s 2>&1 | %FileCheck %s '--implicit-check-not=error:' '--implicit-check-not=warning:' // REQUIRES: OS=macosx func markUsed<T>(_ t: T) {} @available(OSX, introduced: 10.9) func globalFuncAvailableOn10_9() -> Int { return 9 } @available(OSX, introduced: 10.51) func globalFuncAvailableOn10_51() -> Int { return 10 } @available(OSX, introduced: 10.52) func globalFuncAvailableOn10_52() -> Int { return 11 } // Top level should reflect the minimum deployment target. let ignored1: Int = globalFuncAvailableOn10_9() let ignored2: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let ignored3: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Functions without annotations should reflect the minimum deployment target. func functionWithoutAvailability() { // expected-note@-1 2{{add @available attribute to enclosing global function}} let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Functions with annotations should refine their bodies. @available(OSX, introduced: 10.51) func functionAvailableOn10_51() { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // Nested functions should get their own refinement context. @available(OSX, introduced: 10.52) func innerFunctionAvailableOn10_52() { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() } let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Don't allow script-mode globals to marked potentially unavailable. Their // initializers are eagerly executed. @available(OSX, introduced: 10.51) // expected-error {{global variable cannot be marked potentially unavailable with '@available' in script mode}} var potentiallyUnavailableGlobalInScriptMode: Int = globalFuncAvailableOn10_51() // Still allow other availability annotations on script-mode globals @available(OSX, deprecated: 10.51) var deprecatedGlobalInScriptMode: Int = 5 if #available(OSX 10.51, *) { let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(OSX 10.51, *) { let _: Int = globalFuncAvailableOn10_51() let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } else { let _: Int = globalFuncAvailableOn10_9() let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) @available(iOS, introduced: 8.0) func globalFuncAvailableOnOSX10_51AndiOS8_0() -> Int { return 10 } if #available(OSX 10.51, iOS 8.0, *) { let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() } if #available(iOS 9.0, *) { let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() // expected-error {{'globalFuncAvailableOnOSX10_51AndiOS8_0()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Multiple potentially unavailable references in a single statement let ignored4: (Int, Int) = (globalFuncAvailableOn10_51(), globalFuncAvailableOn10_52()) // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 2{{add 'if #available' version check}} _ = globalFuncAvailableOn10_9() let ignored5 = globalFuncAvailableOn10_51 // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Overloaded global functions @available(OSX, introduced: 10.9) func overloadedFunction() {} @available(OSX, introduced: 10.51) func overloadedFunction(_ on1010: Int) {} overloadedFunction() overloadedFunction(0) // expected-error {{'overloadedFunction' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Potentially unavailable methods class ClassWithPotentiallyUnavailableMethod { // expected-note@-1 {{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) func methAvailableOn10_9() {} @available(OSX, introduced: 10.51) func methAvailableOn10_51() {} @available(OSX, introduced: 10.51) class func classMethAvailableOn10_51() {} func someOtherMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} methAvailableOn10_9() methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } func callPotentiallyUnavailableMethods(_ o: ClassWithPotentiallyUnavailableMethod) { // expected-note@-1 2{{add @available attribute to enclosing global function}} let m10_9 = o.methAvailableOn10_9 m10_9() let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() o.methAvailableOn10_9() o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func callPotentiallyUnavailableMethodsViaIUO(_ o: ClassWithPotentiallyUnavailableMethod!) { // expected-note@-1 2{{add @available attribute to enclosing global function}} let m10_9 = o.methAvailableOn10_9 m10_9() let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} m10_51() o.methAvailableOn10_9() o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func callPotentiallyUnavailableClassMethod() { // expected-note@-1 2{{add @available attribute to enclosing global function}} ClassWithPotentiallyUnavailableMethod.classMethAvailableOn10_51() // expected-error {{'classMethAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let m10_51 = ClassWithPotentiallyUnavailableMethod.classMethAvailableOn10_51 // expected-error {{'classMethAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() } class SubClassWithPotentiallyUnavailableMethod : ClassWithPotentiallyUnavailableMethod { // expected-note@-1 {{add @available attribute to enclosing class}} func someMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} methAvailableOn10_9() methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } class SubClassOverridingPotentiallyUnavailableMethod : ClassWithPotentiallyUnavailableMethod { // expected-note@-1 2{{add @available attribute to enclosing class}} override func methAvailableOn10_51() { // expected-note@-1 2{{add @available attribute to enclosing instance method}} methAvailableOn10_9() super.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let m10_9 = super.methAvailableOn10_9 m10_9() let m10_51 = super.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} m10_51() } func someMethod() { methAvailableOn10_9() // Calling our override should be fine methAvailableOn10_51() } } class ClassWithPotentiallyUnavailableOverloadedMethod { @available(OSX, introduced: 10.9) func overloadedMethod() {} @available(OSX, introduced: 10.51) func overloadedMethod(_ on1010: Int) {} } func callPotentiallyUnavailableOverloadedMethod(_ o: ClassWithPotentiallyUnavailableOverloadedMethod) { // expected-note@-1 {{add @available attribute to enclosing global function}} o.overloadedMethod() o.overloadedMethod(0) // expected-error {{'overloadedMethod' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Initializers class ClassWithPotentiallyUnavailableInitializer { // expected-note@-1 {{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) required init() { } @available(OSX, introduced: 10.51) required init(_ val: Int) { } convenience init(s: String) { // expected-note@-1 {{add @available attribute to enclosing initializer}} self.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) convenience init(onlyOn1010: String) { self.init(5) } } func callPotentiallyUnavailableInitializer() { // expected-note@-1 2{{add @available attribute to enclosing global function}} _ = ClassWithPotentiallyUnavailableInitializer() _ = ClassWithPotentiallyUnavailableInitializer(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let i = ClassWithPotentiallyUnavailableInitializer.self _ = i.init() _ = i.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } class SuperWithWithPotentiallyUnavailableInitializer { @available(OSX, introduced: 10.9) init() { } @available(OSX, introduced: 10.51) init(_ val: Int) { } } class SubOfClassWithPotentiallyUnavailableInitializer : SuperWithWithPotentiallyUnavailableInitializer { // expected-note@-1 {{add @available attribute to enclosing class}} override init(_ val: Int) { // expected-note@-1 {{add @available attribute to enclosing initializer}} super.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } override init() { super.init() } @available(OSX, introduced: 10.51) init(on1010: Int) { super.init(22) } } // Properties class ClassWithPotentiallyUnavailableProperties { // expected-note@-1 4{{add @available attribute to enclosing class}} var nonLazyAvailableOn10_9Stored: Int = 9 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} var nonLazyAvailableOn10_51Stored : Int = 10 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} let nonLazyLetAvailableOn10_51Stored : Int = 10 // Make sure that we don't emit a Fix-It to mark a stored property as potentially unavailable. // We don't support potentially unavailable stored properties yet. var storedPropertyOfPotentiallyUnavailableType: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} @available(OSX, introduced: 10.9) lazy var availableOn10_9Stored: Int = 9 @available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}} lazy var availableOn10_51Stored : Int = 10 @available(OSX, introduced: 10.9) var availableOn10_9Computed: Int { get { let _: Int = availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _: Int = availableOn10_51Stored } return availableOn10_9Stored } set(newVal) { availableOn10_9Stored = newVal } } @available(OSX, introduced: 10.51) var availableOn10_51Computed: Int { get { return availableOn10_51Stored } set(newVal) { availableOn10_51Stored = newVal } } var propWithSetterOnlyAvailableOn10_51 : Int { // expected-note@-1 {{add @available attribute to enclosing property}} get { _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} return 0 } @available(OSX, introduced: 10.51) set(newVal) { _ = globalFuncAvailableOn10_51() } } var propWithGetterOnlyAvailableOn10_51 : Int { // expected-note@-1 {{add @available attribute to enclosing property}} @available(OSX, introduced: 10.51) get { _ = globalFuncAvailableOn10_51() return 0 } set(newVal) { _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } var propWithGetterAndSetterOnlyAvailableOn10_51 : Int { @available(OSX, introduced: 10.51) get { return 0 } @available(OSX, introduced: 10.51) set(newVal) { } } var propWithSetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithPotentiallyUnavailableProperties { get { return ClassWithPotentiallyUnavailableProperties() } @available(OSX, introduced: 10.51) set(newVal) { } } var propWithGetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithPotentiallyUnavailableProperties { @available(OSX, introduced: 10.51) get { return ClassWithPotentiallyUnavailableProperties() } set(newVal) { } } } @available(OSX, introduced: 10.51) class ClassWithReferencesInInitializers { var propWithInitializer10_51: Int = globalFuncAvailableOn10_51() var propWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} lazy var lazyPropWithInitializer10_51: Int = globalFuncAvailableOn10_51() lazy var lazyPropWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} } func accessPotentiallyUnavailableProperties(_ o: ClassWithPotentiallyUnavailableProperties) { // expected-note@-1 17{{add @available attribute to enclosing global function}} // Stored properties let _: Int = o.availableOn10_9Stored let _: Int = o.availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.availableOn10_9Stored = 9 o.availableOn10_51Stored = 10 // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Computed Properties let _: Int = o.availableOn10_9Computed let _: Int = o.availableOn10_51Computed // expected-error {{'availableOn10_51Computed' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.availableOn10_9Computed = 9 o.availableOn10_51Computed = 10 // expected-error {{'availableOn10_51Computed' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Getter allowed on 10.9 but setter is not let _: Int = o.propWithSetterOnlyAvailableOn10_51 o.propWithSetterOnlyAvailableOn10_51 = 5 // expected-error {{setter for 'propWithSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // Setter is allowed on 10.51 and greater o.propWithSetterOnlyAvailableOn10_51 = 5 } // Setter allowed on 10.9 but getter is not o.propWithGetterOnlyAvailableOn10_51 = 5 let _: Int = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // Getter is allowed on 10.51 and greater let _: Int = o.propWithGetterOnlyAvailableOn10_51 } // Tests for nested member refs // Both getters are potentially unavailable. let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}} expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} // Nested getter is potentially unavailable, outer getter is available let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Nested getter is available, outer getter is potentially unavailable let _:Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} // Both getters are always available. let _: Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // Nesting in source of assignment var v: Int v = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} v = (o.propWithGetterOnlyAvailableOn10_51) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = v // muffle warning // Inout requires access to both getter and setter func takesInout(_ i : inout Int) { } takesInout(&o.propWithGetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} takesInout(&o.propWithSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because setter for 'propWithSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} takesInout(&o.propWithGetterAndSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} expected-error {{cannot pass as inout because setter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} takesInout(&o.availableOn10_9Computed) takesInout(&o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.availableOn10_9Computed) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // _silgen_name @_silgen_name("SomeName") @available(OSX, introduced: 10.51) func funcWith_silgen_nameAvailableOn10_51(_ p: ClassAvailableOn10_51?) -> ClassAvailableOn10_51 // Enums @available(OSX, introduced: 10.51) enum EnumIntroducedOn10_51 { case Element } @available(OSX, introduced: 10.52) enum EnumIntroducedOn10_52 { case Element } @available(OSX, introduced: 10.51) enum CompassPoint { case North case South case East @available(OSX, introduced: 10.52) case West case WithAvailableByEnumPayload(p : EnumIntroducedOn10_51) // expected-error@+1 {{enum cases with associated values cannot be marked potentially unavailable with '@available'}} @available(OSX, introduced: 10.52) case WithAvailableByEnumElementPayload(p : EnumIntroducedOn10_52) // expected-error@+1 2{{enum cases with associated values cannot be marked potentially unavailable with '@available'}} @available(OSX, introduced: 10.52) case WithAvailableByEnumElementPayload1(p : EnumIntroducedOn10_52), WithAvailableByEnumElementPayload2(p : EnumIntroducedOn10_52) case WithPotentiallyUnavailablePayload(p : EnumIntroducedOn10_52) // expected-error {{'EnumIntroducedOn10_52' is only available in macOS 10.52 or newer}} case WithPotentiallyUnavailablePayload1(p : EnumIntroducedOn10_52), WithPotentiallyUnavailablePayload2(p : EnumIntroducedOn10_52) // expected-error 2{{'EnumIntroducedOn10_52' is only available in macOS 10.52 or newer}} @available(OSX, unavailable) case WithPotentiallyUnavailablePayload3(p : EnumIntroducedOn10_52) } @available(OSX, introduced: 10.52) func functionTakingEnumIntroducedOn10_52(_ e: EnumIntroducedOn10_52) { } func useEnums() { // expected-note@-1 3{{add @available attribute to enclosing global function}} let _: CompassPoint = .North // expected-error {{'CompassPoint' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _: CompassPoint = .North let _: CompassPoint = .West // expected-error {{'West' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(OSX 10.52, *) { let _: CompassPoint = .West } // Pattern matching on an enum element does not require it to be definitely available if #available(OSX 10.51, *) { let point: CompassPoint = .North switch (point) { case .North, .South, .East: markUsed("NSE") case .West: // We do not expect an error here markUsed("W") case .WithPotentiallyUnavailablePayload(_): markUsed("WithPotentiallyUnavailablePayload") case .WithPotentiallyUnavailablePayload1(_): markUsed("WithPotentiallyUnavailablePayload1") case .WithPotentiallyUnavailablePayload2(_): markUsed("WithPotentiallyUnavailablePayload2") case .WithAvailableByEnumPayload(_): markUsed("WithAvailableByEnumPayload") case .WithAvailableByEnumElementPayload1(_): markUsed("WithAvailableByEnumElementPayload1") case .WithAvailableByEnumElementPayload2(_): markUsed("WithAvailableByEnumElementPayload2") case .WithAvailableByEnumElementPayload(let p): markUsed("WithAvailableByEnumElementPayload") // For the moment, we do not incorporate enum element availability into // TRC construction. Perhaps we should? functionTakingEnumIntroducedOn10_52(p) // expected-error {{'functionTakingEnumIntroducedOn10_52' is only available in macOS 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} } } } // Classes @available(OSX, introduced: 10.9) class ClassAvailableOn10_9 { func someMethod() {} class func someClassMethod() {} var someProp : Int = 22 } @available(OSX, introduced: 10.51) class ClassAvailableOn10_51 { // expected-note {{enclosing scope requires availability of macOS 10.51 or newer}} func someMethod() {} class func someClassMethod() { let _ = ClassAvailableOn10_51() } var someProp : Int = 22 @available(OSX, introduced: 10.9) // expected-error {{instance method cannot be more available than enclosing scope}} func someMethodAvailableOn10_9() { } @available(OSX, introduced: 10.52) var propWithGetter: Int { // expected-note{{enclosing scope requires availability of macOS 10.52 or newer}} @available(OSX, introduced: 10.51) // expected-error {{getter cannot be more available than enclosing scope}} get { return 0 } } } func classAvailability() { // expected-note@-1 3{{add @available attribute to enclosing global function}} ClassAvailableOn10_9.someClassMethod() ClassAvailableOn10_51.someClassMethod() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} _ = ClassAvailableOn10_9.self _ = ClassAvailableOn10_51.self // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let o10_9 = ClassAvailableOn10_9() let o10_51 = ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o10_9.someMethod() o10_51.someMethod() let _ = o10_9.someProp let _ = o10_51.someProp } func castingPotentiallyUnavailableClass(_ o : AnyObject) { // expected-note@-1 3{{add @available attribute to enclosing global function}} let _ = o as! ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o as? ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o is ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } protocol Creatable { init() } @available(OSX, introduced: 10.51) class ClassAvailableOn10_51_Creatable : Creatable { required init() {} } func create<T : Creatable>() -> T { return T() } class ClassWithGenericTypeParameter<T> { } class ClassWithTwoGenericTypeParameter<T, S> { } func classViaTypeParameter() { // expected-note@-1 9{{add @available attribute to enclosing global function}} let _ : ClassAvailableOn10_51_Creatable = // expected-error {{'ClassAvailableOn10_51_Creatable' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} create() let _ = create() as ClassAvailableOn10_51_Creatable // expected-error {{'ClassAvailableOn10_51_Creatable' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = [ClassAvailableOn10_51]() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithGenericTypeParameter<ClassAvailableOn10_51> = ClassWithGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, String> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<String, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error 2{{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add 'if #available' version check}} let _: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Potentially unavailable class used in declarations class ClassWithDeclarationsOfPotentiallyUnavailableClasses { // expected-note@-1 6{{add @available attribute to enclosing class}} @available(OSX, introduced: 10.51) init() {} var propertyOfPotentiallyUnavailableType: ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} @available(OSX, introduced: 10.51) static var potentiallyUnavailableStaticPropertyOfPotentiallyUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51() @available(OSX, introduced: 10.51) static var potentiallyUnavailableStaticPropertyOfOptionalPotentiallyUnavailableType: ClassAvailableOn10_51? func methodWithPotentiallyUnavailableParameterType(_ o : ClassAvailableOn10_51) { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing instance method}} } @available(OSX, introduced: 10.51) func potentiallyUnavailableMethodWithPotentiallyUnavailableParameterType(_ o : ClassAvailableOn10_51) {} func methodWithPotentiallyUnavailableReturnType() -> ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add @available attribute to enclosing instance method}} return ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, unavailable) func unavailableMethodWithPotentiallyUnavailableParameterType(_ o : ClassAvailableOn10_51) {} @available(OSX, introduced: 10.51) func potentiallyUnavailableMethodWithPotentiallyUnavailableReturnType() -> ClassAvailableOn10_51 { return ClassAvailableOn10_51() } @available(OSX, unavailable) func unavailableMethodWithPotentiallyUnavailableReturnType() -> ClassAvailableOn10_51 { guard #available(OSX 10.51, *) else { fatalError() } return ClassAvailableOn10_51() } func methodWithPotentiallyUnavailableLocalDeclaration() { // expected-note@-1 {{add @available attribute to enclosing instance method}} let _ : ClassAvailableOn10_51 = methodWithPotentiallyUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.51) func potentiallyUnavailableMethodWithPotentiallyUnavailableLocalDeclaration() { let _ : ClassAvailableOn10_51 = methodWithPotentiallyUnavailableReturnType() } @available(OSX, unavailable) func unavailableMethodWithPotentiallyUnavailableLocalDeclaration() { let _ : ClassAvailableOn10_51 = methodWithPotentiallyUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } func referToPotentiallyUnavailableStaticProperty() { // expected-note@-1 {{add @available attribute to enclosing global function}} let _ = ClassWithDeclarationsOfPotentiallyUnavailableClasses.potentiallyUnavailableStaticPropertyOfPotentiallyUnavailableType // expected-error {{'potentiallyUnavailableStaticPropertyOfPotentiallyUnavailableType' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } class ClassExtendingPotentiallyUnavailableClass : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing class}} } @available(OSX, introduced: 10.51) class PotentiallyUnavailableClassExtendingPotentiallyUnavailableClass : ClassAvailableOn10_51 { } @available(OSX, unavailable) class UnavailableClassExtendingPotentiallyUnavailableClass : ClassAvailableOn10_51 { } // Method availability is contravariant class SuperWithAlwaysAvailableMembers { func shouldAlwaysBeAvailableMethod() { // expected-note {{overridden declaration is here}} } var shouldAlwaysBeAvailableProperty: Int { // expected-note {{overridden declaration is here}} get { return 9 } set(newVal) {} } var setterShouldAlwaysBeAvailableProperty: Int { get { return 9 } set(newVal) {} // expected-note {{overridden declaration is here}} } var getterShouldAlwaysBeAvailableProperty: Int { get { return 9 } // expected-note {{overridden declaration is here}} set(newVal) {} } } class SubWithLimitedMemberAvailability : SuperWithAlwaysAvailableMembers { @available(OSX, introduced: 10.51) override func shouldAlwaysBeAvailableMethod() { // expected-error {{overriding 'shouldAlwaysBeAvailableMethod' must be as available as declaration it overrides}} } @available(OSX, introduced: 10.51) override var shouldAlwaysBeAvailableProperty: Int { // expected-error {{overriding 'shouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} get { return 10 } set(newVal) {} } override var setterShouldAlwaysBeAvailableProperty: Int { get { return 9 } @available(OSX, introduced: 10.51) set(newVal) {} // expected-error {{overriding setter for 'setterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} // This is a terrible diagnostic. rdar://problem/20427938 } override var getterShouldAlwaysBeAvailableProperty: Int { @available(OSX, introduced: 10.51) get { return 9 } // expected-error {{overriding getter for 'getterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}} set(newVal) {} } } @available(OSX, introduced: 10.51) class SubWithLimitedAvailablility : SuperWithAlwaysAvailableMembers { override func shouldAlwaysBeAvailableMethod() {} override var shouldAlwaysBeAvailableProperty: Int { get { return 10 } set(newVal) {} } override var setterShouldAlwaysBeAvailableProperty: Int { get { return 9 } set(newVal) {} } override var getterShouldAlwaysBeAvailableProperty: Int { get { return 9 } set(newVal) {} } } class SuperWithLimitedMemberAvailability { @available(OSX, introduced: 10.51) func someMethod() { } @available(OSX, introduced: 10.51) var someProperty: Int { get { return 10 } set(newVal) {} } } class SubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability { // expected-note@-1 2{{add @available attribute to enclosing class}} @available(OSX, introduced: 10.9) override func someMethod() { super.someMethod() // expected-error {{'someMethod()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { super.someMethod() } } @available(OSX, introduced: 10.9) override var someProperty: Int { get { let _ = super.someProperty // expected-error {{'someProperty' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { let _ = super.someProperty } return 9 } set(newVal) {} } } @available(OSX, introduced: 10.51) class SubWithLimitedAvailability : SuperWithLimitedMemberAvailability { override func someMethod() { super.someMethod() } override var someProperty: Int { get { super.someProperty } set(newVal) { super.someProperty = newVal } } } @available(OSX, introduced: 10.52) class SubWithMoreLimitedAvailability : SuperWithLimitedMemberAvailability { override func someMethod() { super.someMethod() } override var someProperty: Int { get { super.someProperty } set(newVal) { super.someProperty = newVal } } } @available(OSX, introduced: 10.52) class SubWithMoreLimitedAvailabilityAndRedundantMemberAvailability : SuperWithLimitedMemberAvailability { @available(OSX, introduced: 10.52) override func someMethod() { super.someMethod() } @available(OSX, introduced: 10.52) override var someProperty: Int { get { super.someProperty } set(newVal) { super.someProperty = newVal } } } @available(OSX, unavailable) class UnavailableSubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability { override func someMethod() { } override var someProperty: Int { get { return 5 } set(newVal) {} } } // Inheritance and availability @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_9 { } @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.9) protocol ProtocolAvailableOn10_9InheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} } @available(OSX, introduced: 10.51) protocol ProtocolAvailableOn10_51InheritingFromProtocolAvailableOn10_9 : ProtocolAvailableOn10_9 { } @available(OSX, unavailable) protocol UnavailableProtocolInheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfClassAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} } @available(OSX, unavailable) class UnavailableSubclassOfClassAvailableOn10_51 : ClassAvailableOn10_51 { } // We allow nominal types to conform to protocols that are less available than the types themselves. @available(OSX, introduced: 10.9) class ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { } func castToPotentiallyUnavailableProtocol() { // expected-note@-1 2{{add @available attribute to enclosing global function}} let o: ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 = ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51() let _: ProtocolAvailableOn10_51 = o // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = o as ProtocolAvailableOn10_51 // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfClassAvailableOn10_51AlsoAdoptingProtocolAvailableOn10_51 : ClassAvailableOn10_51, ProtocolAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} } class SomeGenericClass<T> { } @available(OSX, introduced: 10.9) class SubclassAvailableOn10_9OfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> { // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} } @available(OSX, unavailable) class UnavailableSubclassOfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> { } func GenericWhereClause<T>(_ t: T) where T: ProtocolAvailableOn10_51 { // expected-error * {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing global function}} } @available(OSX, unavailable) func UnavailableGenericWhereClause<T>(_ t: T) where T: ProtocolAvailableOn10_51 { } func GenericSignature<T : ProtocolAvailableOn10_51>(_ t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing global function}} } @available(OSX, unavailable) func UnavailableGenericSignature<T : ProtocolAvailableOn10_51>(_ t: T) { } struct GenericType<T> { // expected-note {{add @available attribute to enclosing generic struct}} func nonGenericWhereClause() where T : ProtocolAvailableOn10_51 {} // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing instance method}} @available(OSX, unavailable) func unavailableNonGenericWhereClause() where T : ProtocolAvailableOn10_51 {} struct NestedType where T : ProtocolAvailableOn10_51 {} // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 2{{add @available attribute to enclosing struct}} @available(OSX, unavailable) struct UnavailableNestedType where T : ProtocolAvailableOn10_51 {} } // Extensions extension ClassAvailableOn10_51 { } // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add @available attribute to enclosing extension}} @available(OSX, unavailable) extension ClassAvailableOn10_51 { } @available(OSX, introduced: 10.51) extension ClassAvailableOn10_51 { func m() { // expected-note@-1 {{add @available attribute to enclosing instance method}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } } class ClassToExtend { } @available(OSX, introduced: 10.51) extension ClassToExtend { func extensionMethod() { } @available(OSX, introduced: 10.52) func extensionMethod10_52() { } class ExtensionClass { } // We rely on not allowing nesting of extensions, so test to make sure // this emits an error. // CHECK:error: declaration is only valid at file scope extension ClassToExtend { } // expected-error {{declaration is only valid at file scope}} } // We allow protocol extensions for protocols that are less available than the // conforming class. extension ClassToExtend : ProtocolAvailableOn10_51 { } @available(OSX, introduced: 10.51) extension ClassToExtend { // expected-note {{enclosing scope requires availability of macOS 10.51 or newer}} @available(OSX, introduced: 10.9) // expected-error {{instance method cannot be more available than enclosing scope}} func extensionMethod10_9() { } } func usePotentiallyUnavailableExtension() { // expected-note@-1 3{{add @available attribute to enclosing global function}} let o = ClassToExtend() o.extensionMethod() // expected-error {{'extensionMethod()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = ClassToExtend.ExtensionClass() // expected-error {{'ExtensionClass' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} o.extensionMethod10_52() // expected-error {{'extensionMethod10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Availability of synthesized designated initializers. @available(OSX, introduced: 10.51) class WidelyAvailableBase { init() {} @available(OSX, introduced: 10.52) init(thing: ()) {} } @available(OSX, introduced: 10.53) class EsotericSmallBatchHipsterThing : WidelyAvailableBase {} @available(OSX, introduced: 10.53) class NestedClassTest { class InnerClass : WidelyAvailableBase {} } // Useless #available(...) checks func functionWithDefaultAvailabilityAndUselessCheck(_ p: Bool) { // Default availability reflects minimum deployment: 10.9 and up if #available(OSX 10.9, *) { // no-warning let _ = globalFuncAvailableOn10_9() } if #available(OSX 10.51, *) { // expected-note {{enclosing scope here}} let _ = globalFuncAvailableOn10_51() if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_51() } } if #available(OSX 10.9, *) { // expected-note {{enclosing scope here}} } else { // Make sure we generate a warning about an unnecessary check even if the else branch of if is dead. if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } } // This 'if' is strictly to limit the scope of the guard fallthrough if p { guard #available(OSX 10.9, *) else { // expected-note {{enclosing scope here}} // Make sure we generate a warning about an unnecessary check even if the else branch of guard is dead. if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } } } // We don't want * generate a warn about useless checks; the check may be required on // another platform if #available(iOS 8.0, *) { } if #available(OSX 10.51, *) { // Similarly do not want '*' to generate a warning in a refined TRC. if #available(iOS 8.0, *) { } } } @available(OSX, unavailable) func explicitlyUnavailable() { } // expected-note 2{{'explicitlyUnavailable()' has been explicitly marked unavailable here}} func functionWithUnavailableInDeadBranch() { if #available(iOS 8.0, *) { } else { // This branch is dead on OSX, so we shouldn't a warning about use of potentially unavailable APIs in it. _ = globalFuncAvailableOn10_51() // no-warning @available(OSX 10.51, *) func localFuncAvailableOn10_51() { _ = globalFuncAvailableOn10_52() // no-warning } localFuncAvailableOn10_51() // no-warning explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}} } guard #available(iOS 8.0, *) else { _ = globalFuncAvailableOn10_51() // no-warning explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}} } } @available(OSX, introduced: 10.51) func functionWithSpecifiedAvailabilityAndUselessCheck() { // expected-note 2{{enclosing scope here}} if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_9() } if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} let _ = globalFuncAvailableOn10_51() } } // #available(...) outside if statement guards func injectToOptional<T>(_ v: T) -> T? { return v } if let _ = injectToOptional(5), #available(OSX 10.52, *) {} // ok // Refining context inside guard if #available(OSX 10.51, *), let _ = injectToOptional(globalFuncAvailableOn10_51()), let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(5), #available(OSX 10.51, *), let _ = injectToOptional(globalFuncAvailableOn10_51()), let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(globalFuncAvailableOn10_51()), #available(OSX 10.51, *), // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if let _ = injectToOptional(5), #available(OSX 10.51, *), // expected-note {{enclosing scope here}} let _ = injectToOptional(6), #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } // Tests for the guard control construct. func useGuardAvailable() { // expected-note@-1 3{{add @available attribute to enclosing global function}} // Guard fallthrough should refine context guard #available(OSX 10.51, *) else { // expected-note {{enclosing scope here}} let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} return } let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } if globalFuncAvailableOn10_51() > 0 { guard #available(OSX 10.52, *), let x = injectToOptional(globalFuncAvailableOn10_52()) else { return } _ = x } let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func twoGuardsInSameBlock(_ p: Int) { // expected-note@-1 {{add @available attribute to enclosing global function}} if (p > 0) { guard #available(OSX 10.51, *) else { return } let _ = globalFuncAvailableOn10_51() guard #available(OSX 10.52, *) else { return } let _ = globalFuncAvailableOn10_52() } let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Refining while loops while globalFuncAvailableOn10_51() > 10 { } // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} while #available(OSX 10.51, *), // expected-note {{enclosing scope here}} globalFuncAvailableOn10_51() > 10 { let _ = globalFuncAvailableOn10_51() let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-1 {{add 'if #available' version check}} while globalFuncAvailableOn10_51() > 11, let _ = injectToOptional(5), #available(OSX 10.52, *) { let _ = globalFuncAvailableOn10_52(); } while #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}} } } // Tests for Fix-It replacement text // The whitespace in the replacement text is particularly important here -- it reflects the level // of indentation for the added if #available() or @available attribute. Note that, for the moment, we hard // code *added* indentation in Fix-Its as 4 spaces (that is, when indenting in a Fix-It, we // take whatever indentation was there before and add 4 spaces to it). functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{1-27=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n} else {\n // Fallback on earlier versions\n}}} let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{1-57=if #available(macOS 10.51, *) {\n let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil\n} else {\n // Fallback on earlier versions\n}}} func fixitForReferenceInGlobalFunction() { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } public func fixitForReferenceInGlobalFunctionWithDeclModifier() { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func fixitForReferenceInGlobalFunctionWithAttribute() -> Never { // expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}} _ = 0 // Avoid treating the call to functionAvailableOn10_51 as an implicit return functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func takesAutoclosure(_ c : @autoclosure () -> ()) { } class ClassForFixit { // expected-note@-1 12{{add @available attribute to enclosing class}} {{1-1=@available(macOS 10.51, *)\n}} func fixitForReferenceInMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } func fixitForReferenceNestedInMethod() { // expected-note@-1 3{{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} func inner() { functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } let _: () -> () = { () in functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } takesAutoclosure(functionAvailableOn10_51()) // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-49=if #available(macOS 10.51, *) {\n takesAutoclosure(functionAvailableOn10_51())\n } else {\n // Fallback on earlier versions\n }}} } var fixitForReferenceInPropertyAccessor: Int { // expected-note@-1 {{add @available attribute to enclosing property}} {{3-3=@available(macOS 10.51, *)\n }} get { functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} return 5 } } var fixitForReferenceInPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} lazy var fixitForReferenceInLazyPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} private lazy var fixitForReferenceInPrivateLazyPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} lazy private var fixitForReferenceInLazyPrivatePropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} static var fixitForReferenceInStaticPropertyType: ClassAvailableOn10_51? = nil // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add @available attribute to enclosing static property}} {{3-3=@available(macOS 10.51, *)\n }} var fixitForReferenceInPropertyTypeMultiple: ClassAvailableOn10_51? = nil, other: Int = 7 // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} func fixitForRefInGuardOfIf() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} if (globalFuncAvailableOn10_51() > 1066) { let _ = 5 let _ = 6 } // expected-error@-4 {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-5 {{add 'if #available' version check}} {{5-6=if #available(macOS 10.51, *) {\n if (globalFuncAvailableOn10_51() > 1066) {\n let _ = 5\n let _ = 6\n }\n } else {\n // Fallback on earlier versions\n }}} } } extension ClassToExtend { // expected-note@-1 {{add @available attribute to enclosing extension}} func fixitForReferenceInExtensionMethod() { // expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }} functionAvailableOn10_51() // expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}} } } enum EnumForFixit { // expected-note@-1 2{{add @available attribute to enclosing enum}} {{1-1=@available(macOS 10.51, *)\n}} case CaseWithPotentiallyUnavailablePayload(p: ClassAvailableOn10_51) // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} case CaseWithPotentiallyUnavailablePayload2(p: ClassAvailableOn10_51), WithoutPayload // expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} } @objc class Y { var z = 0 } @objc class X { @objc var y = Y() } func testForFixitWithNestedMemberRefExpr() { // expected-note@-1 2{{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.52, *)\n}} let x = X() x.y.z = globalFuncAvailableOn10_52() // expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-39=if #available(macOS 10.52, *) {\n x.y.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}} // Access via dynamic member reference let anyX: AnyObject = x anyX.y?.z = globalFuncAvailableOn10_52() // expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}} // expected-note@-2 {{add 'if #available' version check}} {{3-43=if #available(macOS 10.52, *) {\n anyX.y?.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}} } // Protocol Conformances protocol ProtocolWithRequirementMentioningPotentiallyUnavailable { // expected-note@-1 2{{add @available attribute to enclosing protocol}} func hasPotentiallyUnavailableParameter(_ p: ClassAvailableOn10_51) // expected-error * {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing instance method}} func hasPotentiallyUnavailableReturn() -> ClassAvailableOn10_51 // expected-error * {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 * {{add @available attribute to enclosing instance method}} @available(OSX 10.51, *) func hasPotentiallyUnavailableWithAnnotation(_ p: ClassAvailableOn10_51) -> ClassAvailableOn10_51 } protocol HasMethodF { associatedtype T func f(_ p: T) // expected-note 3{{protocol requirement here}} } class TriesToConformWithFunctionIntroducedOn10_51 : HasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50.0 and newer}} } class ConformsWithFunctionIntroducedOnMinimumDeploymentTarget : HasMethodF { // Even though this function is less available than its requirement, // it is available on a deployment targets, so the conformance is safe. @available(OSX, introduced: 10.9) func f(_ p: Int) { } } class SuperHasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-note {{'f' declared here}} } class TriesToConformWithPotentiallyUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50.0 and newer}} // The conformance here is generating an error on f in the super class. } @available(OSX, introduced: 10.51) class ConformsWithPotentiallyUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // Limiting this class to only be available on 10.51 and newer means that // the witness in SuperHasMethodF is safe for the requirement on HasMethodF. // in order for this class to be referenced we must be running on 10.51 or // greater. } class ConformsByOverridingFunctionInSuperClass : SuperHasMethodF, HasMethodF { // Now the witness is this f() (which is always available) and not the f() // from the super class, so conformance is safe. override func f(_ p: Int) { } } // Attempt to conform in protocol extension with unavailable witness // in extension class HasNoMethodF1 { } extension HasNoMethodF1 : HasMethodF { @available(OSX, introduced: 10.51) func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50.0 and newer}} } class HasNoMethodF2 { } @available(OSX, introduced: 10.51) extension HasNoMethodF2 : HasMethodF { // This is OK, because the conformance was introduced by an extension. func f(_ p: Int) { } } @available(OSX, introduced: 10.51) class HasNoMethodF3 { } @available(OSX, introduced: 10.51) extension HasNoMethodF3 : HasMethodF { // We expect this conformance to succeed because on every version where HasNoMethodF3 // is available, HasNoMethodF3's f() is as available as the protocol requirement func f(_ p: Int) { } } @available(OSX, introduced: 10.51) protocol HasMethodFOn10_51 { func f(_ p: Int) } class ConformsToPotentiallyUnavailableProtocolWithPotentiallyUnavailableWitness : HasMethodFOn10_51 { @available(OSX, introduced: 10.51) func f(_ p: Int) { } } @available(OSX, introduced: 10.51) class HasNoMethodF4 { } @available(OSX, introduced: 10.52) extension HasNoMethodF4 : HasMethodFOn10_51 { // This is OK, because the conformance was introduced by an extension. func f(_ p: Int) { } } @available(OSX, introduced: 10.51) protocol HasTakesClassAvailableOn10_51 { func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) // expected-note 2{{protocol requirement here}} } class AttemptsToConformToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.52) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available in macOS 10.51 and newer}} } } class ConformsToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.51) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { } } class TakesClassAvailableOn10_51_A { } extension TakesClassAvailableOn10_51_A : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.52) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available in macOS 10.51 and newer}} } } class TakesClassAvailableOn10_51_B { } extension TakesClassAvailableOn10_51_B : HasTakesClassAvailableOn10_51 { @available(OSX, introduced: 10.51) func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { } } // We want conditional availability to play a role in picking a witness for a // protocol requirement. class TestAvailabilityAffectsWitnessCandidacy : HasMethodF { // Test that we choose the less specialized witness, because the more specialized // witness is conditionally unavailable. @available(OSX, introduced: 10.51) func f(_ p: Int) { } func f<T>(_ p: T) { } } protocol HasPotentiallyUnavailableMethodF { @available(OSX, introduced: 10.51) func f(_ p: String) } class ConformsWithPotentiallyUnavailableFunction : HasPotentiallyUnavailableMethodF { @available(OSX, introduced: 10.9) func f(_ p: String) { } } func usePotentiallyUnavailableProtocolMethod(_ h: HasPotentiallyUnavailableMethodF) { // expected-note@-1 {{add @available attribute to enclosing global function}} h.f("Foo") // expected-error {{'f' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func usePotentiallyUnavailableProtocolMethod<H : HasPotentiallyUnavailableMethodF> (_ h: H) { // expected-note@-1 {{add @available attribute to enclosing global function}} h.f("Foo") // expected-error {{'f' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Short-form @available() annotations @available(OSX 10.51, *) class ClassWithShortFormAvailableOn10_51 { } @available(OSX 10.53, *) class ClassWithShortFormAvailableOn10_53 { } @available(OSX 10.54, *) class ClassWithShortFormAvailableOn10_54 { } @available(OSX 10.9, *) func funcWithShortFormAvailableOn10_9() { let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(OSX 10.51, *) func funcWithShortFormAvailableOn10_51() { let _ = ClassWithShortFormAvailableOn10_51() } @available(iOS 14.0, *) func funcWithShortFormAvailableOniOS14() { // expected-note@-1 {{add @available attribute to enclosing global function}} let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} } @available(iOS 14.0, OSX 10.53, *) func funcWithShortFormAvailableOniOS14AndOSX10_53() { let _ = ClassWithShortFormAvailableOn10_51() } // Not idiomatic but we need to be able to handle it. @available(iOS 8.0, *) @available(OSX 10.51, *) func funcWithMultipleShortFormAnnotationsForDifferentPlatforms() { let _ = ClassWithShortFormAvailableOn10_51() } @available(OSX 10.51, *) @available(OSX 10.53, *) @available(OSX 10.52, *) func funcWithMultipleShortFormAnnotationsForTheSamePlatform() { let _ = ClassWithShortFormAvailableOn10_53() let _ = ClassWithShortFormAvailableOn10_54() // expected-error {{'ClassWithShortFormAvailableOn10_54' is only available in macOS 10.54 or newer}} // expected-note@-1 {{add 'if #available' version check}} } func useShortFormAvailable() { // expected-note@-1 4{{add @available attribute to enclosing global function}} funcWithShortFormAvailableOn10_9() funcWithShortFormAvailableOn10_51() // expected-error {{'funcWithShortFormAvailableOn10_51()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithShortFormAvailableOniOS14() funcWithShortFormAvailableOniOS14AndOSX10_53() // expected-error {{'funcWithShortFormAvailableOniOS14AndOSX10_53()' is only available in macOS 10.53 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithMultipleShortFormAnnotationsForDifferentPlatforms() // expected-error {{'funcWithMultipleShortFormAnnotationsForDifferentPlatforms()' is only available in macOS 10.51 or newer}} // expected-note@-1 {{add 'if #available' version check}} funcWithMultipleShortFormAnnotationsForTheSamePlatform() // expected-error {{'funcWithMultipleShortFormAnnotationsForTheSamePlatform()' is only available in macOS 10.53 or newer}} // expected-note@-1 {{add 'if #available' version check}} } // Unavailability takes precedence over availability and is inherited @available(OSX 10.9, *) @available(OSX, unavailable) func unavailableWins() { } // expected-note@-1 {{'unavailableWins()' has been explicitly marked unavailable here}} struct HasUnavailableExtension { @available(OSX, unavailable) public func directlyUnavailable() { } // expected-note@-1 {{'directlyUnavailable()' has been explicitly marked unavailable here}} } @available(OSX, unavailable) extension HasUnavailableExtension { public func inheritsUnavailable() { } // expected-note@-1 {{'inheritsUnavailable()' has been explicitly marked unavailable here}} @available(OSX 10.9, *) public func moreAvailableButStillUnavailable() { } // expected-note@-1 {{'moreAvailableButStillUnavailable()' has been explicitly marked unavailable here}} } func useHasUnavailableExtension(_ s: HasUnavailableExtension) { unavailableWins() // expected-error {{'unavailableWins()' is unavailable}} s.directlyUnavailable() // expected-error {{'directlyUnavailable()' is unavailable}} s.inheritsUnavailable() // expected-error {{'inheritsUnavailable()' is unavailable in macOS}} s.moreAvailableButStillUnavailable() // expected-error {{'moreAvailableButStillUnavailable()' is unavailable in macOS}} }
apache-2.0
6d96e15da85ef8dec1eb587a0e3db6c6
41.059161
357
0.715056
3.850705
false
false
false
false
space-app-challenge-london/iOS-client
SpaceApps001/ListView.swift
1
1583
// // ListViewViewController.swift // SpaceApps001 // // Created by Remi Robert on 29/04/2017. // Copyright © 2017 Bratt Neumayer. All rights reserved. // import UIKit import Cartography import RxSwift import RxCocoa class ListView<C, M>: UITableView, UITableViewDelegate where C: CellType, M == C.Model { var modelSelect: Observable<M> { return self.rx.itemSelected.flatMap({ indexPath in return Observable.just(self.source.datas[indexPath.row]) }) } var source: DataSource<C, M>! private func comonInit(datas: [M] = []) { source = DataSource<C, M>(tableview: self, datas: datas) configureTableView() } init(datas: [M] = []) { super.init(frame: CGRect.zero, style: .plain) comonInit(datas: datas) } override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) comonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func configureTableView() { self.registerCell(identifier: C.identifier) tableFooterView = UIView() backgroundColor = UIColor.clear delegate = self } open func reset() { guard let indexPath = indexPathForSelectedRow else {return} deselectRow(at: indexPath, animated: false) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let model = source.datas[indexPath.row] return C.height(model: model) } }
mit
cfd962ee80cd995b83da319f73f41a76
25.813559
94
0.641593
4.207447
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Browser/SessionRestoreHelper.swift
1
1213
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit protocol SessionRestoreHelperDelegate: class { func sessionRestoreHelper(helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) } class SessionRestoreHelper: TabHelper { weak var delegate: SessionRestoreHelperDelegate? private weak var tab: Tab? required init(tab: Tab) { self.tab = tab } func scriptMessageHandlerName() -> String? { return "sessionRestoreHelper" } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let tab = tab, params = message.body as? [String: AnyObject] { if params["name"] as! String == "didRestoreSession" { dispatch_async(dispatch_get_main_queue()) { self.delegate?.sessionRestoreHelper(self, didRestoreSessionForTab: tab) } } } } class func name() -> String { return "SessionRestoreHelper" } }
mpl-2.0
025aadf1cfea60f75ca9a57538412cac
31.810811
130
0.671063
4.852
false
false
false
false
kripple/bti-watson
ios-app/Carthage/Checkouts/Starscream/SSLSecurity.swift
5
7728
////////////////////////////////////////////////////////////////////////////////////////////////// // // SSLSecurity.swift // Starscream // // Created by Dalton Cherry on 5/16/15. // Copyright (c) 2015 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import Security public class SSLCert { var certData: NSData? var key: SecKeyRef? /** Designated init for certificates - parameter data: is the binary data of the certificate - returns: a representation security object to be used with */ public init(data: NSData) { self.certData = data } /** Designated init for public keys - parameter key: is the public key to be used - returns: a representation security object to be used with */ public init(key: SecKeyRef) { self.key = key } } public class SSLSecurity { public var validatedDN = true //should the domain name be validated? var isReady = false //is the key processing done? var certificates: [NSData]? //the certificates var pubKeys: [SecKeyRef]? //the public keys var usePublicKeys = false //use public keys or certificate validation? /** Use certs from main app bundle - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public convenience init(usePublicKeys: Bool = false) { let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".") var collect = Array<SSLCert>() for path in paths { if let d = NSData(contentsOfFile: path as String) { collect.append(SSLCert(data: d)) } } self.init(certs:collect, usePublicKeys: usePublicKeys) } /** Designated init - parameter keys: is the certificates or public keys to use - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public init(certs: [SSLCert], usePublicKeys: Bool) { self.usePublicKeys = usePublicKeys if self.usePublicKeys { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), { var collect = Array<SecKeyRef>() for cert in certs { if let data = cert.certData where cert.key == nil { cert.key = self.extractPublicKey(data) } if let k = cert.key { collect.append(k) } } self.pubKeys = collect self.isReady = true }) } else { var collect = Array<NSData>() for cert in certs { if let d = cert.certData { collect.append(d) } } self.certificates = collect self.isReady = true } } /** Valid the trust and domain name. - parameter trust: is the serverTrust to validate - parameter domain: is the CN domain to validate - returns: if the key was successfully validated */ public func isValid(trust: SecTrustRef, domain: String?) -> Bool { var tries = 0 while(!self.isReady) { usleep(1000) tries += 1 if tries > 5 { return false //doesn't appear it is going to ever be ready... } } var policy: SecPolicyRef if self.validatedDN { policy = SecPolicyCreateSSL(true, domain) } else { policy = SecPolicyCreateBasicX509() } SecTrustSetPolicies(trust,policy) if self.usePublicKeys { if let keys = self.pubKeys { let serverPubKeys = publicKeyChainForTrust(trust) for serverKey in serverPubKeys as [AnyObject] { for key in keys as [AnyObject] { if serverKey.isEqual(key) { return true } } } } } else if let certs = self.certificates { let serverCerts = certificateChainForTrust(trust) var collect = Array<SecCertificate>() for cert in certs { collect.append(SecCertificateCreateWithData(nil,cert)!) } SecTrustSetAnchorCertificates(trust,collect) var result: SecTrustResultType = 0 SecTrustEvaluate(trust,&result) let r = Int(result) if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed { var trustedCount = 0 for serverCert in serverCerts { for cert in certs { if cert == serverCert { trustedCount++ break } } } if trustedCount == serverCerts.count { return true } } } return false } /** Get the public key from a certificate data - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKey(data: NSData) -> SecKeyRef? { let possibleCert = SecCertificateCreateWithData(nil,data) if let cert = possibleCert { return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509()) } return nil } /** Get the public key from a certificate - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? { var possibleTrust: SecTrust? SecTrustCreateWithCertificates(cert, policy, &possibleTrust) if let trust = possibleTrust { var result: SecTrustResultType = 0 SecTrustEvaluate(trust, &result) return SecTrustCopyPublicKey(trust) } return nil } /** Get the certificate chain for the trust - parameter trust: is the trust to lookup the certificate chain for - returns: the certificate chain for the trust */ func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> { var collect = Array<NSData>() for var i = 0; i < SecTrustGetCertificateCount(trust); i++ { let cert = SecTrustGetCertificateAtIndex(trust,i) collect.append(SecCertificateCopyData(cert!)) } return collect } /** Get the public key chain for the trust - parameter trust: is the trust to lookup the certificate chain and extract the public keys - returns: the public keys from the certifcate chain for the trust */ func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> { var collect = Array<SecKeyRef>() let policy = SecPolicyCreateBasicX509() for var i = 0; i < SecTrustGetCertificateCount(trust); i++ { let cert = SecTrustGetCertificateAtIndex(trust,i) if let key = extractPublicKeyFromCert(cert!, policy: policy) { collect.append(key) } } return collect } }
mit
0c00ea37a688766a0bb2039b8e0582d1
31.607595
121
0.548784
5.527897
false
false
false
false
auth0/Auth0.swift
Auth0Tests/UsersSpec.swift
1
12728
import Foundation import Quick import Nimble import OHHTTPStubs #if SWIFT_PACKAGE import OHHTTPStubsSwift #endif @testable import Auth0 private let Domain = "samples.auth0.com" private let Token = UUID().uuidString private let NonExistentUser = "auth0|notfound" private let Timeout: DispatchTimeInterval = .seconds(2) private let Provider = "facebook" class UsersSpec: QuickSpec { override func spec() { let users = Auth0.users(token: Token, domain: Domain) beforeEach { stub(condition: isHost(Domain)) { _ in catchAllResponse() }.name = "YOU SHALL NOT PASS!" } afterEach { HTTPStubs.removeAllStubs() } describe("GET /users/:identifier") { beforeEach { stub(condition: isUsersPath(Domain, identifier: UserId) && isMethodGET() && hasBearerToken(Token)) { _ in apiSuccessResponse(json: ["user_id": UserId, "email": SupportAtAuth0]) } .name = "User Fetch" stub(condition: isUsersPath(Domain, identifier: UserId) && isMethodGET() && hasQueryParameters(["fields": "user_id", "include_fields": "true"]) && hasBearerToken(Token)) { _ in apiSuccessResponse(json: ["user_id": UserId]) } .name = "User Fetch including fields" stub(condition: isUsersPath(Domain, identifier: UserId) && isMethodGET() && hasQueryParameters(["fields": "user_id", "include_fields": "false"]) && hasBearerToken(Token)) { _ in apiSuccessResponse(json: ["email": SupportAtAuth0]) } .name = "User Fetch excluding fields" } it("should return single user by id") { waitUntil(timeout: Timeout) { done in users.get(UserId).start { result in expect(result).to(haveObjectWithAttributes(["user_id", "email"])) done() } } } it("should return specified user fields") { waitUntil(timeout: Timeout) { done in users.get(UserId, fields: ["user_id"]).start { result in expect(result).to(haveObjectWithAttributes(["user_id"])) done() } } } it("should exclude specified user fields") { waitUntil(timeout: Timeout) { done in users.get(UserId, fields: ["user_id"], include: false).start { result in expect(result).to(haveObjectWithAttributes(["email"])) done() } } } it("should fail request with management error") { stub(condition: isUsersPath(Domain, identifier: NonExistentUser) && isMethodGET() && hasBearerToken(Token)) { _ in managementErrorResponse(error: "not_found", description: "not found user", code: "user_not_found", statusCode: 400)}.name = "user not found" waitUntil(timeout: Timeout) { done in users.get(NonExistentUser).start { result in expect(result).to(haveManagementError("not_found", description: "not found user", code: "user_not_found", statusCode: 400)) done() } } } it("should fail request with generic error") { stub(condition: isUsersPath(Domain, identifier: NonExistentUser) && isMethodGET() && hasBearerToken(Token)) { _ in return apiFailureResponse(string: "foo", statusCode: 400) }.name = "user not found" waitUntil(timeout: Timeout) { done in users.get(NonExistentUser).start { result in expect(result).to(haveManagementError(description: "foo", statusCode: 400)) done() } } } } describe("PATCH /users/:identifier") { it("should send attributes") { stub(condition: isUsersPath(Domain, identifier: UserId) && isMethodPATCH() && hasAllOf(["username": Support, "connection": Provider]) && hasBearerToken(Token)) { _ in apiSuccessResponse(json: ["user_id": UserId, "email": SupportAtAuth0, "username": Support, "connection": Provider]) } .name = "User Patch" waitUntil(timeout: Timeout) { done in let attributes = UserPatchAttributes().username(Support, connection: Provider) users.patch(UserId, attributes: attributes).start { result in expect(result).to(haveObjectWithAttributes(["user_id", "email", "username", "connection"])) done() } } } it("should patch userMetadata") { let metadata = ["role": "admin"] stub(condition: isUsersPath(Domain, identifier: UserId) && isMethodPATCH() && hasUserMetadata(metadata) && hasBearerToken(Token)) { _ in apiSuccessResponse(json: ["user_id": UserId, "email": SupportAtAuth0]) } .name = "User Patch user_metadata" waitUntil(timeout: Timeout) { done in users.patch(UserId, userMetadata: metadata).start { result in expect(result).to(haveObjectWithAttributes(["user_id", "email"])) done() } } } it("should fail request with management error") { stub(condition: isUsersPath(Domain, identifier: NonExistentUser) && isMethodPATCH() && hasBearerToken(Token)) { _ in managementErrorResponse(error: "not_found", description: "not found user", code: "user_not_found", statusCode: 400)}.name = "user not found" waitUntil(timeout: Timeout) { done in users.patch(NonExistentUser, attributes: UserPatchAttributes().blocked(true)).start { result in expect(result).to(haveManagementError("not_found", description: "not found user", code: "user_not_found", statusCode: 400)) done() } } } it("should fail request with generic error") { stub(condition: isUsersPath(Domain, identifier: NonExistentUser) && isMethodPATCH() && hasBearerToken(Token)) { _ in return apiFailureResponse(string: "foo", statusCode: 400) }.name = "user not found" waitUntil(timeout: Timeout) { done in users.patch(NonExistentUser, attributes: UserPatchAttributes().blocked(true)).start { result in expect(result).to(haveManagementError(description: "foo", statusCode: 400)) done() } } } } describe("PATCH /users/:identifier/identities") { it("should link with just a token") { stub(condition: isLinkPath(Domain, identifier: UserId) && isMethodPOST() && hasAllOf(["link_with": "token"]) && hasBearerToken(Token)) { _ in apiSuccessResponse(jsonArray: [["user_id": UserId, "email": SupportAtAuth0]])}.name = "user linked" waitUntil(timeout: Timeout) { done in users.link(UserId, withOtherUserToken: "token").start { result in expect(result).to(beSuccessful()) done() } } } it("should link without a token") { stub(condition: isLinkPath(Domain, identifier: UserId) && isMethodPOST() && hasAllOf(["user_id": "other_id", "provider": Provider]) && hasBearerToken(Token)) { _ in apiSuccessResponse(jsonArray: [["user_id": UserId, "email": SupportAtAuth0]])}.name = "user linked" waitUntil(timeout: Timeout) { done in users.link(UserId, withUser: "other_id", provider: Provider).start { result in expect(result).to(beSuccessful()) done() } } } it("should link without a token specifying a connection id") { stub(condition: isLinkPath(Domain, identifier: UserId) && isMethodPOST() && hasAllOf(["user_id": "other_id", "provider": Provider, "connection_id": "conn_1"]) && hasBearerToken(Token)) { _ in apiSuccessResponse(jsonArray: [["user_id": UserId, "email": SupportAtAuth0]])}.name = "user linked" waitUntil(timeout: Timeout) { done in users.link(UserId, withUser: "other_id", provider: Provider, connectionId: "conn_1").start { result in expect(result).to(beSuccessful()) done() } } } it("should fail request with management error") { stub(condition: isLinkPath(Domain, identifier: NonExistentUser) && isMethodPOST() && hasBearerToken(Token)) { _ in managementErrorResponse(error: "not_found", description: "not found user", code: "user_not_found", statusCode: 400)}.name = "user not found" waitUntil(timeout: Timeout) { done in users.link(NonExistentUser, withOtherUserToken: "token").start { result in expect(result).to(haveManagementError("not_found", description: "not found user", code: "user_not_found", statusCode: 400)) done() } } } it("should fail request with generic error") { stub(condition: isLinkPath(Domain, identifier: NonExistentUser) && isMethodPOST() && hasBearerToken(Token)) { _ in return apiFailureResponse(string: "foo", statusCode: 400) }.name = "user not found" waitUntil(timeout: Timeout) { done in users.link(NonExistentUser, withOtherUserToken: "token").start { result in expect(result).to(haveManagementError(description: "foo", statusCode: 400)) done() } } } } describe("DELETE /users/:identifier/identities/:provider/:identityId") { it("should unlink") { stub(condition: isUnlinkPath(Domain, identifier: "other_id", provider: Provider, identityId: UserId) && isMethodDELETE() && hasBearerToken(Token)) { _ in return apiSuccessResponse(jsonArray: []) }.name = "user unlinked" waitUntil(timeout: Timeout) { done in users.unlink(identityId: UserId, provider: Provider, fromUserId: "other_id").start { result in expect(result).to(beSuccessful()) done() } } } it("should fail request with management error") { stub(condition: isUnlinkPath(Domain, identifier: "other_id", provider: Provider, identityId: NonExistentUser) && isMethodDELETE() && hasBearerToken(Token)) { _ in return managementErrorResponse(error: "not_found", description: "not found user", code: "user_not_found", statusCode: 400) }.name = "user not found" waitUntil(timeout: Timeout) { done in users.unlink(identityId: NonExistentUser, provider: Provider, fromUserId: "other_id").start { result in expect(result).to(haveManagementError("not_found", description: "not found user", code: "user_not_found", statusCode: 400)) done() } } } it("should fail request with generic error") { stub(condition: isUnlinkPath(Domain, identifier: "other_id", provider: Provider, identityId: NonExistentUser) && isMethodDELETE() && hasBearerToken(Token)) { _ in return apiFailureResponse(string: "foo", statusCode: 400) }.name = "user not found" waitUntil(timeout: Timeout) { done in users.unlink(identityId: NonExistentUser, provider: Provider, fromUserId: "other_id").start { result in expect(result).to(haveManagementError(description: "foo", statusCode: 400)) done() } } } } } }
mit
3db9d3ed0d10ccd71c4176450186d6d6
49.110236
273
0.539833
4.950603
false
false
false
false
2RKowski/two-blobs
TwoBlobs/NowPlayingRepresentable.swift
1
1149
// // NowPlayingRepresentable.swift // TwoBlobs // // Created by Lësha Turkowski on 10/01/2017. // Copyright © 2017 Amblyofetus. All rights reserved. // import MediaPlayer typealias NowPlayingInfo = MediaItemDescription protocol NowPlayingRepresentable { var nowPlayingInfo: NowPlayingInfo { get } } struct MediaItemDescription { let artist: String let title: String let artwork: MPMediaItemArtwork? init(artist: String, title: String, artworkAssetName: String) { self.artist = artist self.title = title artwork = .from(assetWithName: artworkAssetName) } } extension MPMediaItemArtwork { static func from(assetWithName name: String) -> MPMediaItemArtwork? { guard let image = UIImage(named: name) else { return nil } let albumArt: MPMediaItemArtwork if #available(iOS 10.0, *) { albumArt = MPMediaItemArtwork(boundsSize: image.size) { _ in return image } } else { albumArt = MPMediaItemArtwork(image: image) } return albumArt } }
mit
e0c2ed1e21b704b52ef93bb3a5677896
23.404255
73
0.626853
4.662602
false
false
false
false
xusader/firefox-ios
Client/Frontend/Widgets/Toolbar.swift
3
2824
import Foundation import Snap class Toolbar : UIView { var drawTopBorder = false var drawBottomBorder = false var drawSeperators = false override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func drawLine(context: CGContextRef, start: CGPoint, end: CGPoint) { CGContextSetStrokeColorWithColor(context, UIColor.darkGrayColor().CGColor) CGContextSetLineWidth(context, 1) CGContextMoveToPoint(context, start.x, start.y) CGContextAddLineToPoint(context, end.x, end.y) CGContextStrokePath(context) } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() if drawTopBorder { drawLine(context, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0)) } if drawBottomBorder { drawLine(context, start: CGPoint(x: 0, y: frame.height), end: CGPoint(x: frame.width, y: frame.height)) } if drawSeperators { var skippedFirst = false for view in subviews { if let view = view as? UIView { if skippedFirst { let frame = view.frame drawLine(context, start: CGPoint(x: frame.origin.x, y: frame.origin.y), end: CGPoint(x: frame.origin.x, y: frame.origin.y + view.frame.height)) } else { skippedFirst = true } } } } } func addButtons(buttons: UIButton...) { for button in buttons { button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled) button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit addSubview(button) } } override func updateConstraints() { var prev: UIView? = nil for view in self.subviews { if let view = view as? UIView { view.snp_remakeConstraints { make in if let prev = prev { make.left.equalTo(prev.snp_right) } else { make.left.equalTo(self) } prev = view make.centerY.equalTo(self) make.height.equalTo(AppConstants.ToolbarHeight) make.width.equalTo(self).dividedBy(self.subviews.count) } } } super.updateConstraints() } }
mpl-2.0
12c8160667ef68b46f60b8be6fa82b27
33.45122
115
0.547096
5.060932
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Mac/RedditOS-master/RedditOs/RedditOsApp.swift
1
4034
// // RedditOsApp.swift // RedditOs // // Created by Thomas Ricouard on 08/07/2020. // import AppKit import SwiftUI import Backend @main struct RedditOsApp: App { @StateObject private var uiState = UIState.shared @StateObject private var localData = LocalDataStore() @SceneBuilder var body: some Scene { WindowGroup { NavigationView { SidebarView() } .frame(minWidth: 1300, minHeight: 800) .environmentObject(localData) .environmentObject(OauthClient.shared) .environmentObject(CurrentUserStore.shared) .environmentObject(uiState) .onOpenURL { url in OauthClient.shared.handleNextURL(url: url) } .sheet(item: $uiState.presentedSheetRoute, content: { $0.makeView() }) } .commands { CommandMenu("Subreddit") { Button(action: { uiState.selectedSubreddit?.listings = nil uiState.selectedSubreddit?.fetchListings() }) { Text("Refresh") } .disabled(uiState.selectedSubreddit != nil) .keyboardShortcut("r", modifiers: [.command]) Divider() Button(action: { if let subreddit = uiState.selectedSubreddit?.subreddit { let small = SubredditSmall.makeSubredditSmall(with: subreddit) if localData.favorites.contains(small) { localData.remove(favorite: small) } else { localData.add(favorite: small) } } }) { Text("Toggle favorite") } .disabled(uiState.selectedSubreddit != nil) .keyboardShortcut("f", modifiers: [.command, .shift]) } CommandMenu("Post") { Button(action: { uiState.selectedPost?.fechComments() }) { Text("Refresh comments") } .disabled(uiState.selectedPost != nil) .keyboardShortcut("r", modifiers: [.command, .shift]) Button(action: { uiState.selectedPost?.toggleSave() }) { Text(uiState.selectedPost?.post.saved == true ? "Unsave" : "Save") } .disabled(uiState.selectedPost != nil) .keyboardShortcut("s", modifiers: .command) Divider() Button(action: { uiState.selectedPost?.postVote(vote: .upvote) }) { Text("Upvote") } .disabled(uiState.selectedPost != nil) .keyboardShortcut(.upArrow, modifiers: .shift) Button(action: { uiState.selectedPost?.postVote(vote: .downvote) }) { Text("Downvote") } .disabled(uiState.selectedPost != nil) .keyboardShortcut(.downArrow, modifiers: .shift) } #if DEBUG CommandMenu("Debug") { Button(action: { switch OauthClient.shared.authState { case let .authenthicated(token): NSPasteboard.general.clearContents() NSPasteboard.general.setString(token, forType: .string) default: break } }) { Text("Copy oauth token to pasteboard") } } #endif } Settings { SettingsView() } } }
mit
12a596a5c5fe866d2f671492f8e99e99
32.89916
86
0.448686
5.641958
false
false
false
false
avito-tech/Marshroute
Marshroute/Sources/Transitions/TransitionContexts/RestoredTransitionContext.swift
1
3118
import UIKit /// Описание одного из совершенных обработчиком переходов, восстановленное из истории /// Заведомо известно, что живы все участники изначального перехода. /// Отличается от CompletedTransitionContext тем, что все поля в нем уже не `optional` и не `weak` public struct RestoredTransitionContext { /// идентификатор перехода /// для точной отмены нужного перехода и возвращения на предыдущий экран через /// ```swift /// undoTransitionWith(transitionId:) public let transitionId: TransitionId /// обработчик переходов для роутера модуля, с контоллера которого перешли public let sourceTransitionsHandler: AnimatingTransitionsHandler /// контроллер, на который перешли public let targetViewController: UIViewController /// обработчик переходов для роутера модуля, на контроллер которого перешли public let targetTransitionsHandlerBox: RestoredTransitionTargetTransitionsHandlerBox /// параметры перехода, на которые нужно держать сильную ссылку (например, обработчик переходов SplitViewController'а) public let storableParameters: TransitionStorableParameters? /// параметры запуска анимации перехода public let sourceAnimationLaunchingContextBox: SourceAnimationLaunchingContextBox } // MARK: - Init public extension RestoredTransitionContext { init?(completedTransition context: CompletedTransitionContext?) { guard let context = context else { return nil } guard let sourceTransitionsHandler = context.sourceTransitionsHandler else { return nil } guard let targetViewController = context.targetViewController else { return nil } guard let targetTransitionsHandlerBox = RestoredTransitionTargetTransitionsHandlerBox( completedTransitionTargetTransitionsHandlerBox: context.targetTransitionsHandlerBox) else { return nil } self.transitionId = context.transitionId self.sourceTransitionsHandler = sourceTransitionsHandler self.targetViewController = targetViewController self.targetTransitionsHandlerBox = targetTransitionsHandlerBox self.storableParameters = context.storableParameters self.sourceAnimationLaunchingContextBox = context.sourceAnimationLaunchingContextBox } } // MARK: - Equatable extension RestoredTransitionContext: Equatable {} public func ==(lhs: RestoredTransitionContext, rhs: RestoredTransitionContext) -> Bool { return lhs.transitionId == rhs.transitionId }
mit
4db03fe42b99867ee1ea3565f47d6fea
39.765625
122
0.740897
4.950664
false
false
false
false
february29/Learning
swift/Fch_Contact/Fch_Contact/AppClasses/ViewController/FontViewController.swift
1
3096
// // FontViewController.swift // Fch_Contact // // Created by bai on 2018/1/15. // Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved. // import UIKit import SnapKit class FontViewController: BBaseViewController ,UITableViewDelegate,UITableViewDataSource{ let dataArray = [FontSize.small,FontSize.middle,FontSize.large] lazy var tableView:UITableView = { let table = UITableView.init(frame: CGRect.zero, style: .grouped); table.showsVerticalScrollIndicator = false; table.showsHorizontalScrollIndicator = false; // table.estimatedRowHeight = 30; table.delegate = self; table.dataSource = self; table.setBackgroundColor(.tableBackground); table.setSeparatorColor(.primary); table.register(FontTableViewCell.self, forCellReuseIdentifier: "cell") table.rowHeight = UITableViewAutomaticDimension; // table.separatorStyle = .none; table.tableFooterView = UIView(); return table; }(); override func viewDidLoad() { super.viewDidLoad() self.title = BLocalizedString(key: "Font Size"); self.view.addSubview(self.tableView); self.tableView.snp.makeConstraints { (make) in make.left.right.top.bottom.equalToSuperview(); } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = FontTableViewCell.init(style: .default, reuseIdentifier: "cell"); cell.coloumLable1?.text = dataArray[indexPath.row].displayName; if indexPath.row == 0 { cell.coloumLable1?.font = UIFont.systemFont(ofSize: 11); }else if indexPath.row == 1{ cell.coloumLable1?.font = UIFont.systemFont(ofSize: 13); }else{ cell.coloumLable1?.font = UIFont.systemFont(ofSize: 15); } // cell.setSelected(true, animated: false); return cell; } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { FontCenter.shared.fontSize = dataArray[indexPath.row] ; let setting = UserDefaults.standard.getUserSettingModel() setting.fontSize = dataArray[indexPath.row]; UserDefaults.standard.setUserSettingModel(model: setting); } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 1; } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 45; } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return UIView(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
d880373f673751e27d09c9de2812fea5
27.95283
100
0.622353
5.031148
false
false
false
false
FreddyZeng/Charts
Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift
1
6513
// // BarChartDataEntry.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class BarChartDataEntry: ChartDataEntry { /// the values the stacked barchart holds private var _yVals: [Double]? /// the ranges for the individual stack values - automatically calculated private var _ranges: [Range]? /// the sum of all negative values this entry (if stacked) contains private var _negativeSum: Double = 0.0 /// the sum of all positive values this entry (if stacked) contains private var _positiveSum: Double = 0.0 public required init() { super.init() } /// 设置柱状图的线性渐变色 @objc public var linearGradientColors = [NSUIColor]() /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double) { super.init(x: x, y: y) } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double, data: AnyObject?) { super.init(x: x, y: y, data: data) } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double, icon: NSUIImage?) { super.init(x: x, y: y, icon: icon) } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double, icon: NSUIImage?, data: AnyObject?) { super.init(x: x, y: y, icon: icon, data: data) } /// Constructor for stacked bar entries. @objc public init(x: Double, yValues: [Double]) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues)) self._yVals = yValues calcPosNegSum() calcRanges() } /// Constructor for stacked bar entries. One data object for whole stack @objc public init(x: Double, yValues: [Double], data: AnyObject?) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues), data: data) self._yVals = yValues calcPosNegSum() calcRanges() } /// Constructor for stacked bar entries. One data object for whole stack @objc public init(x: Double, yValues: [Double], icon: NSUIImage?, data: AnyObject?) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues), icon: icon, data: data) self._yVals = yValues calcPosNegSum() calcRanges() } /// Constructor for stacked bar entries. One data object for whole stack @objc public init(x: Double, yValues: [Double], icon: NSUIImage?) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues), icon: icon) self._yVals = yValues calcPosNegSum() calcRanges() } @objc open func sumBelow(stackIndex :Int) -> Double { guard let yVals = _yVals else { return 0 } var remainder: Double = 0.0 var index = yVals.count - 1 while (index > stackIndex && index >= 0) { remainder += yVals[index] index -= 1 } return remainder } /// - returns: The sum of all negative values this entry (if stacked) contains. (this is a positive number) @objc open var negativeSum: Double { return _negativeSum } /// - returns: The sum of all positive values this entry (if stacked) contains. @objc open var positiveSum: Double { return _positiveSum } @objc open func calcPosNegSum() { guard let _yVals = _yVals else { _positiveSum = 0.0 _negativeSum = 0.0 return } var sumNeg: Double = 0.0 var sumPos: Double = 0.0 for f in _yVals { if f < 0.0 { sumNeg += -f } else { sumPos += f } } _negativeSum = sumNeg _positiveSum = sumPos } /// Splits up the stack-values of the given bar-entry into Range objects. /// - parameter entry: /// - returns: @objc open func calcRanges() { let values = yValues if values?.isEmpty != false { return } if _ranges == nil { _ranges = [Range]() } else { _ranges?.removeAll() } _ranges?.reserveCapacity(values!.count) var negRemain = -negativeSum var posRemain: Double = 0.0 for i in 0 ..< values!.count { let value = values![i] if value < 0 { _ranges?.append(Range(from: negRemain, to: negRemain - value)) negRemain -= value } else { _ranges?.append(Range(from: posRemain, to: posRemain + value)) posRemain += value } } } // MARK: Accessors /// the values the stacked barchart holds @objc open var isStacked: Bool { return _yVals != nil } /// the values the stacked barchart holds @objc open var yValues: [Double]? { get { return self._yVals } set { self.y = BarChartDataEntry.calcSum(values: newValue) self._yVals = newValue calcPosNegSum() calcRanges() } } /// - returns: The ranges of the individual stack-entries. Will return null if this entry is not stacked. @objc open var ranges: [Range]? { return _ranges } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! BarChartDataEntry copy._yVals = _yVals copy.y = y copy._negativeSum = _negativeSum return copy } /// Calculates the sum across all values of the given stack. /// /// - parameter vals: /// - returns: private static func calcSum(values: [Double]?) -> Double { guard let values = values else { return 0.0 } var sum = 0.0 for f in values { sum += f } return sum } }
apache-2.0
ab97a661eff0f56c9a111274b845d9fa
24.964
111
0.532275
4.501387
false
false
false
false
Electrode-iOS/ELCodable
ELCodable/Decimal.swift
1
7846
// // Decimal.swift // Decimal // // Created by Brandon Sneed on 11/7/15. // Copyright © 2015 WalmartLabs. All rights reserved. // import Foundation public struct Decimal { public let value: NSDecimalNumber /// Create an instance initialized to zero. public init() { value = NSDecimalNumber.zero } /// Create an instance initialized to `value`. public init(_ value: NSDecimalNumber) { self.value = value } public init(_ value: NSNumber) { self.value = NSDecimalNumber(decimal: value.decimalValue) } public init(_ value: Float) { self.value = NSDecimalNumber(value: value) } public init(_ value: Double) { self.value = NSDecimalNumber(value: value) } public init(_ value: String) { self.value = NSDecimalNumber(string: value) } public init(_ v: UInt8) { value = NSDecimalNumber(value: v) } public init(_ v: Int8) { value = NSDecimalNumber(value: v) } public init(_ v: UInt16) { value = NSDecimalNumber(value: v) } public init(_ v: Int16) { value = NSDecimalNumber(value: v) } public init(_ v: UInt32) { value = NSDecimalNumber(value: v) } public init(_ v: Int32) { value = NSDecimalNumber(value: v) } public init(_ v: UInt64) { value = NSDecimalNumber(value: v) } public init(_ v: Int64) { value = NSDecimalNumber(value: v) } public init(_ v: UInt) { value = NSDecimalNumber(value: v) } public init(_ v: Int) { value = NSDecimalNumber(value: v) } } extension Decimal: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(value.hash) } } extension Decimal: CustomStringConvertible { /// A textual representation of `self`. public var description: String { return String(reflecting: value) } } extension Decimal: CustomDebugStringConvertible { /// A textual representation of `self`. public var debugDescription: String { return String(reflecting: value) } } extension Decimal /*: FloatingPointType*/ { // It complains about _BitsType missing, no idea wtf that is. /// The positive infinity. public static var infinity: Decimal { return Decimal(Double.infinity) } /// A quiet NaN. public static var NaN: Decimal { return Decimal(NSDecimalNumber.notANumber) } /// A quiet NaN. public static var quietNaN: Decimal { return NaN } /// `true` iff `self` is negative. public var isSignMinus: Bool { guard let doubleValue = doubleValue else { return false } return (doubleValue.sign == .minus) } /// `true` iff `self` is normal (not zero, subnormal, infinity, or /// NaN). public var isNormal: Bool { return doubleValue?.isNormal ?? false } /// `true` iff `self` is zero, subnormal, or normal (not infinity /// or NaN). public var isFinite: Bool { return doubleValue?.isFinite ?? false } /// `true` iff `self` is +0.0 or -0.0. public var isZero: Bool { return doubleValue?.isZero ?? false } /// `true` iff `self` is subnormal. public var isSubnormal: Bool { return doubleValue?.isSubnormal ?? false } /// `true` iff `self` is infinity. public var isInfinite: Bool { return doubleValue?.isInfinite ?? false } /// `true` iff `self` is NaN. public var isNaN: Bool { return doubleValue?.isNaN ?? false } /// `true` iff `self` is a signaling NaN. public var isSignaling: Bool { return doubleValue?.isSignalingNaN ?? false } private var doubleValue: Double? { return value as? Double } } extension Decimal: Equatable { public static func ==(lhs: Decimal, rhs: Decimal) -> Bool { return lhs.value.compare(rhs.value) == .orderedSame } } extension Decimal: Comparable { public static func <(lhs: Decimal, rhs: Decimal) -> Bool { return lhs.value.compare(rhs.value) == .orderedAscending } public static func <=(lhs: Decimal, rhs: Decimal) -> Bool { let result = lhs.value.compare(rhs.value) if result == .orderedAscending { return true } else if result == .orderedSame { return true } return false } public static func >=(lhs: Decimal, rhs: Decimal) -> Bool { let result = lhs.value.compare(rhs.value) if result == .orderedDescending { return true } else if result == .orderedSame { return true } return false } public static func >(lhs: Decimal, rhs: Decimal) -> Bool { return lhs.value.compare(rhs.value) == .orderedDescending } } extension Decimal: ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.value = NSDecimalNumber(value: value as Int) } } // MARK: Addition operators public func +(lhs: Decimal, rhs: Decimal) -> Decimal { return Decimal(lhs.value.adding(rhs.value)) } public prefix func ++(lhs: Decimal) -> Decimal { return Decimal(lhs.value.adding(NSDecimalNumber.one)) } public postfix func ++(lhs: inout Decimal) -> Decimal { lhs = Decimal(lhs.value.adding(NSDecimalNumber.one)) return lhs } public func +=(lhs: inout Decimal, rhs: Decimal) { lhs = Decimal(lhs.value.adding(rhs.value)) } public func +=(lhs: inout Decimal, rhs: Int) { lhs = Decimal(lhs.value.adding(NSDecimalNumber(value: rhs as Int))) } public func +=(lhs: inout Decimal, rhs: Double) { lhs = Decimal(lhs.value.adding(NSDecimalNumber(value: rhs as Double))) } // MARK: Subtraction operators public prefix func -(x: Decimal) -> Decimal { return Decimal(x.value.multiplying(by: NSDecimalNumber(value: -1 as Int))) } public func -(lhs: Decimal, rhs: Decimal) -> Decimal { return Decimal(lhs.value.subtracting(rhs.value)) } public prefix func --(lhs: Decimal) -> Decimal { return Decimal(lhs.value.subtracting(NSDecimalNumber.one)) } public postfix func --(lhs: inout Decimal) -> Decimal { lhs = Decimal(lhs.value.subtracting(NSDecimalNumber.one)) return lhs } public func -=(lhs: inout Decimal, rhs: Decimal) { lhs = Decimal(lhs.value.subtracting(rhs.value)) } public func -=(lhs: inout Decimal, rhs: Int) { lhs = Decimal(lhs.value.subtracting(NSDecimalNumber(value: rhs as Int))) } public func -=(lhs: inout Decimal, rhs: Double) { lhs = Decimal(lhs.value.subtracting(NSDecimalNumber(value: rhs as Double))) } // MARK: Multiplication operators public func *(lhs: Decimal, rhs: Decimal) -> Decimal { return Decimal(lhs.value.multiplying(by: rhs.value)) } public func *=(lhs: inout Decimal, rhs: Decimal) { lhs = Decimal(lhs.value.multiplying(by: rhs.value)) } public func *=(lhs: inout Decimal, rhs: Int) { lhs = Decimal(lhs.value.multiplying(by: NSDecimalNumber(value: rhs as Int))) } public func *=(lhs: inout Decimal, rhs: Double) { lhs = Decimal(lhs.value.multiplying(by: NSDecimalNumber(value: rhs as Double))) } // MARK: Division operators public func /(lhs: Decimal, rhs: Decimal) -> Decimal { return Decimal(lhs.value.dividing(by: rhs.value)) } public func /=(lhs: inout Decimal, rhs: Decimal) { lhs = Decimal(lhs.value.dividing(by: rhs.value)) } public func /=(lhs: inout Decimal, rhs: Int) { lhs = Decimal(lhs.value.dividing(by: NSDecimalNumber(value: rhs as Int))) } public func /=(lhs: inout Decimal, rhs: Double) { lhs = Decimal(lhs.value.dividing(by: NSDecimalNumber(value: rhs as Double))) } // MARK: Power-of operators public func ^(lhs: Decimal, rhs: Int) -> Decimal { return Decimal(lhs.value.raising(toPower: rhs)) }
mit
9f3e5d3f4add380e4793dd0c817baaaa
26.051724
105
0.630593
4.002551
false
false
false
false
cocotutch/toaster-ios
Source/ToasterExample/ToastTextLabel.swift
2
1633
// // ToastTextLabel.swift // Muzik7 // // Created by Ben Deckys on 7/02/2016. // Copyright © 2016 Ben Deckys. All rights reserved. // import Foundation import UIKit class ToastTextLabel : UILabel { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) leftInset = 5 rightInset = 5 topInset = 5 bottomInset = 5 } @IBInspectable var topInset: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable var leftInset: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable var bottomInset: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable var rightInset: CGFloat = 0 { didSet { setNeedsDisplay() } } override func drawTextInRect(rect: CGRect) { super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(topInset, leftInset, bottomInset, rightInset))) } override func intrinsicContentSize() -> CGSize { var parentSize: CGSize = super.intrinsicContentSize() parentSize.width += leftInset+rightInset parentSize.height += topInset+bottomInset return parentSize } override func sizeThatFits(size: CGSize) -> CGSize { var parentSize: CGSize = super.sizeThatFits(size) parentSize.width += leftInset+rightInset parentSize.height += topInset+bottomInset return parentSize } }
mit
5b4e54d663651a2686b93686aad4030c
22.666667
121
0.591912
5.006135
false
false
false
false
sindanar/PDStrategy
Example/PDStrategy/PDStrategy/TitleValueScrollCell.swift
1
755
// // TitleValueScrollCell.swift // PDStrategy // // Created by Pavel Deminov on 09/01/2018. // Copyright © 2018 Pavel Deminov. All rights reserved. // import UIKit class TitleValueScrollCell: PDScrollViewCell { private(set) var titleLabel: UILabel! private(set) var valueLabel: UILabel! override func setup() { weak var wSelf = self self.backgroundColor = UIColor.white TitleValueBuilder.addTitle(to: self) { (titleLabel, valueLabel) in wSelf?.titleLabel = titleLabel; wSelf?.valueLabel = valueLabel; } } override func updateUI() { titleLabel.text = itemInfo?.pdTitle valueLabel.text = itemInfo?.pdValue as? String } }
mit
cd2e46106304012af4030e4e55535346
22.5625
74
0.627321
4.284091
false
false
false
false
visenze/visearch-sdk-swift
Example/Example/Lib/KRProgressHUD/KRActivityIndicatorView/KRActivityIndicatorViewStyle.swift
4
5528
// // KRActivityIndicatorViewStyle.swift // KRProgressIndicator // // Copyright © 2016年 Krimpedance. All rights reserved. // import UIKit /** KRActivityIndicatorView's style - Normal size(20x20) - **Black:** the color is a gradation to `.lightGrayColor()` from `.blackColor()`. - **White:** the color is a gradation to `UIColor(white: 0.7, alpha:1)` from `.whiteColor()`. - **Color(startColor, endColor):** the color is a gradation to `endColor` from `startColor`. - Large size(50x50) - **LargeBlack:** the color is same `.Black`. - **LargeWhite:** the color is same `.White`. - **LargeColor(startColor, endColor):** the color is same `.Color()`. */ public enum KRActivityIndicatorViewStyle { case black, white, color(UIColor, UIColor?) case largeBlack, largeWhite, largeColor(UIColor, UIColor?) } extension KRActivityIndicatorViewStyle { mutating func sizeToLarge() { switch self { case .black: self = .largeBlack case .white: self = .largeWhite case let .color(sc, ec): self = .largeColor(sc, ec) default: break } } mutating func sizeToDefault() { switch self { case .largeBlack: self = .black case .largeWhite: self = .white case let .largeColor(sc, ec): self = .color(sc, ec) default: break } } var isLargeStyle: Bool { switch self { case .black, .white, .color(_, _): return false case .largeBlack, .largeWhite, .largeColor(_, _): return true } } var startColor: UIColor { switch self { case .black, .largeBlack: return UIColor.black case .white, .largeWhite: return UIColor.white case let .color(start, _): return start case let .largeColor(start, _): return start } } var endColor: UIColor { switch self { case .black, .largeBlack: return UIColor.lightGray case .white, .largeWhite: return UIColor(white: 0.7, alpha: 1) case let .color(start, end): return end ?? start case let .largeColor(start, end): return end ?? start } } func getGradientColors() -> [CGColor] { let gradient = CAGradientLayer() gradient.frame = CGRect(x: 0, y: 0, width: 1, height: 70) gradient.colors = [startColor.cgColor, endColor.cgColor] var colors: [CGColor] = [startColor.cgColor] colors.append( // 中間色 contentsOf: (1..<7).map { let point = CGPoint(x: 0, y: 10*CGFloat($0)) return gradient.color(point: point).cgColor } ) colors.append(endColor.cgColor) return colors } func getPaths() -> [CGPath] { if isLargeStyle { return KRActivityIndicatorPath.largePaths } else { return KRActivityIndicatorPath.paths } } } /** * KRActivityIndicator Path --------- */ private struct KRActivityIndicatorPath { static let paths: [CGPath] = [ UIBezierPath(ovalIn: CGRect(x: 4.472, y: 0.209, width: 4.801, height: 4.801)).cgPath, UIBezierPath(ovalIn: CGRect(x: 0.407, y: 5.154, width: 4.321, height: 4.321)).cgPath, UIBezierPath(ovalIn: CGRect(x: 0.93, y: 11.765, width: 3.841, height: 3.841)).cgPath, UIBezierPath(ovalIn: CGRect(x: 5.874, y: 16.31, width: 3.361, height: 3.361)).cgPath, UIBezierPath(ovalIn: CGRect(x: 12.341, y: 16.126, width: 3.169, height: 3.169)).cgPath, UIBezierPath(ovalIn: CGRect(x: 16.912, y: 11.668, width: 2.641, height: 2.641)).cgPath, UIBezierPath(ovalIn: CGRect(x: 16.894, y: 5.573, width: 2.115, height: 2.115)).cgPath, UIBezierPath(ovalIn: CGRect(x: 12.293, y: 1.374, width: 1.901, height: 1.901)).cgPath, ] static let largePaths: [CGPath] = [ UIBezierPath(ovalIn: CGRect(x: 12.013, y: 1.962, width: 8.336, height: 8.336)).cgPath, UIBezierPath(ovalIn: CGRect(x: 1.668, y: 14.14, width: 7.502, height: 7.502)).cgPath, UIBezierPath(ovalIn: CGRect(x: 2.792, y: 30.484, width: 6.668, height: 6.668)).cgPath, UIBezierPath(ovalIn: CGRect(x: 14.968, y: 41.665, width: 5.835, height: 5.835)).cgPath, UIBezierPath(ovalIn: CGRect(x: 31.311, y: 41.381, width: 5.001, height: 5.001)).cgPath, UIBezierPath(ovalIn: CGRect(x: 42.496, y: 30.041, width: 4.168, height: 4.168)).cgPath, UIBezierPath(ovalIn: CGRect(x: 42.209, y: 14.515, width: 3.338, height: 3.338)).cgPath, UIBezierPath(ovalIn: CGRect(x: 30.857, y: 4.168, width: 2.501, height: 2.501)).cgPath, ] } /** * CAGradientLayer Extension ------------------------------ */ private extension CAGradientLayer { func color(point: CGPoint) -> UIColor { var pixel: [CUnsignedChar] = [0, 0, 0, 0] let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmap = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmap.rawValue) context?.translateBy(x: -point.x, y: -point.y) render(in: context!) let red: CGFloat = CGFloat(pixel[0])/255.0 let green: CGFloat = CGFloat(pixel[1])/255.0 let blue: CGFloat = CGFloat(pixel[2])/255.0 let alpha: CGFloat = CGFloat(pixel[3])/255.0 return UIColor(red:red, green: green, blue:blue, alpha:alpha) } }
mit
0c52e96ee9a0781d0fe00b54dff5b124
36.040268
151
0.604639
3.676882
false
false
false
false
OrangeJam/iSchool
iSchool/TimetableTableViewController.swift
1
5681
// // TimetableTableViewController.swift // iSchool // // Created by Björn Orri Sæmundsson on 11/09/14. // Copyright (c) 2014 OrangeJam. All rights reserved. // import UIKit class TimetableTableViewController: UITableViewController, UITableViewDataSource { @IBOutlet weak var emptyLabel: UILabel! var weekDay: WeekDay? = nil var dateFormatter: NSDateFormatter { let formatter = NSDateFormatter() formatter.dateFormat = "EEE d. MMM" return formatter } override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView(frame: CGRectZero) self.refreshControl?.addTarget(self, action: "reloadData", forControlEvents: .ValueChanged ) self.tableView.addSubview(emptyLabel) // Add listeners to make sure the red line is always in the correct position. // Add listener for foreground entering. NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadTableView", name: UIApplicationWillEnterForegroundNotification, object: nil) // Add listener for significant time changes (e.g. when a new day starts). NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadTableView", name: UIApplicationSignificantTimeChangeNotification, object: nil) // Set the width of the empty label to be the width of the screen. self.emptyLabel.frame = CGRect(x: 0, y: 0, width: self.tableView.bounds.width, height: self.emptyLabel.frame.height) // Set the text of the empty label. emptyLabel.text = NSLocalizedString("No classes", comment: "Text for the empty label when there are no classes") } // Function that calls self.tableView.reloadData(). // The only purpose is to use it as a selector. func reloadTableView() { self.tableView.reloadData() } override func viewDidAppear(animated: Bool) { let pvc = self.parentViewController! as TimetablePageViewController let deltaDays = weekDay!.rawValue - pvc.currentWeekDay pvc.navigationItem.title = calculateDateTitle(deltaDays) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // This line is to prevent the red line animation from stopping. self.tableView.reloadData() NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshData", name: Notification.classes.rawValue, object: nil ) NSNotificationCenter.defaultCenter().addObserver(self, selector: "endRefresh", name: Notification.networkError.rawValue, object: nil ) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let day = weekDay { let count = DataStore.sharedInstance.getClassesForDay(day).count self.emptyLabel.hidden = !(count == 0) return count } else { self.emptyLabel.hidden = false return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ClassCell", forIndexPath: indexPath) as ClassCell if let day = weekDay { let dayClasses = DataStore.sharedInstance.getClassesForDay(day) let c = dayClasses[indexPath.row] cell.setClass(c) // Update the table view at the end of this class. if c.isNow() { let interval = c.endDate.timeIntervalSinceNow dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { self.tableView.reloadData() }) } // Update the table view at the beginning of the next class. else if !c.isOver() { if indexPath.row == 0 || dayClasses[indexPath.row - 1].isOver() { let interval = c.startDate.timeIntervalSinceNow dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { self.tableView.reloadData() }) } } } return cell } func reloadData() { DataStore.sharedInstance.fetchClasses() } func endRefresh() { self.refreshControl?.endRefreshing() } func refreshData() { self.tableView.reloadData() endRefresh() } func calculateDateTitle(delta: Int) -> String { let deltaDay = NSDateComponents() deltaDay.setValue(delta, forComponent: NSCalendarUnit.DayCalendarUnit) let otherDay = NSCalendar.currentCalendar().dateByAddingComponents(deltaDay, toDate: NSDate(), options: NSCalendarOptions(0))! var date = dateFormatter.stringFromDate(otherDay) let firstLetter = date.substringToIndex(advance(date.startIndex,1)).uppercaseString date = firstLetter + date.substringFromIndex(advance(date.startIndex,1)) return date } }
bsd-3-clause
5ccbea79654d8ab836b064d81aa9f611
37.114094
158
0.634619
5.195791
false
false
false
false
xgdgsc/AlecrimCoreData
Examples/iOS/AlecrimCoreDataExample/MasterViewController.swift
1
4741
// // MasterViewController.swift // AlecrimCoreDataExample // // Created by Vanderlei Martinelli on 2014-11-30. // Copyright (c) 2014 Alecrim. All rights reserved. // import UIKit import CoreData import AlecrimCoreData class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil lazy var fetchedResultsController: FetchedResultsController<Event> = { let frc = dataContext.events.orderByDescending({ $0.timeStamp }).toFetchedResultsController() frc.bindToTableView(self.tableView) return frc }() override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { let newEvent = dataContext.events.createEntity() // Configure the new managed object. newEvent.timeStamp = NSDate() // Save the background data context. let (success, error) = dataContext.save() if !success { // Replace this implementation with code to handle the error appropriately. println("Unresolved error \(error), \(error?.userInfo)") } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let entity = self.fetchedResultsController.entityAtIndexPath(indexPath) let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = entity controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.fetchedResultsController.sections[section].numberOfEntities } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let entity = self.fetchedResultsController.entityAtIndexPath(indexPath) dataContext.events.deleteEntity(entity) if !dataContext.save().0 { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. abort() } } } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let entity = self.fetchedResultsController.entityAtIndexPath(indexPath) cell.textLabel?.text = entity.timeStamp.description } }
mit
75d4eb6cede3619dfc1895653149f81b
37.860656
194
0.681291
5.948557
false
false
false
false
freeskys/FRPinView
FRPinView/FRPinView/FRPinView.swift
1
4628
// // FRPinTextField.swift // FRPinTextField // // Created by Harditya on 10/24/16. // Copyright © 2016 PT DOT Indonesia. All rights reserved. // import UIKit @objc protocol FRPinDelegate { /// User has been filled all the PIN delegate /// /// - Parameter frPinView: frPinView The PIN view func frPin(didFinishInput frPinView: FRPinView) /// User delete PIN value /// /// - Parameter frPinView: frPinView The PIN view @objc optional func frPin(didDeletePin frPinView: FRPinView) } class FRPinView: UIView { // Variables var delegate: FRPinDelegate? var pin: String = "" var tempPin: String = "" var textFields = [UITextField]() var keyboardType: UIKeyboardType = .numberPad var pinViewWidth: Int { return (pinWidth * pinCount) + (pinSpacing * pinCount) } // Outlets @IBInspectable var pinCount: Int = 6 @IBInspectable var pinSpacing: Int = 4 @IBInspectable var pinWidth: Int = 36 @IBInspectable var pinHeight: Int = 36 @IBInspectable var pinCornerRadius: CGFloat = 5 @IBInspectable var pinBorderWidth: CGFloat = 1 init(size: Int, frame: CGRect) { super.init(frame: frame) // Styling textfield self.pinCount = size self.renderTextFields() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { // Add textfields textFields = [UITextField]() self.renderTextFields() } // MARK: - Functions func renderTextFields() { self.createTextFields() self.addRoundedTextField() } /// Generate textfield func createTextFields() { // Create textfield based on size for i in 0..<self.pinCount { let textField = UITextField() // Set textfield params textField.keyboardType = keyboardType textField.textAlignment = .center textField.backgroundColor = UIColor.white textField.tintColor = textField.backgroundColor textField.delegate = self textField.isSecureTextEntry = true // Styling textfield textField.layer.cornerRadius = self.pinCornerRadius textField.layer.borderWidth = self.pinBorderWidth textField.layer.borderColor = UIColor(red: 0.91, green: 0.91, blue: 0.91, alpha: 1.00).cgColor if i > 0 { textField.isUserInteractionEnabled = false } textFields.append(textField) } } /// Make textfield rounded func addRoundedTextField() { var nextX: Int = pinSpacing for i in 0..<pinCount { textFields[i].frame = CGRect(x: nextX, y: 10, width: pinWidth, height: pinHeight) nextX = nextX + pinSpacing + pinWidth self.addSubview(textFields[i]) } } /// Move forward to textfield /// /// - Parameter textField: textField Current textfield func moveFrom(currentTextField textField: UITextField) { for i in 0..<pinCount { if textField == textFields[i] { textFields[i+1].becomeFirstResponder() break } } } /// Move backward from textfield /// /// - Parameter textField: textField Current textfield func moveBackwardFrom(currentTextField textField: UITextField) { for i in 0..<pinCount { if textField == textFields[i] { textFields[i].text = "" textFields[i-1].becomeFirstResponder() break } } } /// Get text from all pin textfields /// /// - Returns: return String Text from all pin textfields func getText() -> String { return pin } /// Reset text values func resetText() { for i in 0..<pinCount { textFields[i].text = "" } } /// Make the first textfield become first responder func focus() { textFields[0].becomeFirstResponder() } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
mit
107e640ee582c09cdaf8519055eff30c
26.541667
106
0.557597
5.084615
false
false
false
false
nanoxd/Rex
Source/Signal.swift
1
3404
// // Signal.swift // Rex // // Created by Neil Pankey on 5/9/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa /// Applies `transform` to values from `signal` with non-`nil` results unwrapped and /// forwared on the returned signal. public func filterMap<T, U, E>(transform: T -> U?)(signal: Signal<T, E>) -> Signal<U, E> { return Signal { observer in signal.observe(next: { value in if let val = transform(value) { sendNext(observer, val) } }, error: { error in sendError(observer, error) }, completed: { sendCompleted(observer) }, interrupted: { sendInterrupted(observer) }) } } /// Returns a signal that drops `Error` events, replacing them with `Completed`. public func ignoreError<T, E>(signal: Signal<T, E>) -> Signal<T, NoError> { return signal |> ignoreError(replacement: .Completed) } /// Returns a signal that drops `Error` sending `replacement` terminal event instead. public func ignoreError<T, E>(#replacement: Event<T, NoError>)(signal: Signal<T, E>) -> Signal<T, NoError> { precondition(replacement.isTerminating) return Signal { observer in return signal.observe(Signal.Observer { event in switch event { case let .Next(value): sendNext(observer, value.value) case .Error: observer.put(replacement) case .Completed: sendCompleted(observer) case .Interrupted: sendInterrupted(observer) } }) } } /// Lifts values from `signal` into an optional. public func optionalize<T, E>(signal: Signal<T, E>) -> Signal<T?, E> { return signal |> map { Optional($0) } } /// Forwards events from `signal` until `interval`. Then if signal isn't completed yet, /// terminates with `event` on `scheduler`. /// /// If the interval is 0, the timeout will be scheduled immediately. The signal /// must complete synchronously (or on a faster scheduler) to avoid the timeout. public func timeoutAfter<T, E>(interval: NSTimeInterval, withEvent event: Event<T, E>, onScheduler scheduler: DateSchedulerType) -> Signal<T, E> -> Signal<T, E> { precondition(interval >= 0) precondition(event.isTerminating) return { signal in return Signal { observer in let disposable = CompositeDisposable() let date = scheduler.currentDate.dateByAddingTimeInterval(interval) disposable += scheduler.scheduleAfter(date) { observer.put(event) } disposable += signal.observe(observer) return disposable } } } /// Returns a signal that flattens sequences of elements. The inverse of `collect`. public func uncollect<S: SequenceType, E>(signal: Signal<S, E>) -> Signal<S.Generator.Element, E> { return Signal { observer in return signal.observe(Signal.Observer { event in switch event { case let .Next(sequence): map(sequence.value) { sendNext(observer, $0) } case let .Error(error): sendError(observer, error.value) case .Completed: sendCompleted(observer) case .Interrupted: sendInterrupted(observer) } }) } }
mit
96ce5ffe40d3f487b40adf2f54eaf9e1
33.383838
162
0.608989
4.380952
false
false
false
false
AchillesWang/Swift
Playground/Inheritance.playground/section-1.swift
1
870
// Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" /** * 车辆 */ class Vehicle{ /** * 轮子 */ var numberOfWheels:Int = 0 /** * 最大乘坐人数 */ var maxPassengers: Int = 0 func description() -> String { return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers" } init(){ numberOfWheels = 0; maxPassengers = 1; } } /** * 自行车 */ class Bicycle:Vehicle{ init() {//初始化器默认是不继承的 super.init(); numberOfWheels = 2; println("初始化-->Bicycle") } } class Tandem:Bicycle{ } let someVehicle = Vehicle() var str1 = someVehicle.description() let someBicycle = Bicycle() var str2 = someBicycle.description() let someTandem = Tandem() var str3 = someTandem.description()
apache-2.0
92cfb7875f3a31503be2ce62568b61bd
15
76
0.591912
3.457627
false
false
false
false
ryan-blunden/ga-mobile
Recipes/Recipes/AsyncImageViewController.swift
2
1615
// // AsyncImageViewController.swift // Recipes // // Created by Ryan Blunden on 9/06/2015. // Copyright (c) 2015 RabbitBird Pty Ltd. All rights reserved. // import UIKit class AsyncImageViewController: UIViewController { let syncImageURL = NSURL(string:"http://www.publicdomainpictures.net/pictures/50000/velka/sunset-background-1371188975Z2h.jpg")! let asyncImageURL = NSURL(string:"http://www.publicdomainpictures.net/pictures/50000/velka/sunset-in-antique-1373292453xCD.jpg")! @IBOutlet weak var imageView: UIImageView! @IBAction func onSyncButtonTapped(sender: AnyObject) { let data = NSData(contentsOfURL: syncImageURL) if let imageData = data { imageView.image = UIImage(data: imageData) } } @IBAction func onAsyncButtonTapped(sender: AnyObject) { // The request for our image let imageRequest = NSURLRequest(URL: asyncImageURL) // The operation queue our completionHandler closure will be called on upon completion // Apple states that calling any UIKit API must be done on the main thread (mainQueue) let mainQueue = NSOperationQueue.mainQueue() NSURLConnection.sendAsynchronousRequest(imageRequest, queue: mainQueue, completionHandler: { (response, data, error) -> Void in // If error is nil, everything is good and we have our image data if error == nil { self.imageView.image = UIImage(data: data!) } // Otherwise something went wrong else { Alerts.errorAlert(viewController: self, message: "Error downloading image: \(error.localizedDescription)") } }) } }
gpl-3.0
ccebeff28a0a7128d4aca04d22c82a4c
34.888889
131
0.712074
4.364865
false
false
false
false
bm842/TradingLibrary
Sources/PlaybackBroker.swift
2
2427
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ import Foundation public enum PlaybackStatus: RequestStatus { case success case serviceNotImplemented case noTick public var isSuccess: Bool { return self == .success } public var tradingHaltedForInstrument: Bool { return false } public var description: String { switch self { case .success: return "Success" case .serviceNotImplemented: return "Service not implemented" case .noTick: return "No tick" } } } public class PlaybackBroker: Broker { open var description: String open var accounts: [Account] public init(description: String) { self.description = description accounts = [ ] } open func refreshAccounts(_ completion: @escaping (RequestStatus) -> ()) { completion(PlaybackStatus.success) } open func addAccount(_ description: String, balance: Amount, currency: Currency) -> PlaybackAccount { let account = PlaybackAccount(description: description, balance: balance, currency: currency) accounts.append(account) account.broker = self return account } public func activate() { } public func invalidate() { } }
mit
7b974661131f8e2d4c539ed7f9667011
27.892857
103
0.684384
4.983573
false
false
false
false
dmoreh/HappySad-iOS
HappySad/SignUpViewController.swift
1
2581
// // SignUpViewController.swift // HappySad // // Created by Adam Reis on 1/17/16. // Copyright © 2016 Adam Reis. All rights reserved. // import UIKit class SignUpViewController : PFSignUpViewController { var backgroundImage : UIImageView!; // Colors let seeThroughColor = UIColor(red: 255/255, green: 253/255, blue: 243/255, alpha: 0.9) let darkBlueColor = UIColor(red: 14/255, green: 28/255, blue: 87/255, alpha: 1) let lightBlueColor = UIColor(red: 97/255, green: 187/255, blue: 223/255, alpha: 1) let greyColor = UIColor(red: 90/255, green: 90/255, blue: 90/255, alpha: 1) override func viewDidLoad() { super.viewDidLoad() // set our custom background image backgroundImage = UIImageView(image: UIImage(named: "launch_background")) backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill signUpView!.insertSubview(backgroundImage, atIndex: 0) // remove the parse Logo let logo = UILabel() logo.text = "Day to Day" logo.textColor = darkBlueColor logo.font = UIFont(name: "HelveticaNeue-Thin", size: 60) signUpView?.logo = logo self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal signUpView?.signUpButton?.setBackgroundImage(nil, forState: .Normal) signUpView?.signUpButton?.backgroundColor = lightBlueColor let emailStr = NSAttributedString(string: "Email", attributes: [NSForegroundColorAttributeName:greyColor]) let passwordStr = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName:greyColor]) signUpView?.usernameField?.attributedPlaceholder = emailStr signUpView?.passwordField?.attributedPlaceholder = passwordStr // make fields slightly see-through signUpView?.usernameField?.backgroundColor = seeThroughColor signUpView?.passwordField?.backgroundColor = seeThroughColor } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // stretch background image to fill screen backgroundImage.frame = CGRectMake( 0, 0, signUpView!.frame.width, signUpView!.frame.height) // position logo at top with larger frame signUpView!.logo!.sizeToFit() let logoFrame = signUpView!.logo!.frame signUpView!.logo!.frame = CGRectMake(logoFrame.origin.x, signUpView!.usernameField!.frame.origin.y - logoFrame.height - 140, signUpView!.frame.width, logoFrame.height) } }
mit
6a47a8c86e9dbf3ae11806111eb0d7b9
40.629032
176
0.681008
4.708029
false
false
false
false
superk589/DereGuide
DereGuide/Model/CGSSRankedSkill.swift
2
967
// // CGSSRankedSkill.swift // DereGuide // // Created by zzk on 16/8/8. // Copyright © 2016 zzk. All rights reserved. // import UIKit struct CGSSRankedSkill { var level: Int var skill: CGSSSkill var chance: Int { return skill.procChanceOfLevel(level) } var length: Int { return skill.effectLengthOfLevel(level) } var explainRanked: String { var explain = skill.explainEn! let subs = explain.match(pattern: "[0-9.]+ ~ [0-9.]+") let sub1 = subs[0] let range1 = explain.range(of: sub1 as String) explain.replaceSubrange(range1!, with: String(format: "%@", (Decimal(skill.procChanceOfLevel(level)) / 100).description)) let sub2 = subs[1] let range2 = explain.range(of: sub2 as String) explain.replaceSubrange(range2!, with: String(format: "%@", (Decimal(skill.effectLengthOfLevel(level)) / 100).description)) return explain } }
mit
751201c6edfbf80de6025b9a09af215e
27.411765
131
0.622153
3.788235
false
false
false
false
asp2insp/CodePathFinalProject
Pretto/SecondIntroView.swift
2
1926
// // SecondIntroView.swift // Pretto // // Created by Francisco de la Pena on 6/22/15. // Copyright (c) 2015 Pretto. All rights reserved. // import UIKit class SecondIntroView: UIView { @IBOutlet var mainView: UIView! @IBOutlet var flash1: UIImageView! @IBOutlet var flash2: UIImageView! /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ override init(frame: CGRect) { super.init(frame: frame) customInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) customInit() } private func customInit() { // 1. Load the interface file from .xib NSBundle.mainBundle().loadNibNamed("SecondIntroView", owner: self, options: nil) // 2. Some setup self.mainView.frame = self.bounds self.mainView.backgroundColor = UIColor.prettoIntroBlue() self.addAnimations() // 3. Add as a subview self.addSubview(self.mainView) } func animationTrigger() { self.addAnimations() } private func addAnimations(){ UIView.animateWithDuration(0.2, delay: 0.3, options: .Autoreverse | .CurveEaseIn, animations: { self.flash1.transform = CGAffineTransformMakeScale(2.0, 2.0) }, completion: { finished in self.flash1.transform = CGAffineTransformMakeScale(1.0, 1.0) }) UIView.animateWithDuration(0.2, delay: 0.4, options: .Autoreverse | .CurveEaseIn, animations: { self.flash2.transform = CGAffineTransformMakeScale(2.0, 2.0) }, completion: { finished in self.flash2.transform = CGAffineTransformMakeScale(1.0, 1.0) }) } }
mit
28d55c8c661b2b55e84b81ad284563e3
28.630769
103
0.61163
4.377273
false
false
false
false
Arcovv/CleanArchitectureRxSwift
RealmPlatform/Entities/RMAlbum.swift
1
1040
// // RMAlbum.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import QueryKit import Domain import RealmSwift import Realm final class RMAlbum: Object { dynamic var title: String = "" dynamic var uid: String = "" dynamic var userId: String = "" override class func primaryKey() -> String? { return "uid" } } extension RMAlbum { static var title: Attribute<String> { return Attribute("title")} static var userId: Attribute<String> { return Attribute("userId")} static var uid: Attribute<String> { return Attribute("uid")} } extension RMAlbum: DomainConvertibleType { func asDomain() -> Album { return Album(title: title, uid: uid, userId: userId) } } extension Album: RealmRepresentable { func asRealm() -> RMAlbum { return RMAlbum.build { object in object.title = title object.uid = uid object.userId = userId } } }
mit
c0dd3b3fddff9e7dff608748ea573def
21.586957
70
0.637151
4.156
false
false
false
false
mobistix/ios-charts
Charts/Classes/Renderers/TimelineVerticalAxisRenderer.swift
1
3752
// // TimelineVerticalAxisRenderer.swift // Pods // // Created by Rares Zehan on 11/04/16. // // import UIKit class TimelineVerticalAxisRenderer: ChartXAxisRendererHorizontalBarChart { public var showExtended = false public override func renderAxisLabels(context: CGContext) { guard let xAxis = xAxis else { return } if !xAxis.enabled || !xAxis.drawLabelsEnabled || chart?.data === nil { return } let xoffset = xAxis.xOffset if (xAxis.labelPosition == .top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else if (xAxis.labelPosition == .topInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if (xAxis.labelPosition == .bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if (xAxis.labelPosition == .bottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: showExtended ? 0.0 : 0.5)) } else if (xAxis.labelPosition == .bottomOutside) { let bar = self.chart?.data?.dataSets[0] as! IBarChartDataSet! let barSpace = bar?.barSpace ?? 0 let x = viewPortHandler.contentHeight * viewPortHandler.scaleY / CGFloat(xAxis.values.count) * (1.0 - barSpace) let anchor_y = CGFloat(x / xAxis.labelHeight)*0.5 + 1.0 drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: anchor_y)) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } } /// draws the x-labels on the specified y-position public override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint) { guard let xAxis = xAxis, let bd = chart?.data as? BarChartData else { return } let labelFont = xAxis.labelFont let labelTextColor = xAxis.labelTextColor let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0) let step = bd.dataSetCount for i in stride(from: self.minX, to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus) { let label = xAxis.values[i] if (label == nil) { continue } position.x = 0.0 position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0 // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step)) / 2.0 } position.y += 0.5 transformer.pointValueToPixel(&position) drawLabel(context: context, label: label!, xIndex: i, x: pos, y: position.y, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor], anchor: anchor, angleRadians: labelRotationAngleRadians) } } }
apache-2.0
f6b49fa0b58f83344aa70813017c57de
35.076923
239
0.567697
4.609337
false
false
false
false
sshams/puremvc-swift-standard-framework
PureMVC/org/puremvc/swift/core/Model.swift
1
4244
// // Model.swift // PureMVC SWIFT Standard // // Copyright(c) 2015-2025 Saad Shams <[email protected]> // Your reuse is governed by the Creative Commons Attribution 3.0 License // import Foundation /** A Singleton `IModel` implementation. In PureMVC, the `Model` class provides access to model objects (Proxies) by named lookup. The `Model` assumes these responsibilities: * Maintain a cache of `IProxy` instances. * Provide methods for registering, retrieving, and removing `IProxy` instances. Your application must register `IProxy` instances with the `Model`. Typically, you use an `ICommand` to create and register `IProxy` instances once the `Facade` has initialized the Core actors. `@see org.puremvc.swift.patterns.proxy.Proxy Proxy` `@see org.puremvc.swift.interfaces.IProxy IProxy` */ public class Model: IModel { // Mapping of proxyNames to IProxy instances private var proxyMap: [String: IProxy] // Singleton instance private static var instance: IModel? // to ensure operation happens only once private static var token: dispatch_once_t = 0 // Concurrent queue for proxyMap // for speed and convenience of running concurrently while reading, and thread safety of blocking while mutating private let proxyMapQueue = dispatch_queue_create("org.puremvc.model.proxyMapQueue", DISPATCH_QUEUE_CONCURRENT) /// Message constant public static let SINGLETON_MSG = "Model Singleton already constructed!" /** Constructor. This `IModel` implementation is a Singleton, so you should not call the constructor directly, but instead call the static Singleton Factory method `Model.getInstance()` @throws Error Error if Singleton instance has already been constructed */ public init() { assert(Model.instance == nil, Model.SINGLETON_MSG) proxyMap = [:] Model.instance = self initializeModel() } /** Initialize the Singleton `Model` instance. Called automatically by the constructor, this is your opportunity to initialize the Singleton instance in your subclass without overriding the constructor. */ public func initializeModel() { } /** `Model` Singleton Factory method. - parameter closure: reference that returns `IModel` - returns: the Singleton instance */ public class func getInstance(closure: () -> IModel) -> IModel { dispatch_once(&self.token) { self.instance = closure() } return instance! } /** Register an `IProxy` with the `Model`. - parameter proxy: an `IProxy` to be held by the `Model`. */ public func registerProxy(proxy: IProxy) { dispatch_barrier_sync(proxyMapQueue) { self.proxyMap[proxy.proxyName] = proxy proxy.onRegister() } } /** Retrieve an `IProxy` from the `Model`. - parameter proxyName: - returns: the `IProxy` instance previously registered with the given `proxyName`. */ public func retrieveProxy(proxyName: String) -> IProxy? { var proxy: IProxy? dispatch_sync(proxyMapQueue) { proxy = self.proxyMap[proxyName] } return proxy } /** Check if a Proxy is registered - parameter proxyName: - returns: whether a Proxy is currently registered with the given `proxyName`. */ public func hasProxy(proxyName: String) -> Bool { var result = false dispatch_sync(proxyMapQueue) { result = self.proxyMap[proxyName] != nil } return result } /** Remove an `IProxy` from the `Model`. - parameter proxyName: name of the `IProxy` instance to be removed. - returns: the `IProxy` that was removed from the `Model` */ public func removeProxy(proxyName: String) -> IProxy? { var removed: IProxy? dispatch_barrier_sync(proxyMapQueue) { if let proxy = self.proxyMap[proxyName] { proxy.onRemove() removed = self.proxyMap.removeValueForKey(proxyName) } } return removed } }
bsd-3-clause
2f78e01d1e3a5690cfc8f12bad54cb99
27.483221
116
0.644439
4.453305
false
false
false
false
dvSection8/dvSection8
Example/Pods/dvSection8/dvSection8/Classes/API/APIRequests.swift
1
544
// // Request.swift // Rush // // Created by MJ Roldan on 06/07/2017. // Copyright © 2017 Mark Joel Roldan. All rights reserved. // import Foundation public struct APIRequests { var method: HTTPMethod = .get var url: URL? = nil var parameters: Paremeters? = nil var headers: HTTPHeaders? = nil init(_ method: HTTPMethod, url: URL?, parameters: Paremeters?, headers: HTTPHeaders?) { self.method = method self.url = url self.parameters = parameters self.headers = headers } }
mit
6244f89a57dcb6db30e2d24703bf8ff6
20.72
91
0.629834
3.797203
false
false
false
false
accepton/accepton-apple
Pod/Vendor/Alamofire/Manager.swift
1
33997
// Manager.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. */ class Manager { // MARK: - Properties /** A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests. */ static let sharedInstance: Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ static let defaultHTTPHeaders: [String: String] = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage: String = { var components: [String] = [] for (index, languageCode) in (NSLocale.preferredLanguages() as [String]).enumerate() { let q = 1.0 - (Double(index) * 0.1) components.append("\(languageCode);q=\(q)") if q <= 0.5 { break } } return components.joinWithSeparator(",") }() // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) { return mutableUserAgent as String } } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) /// The underlying session. let session: NSURLSession /// The session delegate handling all the task and session delegate callbacks. let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. var startRequestsImmediately: Bool = true /** The background completion handler closure provided by the UIApplicationDelegate `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation will automatically call the handler. If you need to handle your own events before the handler is called, then you need to override the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. `nil` by default. */ var backgroundCompletionHandler: (() -> Void)? // MARK: - Lifecycle /** Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. - parameter configuration: The configuration used to construct the managed session. `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by default. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance. */ init( configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /** Initializes the `Manager` instance with the specified session, delegate and server trust policy. - parameter session: The URL session. - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. */ init?( session: NSURLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = session guard delegate === session.delegate else { return nil } commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Request /** Creates a request for the specified method, URL string, parameters, parameter encoding and headers. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 return request(encodedURLRequest) } /** Creates a request for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ func request(URLRequest: URLRequestConvertible) -> Request { var dataTask: NSURLSessionDataTask! dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } let request = Request(session: session, task: dataTask) delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: - SessionDelegate /** Responsible for handling all delegate callbacks for the underlying session. */ final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } } /** Initializes the `SessionDelegate` instance. - returns: The new `SessionDelegate` instance. */ override init() { super.init() } // MARK: - NSURLSessionDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { sessionDidBecomeInvalidWithError?(session, error) } /** Requests credentials from the delegate in response to a session-level authentication request from the remote server. - parameter session: The session containing the task that requested authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ func URLSession( session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { disposition = .UseCredential credential = NSURLCredential(forTrust: serverTrust) } else { disposition = .CancelAuthenticationChallenge } } } completionHandler(disposition, credential) } /** Tells the delegate that all messages enqueued for a session have been delivered. - parameter session: The session that no longer has any outstanding requests. */ func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the remote server requested an HTTP redirect. - parameter session: The session containing the task whose request resulted in a redirect. - parameter task: The task whose request resulted in a redirect. - parameter response: An object containing the server’s response to the original request. - parameter request: A URL request object filled out with the new location. - parameter completionHandler: A closure that your handler should call with either the value of the request parameter, a modified URL request object, or NULL to refuse the redirect and return the body of the redirect response. */ func URLSession( session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest?) -> Void)) { var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /** Requests credentials from the delegate in response to an authentication request from the remote server. - parameter session: The session containing the task whose request requires authentication. - parameter task: The task whose request requires authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ func URLSession( session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { if let taskDidReceiveChallenge = taskDidReceiveChallenge { completionHandler(taskDidReceiveChallenge(session, task, challenge)) } else if let delegate = self[task] { delegate.URLSession( session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler ) } else { URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) } } /** Tells the delegate when a task requires a new request body stream to send to the remote server. - parameter session: The session containing the task that needs a new body stream. - parameter task: The task that needs a new body stream. - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. */ func URLSession( session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) { if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) } } /** Periodically informs the delegate of the progress of sending body content to the server. - parameter session: The session containing the data task. - parameter task: The data task. - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. - parameter totalBytesSent: The total number of bytes sent so far. - parameter totalBytesExpectedToSend: The expected length of the body data. */ func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task] as? Request.UploadTaskDelegate { delegate.URLSession( session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } /** Tells the delegate that the task finished transferring data. - parameter session: The session containing the task whose request finished transferring data. - parameter task: The task whose request finished transferring data. - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. */ func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidComplete = taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = self[task] { delegate.URLSession(session, task: task, didCompleteWithError: error) } self[task] = nil } // MARK: - NSURLSessionDataDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? // MARK: Delegate Methods /** Tells the delegate that the data task received the initial reply (headers) from the server. - parameter session: The session containing the data task that received an initial reply. - parameter dataTask: The data task that received an initial reply. - parameter response: A URL response object populated with headers. - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a constant to indicate whether the transfer should continue as a data task or should become a download task. */ func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) { var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /** Tells the delegate that the data task was changed to a download task. - parameter session: The session containing the task that was replaced by a download task. - parameter dataTask: The data task that was replaced by a download task. - parameter downloadTask: The new download task that replaced the data task. */ func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) self[downloadTask] = downloadDelegate } } /** Tells the delegate that the data task has received some of the expected data. - parameter session: The session containing the data task that provided data. - parameter dataTask: The data task that provided data. - parameter data: A data object containing the transferred data. */ func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) } } /** Asks the delegate whether the data (or upload) task should store the response in the cache. - parameter session: The session containing the data (or upload) task. - parameter dataTask: The data (or upload) task. - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current caching policy and the values of certain received headers, such as the Pragma and Cache-Control headers. - parameter completionHandler: A block that your handler must call, providing either the original proposed response, a modified version of that response, or NULL to prevent caching the response. If your delegate implements this method, it must call this completion handler; otherwise, your app leaks memory. */ func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse?) -> Void)) { if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } // MARK: - NSURLSessionDownloadDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: Delegate Methods /** Tells the delegate that a download task has finished downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that finished. - parameter location: A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method. */ func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) } } /** Periodically informs the delegate about the download’s progress. - parameter session: The session containing the download task. - parameter downloadTask: The download task. - parameter bytesWritten: The number of bytes transferred since the last time this delegate method was called. - parameter totalBytesWritten: The total number of bytes transferred so far. - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is `NSURLSessionTransferSizeUnknown`. */ func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /** Tells the delegate that the download task has resumed downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that resumed. See explanation in the discussion. - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the existing content, then this value is zero. Otherwise, this value is an integer representing the number of bytes on disk that do not need to be retrieved again. - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is NSURLSessionTransferSizeUnknown. */ func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } // MARK: - NSURLSessionStreamDelegate var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? // MARK: - NSObject override func respondsToSelector(selector: Selector) -> Bool { switch selector { case "URLSession:didBecomeInvalidWithError:": return sessionDidBecomeInvalidWithError != nil case "URLSession:didReceiveChallenge:completionHandler:": return sessionDidReceiveChallenge != nil case "URLSessionDidFinishEventsForBackgroundURLSession:": return sessionDidFinishEventsForBackgroundURLSession != nil case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": return taskWillPerformHTTPRedirection != nil case "URLSession:dataTask:didReceiveResponse:completionHandler:": return dataTaskDidReceiveResponse != nil default: return self.dynamicType.instancesRespondToSelector(selector) } } } }
mit
552ef04b6c6b11a68c6848b5887ce583
47.486448
163
0.640295
6.650166
false
false
false
false
skonb/YapDatabaseExtensions
framework/Pods/PromiseKit/Sources/AnyPromise.swift
3
5189
import Foundation.NSError /** AnyPromise is a Promise that can be used in Objective-C code Swift code can only convert Promises to AnyPromises or vice versa. Libraries that only provide promises will require you to write a small Swift function that can convert those promises into AnyPromises as you require them. To effectively use AnyPromise in Objective-C code you must use `#import` rather than `@import PromiseKit;` #import <PromiseKit/PromiseKit.h> */ /** Resolution.Fulfilled takes an Any. When retrieving the Any you cannot convert it into an AnyObject?. By giving Fulfilled an object that has an AnyObject? property we never have to cast and everything is fine. */ private class Box { let obj: AnyObject? init(_ obj: AnyObject?) { self.obj = obj } } private func box(obj: AnyObject?) -> Resolution { if let error = obj as? NSError { unconsume(error) return .Rejected(error) } else { return .Fulfilled(Box(obj)) } } private func unbox(resolution: Resolution) -> AnyObject? { switch resolution { case .Fulfilled(let box): return (box as! Box).obj case .Rejected(let error): return error } } @objc(PMKAnyPromise) public class AnyPromise: NSObject { var state: State /** @return A new AnyPromise bound to a Promise<T>. The two promises represent the same task, any changes to either will instantly reflect on both. */ public init<T: AnyObject>(bound: Promise<T>) { //WARNING copy pasta from below. FIXME how? var resolve: ((Resolution) -> Void)! state = UnsealedState(resolver: &resolve) bound.pipe { resolution in switch resolution { case .Fulfilled: resolve(box(bound.value)) case .Rejected(let error): resolve(box(error)) } } } public init<T: AnyObject>(bound: Promise<T?>) { //WARNING copy pasta from above. FIXME how? var resolve: ((Resolution) -> Void)! state = UnsealedState(resolver: &resolve) bound.pipe { resolution in switch resolution { case .Fulfilled: resolve(box(bound.value!)) case .Rejected(let error): resolve(box(error)) } } } convenience public init(bound: Promise<Int>) { self.init(bound: bound.then(on: zalgo) { NSNumber(integer: $0) }) } convenience public init(bound: Promise<Void>) { self.init(bound: bound.then(on: zalgo) { _ -> AnyObject? in return nil }) } @objc init(@noescape bridge: ((AnyObject?) -> Void) -> Void) { var resolve: ((Resolution) -> Void)! state = UnsealedState(resolver: &resolve) bridge { result in func preresolve(obj: AnyObject?) { resolve(box(obj)) } if let next = result as? AnyPromise { next.pipe(preresolve) } else { preresolve(result) } } } @objc func pipe(body: (AnyObject?) -> Void) { state.get { seal in func prebody(resolution: Resolution) { body(unbox(resolution)) } switch seal { case .Pending(let handlers): handlers.append(prebody) case .Resolved(let resolution): prebody(resolution) } } } @objc var __value: AnyObject? { if let resolution = state.get() { return unbox(resolution) } else { return nil } } /** A promise starts pending and eventually resolves. @return True if the promise has not yet resolved. */ @objc public var pending: Bool { return state.get() == nil } /** A promise starts pending and eventually resolves. @return True if the promise has resolved. */ @objc public var resolved: Bool { return !pending } /** A promise starts pending and eventually resolves. A fulfilled promise is resolved and succeeded. @return True if the promise was fulfilled. */ @objc public var fulfilled: Bool { switch state.get() { case .Some(.Fulfilled): return true default: return false } } /** A promise starts pending and eventually resolves. A rejected promise is resolved and failed. @return True if the promise was rejected. */ @objc public var rejected: Bool { switch state.get() { case .Some(.Rejected): return true default: return false } } // because you can’t access top-level Swift functions in objc @objc class func setUnhandledErrorHandler(body: (NSError) -> Void) -> (NSError) -> Void { let oldHandler = PMKUnhandledErrorHandler PMKUnhandledErrorHandler = body return oldHandler } } extension AnyPromise: DebugPrintable { override public var debugDescription: String { return "AnyPromise: \(state)" } }
mit
021a6ed45fa2f775570f93231e0aa548
25.464286
93
0.583382
4.578111
false
false
false
false
jpavley/Emoji-Tac-Toe2
Watch Extension/InterfaceController.swift
1
7175
// // InterfaceController.swift // Watch Extension // // Created by John Pavley on 8/1/16. // Copyright © 2016 Epic Loot. All rights reserved. // import WatchKit import Foundation import WatchConnectivity class InterfaceController: WKInterfaceController { var gameEngine = GameEngine(noughtToken: "⭕️", crossToken: "❌", untouchedToken: "⬜️") @IBOutlet var titleLabel: WKInterfaceLabel! @IBOutlet var statusLabel: WKInterfaceLabel! // HINT: Only exists in 42mm layout @IBOutlet var button1: WKInterfaceButton! @IBOutlet var button2: WKInterfaceButton! @IBOutlet var button3: WKInterfaceButton! @IBOutlet var button4: WKInterfaceButton! @IBOutlet var button5: WKInterfaceButton! @IBOutlet var button6: WKInterfaceButton! @IBOutlet var button7: WKInterfaceButton! @IBOutlet var button8: WKInterfaceButton! @IBOutlet var button9: WKInterfaceButton! @IBAction func button1Action() { handleButtonPress(0) } @IBAction func button2Action() { handleButtonPress(1) } @IBAction func button3Action() { handleButtonPress(2) } @IBAction func button4Action() { handleButtonPress(3) } @IBAction func button5Action() { handleButtonPress(4) } @IBAction func button6Action() { handleButtonPress(5) } @IBAction func button7Action() { handleButtonPress(6) } @IBAction func button8Action() { handleButtonPress(7) } @IBAction func button9Action() { handleButtonPress(8) } func handleButtonPress(_ tag: Int) { if gameEngine.aiEnabled { return } if gameEngine.isGameOver() { newGame() return } if gameEngine.gameboard[tag] == .untouched { gameEngine.gameboard[tag] = gameEngine.activePlayerRole let titleText = (gameEngine.round == .playerOneRound) ? gameEngine.playerOne.token : gameEngine.playerTwo.token if let button = buttonForIndex(tag) { button.setTitle(titleText) } checkForEndGame() if !gameEngine.isGameOver() { gameEngine.nextRound() perform(#selector(self.aiTakeTurn), with: nil, afterDelay: 1) } } } func checkForEndGame() { let gameOver = checkForWinner() if gameOver { var winnerMark = "" var statusText = "" switch gameEngine.state { case .playerOneWin: winnerMark = gameEngine.playerOne.token statusText = "\(winnerMark) Wins!" case .playerTwoWin: winnerMark = gameEngine.playerOne.token statusText = "\(winnerMark) Wins!" case .draw: winnerMark = "😔" statusText = " no winner \(winnerMark)" default: print("error in checkForEndGame()") } if statusLabel != nil { statusLabel.setText(statusText) } else { titleLabel.setText(statusText) } } else { gameEngine.nextRound() if statusLabel != nil { let nextMark = gameEngine.activePlayerToken statusLabel.setText("\(nextMark)'s turn") } } } func checkForWinner() -> Bool { gameEngine.checkForWinOrDraw() if gameEngine.isGameOver() { if let winningVector = searchForWin(gameEngine.gameboard) { for cell in winningVector { if let button = buttonForIndex(cell) { button.setBackgroundColor(UIColor.gray) } } return true } } return false } func newGame() { // start with random emojis gameEngine.playerOne.token = emojis[diceRoll(emojis.count/2)] gameEngine.playerTwo.token = emojis[diceRoll(emojis.count/2) + emojis.count/2] gameEngine.nextGame() titleLabel.setText("\(gameEngine.playerOne.token) vs \(gameEngine.playerTwo.token)") if statusLabel != nil { statusLabel.setText("\(gameEngine.activePlayerToken)'s turn") } for i in 0..<gameEngine.gameboard.count { if let button = buttonForIndex(i) { button.setTitle(calcTitleForButton(i)) button.setBackgroundColor(UIColor.darkGray) } } } override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. newGame() } func calcTitleForButton(_ tag: Int) -> String { switch gameEngine.gameboard[tag] { case .untouched: return "" case .nought: return gameEngine.playerOne.token case .cross: return gameEngine.playerTwo.token } } func buttonForIndex(_ index: Int) -> WKInterfaceButton? { switch index { case 0: return button1 case 1: return button2 case 2: return button3 case 3: return button4 case 4: return button5 case 5: return button6 case 6: return button7 case 7: return button8 case 8: return button9 default: print(index) } return nil } @objc func aiTakeTurn() { let (aiCell, _) = aiChoose(gameEngine.gameboard, unpredicible: true) if let aiButton = buttonForIndex(aiCell) { aiButton.setTitle(gameEngine.playerTwo.token) gameEngine.gameboard[aiCell] = .cross gameEngine.nextRound() checkForEndGame() } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } // func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { // emojiGame.noughtMark = message["noughtMark"] as! String // emojiGame.crossMark = message["crossMark"] as! String // // titleLabel.setText("\(emojiGame.noughtMark) vs \(emojiGame.crossMark)") // // for i in 0..<emojiGame.gameBoard.count { // if let button = buttonForIndex(i) { // button.setTitle(calcTitleForButton(i)) // } // } // // } }
mit
44b9260e32281983119f7f4fa9738786
26.332061
92
0.536936
4.938621
false
false
false
false
loudnate/LoopKit
Extensions/NSData.swift
2
1631
// // NSData.swift // LoopKit // // Created by Nate Racklyeft on 8/26/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation // String conversion methods, adapted from https://stackoverflow.com/questions/40276322/hex-binary-string-conversion-in-swift/40278391#40278391 extension Data { init?(hexadecimalString: String) { self.init(capacity: hexadecimalString.utf16.count / 2) // Convert 0 ... 9, a ... f, A ...F to their decimal value, // return nil for all other input characters func decodeNibble(u: UInt16) -> UInt8? { switch u { case 0x30 ... 0x39: // '0'-'9' return UInt8(u - 0x30) case 0x41 ... 0x46: // 'A'-'F' return UInt8(u - 0x41 + 10) // 10 since 'A' is 10, not 0 case 0x61 ... 0x66: // 'a'-'f' return UInt8(u - 0x61 + 10) // 10 since 'a' is 10, not 0 default: return nil } } var even = true var byte: UInt8 = 0 for c in hexadecimalString.utf16 { guard let val = decodeNibble(u: c) else { return nil } if even { byte = val << 4 } else { byte += val self.append(byte) } even = !even } guard even else { return nil } } var hexadecimalString: String { return map { String(format: "%02hhx", $0) }.joined() } } extension Data { static func newPumpEventIdentifier() -> Data { return Data(UUID().uuidString.utf8) } }
mit
bde129fe691c50cb18cf8cfb04aa840f
28.107143
143
0.522086
3.790698
false
false
false
false
loganSims/wsdot-ios-app
wsdot/YouTubeStore.swift
2
2430
// // YouTubeStore.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import Alamofire import SwiftyJSON class YouTubeStore { typealias FetchVideosCompletion = (_ data: [YouTubeItem]?, _ error: Error?) -> () static func getVideos(_ completion: @escaping FetchVideosCompletion) { AF.request("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=10&playlistId=UUmWr7UYgRp4v_HvRfEgquXg&key=" + ApiKeys.getGoogleAPIKey()).validate().responseJSON { response in switch response.result { case .success: if let value = response.data { let json = JSON(value) let videoItems = parsePostsJSON(json) completion(videoItems, nil) } case .failure(let error): print(error) completion(nil, error) } } } fileprivate static func parsePostsJSON(_ json: JSON) ->[YouTubeItem]{ var videoItems = [YouTubeItem]() for (_,postJson):(String, JSON) in json["items"] { let post = YouTubeItem() post.title = postJson["snippet"]["title"].stringValue post.link = "https://www.youtube.com/watch?v=" + postJson["snippet"]["resourceId"]["videoId"].stringValue post.thumbnailLink = postJson["snippet"]["thumbnails"]["default"]["url"].stringValue post.published = TimeUtils.postPubDateToNSDate(postJson["snippet"]["publishedAt"].stringValue, formatStr: "yyyy-MM-dd'T'HH:mm:ss'Z'", isUTC: true) videoItems.append(post) } return videoItems } }
gpl-3.0
e16905fdebbbc29c33a7e5e41ad2eead
36.96875
207
0.628395
4.394213
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch6/6.4.1大小和相等比较.playground/section-1.swift
1
548
// Playground - noun: a place where people can play let 熊: String = "🐻" let 猫: String = "🐱" if 熊 > 猫 { println("🐻 大于 🐱") } else { println("🐻 小于 🐱") } let 🐼 = 熊 + 猫 if 🐼 == "🐻🐱" { println("🐼 是 🐻🐱") } else { println("🐼 不是 🐻🐱") } let emptyString1 = "" let emptyString2 = String() if emptyString1 == emptyString2 { println("相等") } else { println("不相等") } var a = "a" var b = "b" if a > b { println(">") } else { println("<") }
gpl-2.0
5eb7e3e0ca12820323d9017a0d32533f
11.540541
51
0.493534
2.535519
false
false
false
false
LoopKit/LoopKit
LoopKitUI/View Controllers/EmojiInputController.swift
1
5287
// // EmojiInputController.swift // LoopKit // // Copyright © 2017 LoopKit Authors. All rights reserved. // import UIKit public class EmojiInputController: UIInputViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, IdentifiableClass { @IBOutlet private weak var collectionView: UICollectionView! @IBOutlet private weak var sectionIndex: UIStackView! public weak var delegate: EmojiInputControllerDelegate? var emojis: EmojiDataSource! static func instance(withEmojis emojis: EmojiDataSource) -> EmojiInputController { let bundle = Bundle(for: self) let storyboard = UIStoryboard(name: className, bundle: bundle) let controller = storyboard.instantiateInitialViewController() as! EmojiInputController controller.emojis = emojis return controller } public override func viewDidLoad() { super.viewDidLoad() inputView = view as? UIInputView inputView?.allowsSelfSizing = true view.translatesAutoresizingMaskIntoConstraints = false if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.sectionHeadersPinToVisibleBounds = true layout.sectionFootersPinToVisibleBounds = true } setupSectionIndex() // Scroll to medium absorption DispatchQueue.main.async { self.collectionView.scrollToItem(at: IndexPath(row: 0, section: 1), at: .left, animated: false) } } private func setupSectionIndex() { sectionIndex.removeAllArrangedSubviews() for section in emojis.sections { let label = UILabel(frame: .zero) label.text = section.indexSymbol sectionIndex.addArrangedSubview(label) } } @IBOutlet weak var deleteButton: UIButton! { didSet { let image = UIImage(systemName: "delete.left", compatibleWith: traitCollection) deleteButton.setImage(image, for: .normal) } } // MARK: - Actions @IBAction func switchKeyboard(_ sender: Any) { delegate?.emojiInputControllerDidAdvanceToStandardInputMode(self) } @IBAction func deleteBackward(_ sender: Any) { inputView?.playInputClick​() textDocumentProxy.deleteBackward() } @IBAction func indexTouched(_ sender: UIGestureRecognizer) { let xLocation = max(0, sender.location(in: sectionIndex).x / sectionIndex.frame.width) let items = sectionIndex.arrangedSubviews.count let section = min(items - 1, Int(xLocation * CGFloat(items))) collectionView.scrollToItem(at: IndexPath(item: 0, section: section), at: .left, animated: false) } // MARK: - UICollectionViewDataSource public func numberOfSections(in collectionView: UICollectionView) -> Int { return emojis.sections.count } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return emojis.sections[section].items.count } public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kind == UICollectionView.elementKindSectionHeader ? EmojiInputHeaderView.className : "Footer", for: indexPath) if let cell = cell as? EmojiInputHeaderView { cell.titleLabel.text = emojis.sections[indexPath.section].title.localizedUppercase } return cell } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmojiInputCell.className, for: indexPath) as! EmojiInputCell cell.label.text = emojis.sections[indexPath.section].items[indexPath.row] return cell } // MARK: - UICollectionViewDelegateFlowLayout // MARK: - UICollectionViewDelegate public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) inputView?.playInputClick​() textDocumentProxy.insertText(emojis.sections[indexPath.section].items[indexPath.row]) delegate?.emojiInputControllerDidSelectItemInSection(indexPath.section) } } public protocol EmojiInputControllerDelegate: AnyObject { func emojiInputControllerDidAdvanceToStandardInputMode(_ controller: EmojiInputController) func emojiInputControllerDidSelectItemInSection(_ section: Int) } // MARK: - Default Implementations extension EmojiInputControllerDelegate { public func emojiInputControllerDidSelectItemInSection(_ section: Int) { } } extension UIInputView: UIInputViewAudioFeedback { public var enableInputClicksWhenVisible: Bool { return true } func playInputClick​() { let device = UIDevice.current device.playInputClick() } } private extension UIStackView { func removeAllArrangedSubviews() { for view in arrangedSubviews { view.removeFromSuperview() } } }
mit
21bd96bf742514c2f33e61f68100eee1
33.509804
212
0.713826
5.546218
false
false
false
false
zhihuitang/Apollo
Pods/SwiftMagic/SwiftMagic/Classes/Extensions/Extension+UIDevice.swift
1
2511
// // Extension+UIDevice.swift // SwiftMagic // // Created by Zhihui Tang on 2018-01-12. // import Foundation extension UIDevice { func MBFormatter(_ bytes: Int64) -> String { let formatter = ByteCountFormatter() formatter.allowedUnits = ByteCountFormatter.Units.useMB formatter.countStyle = ByteCountFormatter.CountStyle.decimal formatter.includesUnit = false return formatter.string(fromByteCount: bytes) as String } //MARK: Get String Value var totalDiskSpaceInGB:String { return ByteCountFormatter.string(fromByteCount: totalDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal) } var freeDiskSpaceInGB:String { return ByteCountFormatter.string(fromByteCount: freeDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal) } var usedDiskSpaceInGB:String { return ByteCountFormatter.string(fromByteCount: usedDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal) } var totalDiskSpaceInMB:String { return MBFormatter(totalDiskSpaceInBytes) } var freeDiskSpaceInMB:String { return MBFormatter(freeDiskSpaceInBytes) } var usedDiskSpaceInMB:String { return MBFormatter(usedDiskSpaceInBytes) } //MARK: Get raw value var totalDiskSpaceInBytes:Int64 { guard let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String), let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value else { return 0 } return space } var freeDiskSpaceInBytes:Int64 { if #available(iOS 11.0, *) { if let space = try? URL(fileURLWithPath: NSHomeDirectory() as String).resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage { return space ?? 0 } else { return 0 } } else { if let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String), let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value { return freeSpace } else { return 0 } } } var usedDiskSpaceInBytes:Int64 { return totalDiskSpaceInBytes - freeDiskSpaceInBytes } }
apache-2.0
d0c7923d9aef236cb3486f604b802f6e
33.875
210
0.674632
5.166667
false
false
false
false
jaynakus/Signals
SwiftSignalKit/Timer.swift
1
1429
import Foundation public final class Timer { private var timer: DispatchSourceTimer? private var timeout: Double private var `repeat`: Bool private var completion: (Void) -> Void private var queue: Queue public init(timeout: Double, `repeat`: Bool, completion: @escaping(Void) -> Void, queue: Queue) { self.timeout = timeout self.`repeat` = `repeat` self.completion = completion self.queue = queue } deinit { self.invalidate() } public func start() { let timer = DispatchSource.makeTimerSource(queue: self.queue.queue) timer.setEventHandler(handler: { [weak self] in if let strongSelf = self { strongSelf.completion() if !strongSelf.`repeat` { strongSelf.invalidate() } } }) self.timer = timer if self.`repeat` { let time: DispatchTime = DispatchTime.now() + self.timeout timer.scheduleRepeating(deadline: time, interval: self.timeout) } else { let time: DispatchTime = DispatchTime.now() + self.timeout timer.scheduleOneshot(deadline: time) } timer.resume() } public func invalidate() { if let timer = self.timer { timer.cancel() self.timer = nil } } }
mit
19e091d28643d38c273b662e7973a3a6
27.58
101
0.550035
4.893836
false
false
false
false
mgcm/CloudVisionKit
Pod/Classes/GCVLandmark.swift
1
1778
// // GCVLandmark.swift // CloudVisionKit // // Copyright (c) 2016 Milton Moura <[email protected]> // // 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 Unbox public struct GCVPosition: Unboxable { public var x: Float? public var y: Float? public var z: Float? public init(unboxer: Unboxer) { self.x = unboxer.unbox(key: "x") self.y = unboxer.unbox(key: "y") self.z = unboxer.unbox(key: "z") } } public struct GCVLandmark: Unboxable { public var type: String? public var position: GCVPosition? public init(unboxer: Unboxer) { self.type = unboxer.unbox(key: "type") self.position = unboxer.unbox(key: "position") } }
mit
06f11a6cf36d40862126a27b4f7a8b87
34.56
82
0.706412
3.899123
false
false
false
false
nostramap/nostra-sdk-sample-ios
RouteSample/Swift/RouteSample/MarkOnMapViewController.swift
1
3213
// // MarkOnMapViewController.swift // RouteSample // // Copyright © 2559 Globtech. All rights reserved. // import UIKit import ArcGIS import NOSTRASDK protocol MarkOnMapDelegate { func didFinishSelectFromLocation(_ point: AGSPoint); func didFinishSelectToLocation(_ point: AGSPoint); } class MarkOnMapViewController: UIViewController, AGSMapViewLayerDelegate, AGSLayerDelegate { let referrer = "" var delegate:MarkOnMapDelegate?; @IBOutlet weak var mapView: AGSMapView! var isFromLocation = false; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.initializeMap(); } @IBAction func btnOk_Clicked(_ sender: AnyObject) { if isFromLocation { delegate?.didFinishSelectFromLocation(mapView.mapAnchor); } else { delegate?.didFinishSelectToLocation(mapView.mapAnchor); } _ = self.navigationController?.popViewController(animated: true); } @IBAction func btnCancel_Clicked(_ sender: AnyObject) { _ = self.navigationController?.popViewController(animated: true); } func initializeMap() { do { mapView.layerDelegate = self; // Get map permisson. let resultSet = try NTMapPermissionService.execute(); // Get Street map HD (service id: 2) if resultSet.results != nil && resultSet.results.count > 0 { let filtered = resultSet.results.filter({ (mp) -> Bool in return mp.serviceId == 2; }) if filtered.count > 0 { let mapPermisson = filtered.first; let url = URL(string: mapPermisson!.serviceUrl_L); let cred = AGSCredential(token: mapPermisson?.serviceToken_L, referer: referrer); let tiledLayer = AGSTiledMapServiceLayer(url: url, credential: cred) tiledLayer?.delegate = self; mapView.addMapLayer(tiledLayer, withName: mapPermisson!.serviceName); } } } catch let error as NSError { print("error: \(error)"); } } //MARK: Map view and Layer delegate func mapViewDidLoad(_ mapView: AGSMapView!) { mapView.locationDisplay.startDataSource() let env = AGSEnvelope(xmin: 10458701.000000, ymin: 542977.875000, xmax: 11986879.000000, ymax: 2498290.000000, spatialReference: AGSSpatialReference.webMercator()); mapView.zoom(to: env, animated: true); } func layerDidLoad(_ layer: AGSLayer!) { print("\(layer.name) was loaded"); } func layer(_ layer: AGSLayer!, didFailToLoadWithError error: Error!) { print("\(layer.name) failed to load by reason: \(error)"); } }
apache-2.0
bbdde5c8900f4453f2d047319af60e41
28.2
101
0.552615
5.222764
false
false
false
false
rudkx/swift
test/Sema/noimplicitcopy_attr.swift
1
5146
// RUN: %target-typecheck-verify-swift -enable-experimental-move-only -parse-stdlib -disable-availability-checking -verify-syntax-tree import Swift class Klass {} func argumentsAndReturns(@_noImplicitCopy _ x: Klass) -> Klass { return x } func letDecls(_ x: Klass) -> () { @_noImplicitCopy let y: Klass = x print(y) } func varDecls(_ x: Klass, _ x2: Klass) -> () { @_noImplicitCopy var y: Klass = x // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} y = x2 print(y) } func getKlass() -> Builtin.NativeObject { let k = Klass() let b = Builtin.unsafeCastToNativeObject(k) return Builtin.move(b) } @_noImplicitCopy var g: Builtin.NativeObject = getKlass() // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy let g2: Builtin.NativeObject = getKlass() // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy var g3: Builtin.NativeObject { getKlass() } // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} struct MyStruct { // Error if @_noImplicitCopy on struct fields. We do not have move only types and // these are part of MyStruct. // // TODO: Make error specific for move only on struct/enum. @_noImplicitCopy var x: Builtin.NativeObject = getKlass() // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy let y: Builtin.NativeObject = getKlass() // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy var myMoveOnly: Builtin.NativeObject { // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} return getKlass() } func foo<T>(@_noImplicitCopy _ t: T) { } } struct MyGenericStruct<T> { func foo(@_noImplicitCopy _ t: T) { } } protocol P { @_noImplicitCopy var x: Builtin.NativeObject { get } // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} } func foo<T>(@_noImplicitCopy _ t: T) { } // Do not error on class fields. The noImplicitCopy field is separate from the // underlying class itself so the fact the class is not move only does not // suggest that the binding inside the class can be. class MyClass { @_noImplicitCopy var x: Builtin.NativeObject = getKlass() // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy let y: Builtin.NativeObject = getKlass() // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy var myMoveOnly: Builtin.NativeObject { // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} return getKlass() } func foo<T>(@_noImplicitCopy _ t: T) { } } class MyGenericClass<T> { @_noImplicitCopy var x: T? = nil // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy let y: T? = nil // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} @_noImplicitCopy var myMoveOnly: T? { // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} return nil } @_noImplicitCopy var myMoveOnly2: Builtin.NativeObject? { // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} return nil } func foo(@_noImplicitCopy _ t: T) { } } // We need to error on Enums since the case is part of the value and we do not // support move only types. enum MyEnum { case none case noImplicitCopyCase(Klass) // We suport doing it on computed properties though. @_noImplicitCopy var myMoveOnly: Builtin.NativeObject { // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} return getKlass() } } // We need to error on Enums since the case is part of the value and we do not // support move only types. enum MyGenericEnum<T> { case none case noImplicitCopyCase(Klass) // We suport doing it on computed properties though. @_noImplicitCopy var myMoveOnly: Builtin.NativeObject { // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} return getKlass() } // We suport doing it on computed properties though. @_noImplicitCopy var myMoveOnly2: T? { // expected-error {{'@_noImplicitCopy' attribute can only be applied to local lets}} return nil } } struct UnsafePointerWithOwner<T> { var owner: AnyObject? = nil var data: UnsafePointer<T>? = nil func doNothing() {} } func useUnsafePointerWithOwner<T>(_ x: UnsafePointerWithOwner<T>) { // We allow for this here (even without opaque values, since we check this // at the SIL level in SILGen). @_noImplicitCopy let y = x y.doNothing() let z = y print(z) } func useGeneric<T>(_ x: T) { // We allow for this here (even without opaque values, since we check this // at the SIL level in SILGen). @_noImplicitCopy let y = x let z = y print(z) }
apache-2.0
d74de2ef376b9e8371c5ffd233dfb921
35.496454
146
0.686747
4.231908
false
false
false
false
HeshamMegid/HMSegmentedControl-Swift
HMSegmentedControlExample/ViewController.swift
1
2061
// // ViewController.swift // HMSegmentedControl // // Created by Hesham Abd-Elmegid on 8/24/16. // Copyright © 2016 Tinybits. All rights reserved. // import UIKit import HMSegmentedControl class ViewController: UIViewController { let segmentedControl = HMSegmentedControl(items: ["One", "Two", "Three"]) override func viewDidLoad() { view.addSubview(segmentedControl) segmentedControl.backgroundColor = #colorLiteral(red: 0.7683569193, green: 0.9300123453, blue: 0.9995251894, alpha: 1) segmentedControl.translatesAutoresizingMaskIntoConstraints = false segmentedControl.selectionIndicatorPosition = .bottom segmentedControl.selectionIndicatorColor = #colorLiteral(red: 0.1142767668, green: 0.3181744218, blue: 0.4912756383, alpha: 1) segmentedControl.titleTextAttributes = [ NSForegroundColorAttributeName : #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 17) ] segmentedControl.selectedTitleTextAttributes = [ NSForegroundColorAttributeName : #colorLiteral(red: 0.05439098924, green: 0.1344551742, blue: 0.1884709597, alpha: 1), NSFontAttributeName : UIFont.boldSystemFont(ofSize: 17) ] segmentedControl.indexChangedHandler = { index in print(index) // print(self.segmentedControl.selectedSegmentIndex) // self.segmentedControl.selectedSegmentIndex = 1 } NSLayoutConstraint.activate( [segmentedControl.leftAnchor.constraint(equalTo: view.leftAnchor), segmentedControl.heightAnchor.constraint(equalToConstant: 50), segmentedControl.rightAnchor.constraint(equalTo: view.rightAnchor), segmentedControl.topAnchor.constraint(equalTo: view.topAnchor, constant: 40)] ) } override func viewDidAppear(_ animated: Bool) { segmentedControl.setSelectedSegmentIndex(2, animated: false) } }
apache-2.0
659034ce2055beecb77e42d68de6df58
38.615385
134
0.681553
5
false
false
false
false
JGiola/swift
test/SILGen/value_ownership.swift
1
5943
// RUN: %target-swift-emit-silgen -emit-verbose-sil %s | %FileCheck %s protocol OwnershipProto { __consuming func elided(_ default: String, _ shared: __shared String, _ owned: __owned String) __consuming func explicit(_ default: String, _ shared: __shared String, _ owned: __owned String) var elidedPropertyGet: String { __consuming get } var explicitPropertyGet: String { __consuming get } } struct Witness: OwnershipProto { var x: String func elided(_ default: String, _ shared: String, _ owned: String) { } __consuming func explicit(_ default: String, _ toShared: __shared String, _ toOwned: __owned String) { } var elidedPropertyGet: String { return "" } var explicitPropertyGet: String { __consuming get { return "" } } } // Check the conventions of the witnesses // CHECK-LABEL: sil hidden [ossa] @$s15value_ownership7WitnessV6elidedyySS_S2StF : $@convention(method) (@guaranteed String, @guaranteed String, @guaranteed String, @guaranteed Witness) -> () { // CHECK-LABEL: sil hidden [ossa] @$s15value_ownership7WitnessV8explicityySS_SShSSntF : $@convention(method) (@guaranteed String, @guaranteed String, @owned String, @owned Witness) -> () { // CHECK-LABEL: sil hidden [ossa] @$s15value_ownership7WitnessV17elidedPropertyGetSSvg : $@convention(method) (@guaranteed Witness) -> @owned String // CHECK-LABEL: sil hidden [ossa] @$s15value_ownership7WitnessV19explicitPropertyGetSSvg : $@convention(method) (@owned Witness) -> @owned String // Check the elided witness' thunk has the right conventions and borrows where necessary // CHECK-LABEL: @$s15value_ownership7WitnessVAA14OwnershipProtoA2aDP6elidedyySS_SShSSntFTW : // CHECK: bb0([[DEFAULT2DEFAULT:%.*]] : @guaranteed $String, [[SHARED2DEFAULT:%.*]] : @guaranteed $String, [[OWNED2DEFAULT:%.*]] : @owned $String, [[WITNESS_VALUE:%.*]] : $*Witness): // CHECK: [[LOAD_WITNESS:%.*]] = load [take] [[WITNESS_VALUE]] : $*Witness // CHECK: [[BORROW_WITNESS:%.*]] = begin_borrow [[LOAD_WITNESS]] // CHECK: [[WITNESS_FUNC:%.*]] = function_ref @$s15value_ownership7WitnessV6elidedyySS_S2StF // CHECK: [[BORROWOWNED2DEFAULT:%.*]] = begin_borrow [[OWNED2DEFAULT]] : $String // CHECK: apply [[WITNESS_FUNC]]([[DEFAULT2DEFAULT]], [[SHARED2DEFAULT]], [[BORROWOWNED2DEFAULT]], [[BORROW_WITNESS]]) // CHECK: end_borrow [[BORROWOWNED2DEFAULT]] : $String // CHECK: end_borrow [[BORROW_WITNESS]] // CHECK: destroy_value [[LOAD_WITNESS]] // CHECK: } // end sil function '$s15value_ownership7WitnessVAA14OwnershipProtoA2aDP6elidedyySS_SShSSntFTW' // Check that the explicit witness' thunk doesn't copy or borrow // CHECK-LABEL: @$s15value_ownership7WitnessVAA14OwnershipProtoA2aDP8explicityySS_SShSSntFTW : // CHECK: bb0([[ARG0:%.*]] : @guaranteed $String, [[ARG1:%.*]] : @guaranteed $String, [[ARG2:%.*]] : @owned $String, [[WITNESS_VALUE:%.*]] : $*Witness): // CHECK-NEXT: [[LOAD_WITNESS:%.*]] = load [take] [[WITNESS_VALUE]] : $*Witness // CHECK-NEXT: // function_ref Witness.explicit(_:_:_:) // CHECK-NEXT: [[WITNESS_FUNC:%.*]] = function_ref @$s15value_ownership7WitnessV8explicityySS_SShSSntF // CHECK-NEXT: apply [[WITNESS_FUNC]]([[ARG0]], [[ARG1]], [[ARG2]], [[LOAD_WITNESS]]) // CHECK: } // end sil function '$s15value_ownership7WitnessVAA14OwnershipProtoA2aDP8explicityySS_SShSSntFTW' // Check the signature of the property accessor witness thunks. // If a protocol asks for a __consuming get it should get a +1-in +1-out // accessor entry point in its witness table. // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15value_ownership7WitnessVAA14OwnershipProtoA2aDP17elidedPropertyGetSSvgTW : // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15value_ownership7WitnessVAA14OwnershipProtoA2aDP19explicitPropertyGetSSvgTW : // Check that references to a consuming getter are lowered properly. func blackHole<T>(_: T) {} // CHECK-LABEL: sil hidden [ossa] @$s15value_ownership25useConsumingGetterGenericyyxAA14OwnershipProtoRzlF : $@convention(thin) <T where T : OwnershipProto> (@in_guaranteed T) -> () { func useConsumingGetterGeneric<T : OwnershipProto>(_ t: T) { // CHECK: [[FN:%.*]] = witness_method $T, #OwnershipProto.explicitPropertyGet!getter : <Self where Self : OwnershipProto> (__owned Self) -> () -> String : $@convention(witness_method: OwnershipProto) <τ_0_0 where τ_0_0 : OwnershipProto> (@in τ_0_0) -> @owned String // CHECK-NEXT: apply [[FN]]<T>({{%.*}}) : $@convention(witness_method: OwnershipProto) <τ_0_0 where τ_0_0 : OwnershipProto> (@in τ_0_0) -> @owned String blackHole(t.explicitPropertyGet) } // CHECK-LABEL: sil hidden [ossa] @$s15value_ownership29useConsumingGetterExistentialyyAA14OwnershipProto_pF : $@convention(thin) (@in_guaranteed OwnershipProto) -> () { func useConsumingGetterExistential(_ e: OwnershipProto) { // CHECK: [[FN:%.*]] = witness_method $@opened("{{.*}}", OwnershipProto) Self, #OwnershipProto.explicitPropertyGet!getter : <Self where Self : OwnershipProto> (__owned Self) -> () -> String, %2 : $*@opened("{{.*}}", OwnershipProto) Self : $@convention(witness_method: OwnershipProto) <τ_0_0 where τ_0_0 : OwnershipProto> (@in τ_0_0) -> @owned String // CHECK-NEXT: apply [[FN]]<@opened("{{.*}}", OwnershipProto) Self>({{%.*}}) : $@convention(witness_method: OwnershipProto) <τ_0_0 where τ_0_0 : OwnershipProto> (@in τ_0_0) -> @owned String blackHole(e.explicitPropertyGet) } // CHECK-LABEL: sil hidden [ossa] @$s15value_ownership26useConsumingGetterConcreteyyAA7WitnessVF : $@convention(thin) (@guaranteed Witness) -> () { func useConsumingGetterConcrete(_ c: Witness) { // CHECK: [[FN:%.*]] = function_ref @$s15value_ownership7WitnessV19explicitPropertyGetSSvg : $@convention(method) (@owned Witness) -> @owned String // CHECK-NEXT: apply [[FN]]({{%.*}}) : $@convention(method) (@owned Witness) -> @owned String blackHole(c.explicitPropertyGet) }
apache-2.0
7662debaa96398db28a22d514db7b51e
67.172414
354
0.69769
3.612058
false
false
false
false
halo/LinkLiar
LinkLiar/Classes/PrefixesSubmenu.swift
1
5900
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Cocoa class PrefixesSubmenu { // Prevent threads from interfering with one other. let queue: DispatchQueue = DispatchQueue(label: "io.github.halo.LinkLiar.prefixesSubmenuQueue") func update() { Log.debug("Updating...") reloadChosenVendorItems() reloadChosenPrefixesItems() reloadAvailableVendorItems() updateEnability() } private func updateEnability() { self.enableAll(ConfigWriter.isWritable) } private func enableAll(_ enableOrDisable: Bool) { prefixesSubMenuItem.items.forEach { $0.isEnabled = enableOrDisable } } lazy var menuItem: NSMenuItem = { let item = NSMenuItem(title: "Prefixes", action: nil, keyEquivalent: "") item.target = Controller.self item.submenu = self.prefixesSubMenuItem item.toolTip = "When randomizing, which prefixes should be used?" item.keyEquivalentModifierMask = NSEvent.ModifierFlags.option item.isAlternate = true self.update() return item }() private lazy var prefixesSubMenuItem: NSMenu = { let submenu: NSMenu = NSMenu() submenu.autoenablesItems = false // <-- Here the active vendors will be injected --> submenu.addItem(NSMenuItem.separator()) // <-- Here the active prefixes will be injected --> submenu.addItem(NSMenuItem.separator()) submenu.addItem(self.addVendorItem) submenu.addItem(self.addPrefixItem) return submenu }() private lazy var addPrefixItem: NSMenuItem = { let item = NSMenuItem(title: "Add prefix...", action: #selector(Controller.addPrefix), keyEquivalent: "") item.target = Controller.self item.toolTip = "Add all prefixes of a vendor." return item }() private lazy var addVendorItem: NSMenuItem = { let item = NSMenuItem(title: "Add Vendor", action: #selector(Controller.addVendor), keyEquivalent: "") item.target = Controller.self item.submenu = self.vendorsSubMenuItem item.toolTip = "When randomizing, which prefixes should be used?" return item }() private lazy var vendorsSubMenuItem: NSMenu = { let submenu: NSMenu = NSMenu() submenu.autoenablesItems = false // <-- Here the available vendors will be injected --> return submenu }() private func reloadChosenVendorItems() { queue.sync { Log.debug("Loading chosen vendors into submenu...") // Remove all currently listed vendors for item in prefixesSubMenuItem.items { if (item.representedObject is Vendor) { prefixesSubMenuItem.removeItem(item) } } // Replenish active vendors // In reverse order because we insert them from the top and they move down. Config.instance.prefixes.vendors.reversed().forEach { let item = NSMenuItem(title: $0.title, action: #selector(Controller.removeVendor), keyEquivalent: "") item.representedObject = $0 item.target = Controller.self item.toolTip = "Remove vendor \"\($0.name)\" with its \"\(String($0.prefixes.count))\" prefixes from the list of prefixes." prefixesSubMenuItem.insertItem(item, at: 0) } } } private func reloadChosenPrefixesItems() { queue.sync { Log.debug("Loading chosen prefixes into submenu...") // Remove all currently listed vendors for item in prefixesSubMenuItem.items { if (item.representedObject is MACPrefix) { prefixesSubMenuItem.removeItem(item) } } // Replenish active vendors Config.instance.prefixes.prefixes.reversed().forEach { let item = NSMenuItem(title: $0.formatted, action: #selector(Controller.removePrefix), keyEquivalent: "") item.representedObject = $0 item.target = Controller.self item.toolTip = "Remove custom prefix \"\($0.formatted)\" from the list of prefixes." prefixesSubMenuItem.insertItem(item, at: prefixesSubMenuItem.items.count - 3) } } } private func reloadAvailableVendorItems() { queue.sync { Log.debug("Loading available vendors into submenu...") // Remove all currently listed vendors for item in vendorsSubMenuItem.items { if (item.representedObject is Vendor) { vendorsSubMenuItem.removeItem(item) } } // Replenish active vendors // In reverse order because we insert them from the top and they move down. Vendors.available.forEach { let item = NSMenuItem(title: $0.title, action: #selector(Controller.addVendor), keyEquivalent: "") item.representedObject = $0 item.target = Controller.self item.toolTip = "Add vendor \"\($0.name)\" with its \"\(String($0.prefixes.count))\" prefixes to the list of prefixes." vendorsSubMenuItem.insertItem(item, at: 0) } } } }
mit
ed97e51cc42a81856e76d67c95a2ae75
37.064516
133
0.693559
4.507257
false
false
false
false
mlilback/rc2SwiftClient
MacClient/MacAppDelegate.swift
1
23535
// // MacAppDelegate.swift // // Copyright © 2016 Mark Lilback. This file is licensed under the ISC license. // import Cocoa import Rc2Common import ClientCore import ReactiveSwift import SwiftyUserDefaults import Networking import SBInjector import Model import os import MJLLogger import AppCenter import AppCenterAnalytics import AppCenterCrashes /// incremented when data in ~/Library needs to be cleared (such has when the format has changed) let currentSupportDataVersion: Int = 2 private struct Actions { static let showPreferences = #selector(MacAppDelegate.showPreferencesWindow(_:)) static let newWorkspace = #selector(MacAppDelegate.newWorkspace(_:)) static let showWorkspace = #selector(MacAppDelegate.showWorkspace(_:)) static let showLog = #selector(MacAppDelegate.showLogWindow(_:)) static let resetLogs = #selector(MacAppDelegate.resetLogs(_:)) static let toggleCloud = #selector(MacAppDelegate.toggleCloudUsage(_:)) } private extension DefaultsKeys { static let supportDataVersion = DefaultsKey<Int>("currentSupportDataVersion", defaultValue: currentSupportDataVersion) static let connectToCloud = DefaultsKey<Bool?>("connectToCloud") } @NSApplicationMain class MacAppDelegate: NSObject, NSApplicationDelegate { // MARK: - properties let logger = AppLogger() var mainStoryboard: NSStoryboard! var sessionWindowControllers = Set<MainWindowController>() var startupWindowController: StartupWindowController? var startupController: StartupController? var loginController: LoginViewController? var loginWindowController: NSWindowController? private var onboardingController: OnboardingWindowController? private var preferencesWindowController: NSWindowController? private var appStatus: MacAppStatus? @IBOutlet weak var workspaceMenu: NSMenu! private let connectionManager = ConnectionManager() private var dockMenu: NSMenu? private var dockOpenMenu: NSMenu? @IBOutlet weak var logLevelMenuSeperator: NSMenuItem? private var sessionsBeingRestored: [WorkspaceIdentifier: (NSWindow?, Error?) -> Void] = [:] private var workspacesBeingOpened = Set<WorkspaceIdentifier>() private lazy var templateManager: CodeTemplateManager = { do { let dataFolder = try AppInfo.subdirectory(type: .applicationSupportDirectory, named: "CodeTemplates", create: true) let defaultFolder = Bundle.main.resourceURL!.appendingPathComponent("CodeTemplates") return try CodeTemplateManager(dataFolderUrl: dataFolder, defaultFolderUrl: defaultFolder) } catch { Log.error("failed to load template manager: \(error)", .app) fatalError("failed to load template manager") } }() // MARK: - NSApplicationDelegate func applicationWillFinishLaunching(_ notification: Notification) { logger.start() logger.installLoggingUI(addMenusAfter: logLevelMenuSeperator) checkIfSupportFileResetNeeded() mainStoryboard = NSStoryboard(name: .mainBoard, bundle: nil) precondition(mainStoryboard != nil) DispatchQueue.global().async { HelpController.shared.verifyDocumentationInstallation() } let cdUrl = Bundle(for: type(of: self)).url(forResource: "CommonDefaults", withExtension: "plist") // swiftlint:disable:next force_cast UserDefaults.standard.register(defaults: NSDictionary(contentsOf: cdUrl!) as! [String: AnyObject]) // without cloud, we now force to be local UserDefaults.standard[.currentCloudHost] = ServerHost.localHost NotificationCenter.default.addObserver(self, selector: #selector(MacAppDelegate.windowWillClose(_:)), name: NSWindow.willCloseNotification, object: nil) DispatchQueue.main.async { self.beginStartup() } } func applicationDidFinishLaunching(_ aNotification: Notification) { //skip startup actions if running unit tests guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil, ProcessInfo.processInfo.environment["HOCKEYAPP_ENABLED"] == nil else { return } #if HOCKEYAPP_ENABLED setupAppCenter() #endif } func applicationWillTerminate(_ aNotification: Notification) { NotificationCenter.default.removeObserver(self, name: NSWindow.willCloseNotification, object: nil) } func applicationShouldOpenUntitledFile(_ sender: NSApplication) -> Bool { return NSApp.modalWindow == nil } func applicationOpenUntitledFile(_ sender: NSApplication) -> Bool { //bookmarkWindowController?.window?.makeKeyAndOrderFront(self) onboardingController?.window?.makeKeyAndOrderFront(self) return true } func applicationDockMenu(_ sender: NSApplication) -> NSMenu? { if nil == dockMenu { dockMenu = NSMenu(title: "Dock") dockOpenMenu = NSMenu(title: "Open") let openMI = NSMenuItem(title: "Open", action: nil, keyEquivalent: "") openMI.submenu = dockOpenMenu dockMenu?.addItem(openMI) updateOpen(menu: dockOpenMenu!) } return dockMenu } } // MARK: - basic functionality extension MacAppDelegate { @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { guard let action = menuItem.action else { return false } if startupWindowController?.window?.isVisible ?? false { return false } //disable menu items while docker is loading switch action { case Actions.newWorkspace: return true case Actions.resetLogs: return true case Actions.showPreferences: return !(preferencesWindowController?.window?.isMainWindow ?? false) case Actions.showWorkspace: guard let wspaceIdent = menuItem.representedObject as? WorkspaceIdentifier else { return false } return windowController(for: wspaceIdent)?.window?.isMainWindow ?? true case Actions.showLog: return true case Actions.toggleCloud: menuItem.state = (UserDefaults.standard[.connectToCloud] ?? false) ? .on : .off return true default: return false } } /// returns the session associated with window if it is a session window func session(for window: NSWindow?) -> Session? { guard let wc = NSApp.mainWindow?.windowController as? MainWindowController else { return nil } return wc.session } /// returns the window controller for the identified workspace func windowController(for workspaceIdent: WorkspaceIdentifier) -> MainWindowController? { return sessionWindowControllers.first(where: { $0.session?.workspace.wspaceId == workspaceIdent.wspaceId }) } /// returns the window for the specified session func window(for session: Session?) -> NSWindow? { if let window = windowControllerForSession(session!)?.window { return window } return nil } func openSessionWindow(_ session: Session) { defer { workspacesBeingOpened.remove(session.workspace.identifier) } if nil == appStatus { appStatus = MacAppStatus(windowAccessor: window) } let wc = MainWindowController.createFromNib() sessionWindowControllers.insert(wc) let icontext = InjectorContext() icontext.register(AbstractSessionViewController.self) { controller in controller.appStatus = self.appStatus } let sboard = NSStoryboard(name: "MainController", bundle: nil) sboard.injectionContext = icontext //a bug in storyboard loading is causing DI to fail for the rootController when loaded via the window let root = sboard.instantiateController(withIdentifier: "rootController") as? RootViewController wc.contentViewController = root wc.window?.identifier = NSUserInterfaceItemIdentifier(rawValue: "session") wc.window?.restorationClass = type(of: self) //we had to set the content before making visible, and have to set variables after visible wc.window?.makeKeyAndOrderFront(self) wc.appStatus = appStatus wc.session = session wc.setupChildren() if let _ = sessionsBeingRestored.removeValue(forKey: session.workspace.identifier) { //callback(wc.window, nil) if sessionsBeingRestored.count < 1 { advanceStartupStage() } } if onboardingController?.window?.isVisible ?? false { onboardingController?.window?.orderOut(self) } } /// opens a session for workspace. If already open, brings that session window to the front func openSession(workspace: AppWorkspace) { // if already open, bring to front if let controller = windowController(for: workspace.identifier) { controller.window?.orderFront(self) return } guard let conInfo = connectionManager.currentConnection else { Log.warn("asked to open session without connection info"); return } let session = Session(connectionInfo: conInfo, workspace: workspace) // listen for events from that session session.eventSignal.observeResult { result in guard case .success(let event) = result else { return } MSAnalytics.trackEvent(event.type.description, withProperties: event.properties) } session.open().observe(on: UIScheduler()).take(during: session.lifetime).optionalLog("open session").start { [weak self] event in switch event { case .completed: DispatchQueue.main.async { self?.openSessionWindow(session) } case .failed(let err): Log.error("failed to open websocket \(err)", .session) fatalError() case .value: //(let _): // do nothing as using indeterminate progress break case .interrupted: break //should never happen } } } /// convience method that looks up a workspace based on an identifier, then calls openSession(workspace:) func openLocalSession(for wspaceIdentifier: WorkspaceIdentifier?) { guard let ident = wspaceIdentifier else { newWorkspace(self) return } guard !workspacesBeingOpened.contains(ident) else { Log.warn("already opening \(ident)", .app) return } guard let conInfo = connectionManager.currentConnection, let wspace = conInfo.workspace(withIdentifier: ident) else { Log.warn("failed to find workspace \(ident) that we're supposed to open", .app) return } workspacesBeingOpened.insert(ident) openSession(workspace: wspace) } } // MARK: - menus extension MacAppDelegate: NSMenuDelegate { func menuWillOpen(_ menu: NSMenu) { guard menu == workspaceMenu else { return } updateOpen(menu: menu) } /// Adds menu items for workspaces in project /// /// - Parameters: /// - menu: menu to add workspaces to /// - project: project whose workspaces will be added to menu private func update(menu: NSMenu, for project: AppProject) { menu.title = project.name menu.removeAllItems() for aWorkspace in project.workspaces.value.sorted(by: { $0.name < $1.name }) { let wspaceItem = NSMenuItem(title: aWorkspace.name, action: Actions.showWorkspace, keyEquivalent: "") wspaceItem.representedObject = aWorkspace.identifier wspaceItem.tag = aWorkspace.wspaceId menu.addItem(wspaceItem) } } /// Sets menu's items to either be all workspaces in project (if only 1), or submenu items for each project containing its workspaces /// /// - Parameter menu: menu to update fileprivate func updateOpen(menu: NSMenu) { menu.removeAllItems() guard let projects = connectionManager.currentConnection?.projects.value, projects.count > 0 else { return } guard projects.count > 1 else { update(menu: menu, for: projects.first!) return } for aProject in projects.sorted(by: { $0.name < $1.name }) { let pmenu = NSMenu(title: aProject.name) update(menu: pmenu, for: aProject) let pmi = NSMenuItem(title: aProject.name, action: nil, keyEquivalent: "") menu.addItem(pmi) } } } // MARK: - actions extension MacAppDelegate { @IBAction func resetLogs(_ sender: Any?) { logger.resetLogs() } @IBAction func resetSupportFiles(_ sender: Any?) { removeSupportFiles() } @IBAction func newWorkspace(_ sender: Any?) { guard let conInfo = connectionManager.currentConnection, let project = conInfo.defaultProject else { fatalError() } DispatchQueue.main.async { let existingNames = project.workspaces.value.map { $0.name.lowercased() } let prompter = InputPrompter(prompt: "Workspace name:", defaultValue: "new workspace") prompter.validator = { proposedName in return !existingNames.contains(proposedName.lowercased()) } prompter.prompt(window: nil) { success, _ in guard success else { return } let client = Rc2RestClient(conInfo) client.create(workspace: prompter.stringValue, project: conInfo.defaultProject!) .observe(on: UIScheduler()) .startWithFailed { error in //this should never happen unless serious server error self.appStatus?.presentError(error, session: nil) } } } } @IBAction func showWorkspace(_ sender: Any?) { guard let menuItem = sender as? NSMenuItem, let ident = menuItem.representedObject as? WorkspaceIdentifier else { return } if let wc = windowController(for: ident) { wc.window?.makeKeyAndOrderFront(self); return } openLocalSession(for: ident) } @IBAction func showPreferencesWindow(_ sender: Any?) { if nil == preferencesWindowController { let icontext = InjectorContext() icontext.register(TemplatesPrefsController.self) { controller in controller.templateManager = self.templateManager } let sboard = NSStoryboard(name: .prefs, bundle: nil) sboard.injectionContext = icontext preferencesWindowController = sboard.instantiateInitialController() as? NSWindowController preferencesWindowController?.window?.setFrameAutosaveName("PrefsWindow") } preferencesWindowController?.showWindow(self) } @IBAction func showLogWindow(_ sender: Any?) { logger.showLogWindow(sender) } @IBAction func toggleCloudUsage(_ sender: Any?) { // let currentValue = UserDefaults.standard[.connectToCloud] ?? false // UserDefaults.standard[.connectToCloud] = !currentValue // // relaunch application // let task = Process() // task.launchPath = "/bin/sh" // task.arguments = ["-c", "sleep 0.5; open \"\(Bundle.main.bundlePath)\""] // task.launch() // NSApp.terminate(nil) } @IBAction func adjustGlobalLogLevel(_ sender: Any?) { logger.adjustGlobalLogLevel(sender) } @objc func windowWillClose(_ note: Notification) { if let window = note.object as? NSWindow, let sessionWC = window.windowController as? MainWindowController { sessionWindowControllers.remove(sessionWC) } if sessionWindowControllers.count < 1 { // if nothing visible, show onboarding window onboardingController?.window?.makeKeyAndOrderFront(self) } if sessionWindowControllers.count < 1 { // if nothing visible, show onboarding window onboardingController?.window?.makeKeyAndOrderFront(self) } } func windowControllerForSession(_ session: Session) -> MainWindowController? { for wc in sessionWindowControllers where wc.session === session { return wc } return nil } } // MARK: - restoration extension MacAppDelegate: NSWindowRestoration { class func restoreWindow(withIdentifier identifier: NSUserInterfaceItemIdentifier, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Void) { guard let me = NSApp.delegate as? MacAppDelegate else { fatalError("incorrect delegate??") } switch identifier { case .sessionWindow: guard let bmarkData = state.decodeObject(forKey: "bookmark") as? Data, let bmark: Bookmark = try? JSONDecoder().decode(Bookmark.self, from: bmarkData) else { completionHandler(nil, Rc2Error(type: .unknown, nested: nil, explanation: "Unsupported window identifier")) return } completionHandler(nil, nil) me.sessionsBeingRestored[bmark.workspaceIdent] = completionHandler case .logWindow: completionHandler(me.logger.logWindow(show: false), nil) default: completionHandler(nil, Rc2Error(type: .unknown, nested: nil, explanation: "Unsupported window identifier")) } } } // MARK: - private extension MacAppDelegate { private func setupAppCenter() { guard let key = Bundle.main.object(forInfoDictionaryKey: "AppCenterKey") as? String else { Log.error("failed to find API key", .app) return } // disable built-in support for not crashing on exceptions that reach the event loop. Let AppCenter handle them UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true]) // also disable mach handlers, letting them pass up to MSCrashes MSCrashes.disableMachExceptionHandler() MSAppCenter.start(key, withServices: [MSAnalytics.self, MSCrashes.self]) } func checkIfSupportFileResetNeeded() { let defaults = UserDefaults.standard let lastVersion = defaults[.supportDataVersion] let forceReset = ProcessInfo.processInfo.arguments.contains("--resetSupportData") if lastVersion < currentSupportDataVersion || forceReset { removeSupportFiles() } } /// removes files from ~/Library private func removeSupportFiles() { let defaults = UserDefaults.standard defer { defaults[.supportDataVersion] = currentSupportDataVersion } let fm = FileManager() if let cacheDir = (try? fm.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(AppInfo.bundleIdentifier, isDirectory: true)) { Log.info("removing \(cacheDir.path)", .app) try? fm.removeItem(at: cacheDir) } if let supportDir = try? fm.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(AppInfo.bundleIdentifier, isDirectory: true) { Log.info("removing \(supportDir.path)", .app) try? fm.removeItem(at: supportDir) } } } // MARK: - startup extension MacAppDelegate { /// load the setup window and start setup process fileprivate func beginStartup() { precondition(startupController == nil) // load window and setupController. startupWindowController = mainStoryboard.instantiateController(withIdentifier: "StartupWindowController") as? StartupWindowController guard let wc = startupWindowController else { fatalError("failed to load startup window controller") } startupController = startupWindowController!.contentViewController as? StartupController assert(startupController != nil) wc.window?.makeKeyAndOrderFront(self) assert(wc.window!.isVisible) assert(wc.contentViewController?.view.window == wc.window) //move to the next stage advanceStartupStage() } //advances to the next startup stage fileprivate func advanceStartupStage() { guard let setupWC = startupWindowController else { fatalError("advanceStartupStage() called without a setup controller") } switch startupController!.stage { case .initial: startupController!.stage = .localLogin startLoginProcess() case .downloading: break //changes handled via observing pull signal case .localLogin: startupController!.stage = .restoreSessions restoreSessions() case .restoreSessions: startupController!.stage = .complete setupWC.window?.orderOut(nil) setupWC.close() startupController = nil startupWindowController = nil dockMenu = nil if sessionWindowControllers.count < 1 { showOnboarding(self) } else { NSApp.mainWindow?.makeKeyAndOrderFront(self) } case .complete: fatalError("should never reach this point") } } private func handleStartupError(_ error: Rc2Error) { startupWindowController?.window?.orderOut(nil) let alert = NSAlert() alert.messageText = "Error starting application" alert .informativeText = error.nestedDescription ?? error.localizedDescription alert.addButton(withTitle: "Quit") alert.runModal() NSApp.terminate(self) } /// attempt login on host. advances to next startup stage if successful. Handles error by fatal error (if local), or re-prompting for login info if remote private func performLogin(host: ServerHost, password: String) { let loginFactory = LoginFactory() loginFactory.login(to: host, as: host.user, password: password).observe(on: UIScheduler()).startWithResult { result in let conInfo: ConnectionInfo switch result { case .failure(let rerror): var message = rerror.nestedError?.localizedDescription ?? rerror.localizedDescription let nestederror = rerror.nestedError as? NetworkingError if nestederror != nil, case let NetworkingError.invalidHttpStatusCode(rsp) = nestederror!, rsp.statusCode == 401 { message = "invalid userid or password" } self.promptToLogin(previousErrorMessage: message) return case .success(let cinfo): conInfo = cinfo } UserDefaults.standard[.currentCloudHost] = host // only close login window if it was created/shown if let loginWindowController = self.loginWindowController { self.startupWindowController!.window!.endSheet(loginWindowController.window!) self.loginController = nil self.loginWindowController = nil } self.connectionManager.currentConnection = conInfo do { try Keychain(service: Bundle.main.bundleIdentifier!).setString(key: host.keychainKey, value: password) } catch { Log.error("error saving password to keychain: \(error)", .app) } self.advanceStartupStage() } } /// display UI for login info private func promptToLogin(previousErrorMessage: String? = nil) { if nil == loginWindowController { loginWindowController = mainStoryboard.instantiateController(withIdentifier: "LoginWindowController") as? NSWindowController loginController = loginWindowController?.contentViewController as? LoginViewController } guard let loginWindowController = loginWindowController, let loginController = loginController else { fatalError("failed to load login window") } loginController.initialHost = UserDefaults.standard[.currentCloudHost] loginController.statusMessage = previousErrorMessage ?? "" loginController.completionHandler = { host in guard let host = host else { self.startupWindowController!.window!.endSheet(loginWindowController.window!) NSApp.terminate(nil) return } self.performLogin(host: host, password: loginController.enteredPassword) } startupWindowController!.window!.beginSheet(loginWindowController.window!) { _ in } } /// if dockerEnabled, starts local login. If remote and there is a password in the keychain, attempts to login. Otherise, prompts for login info. private func startLoginProcess() { performLogin(host: .localHost, password: "local") // let keychain = Keychain() // if let host = UserDefaults.standard[.currentCloudHost], host.user.count > 0 { // if let password = keychain.getString(host.keychainKey) { // performLogin(host: host, password: password) // return // } // } // promptToLogin() } @IBAction func showOnboarding(_ sender: Any?) { if nil == onboardingController { // swiftlint:disable:next force_cast onboardingController = (mainStoryboard.instantiateController(withIdentifier: "OnboardingWindowController") as! OnboardingWindowController) onboardingController?.viewController.conInfo = connectionManager.currentConnection onboardingController?.viewController.actionHandler = { message in switch message { case .add: self.newWorkspace(nil) case .open(let wspace): self.openLocalSession(for: wspace.identifier) case .remove(let wspace): let client = Rc2RestClient(self.connectionManager.currentConnection!) client.remove(workspace: wspace).observe(on: UIScheduler()).startWithResult { result in switch result { case .failure(let err): self.appStatus?.presentError(err, session: nil) case .success: Log.info("workspace \(wspace.wspaceId) removed") } } } } } onboardingController!.window?.makeKeyAndOrderFront(self) } private func restoreSessions() { guard sessionsBeingRestored.count > 0 else { advanceStartupStage(); return } for ident in self.sessionsBeingRestored.keys { openLocalSession(for: ident) } //TODO: use startupController for progress, perform async } }
isc
648b2c76191216ad89dc3b09fbaa17a0
36.003145
193
0.748619
4.029105
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/FoundationErrors.swift
1
14743
// 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if os(Windows) import WinSDK #endif /// File-system operation attempted on non-existent file. public var NSFileNoSuchFileError: Int { return CocoaError.Code.fileNoSuchFile.rawValue } /// Failure to get a lock on file. public var NSFileLockingError: Int { return CocoaError.Code.fileLocking.rawValue } /// Read error, reason unknown. public var NSFileReadUnknownError: Int { return CocoaError.Code.fileReadUnknown.rawValue } /// Read error because of a permission problem. public var NSFileReadNoPermissionError: Int { return CocoaError.Code.fileReadNoPermission.rawValue } /// Read error because of an invalid file name. public var NSFileReadInvalidFileNameError: Int { return CocoaError.Code.fileReadInvalidFileName.rawValue } /// Read error because of a corrupted file, bad format, or similar reason. public var NSFileReadCorruptFileError: Int { return CocoaError.Code.fileReadCorruptFile.rawValue } /// Read error because no such file was found. public var NSFileReadNoSuchFileError: Int { return CocoaError.Code.fileReadNoSuchFile.rawValue } /// Read error because the string encoding was not applicable. /// /// Access the bad encoding from the `userInfo` dictionary using /// the `NSStringEncodingErrorKey` key. public var NSFileReadInapplicableStringEncodingError: Int { return CocoaError.Code.fileReadInapplicableStringEncoding.rawValue } /// Read error because the specified URL scheme is unsupported. public var NSFileReadUnsupportedSchemeError: Int { return CocoaError.Code.fileReadUnsupportedScheme.rawValue } /// Read error because the specified file was too large. public var NSFileReadTooLargeError: Int { return CocoaError.Code.fileReadTooLarge.rawValue } /// Read error because the string coding of the file could not be determined. public var NSFileReadUnknownStringEncodingError: Int { return CocoaError.Code.fileReadUnknownStringEncoding.rawValue } /// Write error, reason unknown. public var NSFileWriteUnknownError: Int { return CocoaError.Code.fileWriteUnknown.rawValue } /// Write error because of a permission problem. public var NSFileWriteNoPermissionError: Int { return CocoaError.Code.fileWriteNoPermission.rawValue } /// Write error because of an invalid file name. public var NSFileWriteInvalidFileNameError: Int { return CocoaError.Code.fileWriteInvalidFileName.rawValue } /// Write error returned when `FileManager` class’s copy, move, /// and link methods report errors when the destination file already exists. public var NSFileWriteFileExistsError: Int { return CocoaError.Code.fileWriteFileExists.rawValue } /// Write error because the string encoding was not applicable. /// /// Access the bad encoding from the `userInfo` dictionary /// using the `NSStringEncodingErrorKey` key. public var NSFileWriteInapplicableStringEncodingError: Int { return CocoaError.Code.fileWriteInapplicableStringEncoding.rawValue } /// Write error because the specified URL scheme is unsupported. public var NSFileWriteUnsupportedSchemeError: Int { return CocoaError.Code.fileWriteUnsupportedScheme.rawValue } /// Write error because of a lack of disk space. public var NSFileWriteOutOfSpaceError: Int { return CocoaError.Code.fileWriteOutOfSpace.rawValue } /// Write error because because the volume is read only. public var NSFileWriteVolumeReadOnlyError: Int { return CocoaError.Code.fileWriteVolumeReadOnly.rawValue } public var NSFileManagerUnmountUnknownError: Int { return CocoaError.Code.fileManagerUnmountUnknown.rawValue } public var NSFileManagerUnmountBusyError: Int { return CocoaError.Code.fileManagerUnmountBusy.rawValue } /// Key-value coding validation error. public var NSKeyValueValidationError: Int { return CocoaError.Code.keyValueValidation.rawValue } /// Formatting error (related to display of data). public var NSFormattingError: Int { return CocoaError.Code.formatting.rawValue } /// The user cancelled the operation (for example, by pressing Command-period). /// /// This code is for errors that do not require a dialog displayed and might be /// candidates for special-casing. public var NSUserCancelledError: Int { return CocoaError.Code.userCancelled.rawValue } /// The feature is not supported, either because the file system /// lacks the feature, or required libraries are missing, /// or other similar reasons. /// /// For example, some volumes may not support a Trash folder, so these methods /// will report failure by returning `false` or `nil` and /// an `NSError` with `NSFeatureUnsupportedError`. public var NSFeatureUnsupportedError: Int { return CocoaError.Code.featureUnsupported.rawValue } /// Executable is of a type that is not loadable in the current process. public var NSExecutableNotLoadableError: Int { return CocoaError.Code.executableNotLoadable.rawValue } /// Executable does not provide an architecture compatible with /// the current process. public var NSExecutableArchitectureMismatchError: Int { return CocoaError.Code.executableArchitectureMismatch.rawValue } /// Executable has Objective-C runtime information incompatible /// with the current process. public var NSExecutableRuntimeMismatchError: Int { return CocoaError.Code.executableRuntimeMismatch.rawValue } /// Executable cannot be loaded for some other reason, such as /// a problem with a library it depends on. public var NSExecutableLoadError: Int { return CocoaError.Code.executableLoad.rawValue } /// Executable fails due to linking issues. public var NSExecutableLinkError: Int { return CocoaError.Code.executableLink.rawValue } /// An error was encountered while parsing the property list. public var NSPropertyListReadCorruptError: Int { return CocoaError.Code.propertyListReadCorrupt.rawValue } /// The version number of the property list is unable to be determined. public var NSPropertyListReadUnknownVersionError: Int { return CocoaError.Code.propertyListReadUnknownVersion.rawValue } /// An stream error was encountered while reading the property list. public var NSPropertyListReadStreamError: Int { return CocoaError.Code.propertyListReadStream.rawValue } /// An stream error was encountered while writing the property list. public var NSPropertyListWriteStreamError: Int { return CocoaError.Code.propertyListWriteStream.rawValue } public var NSPropertyListWriteInvalidError: Int { return CocoaError.Code.propertyListWriteInvalid.rawValue } /// The XPC connection was interrupted. public var NSXPCConnectionInterrupted: Int { return CocoaError.Code.xpcConnectionInterrupted.rawValue } /// The XPC connection was invalid. public var NSXPCConnectionInvalid: Int { return CocoaError.Code.xpcConnectionInvalid.rawValue } /// The XPC connection reply was invalid. public var NSXPCConnectionReplyInvalid: Int { return CocoaError.Code.xpcConnectionReplyInvalid.rawValue } /// The item has not been uploaded to iCloud by another device yet. /// /// When this error occurs, you do not need to ask the system /// to start downloading the item. The system will download the item as soon /// as it can. If you want to know when the item becomes available, /// use an `NSMetadataQuer`y object to monitor changes to the file’s URL. public var NSUbiquitousFileUnavailableError: Int { return CocoaError.Code.ubiquitousFileUnavailable.rawValue } /// The item could not be uploaded to iCloud because it would make /// the account go over its quota. public var NSUbiquitousFileNotUploadedDueToQuotaError: Int { return CocoaError.Code.ubiquitousFileNotUploadedDueToQuota.rawValue } /// Connecting to the iCloud servers failed. public var NSUbiquitousFileUbiquityServerNotAvailable: Int { return CocoaError.Code.ubiquitousFileUbiquityServerNotAvailable.rawValue } public var NSUserActivityHandoffFailedError: Int { return CocoaError.Code.userActivityHandoffFailed.rawValue } public var NSUserActivityConnectionUnavailableError: Int { return CocoaError.Code.userActivityConnectionUnavailable.rawValue } public var NSUserActivityRemoteApplicationTimedOutError: Int { return CocoaError.Code.userActivityRemoteApplicationTimedOut.rawValue } public var NSUserActivityHandoffUserInfoTooLargeError: Int { return CocoaError.Code.userActivityHandoffUserInfoTooLarge.rawValue } public var NSCoderReadCorruptError: Int { return CocoaError.Code.coderReadCorrupt.rawValue } public var NSCoderValueNotFoundError: Int { return CocoaError.Code.coderValueNotFound.rawValue } internal func _NSErrorWithErrno(_ posixErrno : Int32, reading : Bool, path : String? = nil, url : URL? = nil, extraUserInfo : [String : Any]? = nil) -> NSError { var cocoaError : CocoaError.Code if reading { switch posixErrno { case EFBIG: cocoaError = .fileReadTooLarge case ENOENT: cocoaError = .fileReadNoSuchFile case EPERM, EACCES: cocoaError = .fileReadNoPermission case ENAMETOOLONG: cocoaError = .fileReadUnknown default: cocoaError = .fileReadUnknown } } else { switch posixErrno { case ENOENT: cocoaError = .fileNoSuchFile case EPERM, EACCES: cocoaError = .fileWriteNoPermission case ENAMETOOLONG: cocoaError = .fileWriteInvalidFileName #if os(Windows) case ENOSPC: cocoaError = .fileWriteOutOfSpace #else case EDQUOT, ENOSPC: cocoaError = .fileWriteOutOfSpace #endif case EROFS: cocoaError = .fileWriteVolumeReadOnly case EEXIST: cocoaError = .fileWriteFileExists default: cocoaError = .fileWriteUnknown } } var userInfo = extraUserInfo ?? [String : Any]() if let path = path { userInfo[NSFilePathErrorKey] = path._nsObject } else if let url = url { userInfo[NSURLErrorKey] = url } userInfo[NSUnderlyingErrorKey] = NSError(domain: NSPOSIXErrorDomain, code: Int(posixErrno)) return NSError(domain: NSCocoaErrorDomain, code: cocoaError.rawValue, userInfo: userInfo) } #if os(Windows) // The codes in this domain are codes returned by GetLastError in the Windows SDK (in WinError.h): // https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes internal let _NSWindowsErrorDomain = "org.swift.Foundation.WindowsError" internal func _NSErrorWithWindowsError(_ windowsError: DWORD, reading: Bool) -> NSError { var cocoaError : CocoaError.Code switch Int32(bitPattern: windowsError) { case ERROR_LOCK_VIOLATION: cocoaError = .fileLocking case ERROR_NOT_LOCKED: cocoaError = .fileLocking case ERROR_LOCK_FAILED: cocoaError = .fileLocking case ERROR_INVALID_EXE_SIGNATURE: cocoaError = .executableNotLoadable case ERROR_EXE_MARKED_INVALID: cocoaError = .executableNotLoadable case ERROR_BAD_EXE_FORMAT: cocoaError = .executableNotLoadable case ERROR_BAD_EXE_FORMAT: cocoaError = .executableNotLoadable case ERROR_LOCKED: cocoaError = .fileLocking default: if reading { switch Int32(bitPattern: windowsError) { case ERROR_FILE_NOT_FOUND: cocoaError = .fileReadNoSuchFile case ERROR_PATH_NOT_FOUND: cocoaError = .fileReadNoSuchFile case ERROR_ACCESS_DENIED: cocoaError = .fileReadNoPermission case ERROR_INVALID_ACCESS: cocoaError = .fileReadNoPermission case ERROR_INVALID_DRIVE: cocoaError = .fileReadNoSuchFile case ERROR_SHARING_VIOLATION: cocoaError = .fileReadNoPermission case ERROR_INVALID_NAME: cocoaError = .fileReadInvalidFileName case ERROR_LABEL_TOO_LONG: cocoaError = .fileReadInvalidFileName case ERROR_BAD_PATHNAME: cocoaError = .fileReadInvalidFileName case ERROR_FILENAME_EXCED_RANGE: cocoaError = .fileReadInvalidFileName case ERROR_DIRECTORY: cocoaError = .fileReadInvalidFileName default: cocoaError = .fileReadUnknown } } else { switch Int32(bitPattern: windowsError) { case ERROR_FILE_NOT_FOUND: cocoaError = .fileNoSuchFile case ERROR_PATH_NOT_FOUND: cocoaError = .fileNoSuchFile case ERROR_ACCESS_DENIED: cocoaError = .fileWriteNoPermission case ERROR_INVALID_ACCESS: cocoaError = .fileWriteNoPermission case ERROR_INVALID_DRIVE: cocoaError = .fileNoSuchFile case ERROR_WRITE_PROTECT: cocoaError = .fileWriteVolumeReadOnly case ERROR_WRITE_FAULT: cocoaError = .fileWriteNoPermission case ERROR_SHARING_VIOLATION: cocoaError = .fileWriteNoPermission case ERROR_FILE_EXISTS: cocoaError = .fileWriteFileExists case ERROR_DISK_FULL: cocoaError = .fileWriteOutOfSpace case ERROR_INVALID_NAME: cocoaError = .fileWriteInvalidFileName case ERROR_LABEL_TOO_LONG: cocoaError = .fileWriteInvalidFileName case ERROR_BAD_PATHNAME: cocoaError = .fileWriteInvalidFileName case ERROR_ALREADY_EXISTS: cocoaError = .fileWriteFileExists case ERROR_FILENAME_EXCED_RANGE: cocoaError = .fileWriteInvalidFileName case ERROR_DIRECTORY: cocoaError = .fileWriteInvalidFileName case ERROR_DISK_RESOURCES_EXHAUSTED: cocoaError = .fileWriteOutOfSpace default: cocoaError = .fileWriteUnknown } } } return NSError(domain: NSCocoaErrorDomain, code: cocoaError.rawValue, userInfo: [ NSUnderlyingErrorKey: NSError(domain: _NSWindowsErrorDomain, code: Int(windowsError)) ]) } #endif
apache-2.0
0c1dc343f0b5a397a265f87f44382280
53.791822
161
0.714092
5.144503
false
false
false
false
OpenSourceContributions/SwiftOCR
framework/SwiftOCR/GPUImage2-master/examples/Mac/FilterShowcase/FilterShowcase/FilterOperations.swift
3
42445
import GPUImage import QuartzCore let filterOperations: Array<FilterOperationInterface> = [ FilterOperation ( filter:{SaturationAdjustment()}, listName:"Saturation", titleName:"Saturation", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:2.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.saturation = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{ContrastAdjustment()}, listName:"Contrast", titleName:"Contrast", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:4.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.contrast = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{BrightnessAdjustment()}, listName:"Brightness", titleName:"Brightness", sliderConfiguration:.enabled(minimumValue:-1.0, maximumValue:1.0, initialValue:0.0), sliderUpdateCallback: {(filter, sliderValue) in filter.brightness = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{LevelsAdjustment()}, listName:"Levels", titleName:"Levels", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.0), sliderUpdateCallback: {(filter, sliderValue) in filter.minimum = Color(red:Float(sliderValue), green:Float(sliderValue), blue:Float(sliderValue)) filter.middle = Color(red:1.0, green:1.0, blue:1.0) filter.maximum = Color(red:1.0, green:1.0, blue:1.0) filter.minOutput = Color(red:0.0, green:0.0, blue:0.0) filter.maxOutput = Color(red:1.0, green:1.0, blue:1.0) }, filterOperationType:.singleInput ), FilterOperation( filter:{ExposureAdjustment()}, listName:"Exposure", titleName:"Exposure", sliderConfiguration:.enabled(minimumValue:-4.0, maximumValue:4.0, initialValue:0.0), sliderUpdateCallback: {(filter, sliderValue) in filter.exposure = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{RGBAdjustment()}, listName:"RGB", titleName:"RGB", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:2.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.green = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{HueAdjustment()}, listName:"Hue", titleName:"Hue", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:360.0, initialValue:90.0), sliderUpdateCallback: {(filter, sliderValue) in filter.hue = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{WhiteBalance()}, listName:"White balance", titleName:"White Balance", sliderConfiguration:.enabled(minimumValue:2500.0, maximumValue:7500.0, initialValue:5000.0), sliderUpdateCallback: {(filter, sliderValue) in filter.temperature = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{MonochromeFilter()}, listName:"Monochrome", titleName:"Monochrome", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.intensity = sliderValue }, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! MonochromeFilter camera --> castFilter --> outputView castFilter.color = Color(red:0.0, green:0.0, blue:1.0, alpha:1.0) return nil }) ), FilterOperation( filter:{FalseColor()}, listName:"False color", titleName:"False Color", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.singleInput ), FilterOperation( filter:{Sharpen()}, listName:"Sharpen", titleName:"Sharpen", sliderConfiguration:.enabled(minimumValue:-1.0, maximumValue:4.0, initialValue:0.0), sliderUpdateCallback: {(filter, sliderValue) in filter.sharpness = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{UnsharpMask()}, listName:"Unsharp mask", titleName:"Unsharp Mask", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:5.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.intensity = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{TransformOperation()}, listName:"Transform (2-D)", titleName:"Transform (2-D)", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:6.28, initialValue:0.75), sliderUpdateCallback:{(filter, sliderValue) in filter.transform = Matrix4x4(CGAffineTransform(rotationAngle:CGFloat(sliderValue))) }, filterOperationType:.singleInput ), FilterOperation( filter:{TransformOperation()}, listName:"Transform (3-D)", titleName:"Transform (3-D)", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:6.28, initialValue:0.75), sliderUpdateCallback:{(filter, sliderValue) in var perspectiveTransform = CATransform3DIdentity perspectiveTransform.m34 = 0.4 perspectiveTransform.m33 = 0.4 perspectiveTransform = CATransform3DScale(perspectiveTransform, 0.75, 0.75, 0.75) perspectiveTransform = CATransform3DRotate(perspectiveTransform, CGFloat(sliderValue), 0.0, 1.0, 0.0) filter.transform = Matrix4x4(perspectiveTransform) }, filterOperationType:.singleInput ), FilterOperation( filter:{Crop()}, listName:"Crop", titleName:"Crop", sliderConfiguration:.enabled(minimumValue:240.0, maximumValue:480.0, initialValue:240.0), sliderUpdateCallback:{(filter, sliderValue) in filter.cropSizeInPixels = Size(width:480.0, height:sliderValue) }, filterOperationType:.singleInput ), FilterOperation( filter:{Luminance()}, listName:"Masking", titleName:"Mask Example", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! Luminance let maskImage = PictureInput(imageName:"Mask.png") castFilter.drawUnmodifiedImageOutsideOfMask = false castFilter.mask = maskImage maskImage.processImage() camera --> castFilter --> outputView return nil }) ), FilterOperation( filter:{GammaAdjustment()}, listName:"Gamma", titleName:"Gamma", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:3.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.gamma = sliderValue }, filterOperationType:.singleInput ), // TODO : Tone curve FilterOperation( filter:{HighlightsAndShadows()}, listName:"Highlights and shadows", titleName:"Highlights and Shadows", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.highlights = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{Haze()}, listName:"Haze / UV", titleName:"Haze / UV", sliderConfiguration:.enabled(minimumValue:-0.2, maximumValue:0.2, initialValue:0.2), sliderUpdateCallback: {(filter, sliderValue) in filter.distance = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{SepiaToneFilter()}, listName:"Sepia tone", titleName:"Sepia Tone", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.intensity = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{AmatorkaFilter()}, listName:"Amatorka (Lookup)", titleName:"Amatorka (Lookup)", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{MissEtikateFilter()}, listName:"Miss Etikate (Lookup)", titleName:"Miss Etikate (Lookup)", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{SoftElegance()}, listName:"Soft elegance (Lookup)", titleName:"Soft Elegance (Lookup)", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{ColorInversion()}, listName:"Color invert", titleName:"Color Invert", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{Solarize()}, listName:"Solarize", titleName:"Solarize", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.threshold = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{Vibrance()}, listName:"Vibrance", titleName:"Vibrance", sliderConfiguration:.enabled(minimumValue:-1.2, maximumValue:1.2, initialValue:0.0), sliderUpdateCallback: {(filter, sliderValue) in filter.vibrance = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{HighlightAndShadowTint()}, listName:"Highlight and shadow tint", titleName:"Highlight / Shadow Tint", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.0), sliderUpdateCallback: {(filter, sliderValue) in filter.shadowTintIntensity = sliderValue }, filterOperationType:.singleInput ), FilterOperation ( filter:{Luminance()}, listName:"Luminance", titleName:"Luminance", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.singleInput ), FilterOperation( filter:{Histogram(type:.rgb)}, listName:"Histogram", titleName:"Histogram", sliderConfiguration:.enabled(minimumValue:4.0, maximumValue:32.0, initialValue:16.0), sliderUpdateCallback: {(filter, sliderValue) in filter.downsamplingFactor = UInt(round(sliderValue)) }, filterOperationType:.custom(filterSetupFunction: {(camera, filter, outputView) in let castFilter = filter as! Histogram let histogramGraph = HistogramDisplay() histogramGraph.overriddenOutputSize = Size(width:256.0, height:330.0) let blendFilter = AlphaBlend() blendFilter.mix = 0.75 camera --> blendFilter camera --> castFilter --> histogramGraph --> blendFilter --> outputView return blendFilter }) ), FilterOperation ( filter:{HistogramEqualization(type:.rgb)}, listName:"Histogram equalization", titleName:"Histogram Equalization", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.singleInput ), FilterOperation( filter:{AverageColorExtractor()}, listName:"Average color", titleName:"Average Color", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! AverageColorExtractor let colorGenerator = SolidColorGenerator(size:outputView.sizeInPixels) castFilter.extractedColorCallback = {color in colorGenerator.renderColor(color) } camera --> castFilter colorGenerator --> outputView return colorGenerator }) ), FilterOperation( filter:{AverageLuminanceExtractor()}, listName:"Average luminosity", titleName:"Average Luminosity", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! AverageLuminanceExtractor let colorGenerator = SolidColorGenerator(size:outputView.sizeInPixels) castFilter.extractedLuminanceCallback = {luminosity in colorGenerator.renderColor(Color(red:luminosity, green:luminosity, blue:luminosity)) } camera --> castFilter colorGenerator --> outputView return colorGenerator }) ), FilterOperation( filter:{LuminanceThreshold()}, listName:"Luminance threshold", titleName:"Luminance Threshold", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.threshold = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{AdaptiveThreshold()}, listName:"Adaptive threshold", titleName:"Adaptive Threshold", sliderConfiguration:.enabled(minimumValue:1.0, maximumValue:20.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.blurRadiusInPixels = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{AverageLuminanceThreshold()}, listName:"Average luminance threshold", titleName:"Avg. Lum. Threshold", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:2.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.thresholdMultiplier = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{Pixellate()}, listName:"Pixellate", titleName:"Pixellate", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:0.3, initialValue:0.05), sliderUpdateCallback: {(filter, sliderValue) in filter.fractionalWidthOfAPixel = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{PolarPixellate()}, listName:"Polar pixellate", titleName:"Polar Pixellate", sliderConfiguration:.enabled(minimumValue:-0.1, maximumValue:0.1, initialValue:0.05), sliderUpdateCallback: {(filter, sliderValue) in filter.pixelSize = Size(width:sliderValue, height:sliderValue) }, filterOperationType:.singleInput ), FilterOperation( filter:{Pixellate()}, listName:"Masked Pixellate", titleName:"Masked Pixellate", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! Pixellate castFilter.fractionalWidthOfAPixel = 0.05 // TODO: Find a way to not hardcode these values #if os(iOS) let circleGenerator = CircleGenerator(size:Size(width:480, height:640)) #else let circleGenerator = CircleGenerator(size:Size(width:1280, height:720)) #endif castFilter.mask = circleGenerator circleGenerator.renderCircleOfRadius(0.25, center:Position.center, circleColor:Color.white, backgroundColor:Color.transparent) camera --> castFilter --> outputView return nil }) ), FilterOperation( filter:{PolkaDot()}, listName:"Polka dot", titleName:"Polka Dot", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:0.3, initialValue:0.05), sliderUpdateCallback: {(filter, sliderValue) in filter.fractionalWidthOfAPixel = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{Halftone()}, listName:"Halftone", titleName:"Halftone", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:0.05, initialValue:0.01), sliderUpdateCallback: {(filter, sliderValue) in filter.fractionalWidthOfAPixel = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{Crosshatch()}, listName:"Crosshatch", titleName:"Crosshatch", sliderConfiguration:.enabled(minimumValue:0.01, maximumValue:0.06, initialValue:0.03), sliderUpdateCallback: {(filter, sliderValue) in filter.crossHatchSpacing = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{SobelEdgeDetection()}, listName:"Sobel edge detection", titleName:"Sobel Edge Detection", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.25), sliderUpdateCallback: {(filter, sliderValue) in filter.edgeStrength = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{PrewittEdgeDetection()}, listName:"Prewitt edge detection", titleName:"Prewitt Edge Detection", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.edgeStrength = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{CannyEdgeDetection()}, listName:"Canny edge detection", titleName:"Canny Edge Detection", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:4.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.blurRadiusInPixels = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{ThresholdSobelEdgeDetection()}, listName:"Threshold edge detection", titleName:"Threshold Edge Detection", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.25), sliderUpdateCallback: {(filter, sliderValue) in filter.threshold = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{HarrisCornerDetector()}, listName:"Harris corner detector", titleName:"Harris Corner Detector", sliderConfiguration:.enabled(minimumValue:0.01, maximumValue:0.70, initialValue:0.20), sliderUpdateCallback: {(filter, sliderValue) in filter.threshold = sliderValue }, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! HarrisCornerDetector // TODO: Get this more dynamically sized #if os(iOS) let crosshairGenerator = CrosshairGenerator(size:Size(width:480, height:640)) #else let crosshairGenerator = CrosshairGenerator(size:Size(width:1280, height:720)) #endif crosshairGenerator.crosshairWidth = 15.0 castFilter.cornersDetectedCallback = { corners in crosshairGenerator.renderCrosshairs(corners) } camera --> castFilter let blendFilter = AlphaBlend() camera --> blendFilter --> outputView crosshairGenerator --> blendFilter return blendFilter }) ), FilterOperation( filter:{NobleCornerDetector()}, listName:"Noble corner detector", titleName:"Noble Corner Detector", sliderConfiguration:.enabled(minimumValue:0.01, maximumValue:0.70, initialValue:0.20), sliderUpdateCallback: {(filter, sliderValue) in filter.threshold = sliderValue }, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! NobleCornerDetector // TODO: Get this more dynamically sized #if os(iOS) let crosshairGenerator = CrosshairGenerator(size:Size(width:480, height:640)) #else let crosshairGenerator = CrosshairGenerator(size:Size(width:1280, height:720)) #endif crosshairGenerator.crosshairWidth = 15.0 castFilter.cornersDetectedCallback = { corners in crosshairGenerator.renderCrosshairs(corners) } camera --> castFilter let blendFilter = AlphaBlend() camera --> blendFilter --> outputView crosshairGenerator --> blendFilter return blendFilter }) ), FilterOperation( filter:{ShiTomasiFeatureDetector()}, listName:"Shi-Tomasi feature detector", titleName:"Shi-Tomasi Feature Detector", sliderConfiguration:.enabled(minimumValue:0.01, maximumValue:0.70, initialValue:0.20), sliderUpdateCallback: {(filter, sliderValue) in filter.threshold = sliderValue }, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! ShiTomasiFeatureDetector // TODO: Get this more dynamically sized #if os(iOS) let crosshairGenerator = CrosshairGenerator(size:Size(width:480, height:640)) #else let crosshairGenerator = CrosshairGenerator(size:Size(width:1280, height:720)) #endif crosshairGenerator.crosshairWidth = 15.0 castFilter.cornersDetectedCallback = { corners in crosshairGenerator.renderCrosshairs(corners) } camera --> castFilter let blendFilter = AlphaBlend() camera --> blendFilter --> outputView crosshairGenerator --> blendFilter return blendFilter }) ), // TODO: Hough transform line detector FilterOperation( filter:{ColourFASTFeatureDetection()}, listName:"ColourFAST feature detection", titleName:"ColourFAST Features", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.singleInput ), FilterOperation( filter:{LowPassFilter()}, listName:"Low pass", titleName:"Low Pass", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.strength = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{HighPassFilter()}, listName:"High pass", titleName:"High Pass", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.strength = sliderValue }, filterOperationType:.singleInput ), // TODO: Motion detector FilterOperation( filter:{SketchFilter()}, listName:"Sketch", titleName:"Sketch", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.edgeStrength = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{ThresholdSketchFilter()}, listName:"Threshold Sketch", titleName:"Threshold Sketch", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.25), sliderUpdateCallback: {(filter, sliderValue) in filter.threshold = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{ToonFilter()}, listName:"Toon", titleName:"Toon", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{SmoothToonFilter()}, listName:"Smooth toon", titleName:"Smooth Toon", sliderConfiguration:.enabled(minimumValue:1.0, maximumValue:6.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.blurRadiusInPixels = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{TiltShift()}, listName:"Tilt shift", titleName:"Tilt Shift", sliderConfiguration:.enabled(minimumValue:0.2, maximumValue:0.8, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.topFocusLevel = sliderValue - 0.1 filter.bottomFocusLevel = sliderValue + 0.1 }, filterOperationType:.singleInput ), FilterOperation( filter:{CGAColorspaceFilter()}, listName:"CGA colorspace", titleName:"CGA Colorspace", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{Posterize()}, listName:"Posterize", titleName:"Posterize", sliderConfiguration:.enabled(minimumValue:1.0, maximumValue:20.0, initialValue:10.0), sliderUpdateCallback: {(filter, sliderValue) in filter.colorLevels = round(sliderValue) }, filterOperationType:.singleInput ), FilterOperation( filter:{Convolution3x3()}, listName:"3x3 convolution", titleName:"3x3 convolution", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! Convolution3x3 castFilter.convolutionKernel = Matrix3x3(rowMajorValues:[ -1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0]) camera --> castFilter --> outputView return nil }) ), FilterOperation( filter:{EmbossFilter()}, listName:"Emboss", titleName:"Emboss", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:5.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.intensity = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{Laplacian()}, listName:"Laplacian", titleName:"Laplacian", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{ChromaKeying()}, listName:"Chroma key", titleName:"Chroma Key", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.00, initialValue:0.40), sliderUpdateCallback: {(filter, sliderValue) in filter.thresholdSensitivity = sliderValue }, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! ChromaKeying let blendFilter = AlphaBlend() blendFilter.mix = 1.0 let inputImage = PictureInput(imageName:blendImageName) inputImage --> blendFilter camera --> castFilter --> blendFilter --> outputView inputImage.processImage() return blendFilter }) ), FilterOperation( filter:{KuwaharaFilter()}, listName:"Kuwahara", titleName:"Kuwahara", sliderConfiguration:.enabled(minimumValue:3.0, maximumValue:9.0, initialValue:3.0), sliderUpdateCallback: {(filter, sliderValue) in filter.radius = Int(round(sliderValue)) }, filterOperationType:.singleInput ), FilterOperation( filter:{KuwaharaRadius3Filter()}, listName:"Kuwahara (radius 3)", titleName:"Kuwahara (Radius 3)", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{Vignette()}, listName:"Vignette", titleName:"Vignette", sliderConfiguration:.enabled(minimumValue:0.5, maximumValue:0.9, initialValue:0.75), sliderUpdateCallback: {(filter, sliderValue) in filter.end = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{GaussianBlur()}, listName:"Gaussian blur", titleName:"Gaussian Blur", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:40.0, initialValue:2.0), sliderUpdateCallback: {(filter, sliderValue) in filter.blurRadiusInPixels = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{BoxBlur()}, listName:"Box blur", titleName:"Box Blur", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:40.0, initialValue:2.0), sliderUpdateCallback: {(filter, sliderValue) in filter.blurRadiusInPixels = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{MedianFilter()}, listName:"Median", titleName:"Median", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{BilateralBlur()}, listName:"Bilateral blur", titleName:"Bilateral Blur", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:10.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.distanceNormalizationFactor = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{MotionBlur()}, listName:"Motion blur", titleName:"Motion Blur", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:180.0, initialValue:0.0), sliderUpdateCallback: {(filter, sliderValue) in filter.blurAngle = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{ZoomBlur()}, listName:"Zoom blur", titleName:"Zoom Blur", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:2.5, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.blurSize = sliderValue }, filterOperationType:.singleInput ), FilterOperation( // TODO: Make this only partially applied to the view filter:{iOSBlur()}, listName:"iOS 7 blur", titleName:"iOS 7 Blur", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{SwirlDistortion()}, listName:"Swirl", titleName:"Swirl", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:2.0, initialValue:1.0), sliderUpdateCallback: {(filter, sliderValue) in filter.angle = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{BulgeDistortion()}, listName:"Bulge", titleName:"Bulge", sliderConfiguration:.enabled(minimumValue:-1.0, maximumValue:1.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in // filter.scale = sliderValue filter.center = Position(0.5, sliderValue) }, filterOperationType:.singleInput ), FilterOperation( filter:{PinchDistortion()}, listName:"Pinch", titleName:"Pinch", sliderConfiguration:.enabled(minimumValue:-2.0, maximumValue:2.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.scale = sliderValue }, filterOperationType:.singleInput ), FilterOperation( filter:{SphereRefraction()}, listName:"Sphere refraction", titleName:"Sphere Refraction", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.15), sliderUpdateCallback:{(filter, sliderValue) in filter.radius = sliderValue }, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! SphereRefraction // Provide a blurred image for a cool-looking background let gaussianBlur = GaussianBlur() gaussianBlur.blurRadiusInPixels = 5.0 let blendFilter = AlphaBlend() blendFilter.mix = 1.0 camera --> gaussianBlur --> blendFilter --> outputView camera --> castFilter --> blendFilter return blendFilter }) ), FilterOperation( filter:{GlassSphereRefraction()}, listName:"Glass sphere", titleName:"Glass Sphere", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.15), sliderUpdateCallback:{(filter, sliderValue) in filter.radius = sliderValue }, filterOperationType:.custom(filterSetupFunction:{(camera, filter, outputView) in let castFilter = filter as! GlassSphereRefraction // Provide a blurred image for a cool-looking background let gaussianBlur = GaussianBlur() gaussianBlur.blurRadiusInPixels = 5.0 let blendFilter = AlphaBlend() blendFilter.mix = 1.0 camera --> gaussianBlur --> blendFilter --> outputView camera --> castFilter --> blendFilter return blendFilter }) ), FilterOperation ( filter:{StretchDistortion()}, listName:"Stretch", titleName:"Stretch", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{Dilation()}, listName:"Dilation", titleName:"Dilation", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{Erosion()}, listName:"Erosion", titleName:"Erosion", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{OpeningFilter()}, listName:"Opening", titleName:"Opening", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), FilterOperation( filter:{ClosingFilter()}, listName:"Closing", titleName:"Closing", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.singleInput ), // TODO: Perlin noise // TODO: JFAVoronoi // TODO: Mosaic FilterOperation( filter:{LocalBinaryPattern()}, listName:"Local binary pattern", titleName:"Local Binary Pattern", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.singleInput ), FilterOperation( filter:{ColorLocalBinaryPattern()}, listName:"Local binary pattern (color)", titleName:"Local Binary Pattern (Color)", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.singleInput ), FilterOperation( filter:{DissolveBlend()}, listName:"Dissolve blend", titleName:"Dissolve Blend", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.5), sliderUpdateCallback: {(filter, sliderValue) in filter.mix = sliderValue }, filterOperationType:.blend ), FilterOperation( filter:{ChromaKeyBlend()}, listName:"Chroma key blend (green)", titleName:"Chroma Key (Green)", sliderConfiguration:.enabled(minimumValue:0.0, maximumValue:1.0, initialValue:0.4), sliderUpdateCallback: {(filter, sliderValue) in filter.thresholdSensitivity = sliderValue }, filterOperationType:.blend ), FilterOperation( filter:{AddBlend()}, listName:"Add blend", titleName:"Add Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{DivideBlend()}, listName:"Divide blend", titleName:"Divide Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{MultiplyBlend()}, listName:"Multiply blend", titleName:"Multiply Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{OverlayBlend()}, listName:"Overlay blend", titleName:"Overlay Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{LightenBlend()}, listName:"Lighten blend", titleName:"Lighten Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{DarkenBlend()}, listName:"Darken blend", titleName:"Darken Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{ColorBurnBlend()}, listName:"Color burn blend", titleName:"Color Burn Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{ColorDodgeBlend()}, listName:"Color dodge blend", titleName:"Color Dodge Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{LinearBurnBlend()}, listName:"Linear burn blend", titleName:"Linear Burn Blend", sliderConfiguration:.disabled, sliderUpdateCallback: nil, filterOperationType:.blend ), FilterOperation( filter:{ScreenBlend()}, listName:"Screen blend", titleName:"Screen Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{DifferenceBlend()}, listName:"Difference blend", titleName:"Difference Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{SubtractBlend()}, listName:"Subtract blend", titleName:"Subtract Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{ExclusionBlend()}, listName:"Exclusion blend", titleName:"Exclusion Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{HardLightBlend()}, listName:"Hard light blend", titleName:"Hard Light Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{SoftLightBlend()}, listName:"Soft light blend", titleName:"Soft Light Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{ColorBlend()}, listName:"Color blend", titleName:"Color Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{HueBlend()}, listName:"Hue blend", titleName:"Hue Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{SaturationBlend()}, listName:"Saturation blend", titleName:"Saturation Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{LuminosityBlend()}, listName:"Luminosity blend", titleName:"Luminosity Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), FilterOperation( filter:{NormalBlend()}, listName:"Normal blend", titleName:"Normal Blend", sliderConfiguration:.disabled, sliderUpdateCallback:nil, filterOperationType:.blend ), // TODO: Poisson blend ]
apache-2.0
1e18828c39d335a08c3d76182ff1346d
35.464777
138
0.62707
5.143602
false
true
false
false
mrdepth/Neocom
Neocom/Neocom/Utility/Views/BarChart.swift
2
5214
// // BarChart.swift // Neocom // // Created by Artem Shimanski on 3/30/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI struct BarChart: View { struct Point { var timestamp: Date var duration: TimeInterval var yield: Double var waste: Double } var startDate: Date var endDate: Date var points: [Point] var capacity: Double private func chart(_ geometry: GeometryProxy, _ max: Double) -> some View { let w = CGFloat(endDate.timeIntervalSince(startDate)) let inset = Double(1.0 / geometry.size.width * w) * 0 let transform = CGAffineTransform(scaleX: geometry.size.width / w, y: geometry.size.height / CGFloat(max)).translatedBy(x: CGFloat(-startDate.timeIntervalSince1970), y: 0) let yield = Path { path in for point in points { if point.yield > 0 { path.addRect(CGRect(x: point.timestamp.timeIntervalSince1970, y: 0, width: point.duration - inset, height: point.yield)) } } }.transform(transform) let waste = Path { path in for point in points { if point.waste > 0 { path.addRect(CGRect(x: point.timestamp.timeIntervalSince1970, y: point.yield, width: point.duration - inset, height: point.waste)) } } }.transform(transform) return ZStack(alignment: .bottomLeading) { yield.foregroundColor(.skyBlueBackground) waste.foregroundColor(.red) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading) .scaleEffect(CGSize(width: 1, height: -1), anchor: .center) } private func grid(_ columns: Int, _ rows: Int) -> some View { ZStack { HStack(spacing: 0) { Divider() ForEach(0..<columns) { _ in Spacer() Divider() } } VStack(spacing: 0) { Divider() ForEach(0..<rows) { _ in Spacer() Divider() } } } } private func progress(_ geometry: GeometryProxy, _ progress: CGFloat) -> some View { Rectangle().frame(width: 1).foregroundColor(.skyBlue).offset(x: geometry.size.width * progress, y: 0) .frame(maxWidth: .infinity, alignment: .leading) } @Environment(\.horizontalSizeClass) var horizontalSizeCLass var body: some View { let max = capacity == 0 ? 1 : capacity let dt = endDate.timeIntervalSince(Date()) let progress = CGFloat(1 - min(dt / endDate.timeIntervalSince(startDate), 1)) let rows = horizontalSizeCLass == .regular ? 24 : 12 let cols = 6 return HStack(alignment: .top) { Text(UnitFormatter.localizedString(from: max, unit: .none, style: .short)).font(.caption).frame(width: 50, alignment: .trailing) VStack { grid(rows, cols).aspectRatio(CGFloat(rows) / CGFloat(cols), contentMode: .fit) .overlay(GeometryReader { self.chart($0, max).drawingGroup() }) .overlay(GeometryReader { self.progress($0, progress)}) StatusLabel(endDate: endDate) .frame(maxWidth: .infinity) .font(.caption) .padding(.horizontal) .background(ProgressView(progress: Float(progress)).accentColor(.skyBlueBackground)) } } } } private struct StatusLabel: View { var endDate: Date @State private var currentTime = Date() var body: some View { let dt = endDate.timeIntervalSince(currentTime) return Group { if dt > 0 { Text(TimeIntervalFormatter.localizedString(from: dt, precision: .seconds)) } else { Text("Finished: \(TimeIntervalFormatter.localizedString(from: -dt, precision: .seconds)) ago") } }.onReceive(Timer.publish(every: 1, on: RunLoop.main, in: .default).autoconnect()) { _ in self.currentTime = Date() } } } struct BarChart_Previews: PreviewProvider { static var previews: some View { let points = (-5..<20).map { BarChart.Point(timestamp: Date(timeIntervalSinceNow: TimeInterval($0) * 3600 * 2), duration: 3600 * 2, yield: Double(abs($0)), waste: Double(abs($0)).squareRoot()) } let max = points.map{$0.yield + $0.waste}.max() ?? 1 return BarChart(startDate: points.first!.timestamp, endDate: points.last!.timestamp.addingTimeInterval(3600 * 2), points: points, capacity: max) } }
lgpl-2.1
c33950628b20637205dc03940f20e4c8
35.201389
179
0.522348
4.826852
false
false
false
false
eilianlove/EmptyKit
EmptyKit/EmptyView.swift
1
11223
// // EmptyView.swift // EmptyKit // // Created by archerzz on 16/11/7. // Copyright © 2016年 archerzz. All rights reserved. // import UIKit /// EmptyView final class EmptyView: UIView { // MARK: - Internal Properties var customView: UIView? { didSet { oldValue?.removeFromSuperview() guard let customView = customView else { return } customView.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(customView) } } var verticalOffset: CGFloat = 0 var verticalSpace: CGFloat = 0 var horizontalSpace: CGFloat = 0 var minimumButtonWidth: CGFloat? = nil var fadeInOnDisplay: Bool = true let contentView: UIView = UIView() var titleLabel: UILabel! var detailLabel: UILabel! var imageView: UIImageView! var button: UIButton! var autoInset: Bool = true // Events var didTappedEmptyView:((UIView) -> Void)? var didTappedButton:((UIButton) -> Void)? // MARK: - Initialization init() { super.init(frame: CGRect.zero) setupContentView() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() guard self.frame != CGRect.zero, autoInset else { return } let inset: UIEdgeInsets if let tableView = superview as? UIScrollView { inset = tableView.contentInset } else { inset = UIEdgeInsets.zero } for constraint in superview?.constraints ?? [] where constraint.firstAttribute == .height { if constraint.firstItem is EmptyView || constraint.secondItem is EmptyView { let constant = -inset.top - inset.bottom constraint.constant = constant } } } // MARK: - Override public override func didMoveToSuperview() { guard fadeInOnDisplay == true else { self.contentView.alpha = 1 return } UIView.animate(withDuration: 0.25, animations: { self.contentView.alpha = 1 }) } public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { guard let hitView = super.hitTest(point, with: event) else { return nil } if hitView.isKind(of: UIControl.classForCoder()) { return hitView } if hitView.isEqual(self.contentView) || hitView.isEqual(customView) { return hitView } return nil } } // MARK: - Internal internal extension EmptyView { func prepareForReuse() { self.contentView.subviews.forEach { $0.removeFromSuperview() } self.removeAllConstraints() setupContentSubviews() } } // MARK: - Constraints private extension EmptyView { func removeAllConstraints() { self.removeConstraints(self.constraints) contentView.removeConstraints(self.contentView.constraints) } } // MARK: - Setup internal extension EmptyView { func setupContentSubviews() { setupTitleLable() setupDetailLabel() setupButton() setupImageView() } func setupContentView() { contentView.translatesAutoresizingMaskIntoConstraints = false contentView.backgroundColor = UIColor.clear contentView.isUserInteractionEnabled = true contentView.alpha = 0 addSubview(contentView) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapEmptyView(_:))) addGestureRecognizer(tapGesture) setupContentSubviews() } func setupTitleLable() { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.autoresizingMask = [.flexibleWidth] label.backgroundColor = .clear label.font = UIFont.systemFont(ofSize: 27) label.textColor = UIColor(white: 0.6, alpha: 1) label.textAlignment = .center label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 label.accessibilityLabel = "empty set title" self.titleLabel = label } func setupDetailLabel() { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = .clear label.font = UIFont.systemFont(ofSize: 17) label.textColor = UIColor(white: 0.6, alpha: 1) label.textAlignment = .center label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 label.accessibilityLabel = "empty set detail label" self.detailLabel = label } func setupImageView() { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = UIColor.clear imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = false imageView.accessibilityIdentifier = "empty set background image" self.imageView = imageView } func setupButton() { let button = UIButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.contentHorizontalAlignment = .center button.contentVerticalAlignment = .center button.accessibilityIdentifier = "empty set button" button.addTarget(self, action: #selector(EmptyView.didTapButton), for: .touchUpInside) self.button = button } func setupConstraints() { let space = self.verticalSpace let metrics = ["padding": horizontalSpace] var views:[String: UIView] = [:] var names:[String] = [] self.addEquallyRelatedConstraint(with: contentView, attribute: .centerX) let centerY = self.addEquallyRelatedConstraint(with: contentView, attribute: .centerY) self.addConstraints(withVisualFormat: "|[contentView]|", metrics: nil, views: ["contentView": contentView]) // When a custom offset is available, we adjust the vertical constraints' constants if verticalOffset != 0 { centerY.constant = verticalOffset } if let customView = customView { contentView.addEquallyRelatedConstraint(with: customView, attribute: .centerX) contentView.addEquallyRelatedConstraint(with: customView, attribute: .centerY) contentView.addConstraints(withVisualFormat: "H:|[customView]|", metrics: nil, views: ["customView": customView]) contentView.addConstraints(withVisualFormat: "V:|[customView]|", metrics: nil, views: ["customView": customView]) } // Assign the image view's horizontal constraints if self.canShowImage { contentView.addSubview(imageView) let name = "imageView" names.append(name) views[name] = imageView contentView.addEquallyRelatedConstraint(with: imageView, attribute: .centerX) } // Assign the title label's horizontal constraints if self.canShowTitle { contentView.addSubview(titleLabel) let name = "titleLabel" names.append(name) views[name] = titleLabel contentView.addConstraints(withVisualFormat: "|-(>=padding@800)-[\(name)]-(>=padding@800)-|", metrics: metrics, views: views) contentView.addEquallyRelatedConstraint(with: titleLabel, attribute: .centerX) } // Assign the detail label's horizontal constraints if self.canShowDetail { contentView.addSubview(detailLabel) let name = "detailLabel" names.append(name) views[name] = detailLabel contentView.addConstraints(withVisualFormat: "|-(>=padding@800)-[\(name)]-(>=padding@800)-|", metrics: metrics, views: views) contentView.addEquallyRelatedConstraint(with: detailLabel, attribute: .centerX) } // Assign the button's horizontal constraints if self.canShowButton { contentView.addSubview(button) let name = "button" names.append(name) views[name] = button let buttonVFL: String if let minimumButtonWidth = minimumButtonWidth { buttonVFL = name + "(>=\(minimumButtonWidth))" } else { buttonVFL = name } contentView.addConstraints(withVisualFormat: "|-(>=padding@800)-[\(buttonVFL)]-(>=padding@800)-|", metrics: metrics, views: views) contentView.addEquallyRelatedConstraint(with: button, attribute: .centerX) } // Complete verticalFormat var verticalFormat = "" for i in 0..<names.count { let name = names[i] verticalFormat += "[\(name)]" if (i < views.count - 1) { verticalFormat += "-(\(space)@800)-" } } // Assign the vertical constraints to the content view if (verticalFormat.count > 0) { contentView.addConstraints(withVisualFormat: "V:|\(verticalFormat)|", metrics: metrics, views: views) } } } // MARK: - Private Computed Properties private extension EmptyView { var canShowImage: Bool { return (self.imageView.image != nil) } var canShowTitle: Bool { return (self.titleLabel.attributedText?.length ?? 0 > 0) } var canShowDetail: Bool { return (self.detailLabel.attributedText?.length ?? 0 > 0) } var canShowButton: Bool { if self.button.attributedTitle(for: .normal)?.string.lengthOfBytes(using: .unicode) ?? 0 > 0 || self.button.image(for: .normal) != nil { return true } return false } } // MARK: - Actions private extension EmptyView { @objc func didTapButton(_ button: UIButton) { didTappedButton?(button) } @objc func didTapEmptyView(_ gesture: UITapGestureRecognizer) { guard let view = gesture.view else { return } didTappedEmptyView?(view) } } // MARK: - UIView extension extension UIView { func addConstraints(withVisualFormat format: String, metrics: [String : Any]?, views: [String : Any]) { let noLayoutOptions = NSLayoutConstraint.FormatOptions(rawValue: 0) let constraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: noLayoutOptions, metrics: metrics, views: views) self.addConstraints(constraints) } @discardableResult func addEquallyRelatedConstraint(with view: UIView, attribute: NSLayoutConstraint.Attribute) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: view, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1, constant: 0) self.addConstraint(constraint) return constraint } }
mit
be1d30df0f06521899b8bdd14d2e3ed7
31.427746
160
0.618895
5.265134
false
false
false
false
zcfsmile/Swifter
BasicSyntax/007数组/007Array.playground/Contents.swift
1
1316
//: Playground - noun: a place where people can play import UIKit //: 数组使用有序列表存储同一类型的多个值。相同的值可以多次出现在一个数组的不同位置中。 //: 创建数组 var someInts = [Int]() print(someInts.count) type(of: someInts) someInts.append(3) someInts = [] type(of: someInts) var threeDoubles = Array(repeating: 0.0, count: 3) type(of: threeDoubles) var anotherThreeDoubles = Array(repeating: 2.5, count: 3) var sixDoubles = threeDoubles + anotherThreeDoubles var shoppingList: [String] = ["Eggs", "Milk"] //: 访问和修改 print(shoppingList.count) if shoppingList.isEmpty { print("Shopping list is empty!") } else { print("Shopping list is not empty!") } shoppingList.append("Flour") shoppingList += ["Baking Powder"] shoppingList += ["Chocolate Spread", "Cheese", "Butter"] var firstItem = shoppingList[0] shoppingList[0] = "Six eggs" shoppingList.insert("Maple", at: 0) let maple = shoppingList.remove(at: 0) print(shoppingList) print(maple) let last = shoppingList.removeLast() //: 数组的遍历 for item in shoppingList { print(item) } // enumerated()返回一个由每一个数据项索引值和数据值组成的元组 for (index, value) in shoppingList.enumerated() { print("Item \(String(index)) : \(value)") }
mit
3c8aba0f88e98808636963c0ea03c064
17.125
57
0.708621
3.213296
false
false
false
false
alenalen/DYZB
DYZB/DYZB/Classes/Main/View/PageTitleView.swift
1
5856
// // PageTitleView.swift // DYZB // // Created by Alen on 2017/7/21. // Copyright © 2017年 JingKeCompany. All rights reserved. // import UIKit protocol PageTitleViewDelegate:class { func pageTitleView(titleView: PageTitleView, selectIndex: Int) } //MARK:-定义常亮 private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85) private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0) class PageTitleView: UIView { //MARK:-自定义属性 fileprivate var currentIndex : Int = 0 fileprivate var titles : [String] weak var delegate : PageTitleViewDelegate? //MARK:-懒加载 lazy var titleLabels : [UILabel] = [UILabel]() lazy var scrollView :UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //MARK: - 自定义构造函数 init(frame: CGRect ,titles: [String]) { self.titles = titles super.init(frame: frame) //设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:设置UI界面 extension PageTitleView{ fileprivate func setupUI(){ //添加scrollView addSubview(scrollView) scrollView.frame = bounds //添加Title对应的lab setupTitleLabels() //设置底线和活动模块 setupBottonMenuAndScrollLine() } private func setupTitleLabels(){ //确定lab 的一些Frame let labW : CGFloat = frame.width/CGFloat(titles.count) let labH : CGFloat = frame.height - kScrollLineH let labY : CGFloat = 0 for (index,title) in titles.enumerated() { //创建Lab let lab = UILabel() //设置lab属性 lab.text = title lab.tag = index lab.font = UIFont.systemFont(ofSize: 14) lab.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) lab.textAlignment = .center //设置frame let labX : CGFloat = labW * CGFloat(index) lab.frame = CGRect(x: labX, y: labY, width: labW, height: labH) titleLabels.append(lab) //将lab添加到scrollview scrollView.addSubview(lab) //添加手势 lab.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target:self, action: #selector(self.titleLabClick(tapGes:))) lab.addGestureRecognizer(tapGes) } } private func setupBottonMenuAndScrollLine(){ //添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) //添加线 guard let firstLab = titleLabels.first else { return } firstLab.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLab.frame.origin.x, y: frame.height - kScrollLineH, width: firstLab.frame.width, height: kScrollLineH) } } extension PageTitleView{ //事件处理 需要@OBJC @objc fileprivate func titleLabClick(tapGes: UITapGestureRecognizer) { print("------") //获取当前lab的下标 guard let currentLab = tapGes.view as? UILabel else { return } let oldLab = titleLabels[currentIndex] if oldLab.tag != currentLab.tag { currentLab.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLab.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) } //保存lab的下标 currentIndex = currentLab.tag //滑动line位置 let scrollLineX = CGFloat(currentLab.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.25) { [weak self] in self?.scrollLine.frame.origin.x = scrollLineX } //通知 代理做事情 delegate?.pageTitleView(titleView: self, selectIndex: currentIndex) } } extension PageTitleView{ func setTitleViewProgess(progess: CGFloat, sourceInde: Int, targetIndex: Int) { print(#function) let sourceLab = titleLabels[sourceInde] let targetLab = titleLabels[targetIndex] //处理滑块 let moveTotalX = targetLab.frame.origin.x - sourceLab.frame.origin.x let moveX = moveTotalX * progess scrollLine.frame.origin.x = sourceLab.frame.origin.x + moveX //处理颜色渐变 //1取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0,kSelectColor.1 - kNormalColor.1,kSelectColor.2 - kNormalColor.2) sourceLab.textColor = UIColor(r: kSelectColor.0 - colorDelta.0*progess, g: kSelectColor.1 - colorDelta.1*progess, b: kSelectColor.2 - colorDelta.2*progess) targetLab.textColor = UIColor(r: kNormalColor.0 + colorDelta.0*progess, g: kNormalColor.1 + colorDelta.1*progess, b: kNormalColor.2 + colorDelta.2*progess) //记录最新的 currentIndex = targetIndex } }
mit
e6cd1796385b065edefd7273a805842b
28.835106
163
0.604386
4.516103
false
false
false
false
NSManchester/nsmanchester-app-ios
NSManchesterNextMeetup/TodayViewController.swift
1
1030
// // TodayViewController.swift // NSManchesterNextMeetup // // Created by Stuart Sharpe on 07/03/2016. // Copyright © 2016 Ross Butler. All rights reserved. // import UIKit import NotificationCenter class TodayViewController: UIViewController { // Outlets @IBOutlet weak var dateField: UILabel! // Services let dataService: DataService = ServicesFactory.dataService() let networkingService: NetworkingService = ServicesFactory.networkingService() override func viewDidLoad() { super.viewDidLoad() // Update text field with date of next meetup dateField.text = "First Monday of each month" dataService.nextEventString(callback: { [weak self] title in self?.dateField.text = title }) } @IBAction func goToEvent(_ sender: AnyObject) { if let url = URL(string: "nsmanchester://") { extensionContext?.open(url, completionHandler: nil) } } }
mit
1ba41af5fbd3e6ac7c8eb572f7856b96
24.097561
82
0.627794
4.830986
false
false
false
false
Karumi/BothamNetworking
BothamNetworking/NSHTTPClient.swift
1
2690
// // NSHTTPClient.swift // BothamNetworking // // Created by Pedro Vicente Gomez on 20/11/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation public class NSHTTPClient: HTTPClient { public init() {} public func send(_ httpRequest: HTTPRequest, completion: @escaping (Result<HTTPResponse, BothamAPIClientError>) -> Void) { guard let request = mapHTTPRequestToNSURLRequest(httpRequest) else { completion(Result.failure(.unsupportedURLScheme)) return } let session = URLSession.shared session.configuration.timeoutIntervalForRequest = timeout session.configuration.timeoutIntervalForResource = timeout session.dataTask(with: request, completionHandler: { data, response, error in if let error = error { let bothamError = self.mapNSErrorToBothamError(error as NSError) completion(Result.failure(bothamError)) } else if let response = response as? HTTPURLResponse, let data = data { let response = self.mapNSHTTPURlResponseToHTTPResponse(response, data: data) completion(Result.success(response)) } }).resume() } private func mapHTTPRequestToNSURLRequest(_ httpRequest: HTTPRequest) -> URLRequest? { guard let url = mapHTTPRequestURL(httpRequest) else { return nil } let request = NSMutableURLRequest(url: url) request.allHTTPHeaderFields = httpRequest.headers request.httpMethod = httpRequest.httpMethod.rawValue request.httpBody = httpRequest.encodedBody request.timeoutInterval = timeout return request as URLRequest } private func mapHTTPRequestURL(_ httpRequest: HTTPRequest) -> URL? { guard var components = URLComponents(string: httpRequest.url) else { return nil } if let params = httpRequest.parameters { components.queryItems = params.map { (key, value) in return URLQueryItem(name: key, value: value) } } return components.url } private func mapNSHTTPURlResponseToHTTPResponse(_ response: HTTPURLResponse, data: Data) -> HTTPResponse { let statusCode = response.statusCode let headers = response.allHeaderFields.map { (key, value) in (key as! String, value as! String) } return HTTPResponse( statusCode: statusCode, headers: CaseInsensitiveDictionary(dictionary: Dictionary(headers)), body: data) } }
apache-2.0
c55061ca3a610bbc5402628c23ed2b6a
34.853333
98
0.630718
5.345924
false
false
false
false
pavelpark/GitHubClone
GitHubClone/GitHubClone/FoundationExtensions.swift
1
1162
// // FoundationExtensions.swift // GitHubClone // // Created by Pavel Parkhomey on 4/3/17. // Copyright © 2017 Pavel Parkhomey. All rights reserved. // import Foundation extension UserDefaults { func getAccessToken() -> String? { guard let token = UserDefaults.standard.string(forKey: "access_token") else { return nil } return token } func save(accessToken: String) -> Bool { UserDefaults.standard.set(accessToken, forKey: "access_token") return UserDefaults.standard.synchronize() } } extension String { func validate() -> Bool { let pattern = "[^0-9a-zA-Z_-]" do{ let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) let range = NSRange(location: 0, length: self.characters.count) let matches = regex.numberOfMatches(in: self, options: .reportCompletion, range: range) if matches > 0 { return false } return true } catch { return false } } }
mit
9dd93806e8dd8889aaa7bbb0ccc72502
22.693878
99
0.557278
4.700405
false
false
false
false
aschwaighofer/swift
test/Parse/recovery.swift
2
36006
// RUN: %target-typecheck-verify-swift //===--- Helper types used in this file. protocol FooProtocol {} //===--- Tests. func garbage() -> () { var a : Int ) this line is invalid, but we will stop at the keyword below... // expected-error{{expected expression}} return a + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } func moreGarbage() -> () { ) this line is invalid, but we will stop at the declaration... // expected-error{{expected expression}} func a() -> Int { return 4 } return a() + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } class Container<T> { func exists() -> Bool { return true } } func useContainer() -> () { var a : Container<not a type [skip this greater: >] >, b : Int // expected-error{{expected '>' to complete generic argument list}} expected-note{{to match this opening '<'}} b = 5 // no-warning a.exists() } @xyz class BadAttributes { // expected-error{{unknown attribute 'xyz'}} func exists() -> Bool { return true } } // expected-note @+2 {{did you mean 'test'?}} // expected-note @+1 {{'test' declared here}} func test(a: BadAttributes) -> () { _ = a.exists() // no-warning } // Here is an extra random close-brace! } // expected-error{{extraneous '}' at top level}} {{1-3=}} //===--- Recovery for braced blocks. func braceStmt1() { { braceStmt1(); } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } func braceStmt2() { { () in braceStmt2(); } // expected-error {{closure expression is unused}} } func braceStmt3() { { // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} undefinedIdentifier {} // expected-error {{cannot find 'undefinedIdentifier' in scope}} } } //===--- Recovery for misplaced 'static'. static func toplevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}} {{1-8=}} static struct StaticStruct {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static class StaticClass {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static protocol StaticProtocol {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static typealias StaticTypealias = Int // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} class ClassWithStaticDecls { class var a = 42 // expected-error {{class stored properties not supported}} } //===--- Recovery for missing controlling expression in statements. func missingControllingExprInIf() { if // expected-error {{expected expression, var, or let in 'if' condition}} if { // expected-error {{missing condition in an 'if' statement}} } if // expected-error {{missing condition in an 'if' statement}} { } if true { } else if { // expected-error {{missing condition in an 'if' statement}} } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. if { true } { // expected-error {{missing condition in an 'if' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{14-14=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{15-15=do }} expected-warning {{boolean literal is unused}} } if { true }() { // expected-error {{missing condition in an 'if' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{17-17=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> if { { } } // expected-error{{missing condition in an 'if' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{8-8=do }} } func missingControllingExprInWhile() { while // expected-error {{expected expression, var, or let in 'while' condition}} while { // expected-error {{missing condition in a 'while' statement}} } while // expected-error {{missing condition in a 'while' statement}} { } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. while { true } { // expected-error {{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{17-17=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{18-18=do }} expected-warning {{boolean literal is unused}} } while { true }() { // expected-error {{missing condition in a 'while' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{20-20=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> while { { } } // expected-error{{missing condition in a 'while' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{11-11=do }} } func missingControllingExprInRepeatWhile() { repeat { } while // expected-error {{missing condition in a 'while' statement}} { // expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} missingControllingExprInRepeatWhile(); } repeat { } while { true }() // expected-error{{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{10-10=;}} expected-warning {{result of call to closure returning 'Bool' is unused}} } // SR-165 func missingWhileInRepeat() { repeat { } // expected-error {{expected 'while' after body of 'repeat' statement}} } func acceptsClosure<T>(t: T) -> Bool { return true } func missingControllingExprInFor() { for ; { // expected-error {{C-style for statement has been removed in Swift 3}} } for ; // expected-error {{C-style for statement has been removed in Swift 3}} { } for ; true { // expected-error {{C-style for statement has been removed in Swift 3}} } for var i = 0; true { // expected-error {{C-style for statement has been removed in Swift 3}} i += 1 } } func missingControllingExprInForEach() { // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for i { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for var i { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for in { } // expected-error @+1 {{expected pattern}} for 0..<12 { } // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for for in { } for i in { // expected-error {{expected Sequence expression for for-each loop}} } // The #if block is used to provide a scope for the for stmt to force it to end // where necessary to provoke the crash. #if true // <rdar://problem/21679557> compiler crashes on "for{{" // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{{ // expected-note 2 {{to match this opening '{'}} #endif // expected-error {{expected '}' at end of closure}} expected-error {{expected '}' at end of brace statement}} #if true // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{ var x = 42 } #endif // SR-5943 struct User { let name: String? } let users = [User]() for user in users whe { // expected-error {{expected '{' to start the body of for-each loop}} if let name = user.name { let key = "\(name)" } } for // expected-error {{expected pattern}} expected-error {{Sequence expression for for-each loop}} ; // expected-error {{expected '{' to start the body of for-each loop}} } func missingControllingExprInSwitch() { switch // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} switch { // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} } switch // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} { } switch { // expected-error {{expected expression in 'switch' statement}} case _: return } switch { // expected-error {{expected expression in 'switch' statement}} case Int: return // expected-error {{'is' keyword required to pattern match against type name}} {{10-10=is }} case _: return } switch { 42 } { // expected-error {{expected expression in 'switch' statement}} expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error{{consecutive statements on a line must be separated by ';'}} {{16-16=;}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{17-17=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } switch { 42 }() { // expected-error {{expected expression in 'switch' statement}} expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{19-19=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } } //===--- Recovery for missing braces in nominal type decls. struct NoBracesStruct1() // expected-error {{expected '{' in struct}} enum NoBracesUnion1() // expected-error {{expected '{' in enum}} class NoBracesClass1() // expected-error {{expected '{' in class}} protocol NoBracesProtocol1() // expected-error {{expected '{' in protocol type}} extension NoBracesStruct1() // expected-error {{expected '{' in extension}} struct NoBracesStruct2 // expected-error {{expected '{' in struct}} enum NoBracesUnion2 // expected-error {{expected '{' in enum}} class NoBracesClass2 // expected-error {{expected '{' in class}} protocol NoBracesProtocol2 // expected-error {{expected '{' in protocol type}} extension NoBracesStruct2 // expected-error {{expected '{' in extension}} //===--- Recovery for multiple identifiers in decls protocol Multi ident {} // expected-error @-1 {{found an unexpected second identifier in protocol declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{10-21=Multiident}} // expected-note @-3 {{join the identifiers together with camel-case}} {{10-21=MultiIdent}} class CCC CCC<T> {} // expected-error @-1 {{found an unexpected second identifier in class declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{7-14=CCCCCC}} enum EE EE<T> where T : Multi { // expected-error @-1 {{found an unexpected second identifier in enum declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-11=EEEE}} case a a // expected-error @-1 {{found an unexpected second identifier in enum 'case' declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-11=aa}} // expected-note @-3 {{join the identifiers together with camel-case}} {{8-11=aA}} case b } struct SS SS : Multi { // expected-error @-1 {{found an unexpected second identifier in struct declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-13=SSSS}} private var a b : Int = "" // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{15-18=ab}} // expected-note @-3 {{join the identifiers together with camel-case}} {{15-18=aB}} // expected-error @-4 {{cannot convert value of type 'String' to specified type 'Int'}} func f() { var c d = 5 // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{9-12=cd}} // expected-note @-3 {{join the identifiers together with camel-case}} {{9-12=cD}} // expected-warning @-4 {{initialization of variable 'c' was never used; consider replacing with assignment to '_' or removing it}} let _ = 0 } } let (efg hij, foobar) = (5, 6) // expected-error @-1 {{found an unexpected second identifier in constant declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-13=efghij}} // expected-note @-3 {{join the identifiers together with camel-case}} {{6-13=efgHij}} _ = foobar // OK. //===--- Recovery for parse errors in types. struct ErrorTypeInVarDecl1 { var v1 : // expected-error {{expected type}} {{11-11= <#type#>}} } struct ErrorTypeInVarDecl2 { var v1 : Int. // expected-error {{expected member name following '.'}} var v2 : Int } struct ErrorTypeInVarDecl3 { var v1 : Int< // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl4 { var v1 : Int<, // expected-error {{expected type}} {{16-16= <#type#>}} var v2 : Int } struct ErrorTypeInVarDecl5 { var v1 : Int<Int // expected-error {{expected '>' to complete generic argument list}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl6 { var v1 : Int<Int, // expected-note {{to match this opening '<'}} Int // expected-error {{expected '>' to complete generic argument list}} var v2 : Int } struct ErrorTypeInVarDecl7 { var v1 : Int<Int, // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl8 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl9 { var v1 : protocol // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl10 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl11 { var v1 : protocol<FooProtocol, // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern1(_: protocol<) { } // expected-error {{expected identifier for type name}} func ErrorTypeInPattern2(_: protocol<F) { } // expected-error {{expected '>' to complete protocol-constrained type}} // expected-note@-1 {{to match this opening '<'}} // expected-error@-2 {{cannot find type 'F' in scope}} func ErrorTypeInPattern3(_: protocol<F,) { } // expected-error {{expected identifier for type name}} // expected-error@-1 {{cannot find type 'F' in scope}} struct ErrorTypeInVarDecl12 { var v1 : FooProtocol & // expected-error{{expected identifier for type name}} var v2 : Int } struct ErrorTypeInVarDecl13 { // expected-note {{in declaration of 'ErrorTypeInVarDecl13'}} var v1 : & FooProtocol // expected-error {{expected type}} expected-error {{consecutive declarations on a line must be separated by ';'}} expected-error{{expected declaration}} var v2 : Int } struct ErrorTypeInVarDecl16 { var v1 : FooProtocol & // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern4(_: FooProtocol & ) { } // expected-error {{expected identifier for type name}} struct ErrorGenericParameterList1< // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList2<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList3<T, // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} // Note: Don't move braces to a different line here. struct ErrorGenericParameterList4< // expected-error {{expected an identifier to name generic parameter}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList5<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList6<T, // expected-error {{expected an identifier to name generic parameter}} { } struct ErrorTypeInVarDeclFunctionType1 { var v1 : () -> // expected-error {{expected type for function result}} var v2 : Int } struct ErrorTypeInVarDeclArrayType1 { var v1 : Int[+] // expected-error {{array types are now written with the brackets around the element type}} // expected-error @-1 {{expected expression after unary operator}} // expected-error @-2 {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType2 { var v1 : Int[+ // expected-error {{unary operator cannot be separated from its operand}} // expected-error@-1 {{expected ']' in array type}} // expected-note@-2 {{to match this opening '['}} var v2 : Int // expected-error {{expected expression}} } struct ErrorTypeInVarDeclArrayType3 { var v1 : Int[ // expected-error {{expected ']' in array type}} // expected-note@-1 {{to match this opening '['}} ; // expected-error {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType4 { var v1 : Int[1 // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} var v2 : Int] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{12-12=[}} } struct ErrorTypeInVarDeclArrayType5 { // expected-note {{in declaration of 'ErrorTypeInVarDeclArrayType5'}} let a1: Swift.Int] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a2: Set<Int]> // expected-error {{expected '>' to complete generic argument list}} // expected-note {{to match this opening '<'}} let a3: Set<Int>] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a4: Int]? // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} // expected-error @-1 {{consecutive declarations on a line must be separated by ';'}} // expected-error @-1 {{expected declaration}} let a5: Int?] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a6: [Int]] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a7: [String: Int]] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} } struct ErrorTypeInVarDeclDictionaryType { let a1: String: // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} // expected-error @-1 {{expected dictionary value type}} let a2: String: Int] // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} let a3: String: [Int] // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} {{24-24=]}} let a4: String: Int // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} {{22-22=]}} } struct ErrorInFunctionSignatureResultArrayType1 { func foo() -> Int[ { // expected-error {{expected '{' in body of function declaration}} // expected-note@-1 {{to match this opening '['}} return [0] } // expected-error {{expected ']' in array type}} func bar() -> Int] { // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{17-17=[}} return [0] } } struct ErrorInFunctionSignatureResultArrayType2 { func foo() -> Int[0 { // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} return [0] // expected-error {{cannot convert return expression of type '[Int]' to return type 'Int'}} } } struct ErrorInFunctionSignatureResultArrayType3 { func foo() -> Int[0] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType4 { func foo() -> Int[0_1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType5 { func foo() -> Int[0b1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType11 { // expected-note{{in declaration of 'ErrorInFunctionSignatureResultArrayType11'}} func foo() -> Int[(a){a++}] { // expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} expected-error {{cannot find operator '++' in scope; did you mean '+= 1'?}} expected-error {{cannot find 'a' in scope}} expected-error {{expected declaration}} } } //===--- Recovery for missing initial value in var decls. struct MissingInitializer1 { var v1 : Int = // expected-error {{expected initial value after '='}} } //===--- Recovery for expr-postfix. func exprPostfix1(x : Int) { x. // expected-error {{expected member name following '.'}} } func exprPostfix2() { _ = .42 // expected-error {{'.42' is not a valid floating point literal; it must be written '0.42'}} {{7-7=0}} } //===--- Recovery for expr-super. class Base {} class ExprSuper1 { init() { super // expected-error {{expected '.' or '[' after 'super'}} } } class ExprSuper2 { init() { super. // expected-error {{expected member name following '.'}} } } //===--- Recovery for braces inside a nominal decl. struct BracesInsideNominalDecl1 { // expected-note{{in declaration of 'BracesInsideNominalDecl1'}} { // expected-error {{expected declaration}} aaa } typealias A = Int } func use_BracesInsideNominalDecl1() { // Ensure that the typealias decl is not skipped. var _ : BracesInsideNominalDecl1.A // no-error } class SR771 { print("No one else was in the room where it happened") // expected-note {{'print()' previously declared here}} // expected-error @-1 {{expected 'func' keyword in instance method declaration}} // expected-error @-2 {{expected '{' in body of function declaration}} // expected-error @-3 {{expected parameter name followed by ':'}} } extension SR771 { print("The room where it happened, the room where it happened") // expected-error @-1 {{expected 'func' keyword in instance method declaration}} // expected-error @-2 {{expected '{' in body of function declaration}} // expected-error @-3 {{invalid redeclaration of 'print()'}} // expected-error @-4 {{expected parameter name followed by ':'}} } //===--- Recovery for wrong decl introducer keyword. class WrongDeclIntroducerKeyword1 { notAKeyword() {} // expected-error {{expected 'func' keyword in instance method declaration}} func foo() {} class func bar() {} } //===--- Recovery for wrong inheritance clause. class Base2<T> { } class SubModule { class Base1 {} class Base2<T> {} } // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{34-35=}} class WrongInheritanceClause1(Int) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{41-42=}} class WrongInheritanceClause2(Base2<Int>) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{49-50=}} class WrongInheritanceClause3<T>(SubModule.Base1) where T:AnyObject {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{51-52=}} class WrongInheritanceClause4(SubModule.Base2<Int>) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{54-55=}} class WrongInheritanceClause5<T>(SubModule.Base2<Int>) where T:AnyObject {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} class WrongInheritanceClause6(Int {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} class WrongInheritanceClause7<T>(Int where T:AnyObject {} // <rdar://problem/18502220> [swift-crashes 078] parser crash on invalid cast in sequence expr Base=1 as Base=1 // expected-error{{cannot convert value of type 'Int' to type 'Base' in coercion}} // expected-error@-1 {{cannot assign to immutable expression of type 'Base.Type'}} // expected-error@-2 {{cannot assign to immutable expression of type 'Base'}} // expected-error@-3 {{cannot assign value of type '()' to type 'Base.Type'}} // expected-error@-4 {{cannot assign value of type 'Int' to type 'Base'}} // <rdar://problem/18634543> Parser hangs at swift::Parser::parseType public enum TestA { // expected-error @+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1{{expected parameter name followed by ':'}} s._core.count != 0, "Can't form a Character from an empty String") } public enum TestB { // expected-error@+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1 {{expected parameter name followed by ':'}} s._core.count ?= 0, "Can't form a Character from an empty String") } // <rdar://problem/18634543> Infinite loop and unbounded memory consumption in parser class bar {} var baz: bar // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo1(bar!=baz) {} // expected-note {{did you mean 'foo1'?}} // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo2(bar! = baz) {}// expected-note {{did you mean 'foo2'?}} // rdar://19605567 // expected-error@+1{{cannot find 'esp' in scope; did you mean 'test'?}} switch esp { case let (jeb): // expected-error@+5{{top-level statement cannot begin with a closure expression}} // expected-error@+4{{closure expression is unused}} // expected-note@+3{{did you mean to use a 'do' statement?}} // expected-error@+2{{expected an identifier to name generic parameter}} // expected-error@+1{{expected '{' in class}} class Ceac<}> {} // expected-error@+1{{extraneous '}' at top level}} {{1-2=}} } #if true // rdar://19605164 // expected-error@+2{{cannot find type 'S' in scope}} struct Foo19605164 { func a(s: S[{{g) -> Int {} // expected-note {{to match this opening '['}} }}} // expected-error {{expected ']' in array type}} #endif // rdar://19605567 // expected-error@+3{{expected '(' for initializer parameters}} // expected-error@+2{{initializers may only be declared within a type}} // expected-error@+1{{expected an identifier to name generic parameter}} func F() { init<( } )} // expected-note 2{{did you mean 'F'?}} struct InitializerWithName { init x() {} // expected-error {{initializers cannot have a name}} {{8-9=}} } struct InitializerWithNameAndParam { init a(b: Int) {} // expected-error {{initializers cannot have a name}} {{8-9=}} init? c(_ d: Int) {} // expected-error {{initializers cannot have a name}} {{9-10=}} init e<T>(f: T) {} // expected-error {{initializers cannot have a name}} {{8-9=}} init? g<T>(_: T) {} // expected-error {{initializers cannot have a name}} {{9-10=}} } struct InitializerWithLabels { init c d: Int {} // expected-error @-1 {{expected '(' for initializer parameters}} } // rdar://20337695 func f1() { // expected-error @+6 {{cannot find 'C' in scope}} // expected-note @+5 {{did you mean 'n'?}} // expected-error @+4 {{unary operator cannot be separated from its operand}} {{11-12=}} // expected-error @+3 {{'==' is not a prefix unary operator}} // expected-error @+2 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error@+1 {{type annotation missing in pattern}} let n == C { get {} // expected-error {{cannot find 'get' in scope}} } } // <rdar://problem/20489838> QoI: Nonsensical error and fixit if "let" is missing between 'if let ... where' clauses func testMultiPatternConditionRecovery(x: Int?) { // expected-error@+1 {{expected ',' joining parts of a multi-clause condition}} {{15-21=,}} if let y = x where y == 0, let z = x { _ = y _ = z } if var y = x, y == 0, var z = x { z = y; y = z } if var y = x, z = x { // expected-error {{expected 'var' in conditional}} {{17-17=var }} z = y; y = z } // <rdar://problem/20883210> QoI: Following a "let" condition with boolean condition spouts nonsensical errors guard let x: Int? = 1, x == 1 else { } // expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{16-20=Int}} } // rdar://20866942 func testRefutableLet() { var e : Int? let x? = e // expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error @-1 {{expected expression}} // expected-error @-2 {{type annotation missing in pattern}} } // <rdar://problem/19833424> QoI: Bad error message when using Objective-C literals (@"Hello") in Swift files let myString = @"foo" // expected-error {{string literals in Swift are not preceded by an '@' sign}} {{16-17=}} // <rdar://problem/16990885> support curly quotes for string literals // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{35-38="}} let curlyQuotes1 = “hello world!” // expected-error {{unicode curly quote found, replace with '"'}} {{20-23="}} // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{20-23="}} let curlyQuotes2 = “hello world!" // <rdar://problem/21196171> compiler should recover better from "unicode Specials" characters let tryx = 123 // expected-error {{invalid character in source file}} {{5-8= }} // <rdar://problem/21369926> Malformed Swift Enums crash playground service enum Rank: Int { // expected-error {{'Rank' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Ace = 1 case Two = 2.1 // expected-error {{cannot convert value of type 'Double' to raw type 'Int'}} } // rdar://22240342 - Crash in diagRecursivePropertyAccess class r22240342 { lazy var xx: Int = { foo { // expected-error {{cannot find 'foo' in scope}} let issueView = 42 issueView.delegate = 12 } return 42 }() } // <rdar://problem/22387625> QoI: Common errors: 'let x= 5' and 'let x =5' could use Fix-its func r22387625() { let _= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{8-8= }} let _ =5 // expected-error{{'=' must have consistent whitespace on both sides}} {{10-10= }} } // <https://bugs.swift.org/browse/SR-3135> func SR3135() { let _: Int= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{13-13= }} let _: Array<Int>= [] // expected-error{{'=' must have consistent whitespace on both sides}} {{20-20= }} } // <rdar://problem/23086402> Swift compiler crash in CSDiag protocol A23086402 { var b: B23086402 { get } } protocol B23086402 { var c: [String] { get } } func test23086402(a: A23086402) { print(a.b.c + "") // should not crash but: expected-error {{}} } // <rdar://problem/23550816> QoI: Poor diagnostic in argument list of "print" (varargs related) // The situation has changed. String now conforms to the RangeReplaceableCollection protocol // and `ss + s` becomes ambiguous. Diambiguation is provided with the unavailable overload // in order to produce a meaningful diagnostics. (Related: <rdar://problem/31763930>) func test23550816(ss: [String], s: String) { print(ss + s) // expected-error {{'+' is unavailable: Operator '+' cannot be used to append a String to a sequence of strings}} } // <rdar://problem/23719432> [practicalswift] Compiler crashes on &(Int:_) func test23719432() { var x = 42 &(Int:x) // expected-error {{use of extraneous '&'}} } // <rdar://problem/19911096> QoI: terrible recovery when using '·' for an operator infix operator · { // expected-error {{'·' is considered an identifier and must not appear within an operator name}} associativity none precedence 150 } infix operator -@-class Recover1 {} // expected-error {{'@' is not allowed in operator names}} prefix operator -фф--class Recover2 {} // expected-error {{'фф' is considered an identifier and must not appear within an operator name}} // <rdar://problem/21712891> Swift Compiler bug: String subscripts with range should require closing bracket. func r21712891(s : String) -> String { let a = s.startIndex..<s.startIndex _ = a // The specific errors produced don't actually matter, but we need to reject this. return "\(s[a)" // expected-error {{expected ']' in expression list}} expected-note {{to match this opening '['}} } // <rdar://problem/24029542> "Postfix '.' is reserved" error message" isn't helpful func postfixDot(a : String) { _ = a.utf8 _ = a. utf8 // expected-error {{extraneous whitespace after '.' is not permitted}} {{9-12=}} _ = a. // expected-error {{expected member name following '.'}} a. // expected-error {{expected member name following '.'}} } // <rdar://problem/22290244> QoI: "UIColor." gives two issues, should only give one func f() { // expected-note 2{{did you mean 'f'?}} _ = ClassWithStaticDecls. // expected-error {{expected member name following '.'}} } // <rdar://problem/22478168> | SR-11006 // expected-error@+1 {{expected '=' instead of '==' to assign default value for parameter}} {{21-23==}} func SR11006(a: Int == 0) {} // rdar://38225184 extension Collection where Element == Int && Index == Int {} // expected-error@-1 {{expected ',' to separate the requirements of this 'where' clause}} {{43-45=,}}
apache-2.0
a050517e13c00d407acb82846f3e350e
40.898719
469
0.673474
3.956794
false
false
false
false
cuappdev/podcast-ios
old/Podcast/FeedRecastTableViewCell.swift
1
2457
// // FeedRecastTableViewCell.swift // Podcast // // Created by Natasha Armbrust on 5/8/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import UIKit class FeedRecastTableViewCell: UITableViewCell, FeedElementTableViewCell { static let identifier: String = "FeedRecastTableViewCell" let supplierViewHeight: CGFloat = UserSeriesSupplierView.height var delegate: FeedElementTableViewCellDelegate? var supplierView: UIView { return userSeriesSupplierView } var subjectView: UIView { return recastSubjectView } var userSeriesSupplierView = UserSeriesSupplierView() var recastSubjectView = RecastSubjectView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initialize() userSeriesSupplierView.delegate = self recastSubjectView.delegate = self let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapSupplierView)) userSeriesSupplierView.addGestureRecognizer(tapGesture) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(context: FeedContext) { if case .followingRecommendation(let user, let episode) = context { userSeriesSupplierView.setup(with: user, for: context) recastSubjectView.setup(with: episode, for: user) } } func configure(context: FeedContext, _ isExpanded: Bool) { if case .followingRecommendation(let user, let episode) = context { userSeriesSupplierView.setup(with: user, for: context) recastSubjectView.setup(with: episode, for: user, isExpanded: isExpanded) } } @objc func didTapSupplierView() { delegate?.didPress(userSeriesSupplierView: userSeriesSupplierView, in: self) } } extension FeedRecastTableViewCell: RecastSubjectViewDelegate { func didPress(on action: EpisodeAction, for view: RecastSubjectView) { delegate?.didPress(on: action, for: view, in: self) } func expand(_ isExpanded: Bool) { delegate?.expand(isExpanded, for: self) } } extension FeedRecastTableViewCell: SupplierViewDelegate { func didPressFeedControlButton(for supplierView: UserSeriesSupplierView) { delegate?.didPressFeedControlButton(for: supplierView, in: self) } }
mit
dcedcc57ca024fec82d78dc5abb61e36
30.896104
100
0.708469
4.409336
false
false
false
false
jisudong555/swift
weibo/Pods/Alamofire/Source/Manager.swift
37
38097
// Manager.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. */ public class Manager { // MARK: - Properties /** A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests. */ public static let sharedInstance: Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ public static let defaultHTTPHeaders: [String: String] = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joinWithSeparator(", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let version = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let os = NSProcessInfo.processInfo().operatingSystemVersionString var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) { return mutableUserAgent as String } } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) /// The underlying session. public let session: NSURLSession /// The session delegate handling all the task and session delegate callbacks. public let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. public var startRequestsImmediately: Bool = true /** The background completion handler closure provided by the UIApplicationDelegate `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation will automatically call the handler. If you need to handle your own events before the handler is called, then you need to override the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. `nil` by default. */ public var backgroundCompletionHandler: (() -> Void)? // MARK: - Lifecycle /** Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. - parameter configuration: The configuration used to construct the managed session. `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by default. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance. */ public init( configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /** Initializes the `Manager` instance with the specified session, delegate and server trust policy. - parameter session: The URL session. - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. */ public init?( session: NSURLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = session guard delegate === session.delegate else { return nil } commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Request /** Creates a request for the specified method, URL string, parameters, parameter encoding and headers. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 return request(encodedURLRequest) } /** Creates a request for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { var dataTask: NSURLSessionDataTask! dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } let request = Request(session: session, task: dataTask) delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: - SessionDelegate /** Responsible for handling all delegate callbacks for the underlying session. */ public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } } /** Initializes the `SessionDelegate` instance. - returns: The new `SessionDelegate` instance. */ public override init() { super.init() } // MARK: - NSURLSessionDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? /// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`. public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { sessionDidBecomeInvalidWithError?(session, error) } /** Requests credentials from the delegate in response to a session-level authentication request from the remote server. - parameter session: The session containing the task that requested authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ public func URLSession( session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { guard sessionDidReceiveChallengeWithCompletion == nil else { sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) return } var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { disposition = .UseCredential credential = NSURLCredential(forTrust: serverTrust) } else { disposition = .CancelAuthenticationChallenge } } } completionHandler(disposition, credential) } /** Tells the delegate that all messages enqueued for a session have been delivered. - parameter session: The session that no longer has any outstanding requests. */ public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and /// requires the caller to call the `completionHandler`. public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and /// requires the caller to call the `completionHandler`. public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)? /// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and /// requires the caller to call the `completionHandler`. public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the remote server requested an HTTP redirect. - parameter session: The session containing the task whose request resulted in a redirect. - parameter task: The task whose request resulted in a redirect. - parameter response: An object containing the server’s response to the original request. - parameter request: A URL request object filled out with the new location. - parameter completionHandler: A closure that your handler should call with either the value of the request parameter, a modified URL request object, or NULL to refuse the redirect and return the body of the redirect response. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: NSURLRequest? -> Void) { guard taskWillPerformHTTPRedirectionWithCompletion == nil else { taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) return } var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /** Requests credentials from the delegate in response to an authentication request from the remote server. - parameter session: The session containing the task whose request requires authentication. - parameter task: The task whose request requires authentication. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { guard taskDidReceiveChallengeWithCompletion == nil else { taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) return } if let taskDidReceiveChallenge = taskDidReceiveChallenge { let result = taskDidReceiveChallenge(session, task, challenge) completionHandler(result.0, result.1) } else if let delegate = self[task] { delegate.URLSession( session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler ) } else { URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) } } /** Tells the delegate when a task requires a new request body stream to send to the remote server. - parameter session: The session containing the task that needs a new body stream. - parameter task: The task that needs a new body stream. - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: NSInputStream? -> Void) { guard taskNeedNewBodyStreamWithCompletion == nil else { taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) return } if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) } } /** Periodically informs the delegate of the progress of sending body content to the server. - parameter session: The session containing the data task. - parameter task: The data task. - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. - parameter totalBytesSent: The total number of bytes sent so far. - parameter totalBytesExpectedToSend: The expected length of the body data. */ public func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task] as? Request.UploadTaskDelegate { delegate.URLSession( session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } /** Tells the delegate that the task finished transferring data. - parameter session: The session containing the task whose request finished transferring data. - parameter task: The task whose request finished transferring data. - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. */ public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidComplete = taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = self[task] { delegate.URLSession(session, task: task, didCompleteWithError: error) } NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) self[task] = nil } // MARK: - NSURLSessionDataDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and /// requires caller to call the `completionHandler`. public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)? /// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and /// requires caller to call the `completionHandler`. public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)? // MARK: Delegate Methods /** Tells the delegate that the data task received the initial reply (headers) from the server. - parameter session: The session containing the data task that received an initial reply. - parameter dataTask: The data task that received an initial reply. - parameter response: A URL response object populated with headers. - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a constant to indicate whether the transfer should continue as a data task or should become a download task. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: NSURLSessionResponseDisposition -> Void) { guard dataTaskDidReceiveResponseWithCompletion == nil else { dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) return } var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /** Tells the delegate that the data task was changed to a download task. - parameter session: The session containing the task that was replaced by a download task. - parameter dataTask: The data task that was replaced by a download task. - parameter downloadTask: The new download task that replaced the data task. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) self[downloadTask] = downloadDelegate } } /** Tells the delegate that the data task has received some of the expected data. - parameter session: The session containing the data task that provided data. - parameter dataTask: The data task that provided data. - parameter data: A data object containing the transferred data. */ public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) } } /** Asks the delegate whether the data (or upload) task should store the response in the cache. - parameter session: The session containing the data (or upload) task. - parameter dataTask: The data (or upload) task. - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current caching policy and the values of certain received headers, such as the Pragma and Cache-Control headers. - parameter completionHandler: A block that your handler must call, providing either the original proposed response, a modified version of that response, or NULL to prevent caching the response. If your delegate implements this method, it must call this completion handler; otherwise, your app leaks memory. */ public func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: NSCachedURLResponse? -> Void) { guard dataTaskWillCacheResponseWithCompletion == nil else { dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) return } if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } // MARK: - NSURLSessionDownloadDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: Delegate Methods /** Tells the delegate that a download task has finished downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that finished. - parameter location: A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method. */ public func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) } } /** Periodically informs the delegate about the download’s progress. - parameter session: The session containing the download task. - parameter downloadTask: The download task. - parameter bytesWritten: The number of bytes transferred since the last time this delegate method was called. - parameter totalBytesWritten: The total number of bytes transferred so far. - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is `NSURLSessionTransferSizeUnknown`. */ public func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /** Tells the delegate that the download task has resumed downloading. - parameter session: The session containing the download task that finished. - parameter downloadTask: The download task that resumed. See explanation in the discussion. - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the existing content, then this value is zero. Otherwise, this value is an integer representing the number of bytes on disk that do not need to be retrieved again. - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. If this header was not provided, the value is NSURLSessionTransferSizeUnknown. */ public func URLSession( session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } // MARK: - NSURLSessionStreamDelegate var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? // MARK: - NSObject public override func respondsToSelector(selector: Selector) -> Bool { #if !os(OSX) if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) { return sessionDidFinishEventsForBackgroundURLSession != nil } #endif switch selector { case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)): return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return self.dynamicType.instancesRespondToSelector(selector) } } } }
mit
93b8104c63d0365ea258b8d1ce7ec015
49.583001
197
0.652656
6.779815
false
false
false
false
jaouahbi/OMCircularProgressView
OMCircularProgress/Classes/Extensions/UIColor+Crayola.swift
2
41817
import UIKit // from https://github.com/CaptainRedmuff/UIColor-Crayola extension UIColor { public class var crayolaAbsoluteZeroColor:UIColor { return UIColor(crayolared:0.000 , green:0.282 , blue:0.729, alpha:1.0); } public class var crayolaAlienArmpitColor:UIColor { return UIColor(crayolared:0.518 , green:0.871 , blue:0.008, alpha:1.0); } public class var crayolaAlloyOrangeColor:UIColor { return UIColor(crayolared:0.769 , green:0.384 , blue:0.063, alpha:1.0); } public class var crayolaAlmondColor:UIColor { return UIColor(crayolared:0.937 , green:0.871 , blue:0.804, alpha:1.0); } public class var crayolaAmethystColor:UIColor { return UIColor(crayolared:0.392 , green:0.376 , blue:0.604, alpha:1.0); } public class var crayolaAntiqueBrassColor:UIColor { return UIColor(crayolared:0.804 , green:0.584 , blue:0.459, alpha:1.0); } public class var crayolaApricotColor:UIColor { return UIColor(crayolared:0.992 , green:0.851 , blue:0.710, alpha:1.0); } public class var crayolaAquaPearlColor:UIColor { return UIColor(crayolared:0.373 , green:0.745 , blue:0.843, alpha:1.0); } public class var crayolaAquamarineColor:UIColor { return UIColor(crayolared:0.471 , green:0.859 , blue:0.886, alpha:1.0); } public class var crayolaAsparagusColor:UIColor { return UIColor(crayolared:0.529 , green:0.663 , blue:0.420, alpha:1.0); } public class var crayolaAtomicTangerineColor:UIColor { return UIColor(crayolared:1.000 , green:0.643 , blue:0.455, alpha:1.0); } public class var crayolaAztecGoldColor:UIColor { return UIColor(crayolared:0.765 , green:0.600 , blue:0.325, alpha:1.0); } public class var crayolaBabyPowderColor:UIColor { return UIColor(crayolared:0.996 , green:0.996 , blue:0.980, alpha:1.0); } public class var crayolaBananaColor:UIColor { return UIColor(crayolared:1.000 , green:0.820 , blue:0.165, alpha:1.0); } public class var crayolaBananaManiaColor:UIColor { return UIColor(crayolared:0.980 , green:0.906 , blue:0.710, alpha:1.0); } public class var crayolaBdazzledBlueColor:UIColor { return UIColor(crayolared:0.180 , green:0.345 , blue:0.580, alpha:1.0); } public class var crayolaBeaverColor:UIColor { return UIColor(crayolared:0.624 , green:0.506 , blue:0.439, alpha:1.0); } public class var crayolaBigDipORubyColor:UIColor { return UIColor(crayolared:0.612 , green:0.145 , blue:0.259, alpha:1.0); } public class var crayolaBigFootFeetColor:UIColor { return UIColor(crayolared:0.910 , green:0.557 , blue:0.353, alpha:1.0); } public class var crayolaBittersweetColor:UIColor { return UIColor(crayolared:0.992 , green:0.486 , blue:0.431, alpha:1.0); } public class var crayolaBittersweetShimmerColor:UIColor { return UIColor(crayolared:0.749 , green:0.310 , blue:0.318, alpha:1.0); } public class var crayolaBlackColor:UIColor { return UIColor(crayolared:0.000 , green:0.000 , blue:0.000, alpha:1.0); } public class var crayolaBlackCoralPearlColor:UIColor { return UIColor(crayolared:0.329 , green:0.384 , blue:0.435, alpha:1.0); } public class var crayolaBlackShadowsColor:UIColor { return UIColor(crayolared:0.749 , green:0.686 , blue:0.698, alpha:1.0); } public class var crayolaBlastOffBronzeColor:UIColor { return UIColor(crayolared:0.647 , green:0.443 , blue:0.392, alpha:1.0); } public class var crayolaBlizzardBlueColor:UIColor { return UIColor(crayolared:0.675 , green:0.898 , blue:0.933, alpha:1.0); } public class var crayolaBlueColor:UIColor { return UIColor(crayolared:0.122 , green:0.459 , blue:0.996, alpha:1.0); } public class var crayolaBlueBellColor:UIColor { return UIColor(crayolared:0.635 , green:0.635 , blue:0.816, alpha:1.0); } public class var crayolaBlueGrayColor:UIColor { return UIColor(crayolared:0.400 , green:0.600 , blue:0.800, alpha:1.0); } public class var crayolaBlueGreenColor:UIColor { return UIColor(crayolared:0.051 , green:0.596 , blue:0.729, alpha:1.0); } public class var crayolaBlueJeansColor:UIColor { return UIColor(crayolared:0.365 , green:0.678 , blue:0.925, alpha:1.0); } public class var crayolaBlueVioletColor:UIColor { return UIColor(crayolared:0.451 , green:0.400 , blue:0.741, alpha:1.0); } public class var crayolaBlueberryColor:UIColor { return UIColor(crayolared:0.310 , green:0.525 , blue:0.969, alpha:1.0); } public class var crayolaBlushColor:UIColor { return UIColor(crayolared:0.871 , green:0.365 , blue:0.514, alpha:1.0); } public class var crayolaBoogerBusterColor:UIColor { return UIColor(crayolared:0.867 , green:0.886 , blue:0.416, alpha:1.0); } public class var crayolaBrickRedColor:UIColor { return UIColor(crayolared:0.796 , green:0.255 , blue:0.329, alpha:1.0); } public class var crayolaBrightYellowColor:UIColor { return UIColor(crayolared:1.000 , green:0.667 , blue:0.114, alpha:1.0); } public class var crayolaBrownColor:UIColor { return UIColor(crayolared:0.706 , green:0.404 , blue:0.302, alpha:1.0); } public class var crayolaBrownSugarColor:UIColor { return UIColor(crayolared:0.686 , green:0.431 , blue:0.302, alpha:1.0); } public class var crayolaBubbleGumColor:UIColor { return UIColor(crayolared:1.000 , green:0.827 , blue:0.973, alpha:1.0); } public class var crayolaBurnishedBrownColor:UIColor { return UIColor(crayolared:0.631 , green:0.478 , blue:0.455, alpha:1.0); } public class var crayolaBurntOrangeColor:UIColor { return UIColor(crayolared:1.000 , green:0.498 , blue:0.286, alpha:1.0); } public class var crayolaBurntSiennaColor:UIColor { return UIColor(crayolared:0.918 , green:0.494 , blue:0.365, alpha:1.0); } public class var crayolaCadetBlueColor:UIColor { return UIColor(crayolared:0.690 , green:0.718 , blue:0.776, alpha:1.0); } public class var crayolaCanaryColor:UIColor { return UIColor(crayolared:1.000 , green:1.000 , blue:0.600, alpha:1.0); } public class var crayolaCaribbeanGreenColor:UIColor { return UIColor(crayolared:0.110 , green:0.827 , blue:0.635, alpha:1.0); } public class var crayolaCaribbeanGreenPearlColor:UIColor { return UIColor(crayolared:0.416 , green:0.855 , blue:0.557, alpha:1.0); } public class var crayolaCarnationPinkColor:UIColor { return UIColor(crayolared:1.000 , green:0.667 , blue:0.800, alpha:1.0); } public class var crayolaCedarChestColor:UIColor { return UIColor(crayolared:0.788 , green:0.353 , blue:0.286, alpha:1.0); } public class var crayolaCeriseColor:UIColor { return UIColor(crayolared:0.867 , green:0.267 , blue:0.573, alpha:1.0); } public class var crayolaCeruleanColor:UIColor { return UIColor(crayolared:0.114 , green:0.675 , blue:0.839, alpha:1.0); } public class var crayolaCeruleanFrostColor:UIColor { return UIColor(crayolared:0.427 , green:0.608 , blue:0.765, alpha:1.0); } public class var crayolaCherryColor:UIColor { return UIColor(crayolared:0.855 , green:0.149 , blue:0.278, alpha:1.0); } public class var crayolaChestnutColor:UIColor { return UIColor(crayolared:0.737 , green:0.365 , blue:0.345, alpha:1.0); } public class var crayolaChocolateColor:UIColor { return UIColor(crayolared:0.741 , green:0.510 , blue:0.376, alpha:1.0); } public class var crayolaCinnamonSatinColor:UIColor { return UIColor(crayolared:0.804 , green:0.376 , blue:0.494, alpha:1.0); } public class var crayolaCitrineColor:UIColor { return UIColor(crayolared:0.576 , green:0.216 , blue:0.035, alpha:1.0); } public class var crayolaCoconutColor:UIColor { return UIColor(crayolared:0.996 , green:0.996 , blue:0.996, alpha:1.0); } public class var crayolaCopperColor:UIColor { return UIColor(crayolared:0.867 , green:0.580 , blue:0.459, alpha:1.0); } public class var crayolaCopperPennyColor:UIColor { return UIColor(crayolared:0.678 , green:0.435 , blue:0.412, alpha:1.0); } public class var crayolaCornflowerColor:UIColor { return UIColor(crayolared:0.604 , green:0.808 , blue:0.922, alpha:1.0); } public class var crayolaCosmicCobaltColor:UIColor { return UIColor(crayolared:0.180 , green:0.176 , blue:0.533, alpha:1.0); } public class var crayolaCottonCandyColor:UIColor { return UIColor(crayolared:1.000 , green:0.737 , blue:0.851, alpha:1.0); } public class var crayolaCulturedPearlColor:UIColor { return UIColor(crayolared:0.961 , green:0.961 , blue:0.961, alpha:1.0); } public class var crayolaCyberGrapeColor:UIColor { return UIColor(crayolared:0.345 , green:0.259 , blue:0.486, alpha:1.0); } public class var crayolaDaffodilColor:UIColor { return UIColor(crayolared:1.000 , green:1.000 , blue:0.192, alpha:1.0); } public class var crayolaDandelionColor:UIColor { return UIColor(crayolared:0.992 , green:0.859 , blue:0.427, alpha:1.0); } public class var crayolaDeepSpaceSparkleColor:UIColor { return UIColor(crayolared:0.290 , green:0.392 , blue:0.424, alpha:1.0); } public class var crayolaDenimColor:UIColor { return UIColor(crayolared:0.169 , green:0.424 , blue:0.769, alpha:1.0); } public class var crayolaDenimBlueColor:UIColor { return UIColor(crayolared:0.133 , green:0.263 , blue:0.714, alpha:1.0); } public class var crayolaDesertSandColor:UIColor { return UIColor(crayolared:0.937 , green:0.804 , blue:0.722, alpha:1.0); } public class var crayolaDingyDungeonColor:UIColor { return UIColor(crayolared:0.773 , green:0.192 , blue:0.318, alpha:1.0); } public class var crayolaDirtColor:UIColor { return UIColor(crayolared:0.608 , green:0.463 , blue:0.325, alpha:1.0); } public class var crayolaEerieBlackColor:UIColor { return UIColor(crayolared:0.106 , green:0.106 , blue:0.106, alpha:1.0); } public class var crayolaEggplantColor:UIColor { return UIColor(crayolared:0.431 , green:0.318 , blue:0.376, alpha:1.0); } public class var crayolaElectricLimeColor:UIColor { return UIColor(crayolared:0.808 , green:1.000 , blue:0.114, alpha:1.0); } public class var crayolaEmeraldColor:UIColor { return UIColor(crayolared:0.078 , green:0.663 , blue:0.537, alpha:1.0); } public class var crayolaEucalyptusColor:UIColor { return UIColor(crayolared:0.267 , green:0.843 , blue:0.659, alpha:1.0); } public class var crayolaFernColor:UIColor { return UIColor(crayolared:0.443 , green:0.737 , blue:0.471, alpha:1.0); } public class var crayolaFieryRoseColor:UIColor { return UIColor(crayolared:1.000 , green:0.329 , blue:0.439, alpha:1.0); } public class var crayolaForestGreenColor:UIColor { return UIColor(crayolared:0.427 , green:0.682 , blue:0.506, alpha:1.0); } public class var crayolaFreshAirColor:UIColor { return UIColor(crayolared:0.651 , green:0.906 , blue:1.000, alpha:1.0); } public class var crayolaFrostbiteColor:UIColor { return UIColor(crayolared:0.914 , green:0.212 , blue:0.655, alpha:1.0); } public class var crayolaFuchsiaColor:UIColor { return UIColor(crayolared:0.765 , green:0.392 , blue:0.773, alpha:1.0); } public class var crayolaFuzzyWuzzyColor:UIColor { return UIColor(crayolared:0.800 , green:0.400 , blue:0.400, alpha:1.0); } public class var crayolaGargoyleGasColor:UIColor { return UIColor(crayolared:1.000 , green:0.875 , blue:0.275, alpha:1.0); } public class var crayolaGiantsClubColor:UIColor { return UIColor(crayolared:0.690 , green:0.361 , blue:0.322, alpha:1.0); } public class var crayolaGlossyGrapeColor:UIColor { return UIColor(crayolared:0.671 , green:0.573 , blue:0.702, alpha:1.0); } public class var crayolaGoldColor:UIColor { return UIColor(crayolared:0.906 , green:0.776 , blue:0.592, alpha:1.0); } public class var crayolaGoldFusionColor:UIColor { return UIColor(crayolared:0.522 , green:0.459 , blue:0.306, alpha:1.0); } public class var crayolaGoldenrodColor:UIColor { return UIColor(crayolared:0.988 , green:0.851 , blue:0.459, alpha:1.0); } public class var crayolaGraniteGrayColor:UIColor { return UIColor(crayolared:0.404 , green:0.404 , blue:0.404, alpha:1.0); } public class var crayolaGrannySmithAppleColor:UIColor { return UIColor(crayolared:0.659 , green:0.894 , blue:0.627, alpha:1.0); } public class var crayolaGrapeColor:UIColor { return UIColor(crayolared:0.435 , green:0.176 , blue:0.659, alpha:1.0); } public class var crayolaGrayColor:UIColor { return UIColor(crayolared:0.584 , green:0.569 , blue:0.549, alpha:1.0); } public class var crayolaGreenColor:UIColor { return UIColor(crayolared:0.110 , green:0.675 , blue:0.471, alpha:1.0); } public class var crayolaGreenBlueColor:UIColor { return UIColor(crayolared:0.067 , green:0.392 , blue:0.706, alpha:1.0); } public class var crayolaGreenLizardColor:UIColor { return UIColor(crayolared:0.655 , green:0.957 , blue:0.196, alpha:1.0); } public class var crayolaGreenSheenColor:UIColor { return UIColor(crayolared:0.431 , green:0.682 , blue:0.631, alpha:1.0); } public class var crayolaGreenYellowColor:UIColor { return UIColor(crayolared:0.941 , green:0.910 , blue:0.569, alpha:1.0); } public class var crayolaHeatWaveColor:UIColor { return UIColor(crayolared:1.000 , green:0.478 , blue:0.000, alpha:1.0); } public class var crayolaHotMagentaColor:UIColor { return UIColor(crayolared:1.000 , green:0.114 , blue:0.808, alpha:1.0); } public class var crayolaIlluminatingEmeraldColor:UIColor { return UIColor(crayolared:0.192 , green:0.569 , blue:0.467, alpha:1.0); } public class var crayolaInchwormColor:UIColor { return UIColor(crayolared:0.698 , green:0.925 , blue:0.365, alpha:1.0); } public class var crayolaIndigoColor:UIColor { return UIColor(crayolared:0.365 , green:0.463 , blue:0.796, alpha:1.0); } public class var crayolaJadeColor:UIColor { return UIColor(crayolared:0.275 , green:0.604 , blue:0.518, alpha:1.0); } public class var crayolaJasperColor:UIColor { return UIColor(crayolared:0.816 , green:0.325 , blue:0.251, alpha:1.0); } public class var crayolaJazzberryJamColor:UIColor { return UIColor(crayolared:0.792 , green:0.216 , blue:0.404, alpha:1.0); } public class var crayolaJellyBeanColor:UIColor { return UIColor(crayolared:0.855 , green:0.380 , blue:0.306, alpha:1.0); } public class var crayolaJungleGreenColor:UIColor { return UIColor(crayolared:0.231 , green:0.690 , blue:0.561, alpha:1.0); } public class var crayolaKeyLimePearlColor:UIColor { return UIColor(crayolared:0.910 , green:0.957 , blue:0.549, alpha:1.0); } public class var crayolaLapisLazuliColor:UIColor { return UIColor(crayolared:0.263 , green:0.424 , blue:0.725, alpha:1.0); } public class var crayolaLaserLemonColor:UIColor { return UIColor(crayolared:0.996 , green:0.996 , blue:0.133, alpha:1.0); } public class var crayolaLavenderColor:UIColor { return UIColor(crayolared:0.988 , green:0.706 , blue:0.835, alpha:1.0); } public class var crayolaLeatherJacketColor:UIColor { return UIColor(crayolared:0.145 , green:0.208 , blue:0.161, alpha:1.0); } public class var crayolaLemonColor:UIColor { return UIColor(crayolared:1.000 , green:1.000 , blue:0.220, alpha:1.0); } public class var crayolaLemonGlacierColor:UIColor { return UIColor(crayolared:0.992 , green:1.000 , blue:0.000, alpha:1.0); } public class var crayolaLemonYellowColor:UIColor { return UIColor(crayolared:1.000 , green:0.957 , blue:0.310, alpha:1.0); } public class var crayolaLicoriceColor:UIColor { return UIColor(crayolared:0.102 , green:0.067 , blue:0.063, alpha:1.0); } public class var crayolaLilacColor:UIColor { return UIColor(crayolared:0.859 , green:0.569 , blue:0.937, alpha:1.0); } public class var crayolaLilacLusterColor:UIColor { return UIColor(crayolared:0.682 , green:0.596 , blue:0.667, alpha:1.0); } public class var crayolaLimeColor:UIColor { return UIColor(crayolared:0.698 , green:0.953 , blue:0.008, alpha:1.0); } public class var crayolaLumberColor:UIColor { return UIColor(crayolared:1.000 , green:0.894 , blue:0.804, alpha:1.0); } public class var crayolaMacaroniCheeseColor:UIColor { return UIColor(crayolared:1.000 , green:0.741 , blue:0.533, alpha:1.0); } public class var crayolaMagentaColor:UIColor { return UIColor(crayolared:0.965 , green:0.392 , blue:0.686, alpha:1.0); } public class var crayolaMagicMintColor:UIColor { return UIColor(crayolared:0.667 , green:0.941 , blue:0.820, alpha:1.0); } public class var crayolaMagicPotionColor:UIColor { return UIColor(crayolared:1.000 , green:0.267 , blue:0.400, alpha:1.0); } public class var crayolaMahoganyColor:UIColor { return UIColor(crayolared:0.804 , green:0.290 , blue:0.298, alpha:1.0); } public class var crayolaMaizeColor:UIColor { return UIColor(crayolared:0.929 , green:0.820 , blue:0.612, alpha:1.0); } public class var crayolaMalachiteColor:UIColor { return UIColor(crayolared:0.275 , green:0.580 , blue:0.588, alpha:1.0); } public class var crayolaManateeColor:UIColor { return UIColor(crayolared:0.592 , green:0.604 , blue:0.667, alpha:1.0); } public class var crayolaMandarinPearlColor:UIColor { return UIColor(crayolared:0.953 , green:0.478 , blue:0.282, alpha:1.0); } public class var crayolaMangoTangoColor:UIColor { return UIColor(crayolared:1.000 , green:0.510 , blue:0.263, alpha:1.0); } public class var crayolaMaroonColor:UIColor { return UIColor(crayolared:0.784 , green:0.220 , blue:0.353, alpha:1.0); } public class var crayolaMauvelousColor:UIColor { return UIColor(crayolared:0.937 , green:0.596 , blue:0.667, alpha:1.0); } public class var crayolaMelonColor:UIColor { return UIColor(crayolared:0.992 , green:0.737 , blue:0.706, alpha:1.0); } public class var crayolaMetallicSeaweedColor:UIColor { return UIColor(crayolared:0.039 , green:0.494 , blue:0.549, alpha:1.0); } public class var crayolaMetallicSunburstColor:UIColor { return UIColor(crayolared:0.612 , green:0.486 , blue:0.220, alpha:1.0); } public class var crayolaMidnightBlueColor:UIColor { return UIColor(crayolared:0.102 , green:0.282 , blue:0.463, alpha:1.0); } public class var crayolaMidnightPearlColor:UIColor { return UIColor(crayolared:0.439 , green:0.149 , blue:0.439, alpha:1.0); } public class var crayolaMistyMossColor:UIColor { return UIColor(crayolared:0.733 , green:0.706 , blue:0.467, alpha:1.0); } public class var crayolaMoonstoneColor:UIColor { return UIColor(crayolared:0.227 , green:0.659 , blue:0.757, alpha:1.0); } public class var crayolaMountainMeadowColor:UIColor { return UIColor(crayolared:0.188 , green:0.729 , blue:0.561, alpha:1.0); } public class var crayolaMulberryColor:UIColor { return UIColor(crayolared:0.773 , green:0.294 , blue:0.549, alpha:1.0); } public class var crayolaMummysTombColor:UIColor { return UIColor(crayolared:0.510 , green:0.557 , blue:0.518, alpha:1.0); } public class var crayolaMysticMaroonColor:UIColor { return UIColor(crayolared:0.678 , green:0.263 , blue:0.475, alpha:1.0); } public class var crayolaMysticPearlColor:UIColor { return UIColor(crayolared:0.839 , green:0.322 , blue:0.510, alpha:1.0); } public class var crayolaNavyBlueColor:UIColor { return UIColor(crayolared:0.098 , green:0.455 , blue:0.824, alpha:1.0); } public class var crayolaNeonCarrotColor:UIColor { return UIColor(crayolared:1.000 , green:0.639 , blue:0.263, alpha:1.0); } public class var crayolaNewCarColor:UIColor { return UIColor(crayolared:0.129 , green:0.310 , blue:0.776, alpha:1.0); } public class var crayolaOceanBluePearlColor:UIColor { return UIColor(crayolared:0.310 , green:0.259 , blue:0.710, alpha:1.0); } public class var crayolaOceanGreenPearlColor:UIColor { return UIColor(crayolared:0.282 , green:0.749 , blue:0.569, alpha:1.0); } public class var crayolaOgreOdorColor:UIColor { return UIColor(crayolared:0.992 , green:0.322 , blue:0.251, alpha:1.0); } public class var crayolaOliveGreenColor:UIColor { return UIColor(crayolared:0.729 , green:0.722 , blue:0.424, alpha:1.0); } public class var crayolaOnyxColor:UIColor { return UIColor(crayolared:0.208 , green:0.220 , blue:0.224, alpha:1.0); } public class var crayolaOrangeColor:UIColor { return UIColor(crayolared:1.000 , green:0.459 , blue:0.220, alpha:1.0); } public class var crayolaOrangeRedColor:UIColor { return UIColor(crayolared:1.000 , green:0.169 , blue:0.169, alpha:1.0); } public class var crayolaOrangeSodaColor:UIColor { return UIColor(crayolared:0.980 , green:0.357 , blue:0.239, alpha:1.0); } public class var crayolaOrangeYellowColor:UIColor { return UIColor(crayolared:0.973 , green:0.835 , blue:0.408, alpha:1.0); } public class var crayolaOrchidColor:UIColor { return UIColor(crayolared:0.902 , green:0.659 , blue:0.843, alpha:1.0); } public class var crayolaOrchidPearlColor:UIColor { return UIColor(crayolared:0.482 , green:0.259 , blue:0.349, alpha:1.0); } public class var crayolaOuterSpaceColor:UIColor { return UIColor(crayolared:0.255 , green:0.290 , blue:0.298, alpha:1.0); } public class var crayolaOutrageousOrangeColor:UIColor { return UIColor(crayolared:1.000 , green:0.431 , blue:0.290, alpha:1.0); } public class var crayolaPacificBlueColor:UIColor { return UIColor(crayolared:0.110 , green:0.663 , blue:0.788, alpha:1.0); } public class var crayolaPeachColor:UIColor { return UIColor(crayolared:1.000 , green:0.812 , blue:0.671, alpha:1.0); } public class var crayolaPearlyPurpleColor:UIColor { return UIColor(crayolared:0.718 , green:0.408 , blue:0.635, alpha:1.0); } public class var crayolaPeridotColor:UIColor { return UIColor(crayolared:0.671 , green:0.678 , blue:0.282, alpha:1.0); } public class var crayolaPeriwinkleColor:UIColor { return UIColor(crayolared:0.773 , green:0.816 , blue:0.902, alpha:1.0); } public class var crayolaPewterBlueColor:UIColor { return UIColor(crayolared:0.545 , green:0.659 , blue:0.718, alpha:1.0); } public class var crayolaPiggyPinkColor:UIColor { return UIColor(crayolared:0.992 , green:0.867 , blue:0.902, alpha:1.0); } public class var crayolaPineColor:UIColor { return UIColor(crayolared:0.271 , green:0.635 , blue:0.490, alpha:1.0); } public class var crayolaPineGreenColor:UIColor { return UIColor(crayolared:0.082 , green:0.502 , blue:0.471, alpha:1.0); } public class var crayolaPinkFlamingoColor:UIColor { return UIColor(crayolared:0.988 , green:0.455 , blue:0.992, alpha:1.0); } public class var crayolaPinkPearlColor:UIColor { return UIColor(crayolared:0.690 , green:0.439 , blue:0.502, alpha:1.0); } public class var crayolaPinkSherbertColor:UIColor { return UIColor(crayolared:0.969 , green:0.561 , blue:0.655, alpha:1.0); } public class var crayolaPixiePowderColor:UIColor { return UIColor(crayolared:0.224 , green:0.071 , blue:0.522, alpha:1.0); } public class var crayolaPlumColor:UIColor { return UIColor(crayolared:0.557 , green:0.271 , blue:0.522, alpha:1.0); } public class var crayolaPlumpPurpleColor:UIColor { return UIColor(crayolared:0.349 , green:0.275 , blue:0.698, alpha:1.0); } public class var crayolaPolishedPineColor:UIColor { return UIColor(crayolared:0.365 , green:0.643 , blue:0.576, alpha:1.0); } public class var crayolaPrincessPerfumeColor:UIColor { return UIColor(crayolared:1.000 , green:0.522 , blue:0.812, alpha:1.0); } public class var crayolaPurpleHeartColor:UIColor { return UIColor(crayolared:0.455 , green:0.259 , blue:0.784, alpha:1.0); } public class var crayolaPurpleMountainsMajestyColor:UIColor { return UIColor(crayolared:0.616 , green:0.506 , blue:0.729, alpha:1.0); } public class var crayolaPurplePizzazzColor:UIColor { return UIColor(crayolared:0.996 , green:0.306 , blue:0.855, alpha:1.0); } public class var crayolaPurplePlumColor:UIColor { return UIColor(crayolared:0.612 , green:0.318 , blue:0.714, alpha:1.0); } public class var crayolaQuickSilverColor:UIColor { return UIColor(crayolared:0.651 , green:0.651 , blue:0.651, alpha:1.0); } public class var crayolaRadicalRedColor:UIColor { return UIColor(crayolared:1.000 , green:0.286 , blue:0.424, alpha:1.0); } public class var crayolaRawSiennaColor:UIColor { return UIColor(crayolared:0.839 , green:0.541 , blue:0.349, alpha:1.0); } public class var crayolaRawUmberColor:UIColor { return UIColor(crayolared:0.443 , green:0.294 , blue:0.137, alpha:1.0); } public class var crayolaRazzleDazzleRoseColor:UIColor { return UIColor(crayolared:1.000 , green:0.282 , blue:0.816, alpha:1.0); } public class var crayolaRazzmatazzColor:UIColor { return UIColor(crayolared:0.890 , green:0.145 , blue:0.420, alpha:1.0); } public class var crayolaRazzmicBerryColor:UIColor { return UIColor(crayolared:0.553 , green:0.306 , blue:0.522, alpha:1.0); } public class var crayolaRedColor:UIColor { return UIColor(crayolared:0.933 , green:0.125 , blue:0.302, alpha:1.0); } public class var crayolaRedOrangeColor:UIColor { return UIColor(crayolared:1.000 , green:0.325 , blue:0.286, alpha:1.0); } public class var crayolaRedSalsaColor:UIColor { return UIColor(crayolared:0.992 , green:0.227 , blue:0.290, alpha:1.0); } public class var crayolaRedVioletColor:UIColor { return UIColor(crayolared:0.753 , green:0.267 , blue:0.561, alpha:1.0); } public class var crayolaRobinsEggBlueColor:UIColor { return UIColor(crayolared:0.122 , green:0.808 , blue:0.796, alpha:1.0); } public class var crayolaRoseColor:UIColor { return UIColor(crayolared:1.000 , green:0.314 , blue:0.314, alpha:1.0); } public class var crayolaRoseDustColor:UIColor { return UIColor(crayolared:0.620 , green:0.369 , blue:0.435, alpha:1.0); } public class var crayolaRosePearlColor:UIColor { return UIColor(crayolared:0.941 , green:0.220 , blue:0.396, alpha:1.0); } public class var crayolaRoseQuartzColor:UIColor { return UIColor(crayolared:0.741 , green:0.333 , blue:0.612, alpha:1.0); } public class var crayolaRoyalPurpleColor:UIColor { return UIColor(crayolared:0.471 , green:0.318 , blue:0.663, alpha:1.0); } public class var crayolaRubyColor:UIColor { return UIColor(crayolared:0.667 , green:0.251 , blue:0.412, alpha:1.0); } public class var crayolaRustyRedColor:UIColor { return UIColor(crayolared:0.855 , green:0.173 , blue:0.263, alpha:1.0); } public class var crayolaSalmonColor:UIColor { return UIColor(crayolared:1.000 , green:0.608 , blue:0.667, alpha:1.0); } public class var crayolaSalmonPearlColor:UIColor { return UIColor(crayolared:0.945 , green:0.267 , blue:0.290, alpha:1.0); } public class var crayolaSapphireColor:UIColor { return UIColor(crayolared:0.176 , green:0.365 , blue:0.631, alpha:1.0); } public class var crayolaSasquatchSocksColor:UIColor { return UIColor(crayolared:1.000 , green:0.275 , blue:0.506, alpha:1.0); } public class var crayolaScarletColor:UIColor { return UIColor(crayolared:0.988 , green:0.157 , blue:0.278, alpha:1.0); } public class var crayolaScreaminGreenColor:UIColor { return UIColor(crayolared:0.463 , green:1.000 , blue:0.478, alpha:1.0); } public class var crayolaSeaGreenColor:UIColor { return UIColor(crayolared:0.624 , green:0.886 , blue:0.749, alpha:1.0); } public class var crayolaSeaSerpentColor:UIColor { return UIColor(crayolared:0.294 , green:0.780 , blue:0.812, alpha:1.0); } public class var crayolaSepiaColor:UIColor { return UIColor(crayolared:0.647 , green:0.412 , blue:0.310, alpha:1.0); } public class var crayolaShadowColor:UIColor { return UIColor(crayolared:0.541 , green:0.475 , blue:0.365, alpha:1.0); } public class var crayolaShadowBlueColor:UIColor { return UIColor(crayolared:0.467 , green:0.545 , blue:0.647, alpha:1.0); } public class var crayolaShampooColor:UIColor { return UIColor(crayolared:1.000 , green:0.812 , blue:0.945, alpha:1.0); } public class var crayolaShamrockColor:UIColor { return UIColor(crayolared:0.271 , green:0.808 , blue:0.635, alpha:1.0); } public class var crayolaSheenGreenColor:UIColor { return UIColor(crayolared:0.561 , green:0.831 , blue:0.000, alpha:1.0); } public class var crayolaShimmeringBlushColor:UIColor { return UIColor(crayolared:0.851 , green:0.525 , blue:0.584, alpha:1.0); } public class var crayolaShinyShamrockColor:UIColor { return UIColor(crayolared:0.373 , green:0.655 , blue:0.471, alpha:1.0); } public class var crayolaShockingPinkColor:UIColor { return UIColor(crayolared:0.984 , green:0.494 , blue:0.992, alpha:1.0); } public class var crayolaSilverColor:UIColor { return UIColor(crayolared:0.804 , green:0.773 , blue:0.761, alpha:1.0); } public class var crayolaSizzlingRedColor:UIColor { return UIColor(crayolared:1.000 , green:0.220 , blue:0.333, alpha:1.0); } public class var crayolaSizzlingSunriseColor:UIColor { return UIColor(crayolared:1.000 , green:0.859 , blue:0.000, alpha:1.0); } public class var crayolaSkyBlueColor:UIColor { return UIColor(crayolared:0.502 , green:0.855 , blue:0.922, alpha:1.0); } public class var crayolaSlimyGreenColor:UIColor { return UIColor(crayolared:0.161 , green:0.588 , blue:0.090, alpha:1.0); } public class var crayolaSmashedPumpkinColor:UIColor { return UIColor(crayolared:1.000 , green:0.427 , blue:0.227, alpha:1.0); } public class var crayolaSmokeColor:UIColor { return UIColor(crayolared:0.451 , green:0.510 , blue:0.463, alpha:1.0); } public class var crayolaSmokeyTopazColor:UIColor { return UIColor(crayolared:0.514 , green:0.165 , blue:0.051, alpha:1.0); } public class var crayolaSoapColor:UIColor { return UIColor(crayolared:0.808 , green:0.784 , blue:0.937, alpha:1.0); } public class var crayolaSonicSilverColor:UIColor { return UIColor(crayolared:0.459 , green:0.459 , blue:0.459, alpha:1.0); } public class var crayolaSpringFrostColor:UIColor { return UIColor(crayolared:0.529 , green:1.000 , blue:0.165, alpha:1.0); } public class var crayolaSpringGreenColor:UIColor { return UIColor(crayolared:0.925 , green:0.918 , blue:0.745, alpha:1.0); } public class var crayolaSteelBlueColor:UIColor { return UIColor(crayolared:0.000 , green:0.506 , blue:0.671, alpha:1.0); } public class var crayolaSteelTealColor:UIColor { return UIColor(crayolared:0.373 , green:0.541 , blue:0.545, alpha:1.0); } public class var crayolaStrawberryColor:UIColor { return UIColor(crayolared:0.988 , green:0.353 , blue:0.553, alpha:1.0); } public class var crayolaSugarPlumColor:UIColor { return UIColor(crayolared:0.569 , green:0.306 , blue:0.459, alpha:1.0); } public class var crayolaSunburntCyclopsColor:UIColor { return UIColor(crayolared:1.000 , green:0.251 , blue:0.298, alpha:1.0); } public class var crayolaSunglowColor:UIColor { return UIColor(crayolared:1.000 , green:0.812 , blue:0.282, alpha:1.0); } public class var crayolaSunnyPearlColor:UIColor { return UIColor(crayolared:0.949 , green:0.949 , blue:0.478, alpha:1.0); } public class var crayolaSunsetOrangeColor:UIColor { return UIColor(crayolared:0.992 , green:0.369 , blue:0.325, alpha:1.0); } public class var crayolaSunsetPearlColor:UIColor { return UIColor(crayolared:0.945 , green:0.800 , blue:0.475, alpha:1.0); } public class var crayolaSweetBrownColor:UIColor { return UIColor(crayolared:0.659 , green:0.216 , blue:0.192, alpha:1.0); } public class var crayolaTanColor:UIColor { return UIColor(crayolared:0.980 , green:0.655 , blue:0.424, alpha:1.0); } public class var crayolaTartOrangeColor:UIColor { return UIColor(crayolared:0.984 , green:0.302 , blue:0.275, alpha:1.0); } public class var crayolaTealBlueColor:UIColor { return UIColor(crayolared:0.094 , green:0.655 , blue:0.710, alpha:1.0); } public class var crayolaThistleColor:UIColor { return UIColor(crayolared:0.922 , green:0.780 , blue:0.875, alpha:1.0); } public class var crayolaTickleMePinkColor:UIColor { return UIColor(crayolared:0.988 , green:0.537 , blue:0.675, alpha:1.0); } public class var crayolaTigersEyeColor:UIColor { return UIColor(crayolared:0.710 , green:0.412 , blue:0.090, alpha:1.0); } public class var crayolaTimberwolfColor:UIColor { return UIColor(crayolared:0.859 , green:0.843 , blue:0.824, alpha:1.0); } public class var crayolaTropicalRainForestColor:UIColor { return UIColor(crayolared:0.090 , green:0.502 , blue:0.427, alpha:1.0); } public class var crayolaTulipColor:UIColor { return UIColor(crayolared:1.000 , green:0.529 , blue:0.553, alpha:1.0); } public class var crayolaTumbleweedColor:UIColor { return UIColor(crayolared:0.871 , green:0.667 , blue:0.533, alpha:1.0); } public class var crayolaTurquoiseBlueColor:UIColor { return UIColor(crayolared:0.467 , green:0.867 , blue:0.906, alpha:1.0); } public class var crayolaTurquoisePearlColor:UIColor { return UIColor(crayolared:0.231 , green:0.737 , blue:0.816, alpha:1.0); } public class var crayolaTwilightLavenderColor:UIColor { return UIColor(crayolared:0.541 , green:0.286 , blue:0.420, alpha:1.0); } public class var crayolaUnmellowYellowColor:UIColor { return UIColor(crayolared:1.000 , green:1.000 , blue:0.400, alpha:1.0); } public class var crayolaVioletBlueColor:UIColor { return UIColor(crayolared:0.196 , green:0.290 , blue:0.698, alpha:1.0); } public class var crayolaVioletPurpleColor:UIColor { return UIColor(crayolared:0.573 , green:0.431 , blue:0.682, alpha:1.0); } public class var crayolaVioletRedColor:UIColor { return UIColor(crayolared:0.969 , green:0.325 , blue:0.580, alpha:1.0); } public class var crayolaVividTangerineColor:UIColor { return UIColor(crayolared:1.000 , green:0.627 , blue:0.537, alpha:1.0); } public class var crayolaVividVioletColor:UIColor { return UIColor(crayolared:0.561 , green:0.314 , blue:0.616, alpha:1.0); } public class var crayolaWhiteColor:UIColor { return UIColor(crayolared:1.000 , green:1.000 , blue:1.000, alpha:1.0); } public class var crayolaWildBlueYonderColor:UIColor { return UIColor(crayolared:0.635 , green:0.678 , blue:0.816, alpha:1.0); } public class var crayolaWildStrawberryColor:UIColor { return UIColor(crayolared:1.000 , green:0.263 , blue:0.643, alpha:1.0); } public class var crayolaWildWatermelonColor:UIColor { return UIColor(crayolared:0.988 , green:0.424 , blue:0.522, alpha:1.0); } public class var crayolaWinterSkyColor:UIColor { return UIColor(crayolared:1.000 , green:0.000 , blue:0.486, alpha:1.0); } public class var crayolaWinterWizardColor:UIColor { return UIColor(crayolared:0.627 , green:0.902 , blue:1.000, alpha:1.0); } public class var crayolaWintergreenDreamColor:UIColor { return UIColor(crayolared:0.337 , green:0.533 , blue:0.490, alpha:1.0); } public class var crayolaWisteriaColor:UIColor { return UIColor(crayolared:0.804 , green:0.643 , blue:0.871, alpha:1.0); } public class var crayolaYellowColor:UIColor { return UIColor(crayolared:0.988 , green:0.910 , blue:0.514, alpha:1.0); } public class var crayolaYellowGreenColor:UIColor { return UIColor(crayolared:0.773 , green:0.890 , blue:0.518, alpha:1.0); } public class var crayolaYellowOrangeColor:UIColor { return UIColor(crayolared:1.000 , green:0.714 , blue:0.325, alpha:1.0); } public class var crayolaYellowSunshineColor:UIColor { return UIColor(crayolared:1.000 , green:0.969 , blue:0.000, alpha:1.0); } class var cache: NSCache<NSString, UIColor> { return NSCache() } // constructor copy convenience init(color: UIColor) { var red:CGFloat = 0 var green:CGFloat = 0 var blue:CGFloat = 0 var alpha:CGFloat = 1.0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) self.init(red:red , green:green, blue:blue, alpha:alpha); } convenience init(crayolared:CGFloat , green:CGFloat , blue:CGFloat, alpha:CGFloat) { let cacheKey = UIColor.cacheKeyWithRed(red:crayolared , green:green , blue:blue, alpha:alpha); let color = UIColor.cache.object(forKey: cacheKey); if(color != nil) { UIColor.cache.setObject(color!,forKey:cacheKey) self.init(color:color!) } else { self.init(red:crayolared , green:green , blue:blue, alpha:alpha) } } static func cacheKeyWithRed(red:CGFloat , green:CGFloat , blue:CGFloat, alpha:CGFloat) -> NSString { return NSString(format:"%.2f%.2f%.2f%.2f", red, green, blue, alpha); } }
apache-2.0
6541e68ed2d491d198abd8dc806d952e
28.847966
104
0.630055
3.131187
false
false
false
false
ddaguro/clintonconcord
OIMApp/Controls/ADVProgressControl/ADVProgressControl.swift
1
3826
// // ADVPieControl.swift // Mega // // Created by Tope Abayomi on 02/12/2014. // Copyright (c) 2014 App Design Vault. All rights reserved. // import Foundation import UIKit @IBDesignable class ADVProgressControl: UIControl { var label = UILabel() var progressLayer : ADVProgressLayer = ADVProgressLayer() var labelConstraintTop : NSLayoutConstraint! var labelConstraintBottom : NSLayoutConstraint! var labelConstraintLeft : NSLayoutConstraint! var labelConstraintRight : NSLayoutConstraint! @IBInspectable var strokeWidth : CGFloat = 15 { didSet { progressLayer.strokeWidth = strokeWidth progressLayer.setNeedsDisplay() } } @IBInspectable var progress : CGFloat = 0.75 { didSet { progressLayer.progress = progress progressLayer.setNeedsDisplay() } } @IBInspectable var gradientStart : UIColor = UIColor.blackColor() { didSet { progressLayer.gradientStart = gradientStart progressLayer.setNeedsDisplay() } } @IBInspectable var gradientEnd : UIColor = UIColor.whiteColor() { didSet { progressLayer.gradientEnd = gradientEnd progressLayer.setNeedsDisplay() } } @IBInspectable var labelFont : UIFont! = UIFont.systemFontOfSize(14) { didSet { label.font = labelFont } } @IBInspectable var labelTextColor : UIColor = UIColor.lightGrayColor() { didSet { label.textColor = labelTextColor } } @IBInspectable var labelText : String = "STATS 2015" { didSet { label.text = labelText } } override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { super.init(coder: coder) setupView() } func setupView(){ layer.addSublayer(progressLayer) progressLayer.setNeedsDisplay() self.backgroundColor = UIColor.clearColor() label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clearColor() label.textAlignment = .Center addSubview(label) let spacing = strokeWidth + (strokeWidth/2) labelConstraintTop = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: spacing) labelConstraintBottom = NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: -spacing) labelConstraintLeft = NSLayoutConstraint(item: label, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: spacing) labelConstraintRight = NSLayoutConstraint(item: label, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: -spacing) self.addConstraints([labelConstraintTop, labelConstraintBottom, labelConstraintLeft, labelConstraintRight]) } func updateProgress(){ progressLayer.progress = progress progressLayer.setNeedsDisplay() } override func drawRect(rect: CGRect) { progressLayer.frame = bounds label.font = labelFont label.text = labelText label.textColor = labelTextColor let spacing = strokeWidth + (strokeWidth/2) labelConstraintTop.constant = spacing labelConstraintBottom.constant = -spacing labelConstraintLeft.constant = spacing labelConstraintRight.constant = -spacing } }
mit
6b0f105af5fa27cab49a6eda1b332f9d
29.862903
173
0.633037
5.262724
false
false
false
false
mhmiles/PodcastFeedFinder
Carthage/Checkouts/Fuzi/FuziTests/HTMLTests.swift
1
5107
// HTMLTests.swift // Copyright (c) 2015 Ce Zheng // // 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 Fuzi class HTMLTests: XCTestCase { var document: HTMLDocument! override func setUp() { super.setUp() let filePath = Bundle(for: HTMLTests.self).url(forResource: "web", withExtension: "html")! do { document = try HTMLDocument(data: Data(contentsOf: filePath)) } catch { XCTAssertFalse(true, "Error should not be thrown") } } func testRoot() { XCTAssertEqual(document.root!.tag, "html", "html not root element") } func testRootChildren() { let children = document.root?.children XCTAssertNotNil(children) XCTAssertEqual(children?.count, 2, "root element should have exactly two children") XCTAssertEqual(children?.first?.tag, "head", "head not first child of html") XCTAssertEqual(children?.last?.tag, "body", "body not last child of html") } func testTitleXPath() { var idx = 0 for element in document.xpath("//head/title") { XCTAssertEqual(idx, 0, "more than one element found") XCTAssertEqual(element.stringValue, "mattt/Ono", "title mismatch") idx += 1 } XCTAssertEqual(idx, 1, "should be exactly 1 element") } func testTitleCSS() { var idx = 0 for element in document.css("head title") { XCTAssertEqual(idx, 0, "more than one element found") XCTAssertEqual(element.stringValue, "mattt/Ono", "title mismatch") idx += 1 } XCTAssertEqual(idx, 1, "should be exactly 1 element") } func testIDCSS() { var idx = 0 for element in document.css("#account_settings") { XCTAssertEqual(idx, 0, "more than one element found") XCTAssertEqual(element["href"], "/settings/profile", "href mismatch") idx += 1 } XCTAssertEqual(idx, 1, "should be exactly 1 element") } func testThrowError() { do { document = try HTMLDocument(cChars: [CChar]()) XCTAssertFalse(true, "error should have been thrown") } catch XMLError.parserFailure { } catch { XCTAssertFalse(true, "error type should be ParserFailure") } } func testTitle() { XCTAssertEqual(document.title, "mattt/Ono", "title is not correct") } func testHead() { let head = document.head XCTAssertNotNil(head) XCTAssertEqual(head?.children(tag: "link").count, 13, "link element count is incorrect") XCTAssertEqual(head?.children(tag: "meta").count, 38, "meta element count is incorrect") let scripts = head?.children(tag: "script") XCTAssertEqual(scripts?.count, 2, "scripts count is incorrect") XCTAssertEqual(scripts?.first?["src"], "https://github.global.ssl.fastly.net/assets/frameworks-3d18c504ea97dc018d44d64d8fce147a96a944b8.js", "script 1's src is incorrect") XCTAssertEqual(scripts?.last?["src"], "https://github.global.ssl.fastly.net/assets/github-602f74794536bf3e30e883a2cf268ca8e05b651d.js", "script 2's src is incorrect") XCTAssertEqual(head?["prefix"], "og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#", "prefix attribute value is incorrect") } func testBody() { let body = document.body XCTAssertNotNil(body) XCTAssertEqual(body?["class"], "logged_in env-production macintosh vis-public", "body class is incorrect") XCTAssertEqual(body?.children(tag: "div").count, 4, "div count is incorrect") } func testChildNodesWithElementsAndTextNodes() { let mixedNode = document.firstChild(css: "#ajax-error-message") let childNodes = mixedNode?.childNodes(ofTypes: [.Element, .Text]) XCTAssertEqual(childNodes?.count, 5, "should have 5 child nodes") XCTAssertEqual(childNodes?.flatMap { $0.toElement() }.count, 2, "should have 2 element nodes") XCTAssertEqual(childNodes?.flatMap { $0.type == .Element ? $0 : nil }.count, 2, "should have 2 element nodes") XCTAssertEqual(childNodes?.flatMap { $0.type == .Text ? $0 : nil }.count, 3, "should have 3 text nodes") } }
mit
83ef516eea670b29ca042511f06d34f5
41.206612
227
0.695908
4.002351
false
true
false
false
sotownsend/flok-apple
Example/Tests/Tests.swift
1
1171
// https://github.com/Quick/Quick import Quick import Nimble import flok class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
ed52fb66a5ac4b572d16a1023c420893
22.3
63
0.360515
5.443925
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Helpers/UserAgent/UserAgent.swift
1
1697
// // UserAgent.swift // // // Created by Vladislav Fitc on 14/04/2020. // import Foundation public struct UserAgent: Hashable { public let title: String public let version: String public init(title: String, version: String) { self.title = title self.version = version } } extension UserAgent: CustomStringConvertible { public var description: String { let versionOutput: String if version.isEmpty { versionOutput = version } else { versionOutput = "(\(version))" } return [title, versionOutput].filter { !$0.isEmpty }.joined(separator: " ") } } extension UserAgent: UserAgentExtending { public var userAgentExtension: String { return description } } extension UserAgent { static var library: UserAgent { return UserAgent(title: "Algolia for Swift", version: Version.current.description) } } extension UserAgent { static var operatingSystem: UserAgent = { let osVersion = ProcessInfo.processInfo.operatingSystemVersion var osVersionString = "\(osVersion.majorVersion).\(osVersion.minorVersion)" if osVersion.patchVersion != 0 { osVersionString += ".\(osVersion.patchVersion)" } if let osName = osName { return UserAgent(title: osName, version: osVersionString) } else { return UserAgent(title: ProcessInfo.processInfo.operatingSystemVersionString, version: "") } }() private static var osName: String? { #if os(iOS) return "iOS" #elseif os(OSX) return "macOS" #elseif os(tvOS) return "tvOS" #elseif os(watchOS) return "watchOS" #elseif os(Linux) return "Linux" #else return nil #endif } }
mit
84100776ca7c27ca93f97a363fec8f6b
19.445783
96
0.664702
4.296203
false
false
false
false
wanghdnku/Whisper
Whisper/SlideUpTransitionAnimator.swift
1
2498
// // SlideDownTransitionAnimator.swift // NavTransition // // Created by Hayden on 2016/10/19. // Copyright © 2016年 AppCoda. All rights reserved. // import UIKit class SlideUpTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { let duration = 0.5 var isPresenting = true func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)! let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)! let container = transitionContext.containerView // guard let container = transitionContext.containerView else { // return // } let offScreenUp = CGAffineTransform(translationX: 0, y: container.frame.height) let offScreenDown = CGAffineTransform(translationX: 0, y: -container.frame.height) if isPresenting { toView.transform = offScreenUp } container.addSubview(fromView) container.addSubview(toView) // Perform the animation UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: [], animations: { if self.isPresenting { fromView.transform = offScreenDown fromView.alpha = 1.0 toView.transform = CGAffineTransform.identity } else { fromView.transform = offScreenUp fromView.alpha = 1.0 toView.transform = CGAffineTransform.identity } }, completion: { finished in transitionContext.completeTransition(true) }) } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } }
mit
b6bede4b7f6a67dbaa5b874b64707cf5
32.266667
170
0.629259
6.284635
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
NoticiasLeganes/Chat/ViewControllers/ChatVC.swift
1
10067
// // ChatVC.swift // NoticiasLeganes // // Created by Alvaro Informática on 16/1/18. // Copyright © 2018 Alvaro Blazquez Montero. All rights reserved. // import UIKit import Firebase import FirebaseDatabase class ChatVC: UIViewController { /*var viewModel: ChatVM! var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) let chat = "Chat" let channel = "General" let typing = "GeneralTyping" private lazy var messageRef: DatabaseReference = Database.database().reference().child(chat).child(channel) private var newMessageRefHandle: DatabaseHandle? var messages = [JSQMessage]() private lazy var userIsTypingRef: DatabaseReference = Database.database().reference().child(chat).child(typing).child(self.senderId) private var localTyping = false var isTyping: Bool { get { return localTyping } set { localTyping = newValue userIsTypingRef.setValue(newValue) } } private lazy var usersTypingQuery: DatabaseQuery = Database.database().reference().child(chat).child(typing).queryOrderedByValue().queryEqual(toValue: true) lazy var outgoingBubbleImageView: JSQMessagesBubbleImage = self.setupOutgoingBubble() lazy var incomingBubbleImageView: JSQMessagesBubbleImage = self.setupIncomingBubble() var firstTime = true override func viewDidLoad() { super.viewDidLoad() //navigationController?.isNavigationBarHidden = true edgesForExtendedLayout = [] if viewModel.isRegister { senderId = viewModel.uid senderDisplayName = viewModel.alias inputToolbar.contentView.rightBarButtonItem.setTitle("ENVIAR", for: .normal) inputToolbar.contentView.rightBarButtonItemWidth = 60.0 } else { senderId = "" senderDisplayName = "" inputToolbar.contentView.rightBarButtonItem.setTitle("¡Conecta!", for: .normal) inputToolbar.contentView.rightBarButtonItem.isEnabled = true inputToolbar.contentView.rightBarButtonItemWidth = 150.0 inputToolbar.contentView.textView.isUserInteractionEnabled = false inputToolbar.contentView.leftBarButtonItem.isUserInteractionEnabled = false } observeMessages() prepareHideKeyboard() // No avatars collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSize.zero collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero inputToolbar.contentView.leftBarButtonItem.isHidden = true inputToolbar.contentView.leftBarButtonItemWidth = 0.0 Analytics.watchChat() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if firstTime { prepareActivityIndicator() firstTime = false } if viewModel.isRegister && !inputToolbar.contentView.textView.isUserInteractionEnabled { senderId = viewModel.uid senderDisplayName = viewModel.alias inputToolbar.contentView.rightBarButtonItem.setTitle("ENVIAR", for: .normal) inputToolbar.contentView.rightBarButtonItem.isEnabled = false inputToolbar.contentView.rightBarButtonItemWidth = 60.0 inputToolbar.contentView.textView.isUserInteractionEnabled = true } if viewModel.isRegister { observeTyping() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func addMessage(withId id: String, name: String, text: String, date: Date) { if let message = JSQMessage(senderId: id, senderDisplayName: name, date: date, text: text) { messages.append(message) } } private func observeMessages() { //messageRef = Database.database().reference().child(chat).child(channel) let messageQuery = messageRef.queryLimited(toLast: 500) newMessageRefHandle = messageQuery.observe(.childAdded, with: { (snapshot) -> Void in self.activityIndicator.stopAnimating() let messageData = snapshot.value as! Dictionary<String, String> if let id = messageData["senderId"] as String!, let name = messageData["senderName"] as String!, let text = messageData["text"] as String!, let date = messageData["date"]?.toDate(dateFormat: "yyyy-MM-dd HH:mm"), text.count > 0 { self.addMessage(withId: id, name: name, text: text, date: date) self.finishReceivingMessage() } }) } private func observeTyping() { let typingIndicatorRef = Database.database().reference().child(chat).child(typing) userIsTypingRef = typingIndicatorRef.child(senderId) userIsTypingRef.onDisconnectRemoveValue() usersTypingQuery.observe(.value) { (data: DataSnapshot) in if data.childrenCount == 1 && self.isTyping { return } self.showTypingIndicator = data.childrenCount > 0 self.scrollToBottom(animated: true) } }*/ } /* extension ChatVC { override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! { return messages[indexPath.item] } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! { let message = messages[indexPath.item] if message.senderId == senderId { return outgoingBubbleImageView } else { return incomingBubbleImageView } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell let message = messages[indexPath.item] if message.senderId == senderId { cell.textView?.textColor = UIColor.white } else { cell.textView?.textColor = UIColor.black } return cell } override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! { return nil } override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) { if senderId == "" { performSegue(withIdentifier: "Chat2Alias", sender: self) return } let itemRef = messageRef.childByAutoId() let messageItem = [ "senderId": senderId!, "senderName": senderDisplayName!, "text": text!, "date": Date().toString(dateFormat: "yyyy-MM-dd HH:mm") ] itemRef.setValue(messageItem) isTyping = false finishSendingMessage() } override func collectionView(_ collectionView: JSQMessagesCollectionView, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath) -> NSAttributedString? { let message = messages[indexPath.item] return message.senderId == senderId ? nil : NSAttributedString(string: message.senderDisplayName + " - " + message.date.toString(dateFormat: "HH:mm")) } override func collectionView(_ collectionView: JSQMessagesCollectionView, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout, heightForMessageBubbleTopLabelAt indexPath: IndexPath) -> CGFloat { let message = messages[indexPath.item] return message.senderId == senderId ? 0.0 : kJSQMessagesCollectionViewAvatarSizeDefault } private func setupOutgoingBubble() -> JSQMessagesBubbleImage { let bubbleImageFactory = JSQMessagesBubbleImageFactory() return bubbleImageFactory!.outgoingMessagesBubbleImage(with: UIColor.FlatColor.Blue.Leganes) } private func setupIncomingBubble() -> JSQMessagesBubbleImage { let bubbleImageFactory = JSQMessagesBubbleImageFactory() return bubbleImageFactory!.incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray()) } override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapCellAt indexPath: IndexPath!, touchLocation: CGPoint) { view.endEditing(true) } override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAt indexPath: IndexPath!) { view.endEditing(true) } } extension ChatVC { override func textViewDidChange(_ textView: UITextView) { super.textViewDidChange(textView) isTyping = textView.text != "" } } extension ChatVC { func prepareHideKeyboard() { let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)) collectionView.addGestureRecognizer(tap) } @objc func hideKeyboard() { if inputToolbar.contentView.textView.isFirstResponder { inputToolbar.contentView.textView.resignFirstResponder() } } func prepareActivityIndicator() { activityIndicator.center = self.view.center activityIndicator.color = K.mainColor activityIndicator.hidesWhenStopped = true self.view.addSubview(activityIndicator) activityIndicator.startAnimating() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Chat2Alias", let viewController = segue.destination as? AliasVC { viewController.viewModel = viewModel } } }*/
mit
3067f7f27d041c24bddaf53e2d1105f5
36.977358
211
0.676172
5.591111
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorSDK.swift
1
27828
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import JDStatusBarNotification import PushKit import SafariServices import DZNWebViewController @objc public class ActorSDK: NSObject, PKPushRegistryDelegate { // // Shared instance // private static let shared = ActorSDK() public static func sharedActor() -> ActorSDK { return shared } // // Root Objects // /// Main Messenger object public var messenger : ACCocoaMessenger! // Actor Style public let style = ActorStyle() /// SDK Delegate public var delegate: ActorSDKDelegate = ActorSDKDelegateDefault() /// SDK Analytics public var analyticsDelegate: ActorSDKAnalytics? // // Configuration // /// Server Endpoints public var endpoints = [ "tcp://front1-mtproto-api-rev3.actor.im:443", "tcp://front2-mtproto-api-rev3.actor.im:443" ] { didSet { trustedKeys = [] } } /// Trusted Server Keys public var trustedKeys = [ "d9d34ed487bd5b434eda2ef2c283db587c3ae7fb88405c3834d9d1a6d247145b", "4bd5422b50c585b5c8575d085e9fae01c126baa968dab56a396156759d5a7b46", "ff61103913aed3a9a689b6d77473bc428d363a3421fdd48a8e307a08e404f02c", "20613ab577f0891102b1f0a400ca53149e2dd05da0b77a728b62f5ebc8095878", "fc49f2f2465f5b4e038ec7c070975858a8b5542aa6ec1f927a57c4f646e1c143", "6709b8b733a9f20a96b9091767ac19fd6a2a978ba0dccc85a9ac8f6b6560ac1a" ] /// API ID public var apiId = 2 /// API Key public var apiKey = "2ccdc3699149eac0a13926c77ca84e504afd68b4f399602e06d68002ace965a3" /// Push registration mode public var autoPushMode = AAAutoPush.AfterLogin /// Push token registration id. Required for sending push tokens public var apiPushId: Int? = nil /// Strategy about authentication public var authStrategy = AAAuthStrategy.PhoneOnly /// Enable phone book import public var enablePhoneBookImport = true /// Invitation URL for apps public var inviteUrl: String = "https://actor.im/dl" /// Privacy Policy URL public var privacyPolicyUrl: String? = nil /// Privacy Policy Text public var privacyPolicyText: String? = nil /// Terms of Service URL public var termsOfServiceUrl: String? = nil /// Terms of Service Text public var termsOfServiceText: String? = nil /// App name public var appName: String = "Actor" /// Use background on welcome screen public var useBackgroundOnWelcomeScreen: Bool? = false /// Support email public var supportEmail: String? = nil /// Support email public var supportActivationEmail: String? = nil /// Support account public var supportAccount: String? = nil /// Support home page public var supportHomepage: String? = "https://actor.im" /// Support account public var supportTwitter: String? = "actorapp" /// Invite url scheme public var inviteUrlScheme: String? = nil /// Web Invite Domain host public var inviteUrlHost: String? = nil /// Enable voice calls feature public var enableCalls: Bool = true /// Enable experimental features public var enableExperimentalFeatures: Bool = false // // User Onlines // /// Is User online private(set) public var isUserOnline = false /// Disable this if you want manually handle online states public var automaticOnlineHandling = true // // Internal State // /// Is Actor Started private(set) public var isStarted = false private var binder = AABinder() private var syncTask: UIBackgroundTaskIdentifier? private var completionHandler: ((UIBackgroundFetchResult) -> Void)? // View Binding info private(set) public var bindedToWindow: UIWindow! // Reachability private var reachability: Reachability! public override init() { // Auto Loading Application name if let name = NSBundle.mainBundle().objectForInfoDictionaryKey(String(kCFBundleNameKey)) as? String { self.appName = name } } public func createActor() { if isStarted { return } isStarted = true AAActorRuntime.configureRuntime() let builder = ACConfigurationBuilder() // Api Connections let deviceKey = NSUUID().UUIDString let deviceName = UIDevice.currentDevice().name let appTitle = "Actor iOS" for url in endpoints { builder.addEndpoint(url) } for key in trustedKeys { builder.addTrustedKey(key) } builder.setApiConfiguration(ACApiConfiguration(appTitle: appTitle, withAppId: jint(apiId), withAppKey: apiKey, withDeviceTitle: deviceName, withDeviceId: deviceKey)) // Providers builder.setPhoneBookProvider(PhoneBookProvider()) builder.setNotificationProvider(iOSNotificationProvider()) builder.setCallsProvider(iOSCallsProvider()) // Stats builder.setPlatformType(ACPlatformType.IOS()) builder.setDeviceCategory(ACDeviceCategory.MOBILE()) // Locale for lang in NSLocale.preferredLanguages() { log("Found locale :\(lang)") builder.addPreferredLanguage(lang) } // TimeZone let timeZone = NSTimeZone.defaultTimeZone().name log("Found time zone :\(timeZone)") builder.setTimeZone(timeZone) // Logs // builder.setEnableFilesLogging(true) // Application name builder.setCustomAppName(appName) // Config builder.setPhoneBookImportEnabled(jboolean(enablePhoneBookImport)) builder.setVoiceCallsEnabled(jboolean(enableCalls)) builder.setIsEnabledGroupedChatList(false) // builder.setEnableFilesLogging(true) // Creating messenger messenger = ACCocoaMessenger(configuration: builder.build()) // Configure bubbles AABubbles.layouters = delegate.actorConfigureBubbleLayouters(AABubbles.builtInLayouters) checkAppState() // Bind Messenger LifeCycle binder.bind(messenger.getGlobalState().isSyncing, closure: { (value: JavaLangBoolean?) -> () in if value!.booleanValue() { if self.syncTask == nil { self.syncTask = UIApplication.sharedApplication().beginBackgroundTaskWithName("Background Sync", expirationHandler: { () -> Void in }) } } else { if self.syncTask != nil { UIApplication.sharedApplication().endBackgroundTask(self.syncTask!) self.syncTask = nil } if self.completionHandler != nil { self.completionHandler!(UIBackgroundFetchResult.NewData) self.completionHandler = nil } } }) // Bind badge counter binder.bind(Actor.getGlobalState().globalCounter, closure: { (value: JavaLangInteger?) -> () in if let v = value { UIApplication.sharedApplication().applicationIconBadgeNumber = Int(v.integerValue) } else { UIApplication.sharedApplication().applicationIconBadgeNumber = 0 } }) // Push registration if autoPushMode == .FromStart { requestPush() } // Subscribe to network changes do { reachability = try Reachability.reachabilityForInternetConnection() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ActorSDK.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability) try reachability.startNotifier() } catch { print("Unable to create Reachability") return } } @objc func reachabilityChanged(note: NSNotification) { print("reachabilityChanged (\(reachability.isReachable()))") if reachability.isReachable() { messenger.forceNetworkCheck() } } func didLoggedIn() { // Push registration if autoPushMode == .AfterLogin { requestPush() } var controller: UIViewController! = delegate.actorControllerAfterLogIn() if controller == nil { controller = delegate.actorControllerForStart() } if controller == nil { let tab = AARootTabViewController() tab.viewControllers = self.getMainNavigations() tab.selectedIndex = 0 tab.selectedIndex = 1 if (AADevice.isiPad) { let splitController = AARootSplitViewController() splitController.viewControllers = [tab, AANoSelectionViewController()] controller = splitController } else { controller = tab } } bindedToWindow.rootViewController = controller! } // // Push support // /// Token need to be with stripped everything except numbers and letters func pushRegisterToken(token: String) { if !isStarted { fatalError("Messenger not started") } if apiPushId != nil { messenger.registerApplePushWithApnsId(jint(apiPushId!), withToken: token) } } func pushRegisterKitToken(token: String) { if !isStarted { fatalError("Messenger not started") } if apiPushId != nil { messenger.registerApplePushKitWithApnsId(jint(apiPushId!), withToken: token) } } private func requestPush() { let types: UIUserNotificationType = [.Alert, .Badge, .Sound] let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() } private func requestPushKit() { let voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue()) voipRegistry.delegate = self voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP]) } @objc public func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) { if (type == PKPushTypeVoIP) { let tokenString = "\(credentials.token)".replace(" ", dest: "").replace("<", dest: "").replace(">", dest: "") pushRegisterKitToken(tokenString) } } @objc public func pushRegistry(registry: PKPushRegistry!, didInvalidatePushTokenForType type: String!) { if (type == PKPushTypeVoIP) { } } @objc public func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) { if (type == PKPushTypeVoIP) { let aps = payload.dictionaryPayload["aps"] as! [NSString: AnyObject] if let callId = aps["callId"] as? String { if let attempt = aps["attemptIndex"] as? String { Actor.checkCall(jlong(callId)!, withAttempt: jint(attempt)!) } else { Actor.checkCall(jlong(callId)!, withAttempt: 0) } } else if let seq = aps["seq"] as? String { Actor.onPushReceivedWithSeq(jint(seq)!) } } } /// Get main navigations with check in delegate for customize from SDK private func getMainNavigations() -> [AANavigationController] { var mainNavigations = [AANavigationController]() //////////////////////////////////// // contacts //////////////////////////////////// if let contactsController = self.delegate.actorControllerForContacts() { mainNavigations.append(AANavigationController(rootViewController: contactsController)) } else { mainNavigations.append(AANavigationController(rootViewController: AAContactsViewController())) } //////////////////////////////////// // recent dialogs //////////////////////////////////// if let recentDialogs = self.delegate.actorControllerForDialogs() { mainNavigations.append(AANavigationController(rootViewController: recentDialogs)) } else { mainNavigations.append(AANavigationController(rootViewController: AARecentViewController())) } //////////////////////////////////// // settings //////////////////////////////////// if let settingsController = self.delegate.actorControllerForSettings() { mainNavigations.append(AANavigationController(rootViewController: settingsController)) } else { mainNavigations.append(AANavigationController(rootViewController: AASettingsViewController())) } return mainNavigations; } // // Presenting Messenger // public func presentMessengerInWindow(window: UIWindow) { if !isStarted { fatalError("Messenger not started") } self.bindedToWindow = window if messenger.isLoggedIn() { if autoPushMode == .AfterLogin { requestPush() } var controller: UIViewController! = delegate.actorControllerForStart() if controller == nil { let tab = AARootTabViewController() tab.viewControllers = self.getMainNavigations() tab.selectedIndex = 0 tab.selectedIndex = 1 if (AADevice.isiPad) { let splitController = AARootSplitViewController() splitController.viewControllers = [tab, AANoSelectionViewController()] controller = splitController } else { controller = tab } } window.rootViewController = controller! } else { let controller: UIViewController! = delegate.actorControllerForAuthStart() if controller == nil { window.rootViewController = AAWelcomeController() } else { window.rootViewController = controller } } // Bind Status Bar connecting if !style.statusBarConnectingHidden { JDStatusBarNotification.setDefaultStyle { (style) -> JDStatusBarStyle! in style.barColor = self.style.statusBarConnectingBgColor style.textColor = self.style.statusBarConnectingTextColor return style } dispatchOnUi { () -> Void in self.binder.bind(self.messenger.getGlobalState().isSyncing, valueModel2: self.messenger.getGlobalState().isConnecting) { (isSyncing: JavaLangBoolean?, isConnecting: JavaLangBoolean?) -> () in if isSyncing!.booleanValue() || isConnecting!.booleanValue() { if isConnecting!.booleanValue() { JDStatusBarNotification.showWithStatus(AALocalized("StatusConnecting")) } else { JDStatusBarNotification.showWithStatus(AALocalized("StatusSyncing")) } } else { JDStatusBarNotification.dismiss() } } } } } public func presentMessengerInNewWindow() { let window = UIWindow(frame: UIScreen.mainScreen().bounds); window.backgroundColor = UIColor.whiteColor() presentMessengerInWindow(window) window.makeKeyAndVisible() } // // Data Processing // /// Handling URL Opening in application func openUrl(url: String) { if let u = NSURL(string: url) { // Handle phone call if (u.scheme.lowercaseString == "telprompt") { UIApplication.sharedApplication().openURL(u) return } // Handle web invite url if (u.scheme.lowercaseString == "http" || u.scheme.lowercaseString == "https") && inviteUrlHost != nil { if u.host == inviteUrlHost { if let token = u.lastPathComponent { joinGroup(token) return } } } // Handle custom scheme invite url if (u.scheme.lowercaseString == inviteUrlScheme?.lowercaseString) { if (u.host == "invite") { let token = u.query?.componentsSeparatedByString("=")[1] if token != nil { joinGroup(token!) return } } if let bindedController = bindedToWindow?.rootViewController { let alert = UIAlertController(title: nil, message: AALocalized("ErrorUnableToJoin"), preferredStyle: .Alert) alert.addAction(UIAlertAction(title: AALocalized("AlertOk"), style: .Cancel, handler: nil)) bindedController.presentViewController(alert, animated: true, completion: nil) } return } if (url.isValidUrl()){ if let bindedController = bindedToWindow?.rootViewController { // Dismiss Old Presented Controller to show new one if let presented = bindedController.presentedViewController { presented.dismissViewControllerAnimated(true, completion: nil) } // Building Controller for Web preview let controller: UIViewController if #available(iOS 9.0, *) { controller = SFSafariViewController(URL: u) } else { controller = AANavigationController(rootViewController: DZNWebViewController(URL: u)) } if AADevice.isiPad { controller.modalPresentationStyle = .FullScreen } // Presenting controller bindedController.presentViewController(controller, animated: true, completion: nil) } else { // Just Fallback. Might never happend UIApplication.sharedApplication().openURL(u) } } } } /// Handling joining group by token func joinGroup(token: String) { if let bindedController = bindedToWindow?.rootViewController { let alert = UIAlertController(title: nil, message: AALocalized("GroupJoinMessage"), preferredStyle: .Alert) alert.addAction(UIAlertAction(title: AALocalized("AlertNo"), style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: AALocalized("GroupJoinAction"), style: .Default){ (action) -> Void in AAExecutions.execute(Actor.joinGroupViaLinkCommandWithToken(token)!, type: .Safe, ignore: [], successBlock: { (val) -> Void in // TODO: Fix for iPad let groupId = val as! JavaLangInteger let tabBarController = bindedController as! UITabBarController let index = tabBarController.selectedIndex let navController = tabBarController.viewControllers![index] as! UINavigationController if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer.groupWithInt(groupId.intValue)) { navController.pushViewController(customController, animated: true) } else { navController.pushViewController(ConversationViewController(peer: ACPeer.groupWithInt(groupId.intValue)), animated: true) } }, failureBlock: nil) }) bindedController.presentViewController(alert, animated: true, completion: nil) } } /// Tracking page visible func trackPageVisible(page: ACPage) { analyticsDelegate?.analyticsPageVisible(page) } /// Tracking page hidden func trackPageHidden(page: ACPage) { analyticsDelegate?.analyticsPageHidden(page) } /// Tracking event func trackEvent(event: ACEvent) { analyticsDelegate?.analyticsEvent(event) } // // File System // public func fullFilePathForDescriptor(descriptor: String) -> String { return CocoaFiles.pathFromDescriptor(descriptor) } // // Manual Online handling // public func didBecameOnline() { if automaticOnlineHandling { fatalError("Manual Online handling not enabled!") } if !isStarted { fatalError("Messenger not started") } if !isUserOnline { isUserOnline = true messenger.onAppVisible() } } public func didBecameOffline() { if automaticOnlineHandling { fatalError("Manual Online handling not enabled!") } if !isStarted { fatalError("Messenger not started") } if isUserOnline { isUserOnline = false messenger.onAppHidden() } } // // Automatic Online handling // func checkAppState() { if UIApplication.sharedApplication().applicationState == .Active { if !isUserOnline { isUserOnline = true // Mark app as visible messenger.onAppVisible() // Notify Audio Manager about app visiblity change AAAudioManager.sharedAudio().appVisible() // Notify analytics about visibilibty change // Analytics.track(ACAllEvents.APP_VISIBLEWithBoolean(true)) // Hack for resync phone book Actor.onPhoneBookChanged() } } else { if isUserOnline { isUserOnline = false // Notify Audio Manager about app visiblity change AAAudioManager.sharedAudio().appHidden() // Mark app as hidden messenger.onAppHidden() // Notify analytics about visibilibty change // Analytics.track(ACAllEvents.APP_VISIBLEWithBoolean(false)) } } } public func applicationDidFinishLaunching(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() } public func applicationDidBecomeActive(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() } public func applicationWillEnterForeground(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() } public func applicationDidEnterBackground(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } checkAppState() // Keep application running for 40 secs if messenger.isLoggedIn() { var completitionTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid completitionTask = application.beginBackgroundTaskWithName("Completition", expirationHandler: { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid }) // Wait for 40 secs before app shutdown dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(40.0 * Double(NSEC_PER_SEC))), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in application.endBackgroundTask(completitionTask) completitionTask = UIBackgroundTaskInvalid } } } public func applicationWillResignActive(application: UIApplication) { if !automaticOnlineHandling || !isStarted { return } // // This event is fired when user press power button and lock screeen. // In iOS power button also cancel ongoint call. // // messenger.probablyEndCall() checkAppState() } // // Handling remote notifications // public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { if !messenger.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } public func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { // Nothing? } public func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { requestPushKit() } // // Handling background fetch events // public func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { if !messenger.isLoggedIn() { completionHandler(UIBackgroundFetchResult.NoData) return } self.completionHandler = completionHandler } // // Handling invite url // func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { dispatchOnUi { () -> Void in self.openUrl(url.absoluteString) } return true } public func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool { dispatchOnUi { () -> Void in self.openUrl(url.absoluteString) } return true } } public enum AAAutoPush { case None case FromStart case AfterLogin } public enum AAAuthStrategy { case PhoneOnly case EmailOnly case PhoneEmail }
agpl-3.0
cb948ed2b0698ad2a6467e45d832151d
32.691283
197
0.573236
5.681503
false
false
false
false
Vanlol/MyYDW
Pods/ReactiveSwift/Sources/Scheduler.swift
5
18305
// // Scheduler.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2014-06-02. // Copyright (c) 2014 GitHub. All rights reserved. // import Dispatch import Foundation #if os(Linux) import let CDispatch.NSEC_PER_SEC #endif /// Represents a serial queue of work items. public protocol Scheduler: class { /// Enqueues an action on the scheduler. /// /// When the work is executed depends on the scheduler in use. /// /// - parameters: /// - action: The action to be scheduled. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(_ action: @escaping () -> Void) -> Disposable? } /// A particular kind of scheduler that supports enqueuing actions at future /// dates. public protocol DateScheduler: Scheduler { /// The current date, as determined by this scheduler. /// /// This can be implemented to deterministically return a known date (e.g., /// for testing purposes). var currentDate: Date { get } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: The start date. /// - action: A closure of the action to be performed. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? /// Schedules a recurring action at the given interval, beginning at the /// given date. /// /// - parameters: /// - date: The start date. /// - interval: A repetition interval. /// - leeway: Some delta for repetition. /// - action: A closure of the action to be performed. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? } /// A scheduler that performs all work synchronously. public final class ImmediateScheduler: Scheduler { public init() {} /// Immediately calls passed in `action`. /// /// - parameters: /// - action: A closure of the action to be performed. /// /// - returns: `nil`. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { action() return nil } } /// A scheduler that performs all work on the main queue, as soon as possible. /// /// If the caller is already running on the main queue when an action is /// scheduled, it may be run synchronously. However, ordering between actions /// will always be preserved. public final class UIScheduler: Scheduler { private static let dispatchSpecificKey = DispatchSpecificKey<UInt8>() private static let dispatchSpecificValue = UInt8.max private static var __once: () = { DispatchQueue.main.setSpecific(key: UIScheduler.dispatchSpecificKey, value: dispatchSpecificValue) }() #if os(Linux) private var queueLength: Atomic<Int32> = Atomic(0) #else // `inout` references do not guarantee atomicity. Use `UnsafeMutablePointer` // instead. // // https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161205/004147.html private let queueLength: UnsafeMutablePointer<Int32> = { let memory = UnsafeMutablePointer<Int32>.allocate(capacity: 1) memory.initialize(to: 0) return memory }() deinit { queueLength.deinitialize() queueLength.deallocate(capacity: 1) } #endif /// Initializes `UIScheduler` public init() { /// This call is to ensure the main queue has been setup appropriately /// for `UIScheduler`. It is only called once during the application /// lifetime, since Swift has a `dispatch_once` like mechanism to /// lazily initialize global variables and static variables. _ = UIScheduler.__once } /// Queues an action to be performed on main queue. If the action is called /// on the main thread and no work is queued, no scheduling takes place and /// the action is called instantly. /// /// - parameters: /// - action: A closure of the action to be performed on the main thread. /// /// - returns: `Disposable` that can be used to cancel the work before it /// begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { let positionInQueue = enqueue() // If we're already running on the main queue, and there isn't work // already enqueued, we can skip scheduling and just execute directly. if positionInQueue == 1 && DispatchQueue.getSpecific(key: UIScheduler.dispatchSpecificKey) == UIScheduler.dispatchSpecificValue { action() dequeue() return nil } else { let disposable = AnyDisposable() DispatchQueue.main.async { defer { self.dequeue() } guard !disposable.isDisposed else { return } action() } return disposable } } private func dequeue() { #if os(Linux) queueLength.modify { $0 -= 1 } #else OSAtomicDecrement32(queueLength) #endif } private func enqueue() -> Int32 { #if os(Linux) return queueLength.modify { value -> Int32 in value += 1 return value } #else return OSAtomicIncrement32(queueLength) #endif } } /// A scheduler backed by a serial GCD queue. public final class QueueScheduler: DateScheduler { /// A singleton `QueueScheduler` that always targets the main thread's GCD /// queue. /// /// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a /// future date, and will always schedule asynchronously (even if /// already running on the main thread). public static let main = QueueScheduler(internalQueue: DispatchQueue.main) public var currentDate: Date { return Date() } public let queue: DispatchQueue internal init(internalQueue: DispatchQueue) { queue = internalQueue } /// Initializes a scheduler that will target the given queue with its /// work. /// /// - note: Even if the queue is concurrent, all work items enqueued with /// the `QueueScheduler` will be serial with respect to each other. /// /// - warning: Obsoleted in OS X 10.11 @available(OSX, deprecated:10.10, obsoleted:10.11, message:"Use init(qos:name:targeting:) instead") @available(iOS, deprecated:8.0, obsoleted:9.0, message:"Use init(qos:name:targeting:) instead.") public convenience init(queue: DispatchQueue, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler") { self.init(internalQueue: DispatchQueue(label: name, target: queue)) } /// Initializes a scheduler that creates a new serial queue with the /// given quality of service class. /// /// - parameters: /// - qos: Dispatch queue's QoS value. /// - name: A name for the queue in the form of reverse domain. /// - targeting: (Optional) The queue on which this scheduler's work is /// targeted @available(OSX 10.10, *) public convenience init( qos: DispatchQoS = .default, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler", targeting targetQueue: DispatchQueue? = nil ) { self.init(internalQueue: DispatchQueue( label: name, qos: qos, target: targetQueue )) } /// Schedules action for dispatch on internal queue /// /// - parameters: /// - action: A closure of the action to be scheduled. /// /// - returns: `Disposable` that can be used to cancel the work before it /// begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { let d = AnyDisposable() queue.async { if !d.isDisposed { action() } } return d } private func wallTime(with date: Date) -> DispatchWallTime { let (seconds, frac) = modf(date.timeIntervalSince1970) let nsec: Double = frac * Double(NSEC_PER_SEC) let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec)) return DispatchWallTime(timespec: walltime) } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: The start date. /// - action: A closure of the action to be performed. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? { let d = AnyDisposable() queue.asyncAfter(wallDeadline: wallTime(with: date)) { if !d.isDisposed { action() } } return d } /// Schedules a recurring action at the given interval and beginning at the /// given start date. A reasonable default timer interval leeway is /// provided. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - action: Closure of the action to repeat. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, interval: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of // at least 10% of the timer interval. return schedule(after: date, interval: interval, leeway: interval * 0.1, action: action) } /// Schedules a recurring action at the given interval with provided leeway, /// beginning at the given start time. /// /// - precondition: `interval` must be non-negative number. /// - precondition: `leeway` must be non-negative number. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - leeway: Some delta for repetition interval. /// - action: A closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { precondition(interval.timeInterval >= 0) precondition(leeway.timeInterval >= 0) let timer = DispatchSource.makeTimerSource( flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: queue ) timer.scheduleRepeating(wallDeadline: wallTime(with: date), interval: interval, leeway: leeway) timer.setEventHandler(handler: action) timer.resume() return AnyDisposable { timer.cancel() } } } /// A scheduler that implements virtualized time, for use in testing. public final class TestScheduler: DateScheduler { private final class ScheduledAction { let date: Date let action: () -> Void init(date: Date, action: @escaping () -> Void) { self.date = date self.action = action } func less(_ rhs: ScheduledAction) -> Bool { return date.compare(rhs.date) == .orderedAscending } } private let lock = NSRecursiveLock() private var _currentDate: Date /// The virtual date that the scheduler is currently at. public var currentDate: Date { let d: Date lock.lock() d = _currentDate lock.unlock() return d } private var scheduledActions: [ScheduledAction] = [] /// Initializes a TestScheduler with the given start date. /// /// - parameters: /// - startDate: The start date of the scheduler. public init(startDate: Date = Date(timeIntervalSinceReferenceDate: 0)) { lock.name = "org.reactivecocoa.ReactiveSwift.TestScheduler" _currentDate = startDate } private func schedule(_ action: ScheduledAction) -> Disposable { lock.lock() scheduledActions.append(action) scheduledActions.sort { $0.less($1) } lock.unlock() return AnyDisposable { self.lock.lock() self.scheduledActions = self.scheduledActions.filter { $0 !== action } self.lock.unlock() } } /// Enqueues an action on the scheduler. /// /// - note: The work is executed on `currentDate` as it is understood by the /// scheduler. /// /// - parameters: /// - action: An action that will be performed on scheduler's /// `currentDate`. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(_ action: @escaping () -> Void) -> Disposable? { return schedule(ScheduledAction(date: currentDate, action: action)) } /// Schedules an action for execution after some delay. /// /// - parameters: /// - delay: A delay for execution. /// - action: A closure of the action to perform. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after delay: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? { return schedule(after: currentDate.addingTimeInterval(delay), action: action) } /// Schedules an action for execution at or after the given date. /// /// - parameters: /// - date: A starting date. /// - action: A closure of the action to perform. /// /// - returns: Optional disposable that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? { return schedule(ScheduledAction(date: date, action: action)) } /// Schedules a recurring action at the given interval, beginning at the /// given start date. /// /// - precondition: `interval` must be non-negative. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - disposable: A disposable. /// - action: A closure of the action to repeat. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `schedule(after:interval:leeway:action)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. private func schedule(after date: Date, interval: DispatchTimeInterval, disposable: SerialDisposable, action: @escaping () -> Void) { precondition(interval.timeInterval >= 0) disposable.inner = schedule(after: date) { [unowned self] in action() self.schedule(after: date.addingTimeInterval(interval), interval: interval, disposable: disposable, action: action) } } /// Schedules a recurring action after given delay repeated at the given, /// interval, beginning at the given interval counted from `currentDate`. /// /// - parameters: /// - delay: A delay for action's dispatch. /// - interval: A repetition interval. /// - leeway: Some delta for repetition interval. /// - action: A closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. @discardableResult public func schedule(after delay: DispatchTimeInterval, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? { return schedule(after: currentDate.addingTimeInterval(delay), interval: interval, leeway: leeway, action: action) } /// Schedules a recurring action at the given interval with /// provided leeway, beginning at the given start date. /// /// - parameters: /// - date: A date to schedule the first action for. /// - interval: A repetition interval. /// - leeway: Some delta for repetition interval. /// - action: A closure of the action to repeat. /// /// - returns: Optional `Disposable` that can be used to cancel the work /// before it begins. public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? { let disposable = SerialDisposable() schedule(after: date, interval: interval, disposable: disposable, action: action) return disposable } /// Advances the virtualized clock by an extremely tiny interval, dequeuing /// and executing any actions along the way. /// /// This is intended to be used as a way to execute actions that have been /// scheduled to run as soon as possible. public func advance() { advance(by: .nanoseconds(1)) } /// Advances the virtualized clock by the given interval, dequeuing and /// executing any actions along the way. /// /// - parameters: /// - interval: Interval by which the current date will be advanced. public func advance(by interval: DispatchTimeInterval) { lock.lock() advance(to: currentDate.addingTimeInterval(interval)) lock.unlock() } /// Advances the virtualized clock to the given future date, dequeuing and /// executing any actions up until that point. /// /// - parameters: /// - newDate: Future date to which the virtual clock will be advanced. public func advance(to newDate: Date) { lock.lock() assert(currentDate.compare(newDate) != .orderedDescending) while scheduledActions.count > 0 { if newDate.compare(scheduledActions[0].date) == .orderedAscending { break } _currentDate = scheduledActions[0].date let scheduledAction = scheduledActions.remove(at: 0) scheduledAction.action() } _currentDate = newDate lock.unlock() } /// Dequeues and executes all scheduled actions, leaving the scheduler's /// date at `Date.distantFuture()`. public func run() { advance(to: Date.distantFuture) } /// Rewinds the virtualized clock by the given interval. /// This simulates that user changes device date. /// /// - parameters: /// - interval: An interval by which the current date will be retreated. public func rewind(by interval: DispatchTimeInterval) { lock.lock() let newDate = currentDate.addingTimeInterval(-interval) assert(currentDate.compare(newDate) != .orderedAscending) _currentDate = newDate lock.unlock() } }
apache-2.0
5a88057a55d49af6357a3bcdbd4d394c
31.513321
179
0.686807
3.868343
false
false
false
false
adly-holler/Bond
Bond/iOS/Bond+UIDatePicker.swift
9
3737
// // Bond+UIDatePicker.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 @objc class DatePickerDynamicHelper { weak var control: UIDatePicker? var listener: (NSDate -> Void)? init(control: UIDatePicker) { self.control = control control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: .ValueChanged) } func valueChanged(control: UIDatePicker) { self.listener?(control.date) } deinit { control?.removeTarget(self, action: nil, forControlEvents: .ValueChanged) } } class DatePickerDynamic<T>: InternalDynamic<NSDate> { let helper: DatePickerDynamicHelper init(control: UIDatePicker) { self.helper = DatePickerDynamicHelper(control: control) super.init(control.date) self.helper.listener = { [unowned self] in self.updatingFromSelf = true self.value = $0 self.updatingFromSelf = false } } } private var dateDynamicHandleUIDatePicker: UInt8 = 0; extension UIDatePicker /*: Dynamical, Bondable */ { public var dynDate: Dynamic<NSDate> { if let d: AnyObject = objc_getAssociatedObject(self, &dateDynamicHandleUIDatePicker) { return (d as? Dynamic<NSDate>)! } else { let d = DatePickerDynamic<NSDate>(control: self) let bond = Bond<NSDate>() { [weak self, weak d] v in if let s = self, d = d where !d.updatingFromSelf { s.date = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &dateDynamicHandleUIDatePicker, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return d } } public var designatedDynamic: Dynamic<NSDate> { return self.dynDate } public var designatedBond: Bond<NSDate> { return self.dynDate.valueBond } } public func ->> (left: UIDatePicker, right: Bond<NSDate>) { left.designatedDynamic ->> right } public func ->> <U: Bondable where U.BondType == NSDate>(left: UIDatePicker, right: U) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: UIDatePicker, right: UIDatePicker) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: Dynamic<NSDate>, right: UIDatePicker) { left ->> right.designatedBond } public func <->> (left: UIDatePicker, right: UIDatePicker) { left.designatedDynamic <->> right.designatedDynamic } public func <->> (left: Dynamic<NSDate>, right: UIDatePicker) { left <->> right.designatedDynamic } public func <->> (left: UIDatePicker, right: Dynamic<NSDate>) { left.designatedDynamic <->> right }
mit
ecf1ad667ee812c11bcaa035dbf7238c
29.884298
130
0.702168
4.2036
false
false
false
false
alreadyRight/Swift-algorithm
自定义cell编辑状态/Pods/SnapKit/Source/ConstraintAttributes.swift
50
7613
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif internal struct ConstraintAttributes : OptionSet { internal init(rawValue: UInt) { self.rawValue = rawValue } internal init(_ rawValue: UInt) { self.init(rawValue: rawValue) } internal init(nilLiteral: ()) { self.rawValue = 0 } internal private(set) var rawValue: UInt internal static var allZeros: ConstraintAttributes { return self.init(0) } internal static func convertFromNilLiteral() -> ConstraintAttributes { return self.init(0) } internal var boolValue: Bool { return self.rawValue != 0 } internal func toRaw() -> UInt { return self.rawValue } internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) } internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) } // normal internal static var none: ConstraintAttributes { return self.init(0) } internal static var left: ConstraintAttributes { return self.init(1) } internal static var top: ConstraintAttributes { return self.init(2) } internal static var right: ConstraintAttributes { return self.init(4) } internal static var bottom: ConstraintAttributes { return self.init(8) } internal static var leading: ConstraintAttributes { return self.init(16) } internal static var trailing: ConstraintAttributes { return self.init(32) } internal static var width: ConstraintAttributes { return self.init(64) } internal static var height: ConstraintAttributes { return self.init(128) } internal static var centerX: ConstraintAttributes { return self.init(256) } internal static var centerY: ConstraintAttributes { return self.init(512) } internal static var lastBaseline: ConstraintAttributes { return self.init(1024) } @available(iOS 8.0, OSX 10.11, *) internal static var firstBaseline: ConstraintAttributes { return self.init(2048) } @available(iOS 8.0, *) internal static var leftMargin: ConstraintAttributes { return self.init(4096) } @available(iOS 8.0, *) internal static var rightMargin: ConstraintAttributes { return self.init(8192) } @available(iOS 8.0, *) internal static var topMargin: ConstraintAttributes { return self.init(16384) } @available(iOS 8.0, *) internal static var bottomMargin: ConstraintAttributes { return self.init(32768) } @available(iOS 8.0, *) internal static var leadingMargin: ConstraintAttributes { return self.init(65536) } @available(iOS 8.0, *) internal static var trailingMargin: ConstraintAttributes { return self.init(131072) } @available(iOS 8.0, *) internal static var centerXWithinMargins: ConstraintAttributes { return self.init(262144) } @available(iOS 8.0, *) internal static var centerYWithinMargins: ConstraintAttributes { return self.init(524288) } // aggregates internal static var edges: ConstraintAttributes { return self.init(15) } internal static var size: ConstraintAttributes { return self.init(192) } internal static var center: ConstraintAttributes { return self.init(768) } @available(iOS 8.0, *) internal static var margins: ConstraintAttributes { return self.init(61440) } @available(iOS 8.0, *) internal static var centerWithinMargins: ConstraintAttributes { return self.init(786432) } internal var layoutAttributes:[LayoutAttribute] { var attrs = [LayoutAttribute]() if (self.contains(ConstraintAttributes.left)) { attrs.append(.left) } if (self.contains(ConstraintAttributes.top)) { attrs.append(.top) } if (self.contains(ConstraintAttributes.right)) { attrs.append(.right) } if (self.contains(ConstraintAttributes.bottom)) { attrs.append(.bottom) } if (self.contains(ConstraintAttributes.leading)) { attrs.append(.leading) } if (self.contains(ConstraintAttributes.trailing)) { attrs.append(.trailing) } if (self.contains(ConstraintAttributes.width)) { attrs.append(.width) } if (self.contains(ConstraintAttributes.height)) { attrs.append(.height) } if (self.contains(ConstraintAttributes.centerX)) { attrs.append(.centerX) } if (self.contains(ConstraintAttributes.centerY)) { attrs.append(.centerY) } if (self.contains(ConstraintAttributes.lastBaseline)) { attrs.append(.lastBaseline) } #if os(iOS) || os(tvOS) if (self.contains(ConstraintAttributes.firstBaseline)) { attrs.append(.firstBaseline) } if (self.contains(ConstraintAttributes.leftMargin)) { attrs.append(.leftMargin) } if (self.contains(ConstraintAttributes.rightMargin)) { attrs.append(.rightMargin) } if (self.contains(ConstraintAttributes.topMargin)) { attrs.append(.topMargin) } if (self.contains(ConstraintAttributes.bottomMargin)) { attrs.append(.bottomMargin) } if (self.contains(ConstraintAttributes.leadingMargin)) { attrs.append(.leadingMargin) } if (self.contains(ConstraintAttributes.trailingMargin)) { attrs.append(.trailingMargin) } if (self.contains(ConstraintAttributes.centerXWithinMargins)) { attrs.append(.centerXWithinMargins) } if (self.contains(ConstraintAttributes.centerYWithinMargins)) { attrs.append(.centerYWithinMargins) } #endif return attrs } } internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes { return left.union(right) } internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.formUnion(right) } internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.subtract(right) } internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool { return left.rawValue == right.rawValue }
mit
a7f4d2cdef8dd654c674eb51455f5fcc
39.068421
99
0.664521
4.821406
false
false
false
false
pirishd/InstantMock
Tests/InstantMockTests/Mocks/ArgumentFactoryMock.swift
1
1608
// // ArgumentFactoryMock.swift // InstantMock // // Created by Patrick on 13/05/2017. // Copyright 2017 pirishd. All rights reserved. // import InstantMock class ArgumentFactoryMock<T>: ArgumentFactory { var argumentValue: ArgumentValue? var argumentAny: ArgumentAny? var argumentClosure: ArgumentClosure? var argumentVerify: ArgumentVerify? var argumentVerifyOpt: ArgumentVerify? var argumentCapture: ArgumentCapture? func argument(value: T?) -> ArgumentValue { let argValue = ArgumentValueMock<T>(value) self.argumentValue = argValue return argValue } func argumentAny(_ typeDescription: String) -> ArgumentAny { let argAny = ArgumentAnyMock() self.argumentAny = argAny return argAny } func argumentClosure(_ typeDescription: String) -> ArgumentClosure { let argClosure = ArgumentClosureMock() self.argumentClosure = argClosure return argClosure } func argument(condition: @escaping (T) -> Bool) -> ArgumentVerify { let argVerify = ArgumentVerifyMandatoryMock<T>(condition) self.argumentVerify = argVerify return argVerify } func argument(condition: @escaping (T?) -> Bool) -> ArgumentVerify { let argVerify = ArgumentVerifyOptionalMock<T>(condition) self.argumentVerify = argVerify return argVerify } func argumentCapture(_ typeDescription: String) -> ArgumentCapture { let argCapture = ArgumentCaptureMock() self.argumentCapture = argCapture return argCapture } }
mit
7f7f08fe7ec381672e37f2c7ac147376
23.738462
72
0.677239
4.62069
false
false
false
false
athiercelin/Assets
Assets/Assets/AssetsPair.swift
1
930
// // AssetsPair.swift // Assets // // Created by Arnaud Thiercelin on 8/12/16. // Copyright © 2016 Arnaud Thiercelin. All rights reserved. // import Cocoa class AssetsPair: NSObject, NSCoding { var projectAsset: ImageFile! var designerAsset: ImageFile! override init() { // NS_DESIGNATED_INITIALIZER } required public init?(coder aDecoder: NSCoder) { let projectAsset = aDecoder.decodeObject(forKey: "projectAsset") if projectAsset != nil { self.projectAsset = projectAsset as! ImageFile } let designerAsset = aDecoder.decodeObject(forKey: "designerAsset") if designerAsset != nil { self.designerAsset = designerAsset as! ImageFile } } public func encode(with aCoder: NSCoder) { if self.projectAsset != nil { aCoder.encode(self.projectAsset, forKey: "projectAsset") } if self.designerAsset != nil { aCoder.encode(self.designerAsset, forKey: "designerAsset") } } }
mit
5e2b2efb29a6b5dec0f57aa06dfce256
21.119048
68
0.706136
3.40293
false
false
false
false
scamps88/ASBubbleDrag
UIConcept/ASBubbleDrag/BubbleDragView.swift
1
8362
// // BubbleDragView.swift // // // Created by Alberto Scampini on 27/01/2016. // Copyright © 2016 Alberto Scampini. All rights reserved. // import UIKit import Darwin protocol BubbleDragViewDelegate { func selectedIndex(index : NSInteger) } class BubbleDragView: UIView, UICollectionViewDataSource { var delegate : BubbleDragViewDelegate? @IBOutlet var collectionView : UICollectionView! override func drawRect(rect: CGRect) { //prepare collectionView let nib = UINib(nibName: "BubbleCollectionCell", bundle: nil) collectionView.registerNib(nib, forCellWithReuseIdentifier: "BubbleCell") let layout = UICollectionViewFlowLayout() layout.itemSize = CGSizeMake(100, 100) layout.minimumInteritemSpacing = 10 layout.scrollDirection = .Horizontal //self.collectionView.collectionViewLayout = layout self.collectionView.dataSource = self //add gesture recognizers let dragGesture = UIPanGestureRecognizer(target: self, action: #selector(BubbleDragView.handleDrag(_:))) dragGesture.maximumNumberOfTouches = 1 self.addGestureRecognizer(dragGesture) self.initDragItem() } //MARK: public methods var mutableDataSource = Array<UIImage>() var indexDataSource = Array<NSInteger>() func populateWithData(data : Array<UIImage?>) { //check input images self.mutableDataSource = Array<UIImage>() self.mutableDataSource = Array<UIImage>() var indexCount = 0 for image in data { if (image == nil) { self.mutableDataSource.append(UIImage(named: "MenuBubbleV.png")!) } else { self.mutableDataSource.append(image!) } self.indexDataSource.append(indexCount) indexCount += 1 } self.collectionView.reloadData() } //MARK: collectionView DataSource adn Layout func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.mutableDataSource.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("BubbleCell", forIndexPath: indexPath) as! BubbleCollectionCell cell.picture.image = self.mutableDataSource[indexPath.row] return cell } //MARK : drag interaction var selectedItem : NSIndexPath? var dragItem = UIImageView() var dragEnabled = false @IBOutlet var target : UIView! internal func initDragItem () { self.dragItem.frame = CGRect(x: 0, y: 0, width: 100, height: 100) self.dragItem.layer.cornerRadius = 50 self.dragItem.clipsToBounds = true self.dragItem.contentMode = .ScaleAspectFit self.dragItem.backgroundColor = UIColor.whiteColor() self.dragItem.alpha = 0 } internal func handleDrag (pan : UIPanGestureRecognizer) { if pan.state == .Began { //start dragging //if not already animating if self.selectedItem == nil { //check if on scrollview let touch = pan.locationInView(self.collectionView) let indexPath = self.collectionView.indexPathForItemAtPoint(touch) //save selection informations selectedItem = indexPath if (indexPath != nil) { //add item self.dragItem.image = self.mutableDataSource[selectedItem!.row] self.addSubview(self.dragItem) self.dragItem.center = pan.locationInView(self) self.dragItem.alpha = 1 //remove element from collection self.collectionView.performBatchUpdates({ () -> Void in self.mutableDataSource.removeAtIndex(indexPath!.row) self.collectionView.deleteItemsAtIndexPaths([indexPath!]) }, completion: nil) //enable animation mode dragEnabled = true self.collectionView.userInteractionEnabled = false } } } else if pan.state == .Ended { //end dragging if dragEnabled == true { dragEnabled = false //check item position math let p1 = self.target.convertPoint(CGPointMake(50, 50), toView: self) let p2 = self.dragItem.center let distance = sqrt( pow(abs(p1.x - p2.x), 2) + pow(abs(p1.y - p2.y), 2) ) if(distance < 100) { //animation sucked on target UIView.animateWithDuration(0.2, animations: { () -> Void in self.dragItem.center = p1 }, completion: { (flag) -> Void in UIView.animateWithDuration(0.1, animations: { () -> Void in self.dragItem.alpha = 0 }, completion: { (flag) -> Void in self.delegate?.selectedIndex(self.indexDataSource[self.selectedItem!.row]) self.indexDataSource.removeAtIndex(self.selectedItem!.row) self.dragItem.removeFromSuperview() self.selectedItem = nil self.collectionView.userInteractionEnabled = true }) }) } else { //calculate position will have in collection view var endPoint : CGPoint! if (self.mutableDataSource.count == 0) { //empty collection endPoint = CGPoint(x: 50, y: self.collectionView.center.y) } else if (selectedItem!.item <= (self.mutableDataSource.count - 1)) { let cellSelected = self.collectionView.cellForItemAtIndexPath(selectedItem!) endPoint = cellSelected?.convertPoint(CGPointMake(50, 50), toView: self) } else { //last element let lastIndex = NSIndexPath(forItem: self.mutableDataSource.count - 1, inSection: 0) let cellSelected = self.collectionView.cellForItemAtIndexPath(lastIndex) endPoint = cellSelected?.convertPoint(CGPointMake(50, 50), toView: self) endPoint?.x += 110 } //animation sucked back to collection view UIView.animateWithDuration(0.2, animations: { () -> Void in self.dragItem.center = endPoint }, completion: { (flag) -> Void in //insert element to collection self.collectionView.performBatchUpdates({ () -> Void in self.mutableDataSource.insert(self.dragItem.image!, atIndex: self.selectedItem!.row) self.collectionView.insertItemsAtIndexPaths([self.selectedItem!]) }, completion: { (flag) -> Void in self.dragItem.removeFromSuperview() if self.selectedItem!.item == (self.mutableDataSource.count - 1) { // last item (show it) self.collectionView.scrollToItemAtIndexPath(self.selectedItem!, atScrollPosition: .Right, animated: true) } self.selectedItem = nil self.collectionView.userInteractionEnabled = true }) }) } } } else if dragEnabled == true { //dragging self.dragItem.center = pan.locationInView(self) } } }
mit
953044d6425250e392326ea7d0eaabe7
42.546875
141
0.550891
5.790166
false
false
false
false
mindbody/Conduit
Sources/Conduit/Networking/Reachability/NetworkReachability.swift
1
5931
// // NetworkReachability.swift // Conduit // // Created by John Hammerlund on 12/14/16. // Copyright © 2017 MINDBODY. All rights reserved. // #if !os(watchOS) import Foundation import SystemConfiguration /// A handler that fires on any change in network reachability public typealias NetworkReachabilityChangeHandler = (NetworkReachability) -> Void /// Represents the reachability of a specific network connection, or all network connections. public class NetworkReachability { /// Network reachabillity across all connections public static var internet: NetworkReachability = { let sockAddrInSize = UInt8(MemoryLayout<sockaddr>.size) var zeroAddress = sockaddr() zeroAddress.sa_len = sockAddrInSize zeroAddress.sa_family = UInt8(AF_INET) guard let reachability = NetworkReachability(socketAddress: zeroAddress) else { preconditionFailure("Could not initialize reachability") } return reachability }() private let systemReachability: SCNetworkReachability private(set) var observers = [NetworkReachabilityObserver]() private(set) var isPollingReachability = false /// The current reachable status of the network connection public private(set) var status: NetworkStatus /// Attempts to produce a NetworkReachability against a given host /// /// - Parameter hostName: The host to connect to (i.e. mindbodyonline.com) public convenience init?(hostName: String) { guard let data = hostName.data(using: .utf8) else { return nil } var reachability: SCNetworkReachability? data.withUnsafeBytes { ptr in guard let bytes = ptr.baseAddress?.assumingMemoryBound(to: Int8.self) else { return } reachability = SCNetworkReachabilityCreateWithName(nil, bytes) } guard let systemReachability = reachability else { return nil } self.init(systemReachability: systemReachability) } private convenience init?(socketAddress: sockaddr) { var socketAddress = socketAddress let pointer: (UnsafePointer<sockaddr>) -> SCNetworkReachability? = { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } if let systemReachability: SCNetworkReachability = withUnsafePointer(to: &socketAddress, pointer) { self.init(systemReachability: systemReachability) } else { return nil } } private init(systemReachability: SCNetworkReachability) { self.systemReachability = systemReachability self.status = NetworkStatus(systemReachability: systemReachability) configureReachabilityCallback() startPollingReachability() } private func configureReachabilityCallback() { /// SCNetworkReachabilitySetCallback requires a function pointer, /// which means the closure is effectively global, static memory. /// Because of this, the registered callback cannot capture anything, /// and any outside context must be passed through "info", which is a pointer to opaque memory. let unmanagedSelf = Unmanaged<NetworkReachability>.passUnretained(self).toOpaque() var context = SCNetworkReachabilityContext(version: 0, info: UnsafeMutableRawPointer(unmanagedSelf), retain: nil, release: nil, copyDescription: nil) SCNetworkReachabilitySetCallback(systemReachability, { _, reachabilityFlags, info in guard let info = info else { return } let networkStatus = NetworkStatus(systemReachabilityFlags: reachabilityFlags) let networkReachability = Unmanaged<NetworkReachability>.fromOpaque(info).takeUnretainedValue() networkReachability.status = networkStatus for observer in networkReachability.observers { observer.handler(networkReachability) } }, &context) } /// Registers a closure to be fired every time reachability changes /// /// - Parameter handler: The handler to register /// - Returns: An observer that can be unregistered if needed @discardableResult public func register(handler: @escaping NetworkReachabilityChangeHandler) -> NetworkReachabilityObserver { let observer = NetworkReachabilityObserver(handler) observers.append(observer) return observer } /// Unregisters a network reachability observer /// /// - Parameter observer: The observer to unregister public func unregister(observer: NetworkReachabilityObserver) { if let idx = observers.firstIndex(where: { $0 === observer }) { observers.remove(at: idx) } } /// Unregisters all network reachability observers public func unregisterAllObservers() { observers = [] } private func startPollingReachability() { if isPollingReachability == false { isPollingReachability = SCNetworkReachabilityScheduleWithRunLoop(systemReachability, RunLoop.current.getCFRunLoop(), RunLoop.Mode.default as CFString) } } deinit { SCNetworkReachabilitySetCallback(systemReachability, nil, nil) } } /// Responds to network reachability changes based on a reachability configuration public class NetworkReachabilityObserver { let handler: NetworkReachabilityChangeHandler init(_ handler: @escaping NetworkReachabilityChangeHandler) { self.handler = handler } } #endif
apache-2.0
0487936a65abbd368fdb77f0d3c19af5
37.506494
110
0.649747
6.014199
false
false
false
false
rharri/swift-ios
FakeRest/FakeRest/Post.swift
1
1479
// // Post.swift // FakeRest // // Created by Ryan Harri on 2016-11-25. // Copyright © 2016 Ryan Harri. All rights reserved. // import Foundation class Post { // MARK: - Instance Properties var ID: Int? var userID: Int? var title: String? var body: String? // MARK: - Delegate Properties weak var dataSource: PostDataSource? // MARK: - Initializers init() { } init(ID: Int, userID: Int, title: String, body: String) { self.ID = ID self.userID = userID self.title = title self.body = body } init(json: [String:AnyObject]) throws { guard let ID = json["id"] as? Int else { throw SerializationError.missing("id") } guard let userID = json["userId"] as? Int else { throw SerializationError.missing("userId") } guard let title = json["title"] as? String else { throw SerializationError.missing("title") } guard let body = json["body"] as? String else { throw SerializationError.missing("body") } self.ID = ID self.userID = userID self.title = title self.body = body } // MARK: - Instance Methods func post(requestWithID ID: Int, response: @escaping PostDataSource.PostResponse) { dataSource?.post(self, requestedWithID: ID, callback: response) } }
mit
382dd7fa01ed7d1e6a9eed04a0244f47
22.83871
87
0.553451
4.347059
false
false
false
false
melvitax/AFViewHelper
ViewHelperDemo iOS/ViewController.swift
1
7882
// // ViewController.swift // // Created by Melvin Rivera on 7/2/14. // Copyright (c) 2014 All Forces. All rights reserved. // import Foundation import UIKit import QuartzCore class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { var selectedAnimation: Int = 0 var selectedEasing: Int = 0 @IBOutlet weak var forceSlider: UISlider! @IBOutlet weak var forceLabel: UILabel! @IBOutlet weak var durationSlider: UISlider! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var delaySlider: UISlider! @IBOutlet weak var delayLabel: UILabel! @IBOutlet weak var scaleSlider: UISlider! @IBOutlet weak var scaleLabel: UILabel! @IBOutlet weak var rotateSlider: UISlider! @IBOutlet weak var rotateLabel: UILabel! @IBOutlet weak var dampingSlider: UISlider! @IBOutlet weak var dampingLabel: UILabel! @IBOutlet weak var velocitySlider: UISlider! @IBOutlet weak var velocityLabel: UILabel! @IBOutlet weak var xSlider: UISlider! @IBOutlet weak var xLabel: UILabel! @IBOutlet weak var ySlider: UISlider! @IBOutlet weak var yLabel: UILabel! @IBOutlet weak var mainBox: InspectableView! @IBOutlet weak var bigCircle: InspectableView! @IBOutlet weak var smallCircle: InspectableView! override var prefersStatusBarHidden : Bool { return true } override func viewDidLoad() { super.viewDidLoad() // Top Left Square let topLeftSquare = UIView(autoLayout:true) bigCircle.addSubview(topLeftSquare) topLeftSquare.backgroundColor = UIColor(white: 0.1, alpha: 1) topLeftSquare .left(to: bigCircle) .top(to: bigCircle) .width(to: bigCircle, attribute: .width, constant: 0, multiplier: 0.48) .height(to: topLeftSquare, attribute: .width) .layoutIfNeeded() // Top Right Square let topRightSquare = UIView(autoLayout:true) bigCircle.addSubview(topRightSquare) topRightSquare.backgroundColor = UIColor(white: 0.1, alpha: 1) topRightSquare .right(to: bigCircle) .top(to: bigCircle) .size(to: topLeftSquare) .layoutIfNeeded() // Bottom Left Square let bottomLeftSquare = UIView(autoLayout:true) bigCircle.addSubview(bottomLeftSquare) bottomLeftSquare.backgroundColor = UIColor(white: 0.1, alpha: 1) bottomLeftSquare .left(to: bigCircle) .bottom(to: bigCircle) .size(to: topLeftSquare) .layoutIfNeeded() // Bottom Right Square let bottomRightSquare = UIView(autoLayout:true) bigCircle.addSubview(bottomRightSquare) bottomRightSquare.backgroundColor = UIColor(white:0.1, alpha: 1) bottomRightSquare .right(to: bigCircle) .bottom(to: bigCircle) .size(to: topLeftSquare) .layoutIfNeeded() resetValues() } // MARK: View Layout override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) layoutView() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) //view.layoutIfNeeded() coordinator.animate(alongsideTransition: { context in // Create a transition and match the context's duration let transition = CATransition() transition.duration = context.transitionDuration transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) self.bigCircle.layer.add(transition, forKey: "cornerRadius") self.bigCircle.cornerRadius = self.bigCircle.width()/2 self.smallCircle.layer.add(transition, forKey: "cornerRadius") self.smallCircle.cornerRadius = self.smallCircle.width()/2 }, completion: nil) } func layoutView() { view.layoutIfNeeded() bigCircle.cornerRadius = bigCircle.width()/2 smallCircle.cornerRadius = smallCircle.width()/2 } // MARK: UIPickerView func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return component == 0 ? AnimationType.allValues.count : AnimationEasingCurve.allValues.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return component == 0 ? String(describing: AnimationType.allValues[row]) : String(describing: AnimationEasingCurve.allValues[row]) } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: selectedAnimation = row animateView(nil) default: selectedEasing = row animateView() } } // MARK: Actions @IBAction func resetValues(_ sender: AnyObject? = nil) { forceSlider.setValue(1, animated: true) durationSlider.setValue(0.5, animated: true) delaySlider.setValue(0, animated: true) scaleSlider.setValue(1, animated: true) rotateSlider.setValue(0, animated: true) dampingSlider.setValue(0.7, animated: true) velocitySlider.setValue(0.7, animated: true) xSlider.setValue(0, animated: true) ySlider.setValue(0, animated: true) } @IBAction func animateView(_ sender: AnyObject? = nil) { bigCircle.animate(AnimationType.allValues[selectedAnimation], curve: AnimationEasingCurve.allValues[selectedEasing], duration: CGFloat(durationSlider.value), delay: CGFloat(delaySlider.value), force: CGFloat(forceSlider.value), damping: CGFloat(dampingSlider.value),velocity: CGFloat(velocitySlider.value), fromRotation: CGFloat(rotateSlider.value), fromScale: CGFloat(scaleSlider.value), fromX: CGFloat(xSlider.value), fromY: CGFloat(ySlider.value)) } @IBAction func forceSliderChanged(_ sender: AnyObject) { animateView() forceLabel.text = String(format: "Force: %.1f", forceSlider.value) } @IBAction func durationSliderChanged(_ sender: AnyObject) { animateView() durationLabel.text = String(format: "Duration: %.1f", durationSlider.value) } @IBAction func delaySliderChanged(_ sender: AnyObject) { animateView() delayLabel.text = String(format: "Delay: %.1f", delaySlider.value) } @IBAction func scaleSliderChanged(_ sender: AnyObject) { animateView() scaleLabel.text = String(format: "Scale: %.1f", scaleSlider.value) } @IBAction func rotateSliderChanged(_ sender: AnyObject) { animateView() rotateLabel.text = String(format: "Rotate: %.1f", rotateSlider.value) } @IBAction func dampingSliderChanged(_ sender: AnyObject) { animateView() dampingLabel.text = String(format: "Damping: %.1f", dampingSlider.value) } @IBAction func velocitySliderChanged(_ sender: AnyObject) { animateView() velocityLabel.text = String(format: "Velocity: %.1f", velocitySlider.value) } @IBAction func xSliderChanged(_ sender: AnyObject) { animateView() xLabel.text = String(format: "x: %.1f", xSlider.value) } @IBAction func ySliderChanged(_ sender: AnyObject) { animateView() yLabel.text = String(format: "y: %.1f", ySlider.value) } }
mit
25585235f8e8174d986be9c0246ecc71
34.345291
458
0.644126
4.77697
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Access/AttributeKey.swift
1
550
// // AttributeKey.swift // ZeeQL // // Created by Helge Hess on 02/03/17. // Copyright © 2017 ZeeZide GmbH. All rights reserved. // public struct AttributeKey : Key, Equatable { public var key : String { return attribute.name } public let entity : Entity? public let attribute : Attribute public init(_ attribute: Attribute, entity: Entity? = nil) { self.attribute = attribute self.entity = entity } public static func ==(lhs: AttributeKey, rhs: AttributeKey) -> Bool { return lhs.key == rhs.key } }
apache-2.0
276313bcf9cc573874314f3b722bf22e
20.96
71
0.653916
3.760274
false
false
false
false
Syerram/asphalos
asphalos/FormRowDescriptor.swift
1
2495
// // FormRowDescriptor.swift // SwiftForms // // Created by Miguel Angel Ortuno on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit enum FormRowType { case Unknown case Text case URL case Number case NumbersAndPunctuation case Decimal case Name case Phone case NamePhone case Email case Twitter case ASCIICapable case Password case Button case BooleanSwitch case BooleanCheck case SegmentedControl case Picker case Date case Time case DateAndTime case MultipleSelector case Label case Textarea case ReadOnlyTextField case MultiLineLabel case PlainText } typealias TitleFormatter = (NSObject) -> String! class FormRowDescriptor: NSObject { /// MARK: Properties var title: String! var rowType: FormRowType = .Unknown var tag: String! var value: NSObject! { willSet { self.willUpdateValueBlock?(self) } didSet { self.didUpdateValueBlock?(self) } } var required = true var cellClass: AnyClass! var cellAccessoryView: UIView! var placeholder: String! var cellConfiguration: NSDictionary! var willUpdateValueBlock: ((FormRowDescriptor) -> Void)! var didUpdateValueBlock: ((FormRowDescriptor) -> Void)! var visualConstraintsBlock: ((FormBaseCell) -> NSArray)! var options: NSArray! var titleFormatter: TitleFormatter! var selectorControllerClass: AnyClass! var allowsMultipleSelection = false var showInputToolbar = false var dateFormatter: NSDateFormatter! var backgroundColor:UIColor? var tintColor:UIColor? var userInfo: NSDictionary! /// MARK: Init init(tag: String, rowType: FormRowType, title: String, placeholder: String! = nil) { self.tag = tag self.rowType = rowType self.title = title self.placeholder = placeholder } /// MARK: Public interface func titleForOptionAtIndex(index: Int) -> String! { return titleForOptionValue(options[index] as! NSObject) } func titleForOptionValue(optionValue: NSObject) -> String! { if titleFormatter != nil { return titleFormatter(optionValue) } else if optionValue is String { return optionValue as! String } return "\(optionValue)" } }
mit
23d28c3779281def19f521690d627547
21.672727
88
0.638733
4.997996
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Create.swift
24
2570
// // Create.swift // RxSwift // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension Observable { // MARK: create /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> { return AnonymousObservable(subscribe) } } final fileprivate class AnonymousObservableSink<O: ObserverType> : Sink<O>, ObserverType { typealias E = O.E typealias Parent = AnonymousObservable<E> // state private var _isStopped: AtomicInt = 0 #if DEBUG fileprivate var _numberOfConcurrentCalls: AtomicInt = 0 #endif override init(observer: O, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { #if DEBUG if AtomicIncrement(&_numberOfConcurrentCalls) > 1 { rxFatalError("Warning: Recursive call or synchronization error!") } defer { _ = AtomicDecrement(&_numberOfConcurrentCalls) } #endif switch event { case .next: if _isStopped == 1 { return } forwardOn(event) case .error, .completed: if AtomicCompareAndSwap(0, 1, &_isStopped) { forwardOn(event) dispose() } } } func run(_ parent: Parent) -> Disposable { return parent._subscribeHandler(AnyObserver(self)) } } final fileprivate class AnonymousObservable<Element> : Producer<Element> { typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable let _subscribeHandler: SubscribeHandler init(_ subscribeHandler: @escaping SubscribeHandler) { _subscribeHandler = subscribeHandler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = AnonymousObservableSink(observer: observer, cancel: cancel) let subscription = sink.run(self) return (sink: sink, subscription: subscription) } }
mit
56536434df880a3e18622295411525c5
29.951807
145
0.637213
4.801869
false
false
false
false
carolight/sample-code
swift/05-Lighting/Lighting/MBERenderer.swift
1
7771
// // MBERenderer.swift // Lighting // // Created by Caroline Begbie on 1/01/2016. // Copyright © 2016 Caroline Begbie. All rights reserved. // import MetalKit struct MBEUniforms { var modelViewProjectionMatrix: matrix_float4x4 var modelViewMatrix: matrix_float4x4 var normalMatrix: matrix_float3x3 } class MBERenderer: NSObject { weak var device: MTLDevice? var uniformBuffer: MTLBuffer? var pipeline: MTLRenderPipelineState? var depthStencilState: MTLDepthStencilState? var commandQueue: MTLCommandQueue? var meshes = [MBEMesh]() var rotationX: Float = 0 var rotationY: Float = 0 init(device: MTLDevice?) { self.device = device super.init() makeUniformBuffer() makePipeline() loadModel(modelName: "teapot") } private func makeUniformBuffer() { uniformBuffer = device?.newBuffer(withLength: sizeof(MBEUniforms.self), options: []) uniformBuffer?.label = "Uniforms" } private func makePipeline() { let library = device?.newDefaultLibrary() let vertexFunc = library?.newFunction(withName: "vertex_project") let fragmentFunc = library?.newFunction(withName: "fragment_light") let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = vertexFunc pipelineDescriptor.fragmentFunction = fragmentFunc pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineDescriptor.depthAttachmentPixelFormat = .depth32Float pipelineDescriptor.depthAttachmentPixelFormat = .invalid let depthStencilDescriptor = MTLDepthStencilDescriptor() depthStencilDescriptor.depthCompareFunction = .less depthStencilDescriptor.isDepthWriteEnabled = true depthStencilState = device?.newDepthStencilState(with: depthStencilDescriptor) do { pipeline = try device?.newRenderPipelineState(with: pipelineDescriptor) } catch let error as NSError { print("Error creating render pipeline state: \(error)") } commandQueue = device?.newCommandQueue() } private func loadModel(modelName:String) { assert(device != nil, "No device available") guard let device = device else { return } guard let assetURL = Bundle.main.url(forResource: modelName, withExtension: "obj") else { print("Asset \(modelName) does not exist.") return } // See Apple Sample Code MetalKitEssentials /* Create a vertex descriptor for pipeline. Specifies the layout of vertices the pipeline should expect. This must match the shader definitions. */ let mtlVertexDescriptor = MTLVertexDescriptor() // Positions mtlVertexDescriptor.attributes[0].format = .float4 mtlVertexDescriptor.attributes[0].offset = 0 mtlVertexDescriptor.attributes[0].bufferIndex = 0 // Normals mtlVertexDescriptor.attributes[1].format = .float4 mtlVertexDescriptor.attributes[1].offset = 16 mtlVertexDescriptor.attributes[1].bufferIndex = 0 mtlVertexDescriptor.layouts[0].stride = 32 mtlVertexDescriptor.layouts[0].stepRate = 1 mtlVertexDescriptor.layouts[0].stepFunction = .perVertex /* Create a Model I/O vertex descriptor. This specifies the layout of vertices Model I/O should format loaded meshes with. */ let mdlVertexDescriptor = MTKModelIOVertexDescriptorFromMetal(mtlVertexDescriptor) let attributePosition = mdlVertexDescriptor.attributes[0] as! MDLVertexAttribute attributePosition.name = MDLVertexAttributePosition mdlVertexDescriptor.attributes[0] = attributePosition let attributeNormal = mdlVertexDescriptor.attributes[1] as! MDLVertexAttribute attributeNormal.name = MDLVertexAttributeNormal mdlVertexDescriptor.attributes[1] = attributeNormal let bufferAllocator = MTKMeshBufferAllocator(device: device) /* Load Model I/O Asset with mdlVertexDescriptor, specifying vertex layout and bufferAllocator enabling ModelIO to load vertex and index buffers directory into Metal GPU memory. */ let asset = MDLAsset(url: assetURL, vertexDescriptor: mdlVertexDescriptor, bufferAllocator: bufferAllocator) let mtkMeshes:[MTKMesh]? var mdlMeshes:NSArray? do { mtkMeshes = try MTKMesh.newMeshes(from: asset, device: device, sourceMeshes: &mdlMeshes) } catch { print("error creating mesh") return } if let mdlMeshes = mdlMeshes as? [MDLMesh], let mtkMeshes = mtkMeshes { meshes = [] for (index, mtkMesh) in mtkMeshes.enumerated() { let mesh = MBEMesh(mesh: mtkMesh, mdlMesh: mdlMeshes[index], device: device) meshes.append(mesh) } } } } extension MBERenderer: MTKViewDelegate { private func updateUniformsForView(view: MTKView, duration: TimeInterval) { guard let uniformBuffer = uniformBuffer else { print("uniformBuffer not created") return } rotationX += Float(duration) * (π / 2) rotationY += Float(duration) * (π / 3) let scaleFactor:Float = 1 let xAxis = float3(1, 0, 0) let yAxis = float3(0, 1, 0) let xRotation = matrix_float4x4_rotation(axis: xAxis, angle: rotationX) let yRotation = matrix_float4x4_rotation(axis: yAxis, angle: rotationY) let scale = matrix_float4x4_uniform_scale(scale: scaleFactor) let modelMatrix = matrix_multiply(matrix_multiply(xRotation, yRotation), scale) let cameraTranslation = vector_float3(0, 0, -1.5) let viewMatrix = matrix_float4x4_translation(t: cameraTranslation) let drawableSize = view.drawableSize let aspect: Float = Float(drawableSize.width / drawableSize.height) let fov: Float = Float((2 * π) / 5) let near: Float = 0.1 let far: Float = 100 let projectionMatrix = matrix_float4x4_perspective(aspect: aspect, fovy: fov, near: near, far: far) // update uniform data with current viewing and model matrices let uniformPointer = UnsafeMutablePointer<MBEUniforms>(uniformBuffer.contents()) var uniformData = uniformPointer.pointee uniformData.modelViewMatrix = matrix_multiply(viewMatrix, modelMatrix); uniformData.modelViewProjectionMatrix = matrix_multiply(projectionMatrix, uniformData.modelViewMatrix); uniformData.normalMatrix = matrix_float4x4_extract_linear(m: uniformData.modelViewMatrix); uniformPointer.pointee = uniformData } func draw(in view: MTKView) { guard let drawable = view.currentDrawable else { print("drawable not set") return } guard let pipeline = pipeline else { print("pipeline not set") return } guard let commandBuffer = commandQueue?.commandBuffer() else { print("command buffer not set") return } view.clearColor = MTLClearColor(red: 0.85, green: 0.85, blue: 085, alpha: 1) let frameDuration:TimeInterval = 0.02 updateUniformsForView(view: view, duration: frameDuration) // Setup render passes - do calculations before allocating this guard let descriptor = view.currentRenderPassDescriptor else { print("no render pass descriptor") return } // Start render pass let commandEncoder = commandBuffer.renderCommandEncoder(with: descriptor) commandEncoder.setRenderPipelineState(pipeline) commandEncoder.setDepthStencilState(depthStencilState) // Set up uniform buffer commandEncoder.setVertexBuffer(uniformBuffer, offset: 0, at: 1) for mesh in meshes { mesh.renderWithEncoder(encoder: commandEncoder) } commandEncoder.endEncoding() commandBuffer.present(drawable) commandBuffer.commit() } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { } }
mit
5858203b63bbb1614cc8eea5fa336f8a
32.051064
112
0.710313
4.617717
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/EtherClient/Types/EthTypedData.swift
1
5121
// Copyright DApps Platform Inc. All rights reserved. import BigInt import Foundation import TrustCore /* This enum is only used to support decode solidity types (represented by json values) to swift primitive types. */ enum SolidityJSONValue: Decodable { case none case bool(value: Bool) case string(value: String) case address(value: String) // we store number in 64 bit integers case int(value: Int64) case uint(value: UInt64) var string: String { switch self { case .none: return "" case .bool(let bool): return bool ? "true" : "false" case .string(let string): return string case .address(let address): return address case .uint(let uint): return String(uint) case .int(let int): return String(int) } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if let boolValue = try? container.decode(Bool.self) { self = .bool(value: boolValue) } else if let uint = try? container.decode(UInt64.self) { self = .uint(value: uint) } else if let int = try? container.decode(Int64.self) { self = .int(value: int) } else if let string = try? container.decode(String.self) { if CryptoAddressValidator.isValidAddress(string) { self = .address(value: string) } else { self = .string(value: string) } } else { self = .none } } } struct EthTypedData: Decodable { //for signTypedMessage let type: String let name: String let value: SolidityJSONValue var schemaString: String { return "\(type) \(name)" } var schemaData: Data { return Data(bytes: Array(schemaString.utf8)) } var typedData: Data { switch value { case .bool(let bool): let byte: UInt8 = bool ? 0x01 : 0x00 return Data(bytes: [byte]) case .address(let address): let data = Data(hex: String(address.dropFirst(2))) return data case .uint(let uint): if type.starts(with: "bytes") { return uint.getHexData() } let size = parseIntSize(type: type, prefix: "uint") guard size > 0 else { return Data() } return uint.getTypedData(size: size) case .int(let int): if type.starts(with: "bytes") { return int.getHexData() } let size = parseIntSize(type: type, prefix: "int") guard size > 0 else { return Data() } return int.getTypedData(size: size) case .string(let string): if type.starts(with: "bytes") { if string.isHexEncoded { return Data(hex: string) } } else if type.starts(with: "uint") { let size = parseIntSize(type: type, prefix: "uint") guard size > 0 else { return Data() } if let uint = UInt64(string) { return uint.getTypedData(size: size) } else if let bigInt = BigUInt(string) { let encoder = ABIEncoder() try? encoder.encode(bigInt) return encoder.data } } else if type.starts(with: "int") { let size = parseIntSize(type: type, prefix: "int") guard size > 0 else { return Data() } if let int = Int64(string) { return int.getTypedData(size: size) } else if let bigInt = BigInt(string) { let encoder = ABIEncoder() try? encoder.encode(bigInt) return encoder.data } } return Data(bytes: Array(string.utf8)) case .none: return Data() } } } extension FixedWidthInteger { func getHexData() -> Data { var string = String(self, radix: 16) if string.count % 2 != 0 { //pad to even string = "0" + string } let data = Data(hex: string) return data } func getTypedData(size: Int) -> Data { var intValue = self.bigEndian var data = Data(buffer: UnsafeBufferPointer(start: &intValue, count: 1)) let num = size / 8 - 8 if num > 0 { data.insert(contentsOf: [UInt8].init(repeating: 0, count: num), at: 0) } else if num < 0 { data = data.advanced(by: abs(num)) } return data } } private func parseIntSize(type: String, prefix: String) -> Int { guard type.starts(with: prefix) else { return -1 } guard let size = Int(type.dropFirst(prefix.count)) else { if type == prefix { return 256 } return -1 } if size < 8 || size > 256 || size % 8 != 0 { return -1 } return size }
gpl-3.0
fbe70a7a533bf149672659a0f89a67c9
30.036364
110
0.521578
4.271059
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Album/AlbumVars.swift
1
3187
// // AlbumVars.shared.swift // piwigo // // Created by Eddy Lelièvre-Berna on 25/05/2021. // Copyright © 2021 Piwigo.org. All rights reserved. // import Foundation import piwigoKit class AlbumVars: NSObject { // Singleton @objc static let shared = AlbumVars() // Remove deprecated stored objects if needed override init() { // Deprecated data? if let _ = UserDefaults.dataSuite.object(forKey: "recentPeriod") { UserDefaults.dataSuite.removeObject(forKey: "recentPeriod") } } // MARK: - Vars in UserDefaults / Standard // Album variables stored in UserDefaults / Standard /// - Default root album, 0 by default @UserDefault("defaultCategory", defaultValue: 0) @objc var defaultCategory: Int /// - Default album thumbnail size determined from the available image sizes to present 144x144 pixel thumbnails @UserDefault("defaultAlbumThumbnailSize", defaultValue: PiwigoImageData.optimumAlbumThumbnailSizeForDevice().rawValue) @objc var defaultAlbumThumbnailSize: UInt32 /// - List of albums recently visited / used @UserDefault("recentCategories", defaultValue: "0") @objc var recentCategories: String /// - Maximum number of recent categories presented to the user @UserDefault("maxNberRecentCategories", defaultValue: 5) @objc var maxNberRecentCategories: Int /// - Default image sort option @UserDefault("defaultSort", defaultValue: kPiwigoSort.dateCreatedAscending.rawValue) @objc var defaultSort: Int16 /// - Display images titles in collection views @UserDefault("displayImageTitles", defaultValue: true) @objc var displayImageTitles: Bool /// - Album thumbnail size determined from the available image sizes to present 144x144 pixel thumbnails @UserDefault("defaultThumbnailSize", defaultValue: PiwigoImageData.optimumImageThumbnailSizeForDevice().rawValue) @objc var defaultThumbnailSize: UInt32 /// - Number of images per row in portrait mode @UserDefault("thumbnailsPerRowInPortrait", defaultValue: UIDevice.current.userInterfaceIdiom == .phone ? 4 : 6) @objc var thumbnailsPerRowInPortrait: Int /// - Recent period in number of days let recentPeriodKey = 594 // i.e. key used to detect the behaviour of the slider (sum of all periods) let recentPeriodList:[Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,50,60,80,99] @UserDefault("recentPeriodIndex", defaultValue: 6) // i.e index of the period of 7 days var recentPeriodIndex: Int // MARK: - Vars in UserDefaults / App Group // Album variables stored in UserDefaults / App Group /// - None // MARK: - Vars in Memory // Album variables kept in memory /// - Available image sizes @objc var hasSquareSizeImages = true @objc var hasThumbSizeImages = true @objc var hasXXSmallSizeImages = false @objc var hasXSmallSizeImages = false @objc var hasSmallSizeImages = false @objc var hasMediumSizeImages = true @objc var hasLargeSizeImages = false @objc var hasXLargeSizeImages = false @objc var hasXXLargeSizeImages = false }
mit
614e92eb108e1b8a2781f6d8b5129e37
37.373494
122
0.70832
4.411357
false
false
false
false
Yokong/douyu
douyu/douyu/Classes/Main/View/PageContentView.swift
1
3566
// // PageContentView.swift // douyu // // Created by Yoko on 2017/4/25. // Copyright © 2017年 Yokooll. All rights reserved. // import UIKit //MARK:- ------代理协议------ protocol PageContentViewDelegate: class { func pageContentViewDidScroll(offSetX: CGFloat, isLeft: Bool) } fileprivate let cellID = "cell" class PageContentView: UIView { //MARK:- ------外部属性------ weak var delegate: PageContentViewDelegate? //MARK:- ------内部属性------ fileprivate var childVCs = [UIViewController]() fileprivate var parentVC = UIViewController() fileprivate var startOffSet: CGFloat = 0 fileprivate var isLeft: Bool = false //MARK:- ------懒加载属性------ lazy var collectionView: UICollectionView = UICollectionView() init(frame: CGRect, childVCs: [UIViewController], parentVC: UIViewController) { self.childVCs = childVCs self.parentVC = parentVC super.init(frame: frame) setUp() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:- ------基础配置------ extension PageContentView { func setUp() { for child in childVCs { parentVC.addChildViewController(child) } // 添加collectionView let layout = UICollectionViewFlowLayout() layout.itemSize = bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID) addSubview(collectionView) } } //MARK:- ------collectionView数据源, 代理------ extension PageContentView: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVCs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } if let view = childVCs[indexPath.item].view { view.frame = cell.contentView.bounds cell.contentView.addSubview(view) } return cell } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { startOffSet = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if startOffSet < scrollView.contentOffset.x { isLeft = true } else { isLeft = false } delegate?.pageContentViewDidScroll(offSetX: scrollView.contentOffset.x, isLeft: isLeft) } } //MARK:- ------外部方法------ extension PageContentView { func setCollctionViewOffSet(index: Int) { let offSetX = CGFloat(index) * collectionView.bounds.width collectionView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true) } }
mit
e6f3f0c2816f07e237c838e802675661
24.540146
121
0.644756
5.408037
false
false
false
false
gservera/ScheduleKit
ScheduleKit/BaseDefinitions.swift
1
3869
/* * BaseDefinitions.swift * ScheduleKit * * Created: Guillem Servera on 24/12/2014. * Copyright: © 2014-2019 Guillem Servera (https://github.com/gservera) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Cocoa /// The shared calendar object used by the ScheduleKit framework. var sharedCalendar = Calendar.current /// A `Double` value that represents relative time points between the lower and /// upper date bounds in a concrete `SCKView` subclass. Valid values are the ones /// between 0.0 and 1.0, which represent the start date and the end date, /// respectively. Any other values are not valid and should be represented using /// `SCKRelativeTimeLocationInvalid`. internal typealias SCKRelativeTimeLocation = Double /// A `Double` value that represents the relative length (in percentage) for an /// event in a concrete `SCKView` subclass. Valid values are the ones /// between 0.0 and 1.0, which represent zero-length and full length values, /// respectively. Behaviour when using any other values in undefined. internal typealias SCKRelativeTimeLength = Double /// A fallback value generated by ScheduleKit the date of an event object used /// in a `SCKView` subclass does not fit in the view's date interval. internal let SCKRelativeTimeLocationInvalid = SCKRelativeTimeLocation(-Int.max) /// A fallback value generated by ScheduleKit the duration of an event object used /// in a `SCKView` subclass is invalid (negative or too wide). internal let SCKRelativeTimeLengthInvalid = SCKRelativeTimeLocation.leastNormalMagnitude /// Possible color styles for drawing event view backgrounds. @objc public enum SCKEventColorMode: Int { /// Colors events according to their event kind. case byEventKind /// Colors events according to their user's event color. case byEventOwner } extension Calendar { func dateInterval(_ interval: DateInterval, offsetBy value: Int, _ unit: Calendar.Component) -> DateInterval { let start = date(byAdding: unit, value: value, to: interval.start) let end = date(byAdding: unit, value: value, to: interval.end) return DateInterval(start: start!, end: end!) } } extension NSTextField { static func makeLabel(fontSize: CGFloat, color: NSColor) -> NSTextField { let label = NSTextField(frame: .zero) label.translatesAutoresizingMaskIntoConstraints = false label.isBordered = false label.isEditable = false label.isBezeled = false label.drawsBackground = false label.font = .systemFont(ofSize: fontSize) label.textColor = color return label } } extension CGRect { static func fill(_ xPos: CGFloat, _ yPos: CGFloat, _ wDim: CGFloat, _ hDim: CGFloat) { CGRect(x: xPos, y: yPos, width: wDim, height: hDim).fill() } }
mit
b0fe5be72971465a696561c9ba321f40
40.591398
114
0.732678
4.283499
false
false
false
false
zivboy/jetstream-ios
JetstreamTests/DependencyTests.swift
3
2403
// // DependencyTests.swift // Jetstream // // Copyright (c) 2014 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import Jetstream class DependencyTests: XCTestCase { var testModel = TestModel() var anotherTestModel = AnotherTestModel() override func setUp() { testModel = TestModel() anotherTestModel = AnotherTestModel() } override func tearDown() { super.tearDown() } func testDependentListeners() { var fireCount1 = 0 var fireCount2 = 0 testModel.observeChangeImmediately(self, key: "compositeProperty") { () -> Void in fireCount1 += 1 } anotherTestModel.observeChangeImmediately(self, key: "anotherCompositeProperty") { () -> Void in fireCount2 += 1 } testModel.float32 = 2.0 testModel.float32 = 3.0 testModel.anotherArray = [anotherTestModel] XCTAssertEqual(fireCount1, 3, "Dispatched three times") XCTAssertEqual(fireCount2, 0, "Not dispatched") anotherTestModel.anotherString = "kiva" anotherTestModel.anotherInteger = 1 XCTAssertEqual(fireCount1, 3, "Dispatched three times") XCTAssertEqual(fireCount2, 2, "Dispatched twice") } }
mit
254f43c86b18e3661c2d7556a1ee2cbf
35.409091
104
0.678319
4.621154
false
true
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Module/Map/Route/Bus/Main/Controller/BusRouteViewController.swift
1
6315
// // BusRouteViewController.swift // HelloSVU_Swift // // Created by Insect on 2017/10/3. //Copyright © 2017年 Insect. All rights reserved. // import UIKit import DOPDropDownMenu_Enhanced private let BusRouteCellID = "BusRouteCellID" private let kMapsDropDownMenuH: CGFloat = 40 class BusRouteViewController: BaseViewController { // MARK: - LazyLoad private lazy var originPoint = AMapGeoPoint() private lazy var destinationPoint = AMapGeoPoint() private lazy var originLoc = "" private lazy var destinationLoc = "" private let strategy = ["最快捷" , "最经济" , "最少换乘" , "最少步行" , "最舒适" , "不乘地铁"] private let time = ["现在出发"] /// 公交路径规划方案 private var route: AMapRoute? private lazy var menu: DOPDropDownMenu = { let menu = DOPDropDownMenu(origin: CGPoint(x: 0, y: 0), andHeight: kMapsDropDownMenuH) // 创建menu 第一次显示 不会调用点击代理,可以用这个手动调用 menu?.selectDefalutIndexPath() menu?.delegate = self menu?.dataSource = self return menu! }() private lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y: kMapsDropDownMenuH, w: ScreenW, h: view.frame.height - 115 - kMapsDropDownMenuH - kTitleViewH), style: .grouped) tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, w: ScreenW, h: .leastNormalMagnitude)) tableView.dataSource = self tableView.delegate = self tableView.register(cellType: BusRouteCell.self) tableView.showsVerticalScrollIndicator = false tableView.rowHeight = 120 return tableView }() private lazy var search: AMapSearchAPI = { let search = AMapSearchAPI() search?.delegate = self return search! }() private lazy var busRouteRequest: AMapTransitRouteSearchRequest = { let busRouteRequest = AMapTransitRouteSearchRequest() busRouteRequest.requireExtension = true busRouteRequest.city = "南京" return busRouteRequest }() // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() setUpUI() } } // MARK: - 设置 UI 界面 extension BusRouteViewController { private func setUpUI() { automaticallyAdjustsScrollViewInsets = false view.addSubview(menu) view.addSubview(tableView) } // MARK: - 设置底部 private func setUpFooterView() { let contentView = UIView(frame: CGRect(x: 0, y: 0, w: ScreenW, h: 40)) let footer = BusRouteFooterView.loadFromNib() footer.frame = contentView.bounds footer.route = route contentView.addSubview(footer) tableView.tableFooterView = contentView } } // MARK: - 公交路径规划 extension BusRouteViewController { func searchRoutePlanningBus(_ strategy: Int,_ originPoint: AMapGeoPoint, _ destinationPoint: AMapGeoPoint,_ originLoc: String,_ destinationLoc: String) { SVUHUD.show(.black) self.originPoint = originPoint self.destinationPoint = destinationPoint self.originLoc = originLoc self.destinationLoc = destinationLoc busRouteRequest.strategy = strategy busRouteRequest.origin = originPoint busRouteRequest.destination = destinationPoint search.aMapTransitRouteSearch(busRouteRequest) } } // MARK: - AMapSearchDelegate extension BusRouteViewController: AMapSearchDelegate { func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) { SVUHUD.dismiss() } func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse!) { SVUHUD.dismiss() if response.route == nil {return} route = response.route setUpFooterView() tableView.reloadData() } } // MARK: - UITableViewDataSource extension BusRouteViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return route?.transits.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath, cellType: BusRouteCell.self) cell.transit = route?.transits[indexPath.row] return cell } } // MARK: - UITableViewDelegate extension BusRouteViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = BusRouteDetailViewController() vc.route = route! vc.selIndex = indexPath.row vc.originLoc = originLoc vc.destinationLoc = destinationLoc navigationController?.pushViewController(vc, animated: true) } // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // // let cell = tableView.dequeueReusableCell(withIdentifier: BusRouteCellID, for: indexPath) // return cell.cellHeight ?? 0 // } } // MARK: - DOPDropDownMenuDataSource extension BusRouteViewController: DOPDropDownMenuDataSource { func numberOfColumns(in menu: DOPDropDownMenu!) -> Int { return 2 } func menu(_ menu: DOPDropDownMenu!, numberOfRowsInColumn column: Int) -> Int { return column == 0 ? strategy.count: time.count } func menu(_ menu: DOPDropDownMenu!, titleForRowAt indexPath: DOPIndexPath!) -> String! { return indexPath.column == 0 ? strategy[indexPath.row]: time[indexPath.row] } } // MARK: - DOPDropDownMenuDelegate extension BusRouteViewController: DOPDropDownMenuDelegate { func menu(_ menu: DOPDropDownMenu!, didSelectRowAt indexPath: DOPIndexPath!) { /// 公交换乘策略:0-最快捷模式;1-最经济模式;2-最少换乘模式;3-最少步行模式;4-最舒适模式;5-不乘地铁模式 if indexPath.column == 0 { searchRoutePlanningBus(indexPath.row, originPoint, destinationPoint,originLoc,destinationLoc) } } }
apache-2.0
3b79160050e528c42472fc574c2dbf51
30.471503
171
0.661014
4.587613
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/LayoutKit/Sources/Layouts/ButtonLayout.swift
1
10993
// Copyright 2016 LinkedIn Corp. // 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. import UIKit /** Layout for a UIButton. Since UIKit does not provide threadsafe methods to determine the size of a button given its content it's implememtation hard-codes the current observed style of UIButton. If the style of UIButton changes in the future, then the current implementation will need to be updated to reflect the new style. If future-proofing is a concern for your application, then you should not use ButtonLayout and instead implement your own custom layout that uses you own custom button view (e.g. by subclassing UIControl). Similary, if you have your own custom button view, you will need to create your own custom layout for it. */ open class ButtonLayout<Button: UIButton>: BaseLayout<Button>, ConfigurableLayout { public let type: ButtonLayoutType public let title: Text public let image: ButtonLayoutImage public let font: UIFont? public let contentEdgeInsets: UIEdgeInsets public init(type: ButtonLayoutType, title: String, // TODO: support attributed text once we figure out how to get tests to pass image: ButtonLayoutImage = .defaultImage, font: UIFont? = nil, contentEdgeInsets: UIEdgeInsets? = nil, alignment: Alignment = ButtonLayoutDefaults.defaultAlignment, flexibility: Flexibility = ButtonLayoutDefaults.defaultFlexibility, viewReuseId: String? = nil, config: ((Button) -> Void)? = nil) { self.type = type self.title = .unattributed(title) self.image = image self.font = font self.contentEdgeInsets = contentEdgeInsets ?? ButtonLayout.defaultContentEdgeInsets(for: type, image: image) super.init(alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, config: config) } init(type: ButtonLayoutType, title: String, image: ButtonLayoutImage = .defaultImage, font: UIFont? = nil, contentEdgeInsets: UIEdgeInsets? = nil, alignment: Alignment = ButtonLayoutDefaults.defaultAlignment, flexibility: Flexibility = ButtonLayoutDefaults.defaultFlexibility, viewReuseId: String? = nil, viewClass: Button.Type? = nil, config: ((UIButton) -> Void)? = nil) { self.type = type self.title = .unattributed(title) self.image = image self.font = font self.contentEdgeInsets = contentEdgeInsets ?? ButtonLayout.defaultContentEdgeInsets(for: type, image: image) super.init(alignment: alignment, flexibility: flexibility, viewReuseId: viewReuseId, viewClass: viewClass ?? Button.self, config: config) } private static func defaultContentEdgeInsets(for type: ButtonLayoutType, image: ButtonLayoutImage) -> UIEdgeInsets { switch type { case .custom, .detailDisclosure, .infoLight, .infoDark, .contactAdd: return .zero case .system: #if os(tvOS) if case .defaultImage = image { return .zero } return UIEdgeInsets(top: 20, left: 40, bottom: 20, right: 40) #else return .zero #endif } } open func measurement(within maxSize: CGSize) -> LayoutMeasurement { let imageSize = sizeOf(image: image) let titleSize = sizeOfTitle(within: maxSize) let width = max(minWidth, ceil(imageSize.width + titleSize.width + contentEdgeInsets.left + contentEdgeInsets.right)) let height = ceil(max(imageSize.height, titleSize.height) + contentEdgeInsets.top + contentEdgeInsets.bottom + verticalPadding) let size = CGSize(width: width, height: height).decreasedToSize(maxSize) return LayoutMeasurement(layout: self, size: size, maxSize: maxSize, sublayouts: []) } /// Unlike UILabel, UIButton has nonzero height when the title is empty. private func sizeOfTitle(within maxSize: CGSize) -> CGSize { switch title { case .attributed(let text): if text.string.isEmpty && preserveHeightOfEmptyTitle { let attributedText = NSMutableAttributedString(attributedString: text) attributedText.mutableString.setString(" ") return CGSize(width: 0, height: sizeOf(text: .attributed(attributedText), maxSize: maxSize).height) } else { return sizeOf(text: title, maxSize: maxSize) } case .unattributed(let text): if text.isEmpty && preserveHeightOfEmptyTitle { return CGSize(width: 0, height: sizeOf(text: .unattributed(" "), maxSize: maxSize).height) } else { return sizeOf(text: title, maxSize: maxSize) } } } private var preserveHeightOfEmptyTitle: Bool { switch type { case .custom, .system: return true case .detailDisclosure, .infoLight, .infoDark, .contactAdd: return false } } private func sizeOf(text: Text, maxSize: CGSize) -> CGSize { return LabelLayout(text: text, font: fontForMeasurement, numberOfLines: 0).measurement(within: maxSize).size } /** The font that should be used to measure the button's title. This is based on observed behavior of UIButton. */ private var fontForMeasurement: UIFont { switch type { case .custom: return font ?? defaultFontForCustomButton case .system: return font ?? defaultFontForSystemButton case .contactAdd, .infoLight, .infoDark, .detailDisclosure: // Setting a custom font has no effect in this case. return defaultFontForSystemButton } } private var defaultFontForCustomButton: UIFont { #if os(tvOS) return UIFont.systemFont(ofSize: 38, weight: UIFont.Weight.medium) #else return UIFont.systemFont(ofSize: 18) #endif } private var defaultFontForSystemButton: UIFont { #if os(tvOS) return UIFont.systemFont(ofSize: 38, weight: UIFont.Weight.medium) #else return UIFont.systemFont(ofSize: 15) #endif } private func sizeOf(image: ButtonLayoutImage) -> CGSize { switch image { case .size(let size): return size case .image(let image): return image?.size ?? .zero case .defaultImage: switch type { case .custom, .system: return .zero case .contactAdd, .infoLight, .infoDark, .detailDisclosure: #if os(tvOS) return CGSize(width: 37, height: 46) #else return CGSize(width: 22, height: 22) #endif } } } private var minWidth: CGFloat { switch type { case .custom, .system: return hasCustomStyle ? 0 : 30 case .detailDisclosure, .infoLight, .infoDark, .contactAdd: return 0 } } private var hasCustomStyle: Bool { return hasCustomImage || contentEdgeInsets != .zero } private var hasCustomImage: Bool { switch image { case .size, .image: return true case .defaultImage: return false } } private var verticalPadding: CGFloat { switch type { case .custom, .system: return hasCustomStyle ? 0 : 12 case .detailDisclosure, .infoLight, .infoDark, .contactAdd: #if os(tvOS) return isTitleEmpty && !hasCustomImage ? -9 : 0 #else return 0 #endif } } private var isTitleEmpty: Bool { switch title { case .unattributed(let text): return text.isEmpty case .attributed(let text): return text.string.isEmpty } } open func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement { let frame = alignment.position(size: measurement.size, in: rect) return LayoutArrangement(layout: self, frame: frame, sublayouts: []) } open override func makeView() -> View { return Button(type: type.buttonType) } open override func configure(view: Button) { config?(view) view.contentEdgeInsets = contentEdgeInsets if let font = font { view.titleLabel?.font = font } switch title { case .unattributed(let text): view.setTitle(text, for: .normal) case .attributed(let text): view.setAttributedTitle(text, for: .normal) } switch image { case .image(let image): view.setImage(image, for: .normal) case .size, .defaultImage: break } } open override var needsView: Bool { return true } } /** The image that appears on the button. */ public enum ButtonLayoutImage { /** Use the default image for the button type. (i.e. no image for .custom and .system, and the appropriate image for the other button types). */ case defaultImage /** Specify the size of the image that will be set on the UIButton at a later point (e.g. if you are loading the image from network). */ case size(CGSize) /** The image to set on the button for UIControlState.normal. You may configure the image for other states in the config block, but they should be the same size as this image. */ case image(UIImage?) } /** Maps to UIButtonType. This prevents LayoutKit from breaking if a new UIButtonType is added. */ public enum ButtonLayoutType { case custom case system case detailDisclosure case infoLight case infoDark case contactAdd public var buttonType: UIButtonType { switch (self) { case .custom: return .custom case .system: return .system case .detailDisclosure: return .detailDisclosure case .infoLight: return .infoLight case .infoDark: return .infoDark case .contactAdd: return .contactAdd } } } public class ButtonLayoutDefaults { public static let defaultAlignment = Alignment.topLeading public static let defaultFlexibility = Flexibility.flexible }
mit
5667af23a42e4926710fb348a044e856
33.678233
145
0.621577
4.88795
false
false
false
false
vector-im/riot-ios
Riot/Modules/MajorUpdate/MajorUpdateViewController.swift
1
5876
// File created from ScreenTemplate // $ createScreen.sh SecretsSetupRecoveryKey SecretsSetupRecoveryKey /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit @objc final class MajorUpdateViewController: UIViewController { // MARK: - Constants private enum Sizing { static var viewController: MajorUpdateViewController? static var widthConstraint: NSLayoutConstraint? } // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var oldLogoImageView: UIImageView! @IBOutlet private weak var disclosureImageView: UIImageView! @IBOutlet private weak var newLogoImageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var learnMoreButton: RoundedButton! @IBOutlet private weak var doneButton: UIButton! // MARK: Private private var theme: Theme! // MARK: Public @objc var didTapLearnMoreButton: (() -> Void)? @objc var didTapDoneButton: (() -> Void)? // MARK: - Setup @objc class func instantiate() -> MajorUpdateViewController { let viewController = StoryboardScene.MajorUpdateViewController.initialScene.instantiate() viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide back button self.navigationItem.setHidesBackButton(true, animated: animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.disclosureImageView.tintColor = theme.noticeSecondaryColor self.newLogoImageView.tintColor = theme.tintColor self.titleLabel.textColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textSecondaryColor self.learnMoreButton.update(theme: theme) theme.applyStyle(onButton: self.doneButton) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { self.vc_removeBackTitle() self.oldLogoImageView.image = Asset.Images.oldLogo.image self.disclosureImageView.image = Asset.Images.disclosureIcon.image self.newLogoImageView.image = Asset.Images.launchScreenLogo.image self.titleLabel.text = VectorL10n.majorUpdateTitle self.informationLabel.text = VectorL10n.majorUpdateInformation self.learnMoreButton.setTitle(VectorL10n.majorUpdateLearnMoreAction, for: .normal) self.doneButton.setTitle(VectorL10n.majorUpdateDoneAction, for: .normal) } // MARK: - Actions @IBAction private func learnMoreButtonAction(_ sender: Any) { self.didTapLearnMoreButton?() } @IBAction private func doneButtonAction(_ sender: Any) { self.didTapDoneButton?() } } // MARK: - SlidingModalPresentable extension MajorUpdateViewController: SlidingModalPresentable { func allowsDismissOnBackgroundTap() -> Bool { return true } func layoutHeightFittingWidth(_ width: CGFloat) -> CGFloat { let sizingViewContoller: MajorUpdateViewController if let viewController = MajorUpdateViewController.Sizing.viewController { sizingViewContoller = viewController } else { sizingViewContoller = MajorUpdateViewController.instantiate() MajorUpdateViewController.Sizing.viewController = sizingViewContoller } let sizingViewContollerView: UIView = sizingViewContoller.view if let widthConstraint = MajorUpdateViewController.Sizing.widthConstraint { widthConstraint.constant = width } else { let widthConstraint = sizingViewContollerView.widthAnchor.constraint(equalToConstant: width) widthConstraint.isActive = true MajorUpdateViewController.Sizing.widthConstraint = widthConstraint sizingViewContollerView.heightAnchor.constraint(equalToConstant: 0) } sizingViewContollerView.layoutIfNeeded() return sizingViewContoller.scrollView.contentSize.height } }
apache-2.0
9cfa4042bfb1e657497e04c078b89d9b
32.386364
137
0.681926
5.732683
false
false
false
false
NachoSoto/AsyncImageView
AsyncImageView/Renderers/RemoteImageRenderer.swift
1
2023
// // RemoteImageRenderer.swift // AsyncImageView // // Created by Nacho Soto on 11/22/15. // Copyright © 2015 Nacho Soto. All rights reserved. // import UIKit import ReactiveSwift public protocol RemoteRenderDataType: RenderDataType { var imageURL: URL { get } } /// `RendererType` which downloads images. /// /// Note that this Renderer will ignore `RenderDataType.size` and instead /// download the original image. /// Consider chaining this with `ImageInflaterRenderer`. public final class RemoteImageRenderer<T: RemoteRenderDataType>: RendererType { private let session: URLSession public init(session: URLSession = URLSession.shared) { self.session = session } public func renderImageWithData(_ data: T) -> SignalProducer<UIImage, RemoteImageRendererError> { return self.session.reactive.data(with: URLRequest(url: data.imageURL)) .mapError(RemoteImageRendererError.loadingError) .attemptMap { (data, response) in Result( (response as? HTTPURLResponse).map { (data, $0) }, failWith: .invalidResponse ) } .flatMap(.merge) { (content, response) -> SignalProducer<Foundation.Data, RemoteImageRendererError> in let statusCode = response.statusCode if statusCode >= 200 && statusCode < 300 { return SignalProducer(value: content) } else if statusCode == 404 { return SignalProducer(error: .notFound(url: data.imageURL)) } else { return SignalProducer(error: .invalidStatusCode(statusCode: statusCode)) } } .observe(on: QueueScheduler()) .flatMap(.merge) { data in return SignalProducer { Result( UIImage(data: data), failWith: RemoteImageRendererError.decodingError ) } } } } public enum RemoteImageRendererError: Error { case loadingError(originalError: Error) case invalidResponse case notFound(url: URL) case invalidStatusCode(statusCode: Int) case decodingError }
mit
aa8c8d2351620d4f29a4a5a939b10aa0
29.179104
105
0.679031
4.311301
false
false
false
false
CCIP-App/CCIP-iOS
OPass/Views/Tabs/Schedule/ScheduleView.swift
1
12861
// // ScheduleView.swift // OPass // // Created by 張智堯 on 2022/3/2. // 2022 OPass. // import SwiftUI import SwiftDate struct ScheduleView: View { @ObservedObject var eventAPI: EventAPIViewModel @State private var selectDayIndex: Int @State private var filter = Filter.all @State private var isError = false @AppStorage("AutoSelectScheduleDay") var autoSelectScheduleDay = true init(eventAPI: EventAPIViewModel) { self.eventAPI = eventAPI if AppStorage(wrappedValue: true, "AutoSelectScheduleDay").wrappedValue { self.selectDayIndex = eventAPI.schedule?.sessions.count == 1 ? 0 : eventAPI.schedule?.sessions.firstIndex { $0.header[0].isToday } ?? 0 } else { self.selectDayIndex = 0 } } var body: some View { VStack { if !isError { if let allScheduleData = eventAPI.schedule { VStack(spacing: 0) { if allScheduleData.sessions.count > 1 { SelectDayView(selectDayIndex: $selectDayIndex, sessions: allScheduleData.sessions) .background(Color("SectionBackgroundColor")) } let filteredModel = allScheduleData.sessions[selectDayIndex].filter({ session in switch filter { case .all: return true case .liked: return eventAPI.liked_sessions.contains(session.id) case .tag(let tag): return session.tags.contains(tag) case .type(let type): return session.type == type case .room(let room): return session.room == room case .speaker(let speaker): return session.speakers.contains(speaker) } }) Form { ForEach(filteredModel.header, id: \.self) { header in Section { ForEach(filteredModel.data[header]!.sorted { $0.end < $1.end }, id: \.id) { detail in NavigationLink(value: Router.mainDestination.sessionDetail(detail)) { SessionOverView( room: eventAPI.schedule?.rooms.data[detail.room]?.localized().name ?? detail.room, start: detail.start, end: detail.end, title: detail.localized().title ) } } } .listRowInsets(.init(top: 10, leading: 15, bottom: 10, trailing: 15)) } } .refreshable { try? await eventAPI.loadSchedule() } .overlay { if filteredModel.isEmpty { VStack(alignment: .center) { Image(systemName: "text.badge.xmark") .resizable() .scaledToFit() .foregroundColor(Color("LogoColor")) .frame(width: UIScreen.main.bounds.width * 0.15) .padding(.bottom) Text(LocalizedStringKey("NoFilteredEvent")) .multilineTextAlignment(.center) .foregroundColor(.gray) } } } } } else { ProgressView(LocalizedStringKey("Loading")) .task { await ScheduleFirstLoad() } } } else { ErrorWithRetryView { self.isError = false Task { await ScheduleFirstLoad() } } } } .navigationBarTitleDisplayMode(.inline) .toolbar { if let displayText = eventAPI.settings.feature(ofType: .schedule)?.display_text { ToolbarItem(placement: .principal) { Text(displayText.localized()).font(.headline) } } ToolbarItem(placement: .navigationBarTrailing) { Menu { Picker(selection: $filter, label: EmptyView()) { Label("AllSessions", systemImage: "list.bullet") .tag(Filter.all) Label("Favorite", systemImage: "heart\(filter == .liked ? ".fill" : "")") .tag(Filter.liked) if let schedule = eventAPI.schedule, schedule.tags.id.isNotEmpty { Menu { Picker(selection: $filter, label: EmptyView()) { ForEach(schedule.tags.id, id: \.self) { id in Text(schedule.tags.data[id]?.localized().name ?? id) .tag(Filter.tag(id)) } } } label: { Label("Tags", systemImage: { switch filter { case .tag(_): return "tag.fill" default: return "tag" } }()) } } if let schedule = eventAPI.schedule, schedule.session_types.id.isNotEmpty { Menu { Picker(selection: $filter, label: EmptyView()) { ForEach(schedule.session_types.id, id: \.self) { id in Text(schedule.session_types.data[id]?.localized().name ?? id) .tag(Filter.type(id)) } } } label: { Label("Types", systemImage: { switch filter { case .type(_): return "signpost.right.fill" default: return "signpost.right" } }()) } } if let schedule = eventAPI.schedule, schedule.rooms.id.isNotEmpty { Menu { Picker(selection: $filter, label: EmptyView()) { ForEach(schedule.rooms.id, id: \.self) { id in Text(schedule.rooms.data[id]?.localized().name ?? id) .tag(Filter.room(id)) } } } label: { Label("Places", systemImage: { switch filter { case .room(_): return "map.fill" default: return "map" } }()) } } if let schedule = eventAPI.schedule, schedule.speakers.id.isNotEmpty { Menu { Picker(selection: $filter, label: EmptyView()) { ForEach(schedule.speakers.id, id: \.self) { id in Text(schedule.speakers.data[id]?.localized().name ?? id) .tag(Filter.speaker(id)) } } } label: { Label("Speakers", systemImage: { switch filter { case .speaker(_): return "person.fill" default: return "person" } }()) } } } .labelsHidden() .pickerStyle(.inline) } label: { Image(systemName: "line.3.horizontal.decrease.circle\(filter == .all ? "" : ".fill")") } } } } private func ScheduleFirstLoad() async { do { try await eventAPI.loadSchedule() if eventAPI.schedule?.sessions.count ?? 0 > 1, autoSelectScheduleDay{ self.selectDayIndex = eventAPI.schedule?.sessions.firstIndex { $0.header[0].isToday } ?? 0 } } catch { isError = true } } } private enum Filter: Hashable { case all, liked case tag(String) case type(String) case room(String) case speaker(String) } private struct SelectDayView: View { @Environment(\.colorScheme) var colorScheme @Binding var selectDayIndex: Int let sessions: [SessionModel] private let weekDayName: [LocalizedStringKey] = ["SUN", "MON", "TUE", "WEN", "THR", "FRI", "SAT"] var body: some View { VStack(spacing: 0) { HStack(spacing: 10) { ForEach(0 ..< sessions.count, id: \.self) { index in Button { self.selectDayIndex = index } label: { VStack(alignment: .center, spacing: 0) { Text(weekDayName[sessions[index].header[0].weekday - 1]) .font(.system(.subheadline, design: .monospaced)) Text(String(sessions[index].header[0].day)) .font(.system(.body, design: .monospaced)) } .foregroundColor(index == selectDayIndex ? (colorScheme == .dark ? Color.white : Color.white) : (colorScheme == .dark ? Color.white : Color.black)) .padding(8) .background(Color.blue.opacity(index == selectDayIndex ? 1 : 0)) .cornerRadius(10) } } } Divider().padding(.top, 13) } .frame(maxWidth: .infinity) } } private struct SessionOverView: View { @AppStorage("DimPastSession") var dimPastSession = true @AppStorage("PastSessionOpacity") var pastSessionOpacity: Double = 0.4 let room: String, start: DateInRegion, end: DateInRegion, title: String var body: some View { VStack(alignment: .leading, spacing: 3) { HStack() { Text(room) .font(.caption2) .padding(.vertical, 1) .padding(.horizontal, 8) .foregroundColor(.white) .background(.blue) .cornerRadius(5) Text(String(format: "%d:%02d ~ %d:%02d", start.hour, start.minute, end.hour, end.minute)) .foregroundColor(.gray) .font(.footnote) } Text(title) .lineLimit(2) } .opacity(end.isBeforeDate(DateInRegion(), orEqual: true, granularity: .minute) && dimPastSession ? pastSessionOpacity : 1) } } #if DEBUG struct ScheduleView_Previews: PreviewProvider { static var previews: some View { ScheduleView(eventAPI: OPassAPIViewModel.mock().currentEventAPI!) .environmentObject(OPassAPIViewModel.mock()) } } #endif
gpl-3.0
3e155049764115a7ec23d7c1e1d22e56
43.790941
147
0.392688
6.063679
false
false
false
false
ricardorauber/iOS-Swift
iOS-Swift.playground/Pages/Core Data.xcplaygroundpage/Contents.swift
1
7495
//: ## Core Data //: ---- //: [Previous](@previous) import Foundation import CoreData //: Entities var countryEntity = NSEntityDescription() countryEntity.name = "Country" var manufacturerEntity = NSEntityDescription() manufacturerEntity.name = "Manufacturer" var carEntity = NSEntityDescription() carEntity.name = "Car" //: Attributes func newAttribute(name: String, type: NSAttributeType) -> NSAttributeDescription { let attribute = NSAttributeDescription() attribute.name = name attribute.attributeType = type attribute.optional = false attribute.indexed = false return attribute } let countryNameAttribute = newAttribute("name", type: NSAttributeType.StringAttributeType) let manufacturerNameAttribute = newAttribute("name", type: NSAttributeType.StringAttributeType) let carNameAttribute = newAttribute("name", type: NSAttributeType.StringAttributeType) let carPriceAttribute = newAttribute("price", type: NSAttributeType.FloatAttributeType) //: Relationships func newRelationship(name: String, toEntity: NSEntityDescription, toMany: Bool, deleteCascade: Bool) -> NSRelationshipDescription { let relationship = NSRelationshipDescription() relationship.name = name relationship.destinationEntity = toEntity relationship.minCount = 0 if toMany { relationship.maxCount = 0 } else { relationship.maxCount = 1 } if deleteCascade { relationship.deleteRule = NSDeleteRule.CascadeDeleteRule } else { relationship.deleteRule = NSDeleteRule.NullifyDeleteRule } return relationship } let countryRelationshipToManufacturer = newRelationship("manufacturers", toEntity: manufacturerEntity, toMany: true, deleteCascade: true) let manufacturerRelationshipToCountry = newRelationship("country", toEntity: countryEntity, toMany: false, deleteCascade: false) countryRelationshipToManufacturer.inverseRelationship = manufacturerRelationshipToCountry manufacturerRelationshipToCountry.inverseRelationship = countryRelationshipToManufacturer let manufacturerRelationshipToCar = newRelationship("cars", toEntity: carEntity, toMany: true, deleteCascade: true) let carRelationshipToManufacturer = newRelationship("manufacturer", toEntity: manufacturerEntity, toMany: false, deleteCascade: false) manufacturerRelationshipToCar.inverseRelationship = carRelationshipToManufacturer carRelationshipToManufacturer.inverseRelationship = manufacturerRelationshipToCar //: Entities Properties countryEntity.properties = [countryNameAttribute, countryRelationshipToManufacturer] manufacturerEntity.properties = [manufacturerNameAttribute, manufacturerRelationshipToCountry, manufacturerRelationshipToCar] carEntity.properties = [carNameAttribute, carPriceAttribute, carRelationshipToManufacturer] //: Managed Object Model var model = NSManagedObjectModel() model.entities = [countryEntity, manufacturerEntity, carEntity] //: Persistent Store Coordinator let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel:model) do { try persistentStoreCoordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil) } catch { print("error creating persistent store coordinator: \(error)") } //: Managed Object Context var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator //: Child Managed Object Context for Multithreading var childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) childManagedObjectContext.parentContext = managedObjectContext //: Managed Objects func newCountry(name: String) -> NSManagedObject { let country = NSEntityDescription.insertNewObjectForEntityForName(countryEntity.name!, inManagedObjectContext: managedObjectContext) country.setValue(name, forKey: countryNameAttribute.name) return country } func newManufacturer(name: String, country: NSManagedObject) -> NSManagedObject { let manufacturer = NSManagedObject(entity: manufacturerEntity, insertIntoManagedObjectContext: managedObjectContext) manufacturer.setValue(name, forKey: manufacturerNameAttribute.name) manufacturer.setValue(country, forKey: manufacturerRelationshipToCountry.name) return manufacturer } func newCar(name: String, manufacturer: NSManagedObject, price: Float) -> NSManagedObject { let car = NSManagedObject(entity: carEntity, insertIntoManagedObjectContext: managedObjectContext) car.setValue(name, forKey: carNameAttribute.name) car.setValue(price, forKey: carPriceAttribute.name) car.setValue(manufacturer, forKey: carRelationshipToManufacturer.name) return car } let usa = newCountry("United States of America") let germany = newCountry("Germany") let ford = newManufacturer("Ford", country: usa) let volkswagen = newManufacturer("Volkswagen", country: germany) let porsche = newManufacturer("Porsche", country: germany) let fiesta = newCar("Fiesta", manufacturer: ford, price: 15000) let mustang = newCar("Mustang", manufacturer: ford, price: 25000) let golf = newCar("Golf", manufacturer: volkswagen, price: 25000) let touareg = newCar("Touareg", manufacturer: volkswagen, price: 45000) let boxster = newCar("Boxster", manufacturer: porsche, price: 55000) let panamera = newCar("Panamera", manufacturer: porsche, price: 75000) //: Notification When Did Save class NotificationListener: NSObject { func handleDidObjectsDidChangeNotification(notification:NSNotification) { print("objects did change notification received: \(notification)") } func handleWillSaveNotification(notification:NSNotification) { print("will save notification received: \(notification)") } func handleDidSaveNotification(notification:NSNotification) { print("did save notification received: \(notification)") } } let delegate = NotificationListener() NSNotificationCenter.defaultCenter().addObserver(delegate, selector: "handleDidObjectsDidChangeNotification:", name: NSManagedObjectContextObjectsDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(delegate, selector: "handleWillSaveNotification:", name: NSManagedObjectContextWillSaveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(delegate, selector: "handleDidSaveNotification:", name: NSManagedObjectContextDidSaveNotification, object: nil) //: Saving Context do { try managedObjectContext.save() } catch { print("error saving context: \(error)") } //: Fetch Request var fetchRequest = NSFetchRequest(entityName: carEntity.name!) fetchRequest.predicate = NSPredicate(format: "price > %d", 15000) do { let results = try managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject] for result in results { print(result.valueForKey(carNameAttribute.name)) } } catch { print("error executing fetch request: \(error)") } //: Subclassing class Country: NSManagedObject { @NSManaged var name: String? @NSManaged var manufacturers: NSSet? } class Manufacturer: NSManagedObject { @NSManaged var name: String? @NSManaged var cars: NSSet? @NSManaged var country: Country? } class Car: NSManagedObject { @NSManaged var name: String? @NSManaged var price: NSNumber? @NSManaged var manufacturer: Manufacturer? } //: [Next](@next)
mit
ab48816257dd21c0574b302788f9b3b7
37.435897
181
0.792262
4.966865
false
false
false
false
CaueAlvesSilva/FeaturedGames
FeaturedGames/FeaturedGames/Model/FeaturedGame.swift
1
714
// // FeaturedGame.swift // FeaturedGames // // Created by Cauê Silva on 01/08/17. // Copyright © 2017 Caue Alves. All rights reserved. // import Foundation import ObjectMapper struct FeaturedGame: Mappable { var game: Game? var viewers = 0 var channels = 0 init?(map: Map) { mapping(map: map) } init() { } init(name: String, imageURL: String, viewers: Int, channels: Int) { game = Game(name: name, imageURL: imageURL) self.viewers = viewers self.channels = channels } mutating func mapping(map: Map) { game <- map["game"] viewers <- map["viewers"] channels <- map["channels"] } }
mit
7fc428ae8852f9a0d842873540f3795b
18.777778
71
0.571629
3.767196
false
false
false
false
allbto/iOS-DynamicRegistration
Pods/Swiftility/Swiftility/Swiftility/Classes/Extensions/UIKit/UIViewExtensions.swift
1
5810
// // UIViewExtensions.swift // Swiftility // // Created by Allan Barbato on 9/22/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import UIKit // MARK: - Constraints extension UIView { public func addConstraintsWithVisualFormat(format: String, views: [String : UIView] = [:], options: NSLayoutFormatOptions = NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: [String : AnyObject]? = nil) { self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: metrics, views: views)) } } // MARK: - Animations extension UIView { public func addFadeTransition(duration: CFTimeInterval) { let animation:CATransition = CATransition() animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.type = kCATransitionFade animation.duration = duration self.layer.addAnimation(animation, forKey: kCATransitionFade) } } // MARK: - Screenshot extension UIView { public func screenshot() -> UIImage? { let rect = self.bounds UIGraphicsBeginImageContext(rect.size) guard let context = UIGraphicsGetCurrentContext() else { UIGraphicsEndImageContext() return nil } self.layer.renderInContext(context) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } } // MARK: - Frame convinience extension UIView { public func makeFrameIntegral() { self.frame = CGRectIntegral(self.frame) } public var size: CGSize { get { return self.frame.size } set(value) { var newFrame = self.frame; newFrame.size.width = value.width; newFrame.size.height = value.height; self.frame = newFrame } } public var left: CGFloat { get { return self.frame.origin.x } set(value) { var newFrame = self.frame; newFrame.origin.x = value; self.frame = newFrame; } } public var top: CGFloat { get { return self.frame.origin.y } set(value) { var newFrame = self.frame; newFrame.origin.y = value; self.frame = newFrame; } } public var right: CGFloat { get { return self.frame.origin.x + self.frame.size.width } set(value) { var newFrame = self.frame; newFrame.origin.x = value - frame.size.width; self.frame = newFrame; } } public var bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height } set(value) { var newFrame = self.frame; newFrame.origin.y = value - frame.size.height; self.frame = newFrame; } } public var width: CGFloat { get { return self.frame.size.width } set(value) { var newFrame = self.frame; newFrame.size.width = value; self.frame = newFrame; } } public var height: CGFloat { get { return self.frame.size.height } set(value) { var newFrame = self.frame; newFrame.size.height = value; self.frame = newFrame; } } public var centerY: CGFloat { get { return self.center.y } set(value) { self.center = CGPointMake(self.center.x, value) } } public var centerX: CGFloat { get { return self.center.x } set(value) { self.center = CGPointMake(value, self.center.y); } } // MARK: - Margins public var bottomMargin: CGFloat { get { guard let unwrappedSuperview = self.superview else { return 0 } return unwrappedSuperview.height - self.bottom; } set(value) { guard let unwrappedSuperview = self.superview else { return } var frame = self.frame; frame.origin.y = unwrappedSuperview.height - value - self.height; self.frame = frame; } } public var rightMargin: CGFloat { get { guard let unwrappedSuperview = self.superview else { return 0 } return unwrappedSuperview.width - self.right; } set(value) { guard let unwrappedSuperview = self.superview else { return } var frame = self.frame; frame.origin.y = unwrappedSuperview.width - value - self.width; self.frame = frame; } } // MARK: - Center public func centerInSuperview() { if let u = self.superview { self.center = CGPointMake(CGRectGetMidX(u.bounds), CGRectGetMidY(u.bounds)); } } public func centerVertically() { if let unwrappedOptional = self.superview { self.center = CGPointMake(self.center.x, CGRectGetMidY(unwrappedOptional.bounds)); } } public func centerHorizontally() { if let unwrappedOptional = self.superview { self.center = CGPointMake(CGRectGetMidX(unwrappedOptional.bounds), self.center.y); } } // MARK: - Subviews public func removeAllSubviews() { while (self.subviews.count > 0) { if let view = self.subviews.last { view.removeFromSuperview() } } } }
mit
d2f79fb76377315c88d77515663c629f
24.590308
215
0.548976
4.918713
false
false
false
false
seivan/ScalarArithmetic
TestsAndSample/Tests/TestsMathFunctions.swift
1
4355
// // TestsAndSampleTests.swift // TestsAndSampleTests // // Created by Seivan Heidari on 29/06/14. // Copyright (c) 2014 Seivan Heidari. All rights reserved. // import XCTest //extension Double : FloatingPointOperating {} //extension CGFloat : FloatingPointOperating {} class TestsMathFunctionsDouble: XCTestCase { typealias Main = Double; let mainType:Double = 0.5 var expected:Double? let alternativeType:CGFloat = 7.7 func testAcos() { self.expected = acos(self.mainType) XCTAssertEqual(self.expected!, self.mainType.acos) } func testAsin() { self.expected = asin(self.mainType) XCTAssertEqual(self.expected!, self.mainType.asin) } func testAtan() { self.expected = atan(self.mainType) XCTAssertEqual(self.expected!, self.mainType.atan) } func testAtan2() { self.expected = atan2(self.mainType, Main(self.alternativeType)) XCTAssertEqual(self.expected!, self.mainType.atan2(self.alternativeType)) } func testCos() { self.expected = cos(self.mainType) XCTAssertEqual(self.expected!, self.mainType.cos) } func testSin() { self.expected = sin(self.mainType) XCTAssertEqual(self.expected!, self.mainType.sin) } func testTan() { self.expected = tan(self.mainType) XCTAssertEqual(self.expected!, self.mainType.tan) } func testExp() { self.expected = exp(self.mainType) XCTAssertEqual(self.expected!, self.mainType.exp) } func testExp2() { self.expected = exp2(self.mainType) XCTAssertEqual(self.expected!, self.mainType.exp2) } func testLog() { self.expected = log(self.mainType) XCTAssertEqual(self.expected!, self.mainType.log) } func testLog10() { self.expected = log10(self.mainType) XCTAssertEqual(self.expected!, self.mainType.log10) } func testLog2() { self.expected = log2(self.mainType) XCTAssertEqual(self.expected!, self.mainType.log2) } func testPow() { self.expected = pow(self.mainType, Double(self.alternativeType)) XCTAssertEqual(self.expected!, self.mainType.pow(self.alternativeType)) } func testSqrt() { self.expected = sqrt(self.mainType) XCTAssertEqual(self.expected!, self.mainType.sqrt) } } // // TestsCGFloat.swift // TestsAndSample // // Created by Seivan Heidari on 29/06/14. // Copyright (c) 2014 Seivan Heidari. All rights reserved. // import XCTest import CoreGraphics class TestsMathFunctionsCGFloat: XCTestCase { typealias Main = CGFloat let mainType:CGFloat = 0.4 var expected:CGFloat? let alternativeType:Double = 7.7 func testAcos() { self.expected = acos(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.acos)) } func testAsin() { self.expected = asin(self.mainType) XCTAssertEqual(self.expected!, self.mainType.asin) } func testAtan() { self.expected = atan(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.atan)) } func testAtan2() { self.expected = atan2(self.mainType, CGFloat(self.alternativeType)) XCTAssertEqual(self.expected!, (self.mainType.atan2(self.alternativeType))) } func testCos() { self.expected = cos(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.cos)) } func testSin() { self.expected = sin(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.sin)) } func testTan() { self.expected = tan(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.tan)) } func testExp() { self.expected = exp(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.exp)) } func testExp2() { self.expected = exp2(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.exp2)) } func testLog() { self.expected = log(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.log)) } func testLog10() { self.expected = log10(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.log10)) } func testLog2() { self.expected = log2(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.log2)) } func testPow() { self.expected = pow(self.mainType, Main(self.alternativeType)) XCTAssertEqual(self.expected!, self.mainType.pow(self.alternativeType)) } func testSqrt() { self.expected = sqrt(self.mainType) XCTAssertEqual(self.expected!, (self.mainType.sqrt)) } }
mit
3a113e465cd3a9328335ea03d9eddfa0
26.563291
79
0.695522
3.459095
false
true
false
false
MaddTheSane/iNetHack
Classes/TouchInfo.swift
1
1118
// // TouchInfo.swift // iNetHack // // Created by C.W. Betts on 10/3/15. // Copyright 2015 Dirk Zimmermann. All rights reserved. // // This file is part of iNetHack. // // iNetHack is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 2 of the License only. // // iNetHack is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with iNetHack. If not, see <http://www.gnu.org/licenses/>. import UIKit class TouchInfo : NSObject { var pinched = false var moved = false var doubleTap = false var initialLocation: CGPoint /// only updated on -init, for your own use var currentLocation: CGPoint init(touch t: UITouch) { initialLocation = t.location(in: t.view) currentLocation = initialLocation super.init() } }
gpl-2.0
aed8ea23f51b0a695a27d54c555f46d5
26.95
72
0.719141
3.583333
false
false
false
false
apple/swift-docc-symbolkit
Sources/SymbolKit/SymbolGraph/Symbol/FunctionSignature/FunctionParameter.swift
1
1900
/* This source file is part of the Swift.org open source project Copyright (c) 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information See https://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation extension SymbolGraph.Symbol.FunctionSignature { /// An argument of a callable symbol. public struct FunctionParameter: Codable { enum CodingKeys: String, CodingKey { case name case declarationFragments case children } /// The name of the symbol, as referred to in user code (must match the name used in the documentation comment). public var name: String // should we differentiate between internal and external names? /// The syntax used to create the parameter. public var declarationFragments: [SymbolGraph.Symbol.DeclarationFragments.Fragment] /// Sub-parameters of the parameter. public var children: [FunctionParameter] public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) declarationFragments = try container.decodeIfPresent([SymbolGraph.Symbol.DeclarationFragments.Fragment].self, forKey: .declarationFragments) ?? [] children = try container.decodeIfPresent([FunctionParameter].self, forKey: .children) ?? [] } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(declarationFragments, forKey: .declarationFragments) try container.encode(children, forKey: .children) } } }
apache-2.0
3249e560dc8cfec3ad43d74b70cf832c
43.186047
158
0.692105
5.093834
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/KnowledgeGroup.swift
1
3012
import CoreData import EurofurenceWebAPI @objc(KnowledgeGroup) public class KnowledgeGroup: Entity { @nonobjc class func fetchRequest() -> NSFetchRequest<KnowledgeGroup> { return NSFetchRequest<KnowledgeGroup>(entityName: "KnowledgeGroup") } @NSManaged public var fontAwesomeUnicodeCharacterAddress: String @NSManaged public var knowledgeGroupDescription: String @NSManaged public var name: String @NSManaged var order: Int16 @NSManaged var entries: NSOrderedSet public var orderedKnowledgeEntries: [KnowledgeEntry] { entries.array(of: KnowledgeEntry.self) } override public func willSave() { super.willSave() orderKnowledgeEntries() } private func orderKnowledgeEntries() { let orderedEntries = entries.array(of: KnowledgeEntry.self).sorted() // Avoid mutations to the object graph if the set is already sorted. This can cause the managed object context // to remain stuck in a dirty state forever, otherwise. if orderedEntries == self.orderedKnowledgeEntries { return } for entry in orderedEntries { removeFromEntries(entry) } for entry in orderedEntries { addToEntries(entry) } } } // MARK: - Fetching extension KnowledgeGroup { /// Produces an `NSFetchRequest` for fetching all `KnowledgeGroup`s, ordered by the characteristics of the model. /// - Returns: An `NSFetchRequest` for fetching all `KnowledgeGroup`s in their designated order. public static func orderedGroupsFetchRequest() -> NSFetchRequest<KnowledgeGroup> { let fetchRequest: NSFetchRequest<KnowledgeGroup> = KnowledgeGroup.fetchRequest() fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \KnowledgeGroup.order, ascending: true)] return fetchRequest } } // MARK: - KnowledgeGroup + ConsumesRemoteResponse extension KnowledgeGroup: ConsumesRemoteResponse { typealias RemoteObject = EurofurenceWebAPI.KnowledgeGroup func update(context: RemoteResponseConsumingContext<RemoteObject>) throws { identifier = context.remoteObject.id lastEdited = context.remoteObject.lastChangeDateTimeUtc name = context.remoteObject.name knowledgeGroupDescription = context.remoteObject.description order = Int16(context.remoteObject.order) fontAwesomeUnicodeCharacterAddress = context.remoteObject.fontAwesomeIconCharacterUnicodeAddress } } // MARK: Generated accessors for entries extension KnowledgeGroup { @objc(addEntriesObject:) @NSManaged func addToEntries(_ value: KnowledgeEntry) @objc(removeEntriesObject:) @NSManaged func removeFromEntries(_ value: KnowledgeEntry) @objc(addEntries:) @NSManaged func addToEntries(_ values: Set<KnowledgeEntry>) @objc(removeEntries:) @NSManaged func removeFromEntries(_ values: Set<KnowledgeEntry>) }
mit
4d8fff3720a3f031613820eb1c222848
31.387097
118
0.706839
5.284211
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/OpenTelemetryApi/Metrics/LabelSet.swift
1
663
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation /// Normalized name value pairs of metric labels. open class LabelSet: Hashable { public private(set) var labels: [String: String] /// Empty LabelSet. public static var empty = LabelSet() private init() { labels = [String: String]() } public required init(labels: [String: String]) { self.labels = labels } public static func == (lhs: LabelSet, rhs: LabelSet) -> Bool { return lhs.labels == rhs.labels } public func hash(into hasher: inout Hasher) { hasher.combine(labels) } }
apache-2.0
78d72a96faa3be9e100513c2faf927af
21.1
66
0.631976
4.042683
false
false
false
false
santosli/100-Days-of-Swift-3
Project 19/Project 19/ViewController.swift
1
2039
// // ViewController.swift // Project 19 // // Created by Santos on 23/11/2016. // Copyright © 2016 santos. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var demoTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //add left and right navigation button self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) //init color self.navigationItem.title = "New Entry" self.navigationController?.navigationBar.barTintColor = UIColor(red:0.93, green:0.98, blue:0.96, alpha:1.00) self.navigationController?.navigationBar.tintColor = UIColor(red:0.00, green:0.73, blue:0.58, alpha:1.00) //add toolbar above keyboard let keyboardToolbar = UIToolbar() keyboardToolbar.sizeToFit() keyboardToolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) keyboardToolbar.setShadowImage(UIImage(), forToolbarPosition: .any) let cameraButton = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: nil) cameraButton.tintColor = UIColor(red:0.46, green:0.84, blue:0.74, alpha:1.00) let locationButton = UIBarButtonItem.init(image: #imageLiteral(resourceName: "location"), style: .plain, target: nil, action: nil) locationButton.tintColor = UIColor(red:0.46, green:0.84, blue:0.74, alpha:1.00) keyboardToolbar.items = [cameraButton, locationButton] demoTextView.inputAccessoryView = keyboardToolbar } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
d34ea9eadd8508db7459d27486ed842d
37.45283
138
0.678606
4.642369
false
false
false
false
MattYY/PersistentLog
SampleApp/Source/Log/Views/FilterView.swift
1
2917
// // FilterView.swift // SampleApp // // Created by Matthew Yannascoli on 5/17/16. // import UIKit import PersistentLog protocol FilterViewDelegate: class { func filterViewDidUpdateLevel(level: LogLevel) func filterViewDidUpdateFilter(filter: String?) } class FilterView: UIView { private let picker: UIPickerView = { let picker = UIPickerView() picker.translatesAutoresizingMaskIntoConstraints = false picker.backgroundColor = .whiteColor() return picker }() private let filters: [String] private struct Level { let title:String let value: LogLevel? } private let levels: [Level] = [ Level(title: "All", value: nil), Level(title: "Debug", value: .Debug), Level(title: "Info", value: .Info), Level(title: "Warn", value: .Warn), Level(title: "Error", value: .Error) ] weak var delegate: FilterViewDelegate? = nil init(filters: [String]) { self.filters = filters super.init(frame: CGRect.zero) layout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension FilterView: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { if self.filters.count > 0 { return 2 } return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 1 { return filters.count + 1 } return levels.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 1 { if row == 0 { return "All" } else { return filters[row - 1] } } return levels[row].title } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 1 { var filter: String? = nil if row > 0 { filter = filters[row - 1] } delegate?.filterViewDidUpdateFilter(filter) } else { if let level = levels[row].value { delegate?.filterViewDidUpdateLevel(level) } } } } extension FilterView { private func layout() { picker.delegate = self picker.dataSource = self addSubview(picker) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "H:|[picker]|", options: [], metrics: nil, views: ["picker": picker])) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "V:|[picker]|", options: [], metrics: nil, views: ["picker": picker])) } }
mit
cd8b0c7ce70902bccf95144be35ec567
26.271028
109
0.581762
4.837479
false
false
false
false
ChristianKienle/highway
Sources/Task/Model/Task.swift
1
3194
import Foundation import ZFile import Arguments import SourceryAutoProtocols public protocol TaskProtocol: AutoMockable { /// sourcery:inline:Task.AutoGenerateProtocol var name: String { get } var executable: FileProtocol { get set } var arguments: Arguments { get set } var environment: [String : String] { get set } var currentDirectoryUrl: FolderProtocol? { get set } var input: Channel { get set } var output: Channel { get set } var state: State { get set } var capturedOutputData: Data? { get } var readOutputString: String? { get } var trimmedOutput: String? { get } var capturedOutputString: String? { get } var successfullyFinished: Bool { get } var description: String { get } func enableReadableOutputDataCapturing() func throwIfNotSuccess(_ error: Swift.Error) throws /// sourcery:end } public class Task: TaskProtocol, AutoGenerateProtocol { // MARK: - Init public convenience init(commandName: String, arguments: Arguments = .empty, currentDirectoryUrl: FolderProtocol? = nil, provider: ExecutableProviderProtocol) throws { self.init(executable: try provider.executable(with: commandName), arguments: arguments, currentDirectoryUrl: currentDirectoryUrl ) } public init(executable: FileProtocol, arguments: Arguments = .empty, currentDirectoryUrl: FolderProtocol? = nil) { self.executable = executable self.state = .waiting self.arguments = arguments self.currentDirectoryUrl = currentDirectoryUrl } // MARK: - Properties public var name: String { return executable.name } public var executable: FileProtocol public var arguments = Arguments.empty public var environment = [String : String]() public var currentDirectoryUrl: FolderProtocol? public var input: Channel { get { return io.input } set { io.input = newValue } } public var output: Channel { get { return io.output } set { io.output = newValue } } public var state: State public func enableReadableOutputDataCapturing() { io.enableReadableOutputDataCapturing() } public var capturedOutputData: Data? { return io.readOutputData } public var readOutputString: String? { return capturedOutputString } public var trimmedOutput: String? { return capturedOutputString?.trimmingCharacters(in: .whitespacesAndNewlines) } public var capturedOutputString: String? { guard let data = capturedOutputData else { return nil } return String(data: data, encoding: .utf8) } public var successfullyFinished: Bool { return state.successfullyFinished } public func throwIfNotSuccess(_ error: Swift.Error) throws { guard successfullyFinished else { throw "🛣 🔥 \(name) with customError: \n \(error).\n" } } // MARK: - Private private var io = IO() } extension Task: CustomStringConvertible { public var description: String { return "\(name) \(arguments)" } }
mit
5199d03368488aeab0d940f8f65b89ba
29.951456
170
0.659348
4.801205
false
false
false
false
steveholt55/Football-College-Trivia-iOS
FootballCollegeTrivia/Game/GamePresenter.swift
1
5486
// // Copyright © 2016 Brandon Jenniges. All rights reserved. // import UIKit class GamePresenter: NSObject, GameTimerProtocol { unowned let view: GameView let difficulty: Difficulty let gameType: GameType var gameButtons:[UIButton] = [] var canGuess:Bool = true var players:[Player] = [] var player: Player! let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var score:Int = 0 var strikes:Int = 0 required init(view: GameView, difficulty: Difficulty, gameType: GameType) { self.view = view self.difficulty = difficulty self.gameType = gameType super.init() GameTimer.presenter = self } // MARK: - Setup func setup(gameButtons:[UIButton]) { self.gameButtons = gameButtons setupQuestions() setupGamePlaySettings() setupGameModeSpecificSettings() finishGamePreperation() generateQuestion() } func setupQuestions() { self.players = Player.getCurrentArray(self.difficulty) self.players.shuffle() } func setupGamePlaySettings() { canGuess = true score = 0 strikes = 0 } func setupGameModeSpecificSettings() { switch gameType { case .Standard: self.view.applyModeDisplay("2:00", color: .darkGrayColor()) startTimer() case .Survival: self.view.applyModeDisplay(" ", color: .redColor()) case .Practice: self.view.applyModeDisplay("Practice", color: .lightGrayColor()) } } func finishGamePreperation() { self.view.showBestScore(getBestScoreForDifficulty(difficulty, gametype: gameType)) self.view.displayStartText() } // MARK: - Questions func generateQuestion() { canGuess = true if self.players.count == 0 { setupQuestions() // Questions are empty.. reset them generateQuestion() } else { player = players[0] self.players.removeAtIndex(0) self.view.displayPlayer(player) generateAnswers() } } // MARK: - Answers func generateAnswers() { var choices = [String]() choices.append(player.college) var colleges = College.getCurrentArray(player.tier) repeat { let index = Int(arc4random_uniform((UInt32(colleges.count)))) let c = colleges[index] if choices.filter({ el in el == c.name }).count == 0 { choices.append(c.name) } }while( choices.count < 4 ); sortChoices(choices) } func sortChoices(choices: [String]) { let sortedChoices = choices.sort() displayChoices(sortedChoices) } func displayChoices(choices: [String]) { var index = 0 for college in choices { let button = gameButtons[index] button.setTitle(college, forState: .Normal) if appDelegate.testMode { if college == player.college { button.accessibilityIdentifier = "answer" } else { button.accessibilityIdentifier = "" } } index += 1 } } // MARK: - Guesses func checkGuess(button: UIButton) { if !canGuess { return } canGuess = false if button.titleForState(.Normal) == player.college { guessWasCorrect(button) } else { guessWasIncorrect(button) } } func guessWasCorrect(sender: UIButton) { self.view.displayCorrectGuessText() self.correctGuess() sender.correct { () -> Void in self.generateQuestion() } } func guessWasIncorrect(sender: UIButton) { // Display what was correct answer for button in gameButtons { if button.titleForState(.Normal) == player.college { button.correct() self.view.displayWrongGuessText(player.college) } } self.wrongGuess() sender.incorrect { () -> Void in self.generateQuestion() } } func correctGuess() { score += 1 self.view.updateScore(score) } func wrongGuess() { if gameType == .Survival { strikes += 1 self.view.updateStrikes(stringForSurvivalMode(strikes)) if strikes >= 3 { self.view.finishGame() } } else if gameType == .Standard { score -= 1 self.view.updateScore(score) } } func saveHighScore() { if score > getBestScoreForDifficulty(difficulty, gametype: gameType) { saveBestScoreForDifficulty(difficulty, gametype: gameType, score: score) } } // MARK: - Timer func startTimer() { GameTimer.start() } func stopTimer() { GameTimer.stop() } // MARK: - GameTimerProtocol func timeFinished() { self.view.finishGame() } func timeTicked(displayText: String, color: UIColor) { self.view.applyModeDisplay(displayText, color: color) } }
mit
56e40ab66cf19f8e079963d2735e8350
25.497585
90
0.542935
4.716251
false
false
false
false