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
codestergit/swift
test/Constraints/closures.swift
4
18206
// RUN: %target-typecheck-verify-swift func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {} var intArray : [Int] _ = myMap(intArray, { String($0) }) _ = myMap(intArray, { x -> String in String(x) } ) // Closures with too few parameters. func foo(_ x: (Int, Int) -> Int) {} foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} struct X {} func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {} func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {} var strings : [String] _ = mySort(strings, { x, y in x < y }) // Closures with inout arguments. func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U { var t2 = t return f(&t2) } struct X2 { func g() -> Float { return 0 } } _ = f0(X2(), {$0.g()}) // Autoclosure func f1(f: @autoclosure () -> Int) { } func f2() -> Int { } f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}} f1(f: 5) // Ternary in closure var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"} // <rdar://problem/15367882> func foo() { not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}} } // <rdar://problem/15536725> struct X3<T> { init(_: (T) -> ()) {} } func testX3(_ x: Int) { var x = x _ = X3({ x = $0 }) _ = x } // <rdar://problem/13811882> func test13811882() { var _ : (Int) -> (Int, Int) = {($0, $0)} var x = 1 var _ : (Int) -> (Int, Int) = {($0, x)} x = 2 } // <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement // <https://bugs.swift.org/browse/SR-3671> func r21544303() { var inSubcall = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false // This is a problem, but isn't clear what was intended. var somethingElse = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false var v2 : Bool = false v2 = inSubcall { // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } } // <https://bugs.swift.org/browse/SR-3671> func SR3671() { let n = 42 func consume(_ x: Int) {} { consume($0) }(42) ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; // This is technically a valid call, so nothing goes wrong until (42) { $0(3) } { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; { $0(3) } { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; // Equivalent but more obviously unintended. { $0(3) } // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ({ $0(3) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ; // Also a valid call (!!) { $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}} consume(111) } // <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure func r22162441(_ lines: [String]) { _ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} _ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} } func testMap() { let a = 42 [1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier [].reduce { $0 + $1 } // expected-error {{missing argument for parameter #1 in call}} // <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments var _: () -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }} var _: (Int) -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}} var _: (Int) -> Int = { 0 } // expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }} var _: (Int, Int) -> Int = {0} // expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {$0+$1} var _: () -> Int = {a in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}} var _: (Int) -> Int = {a,b in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}} var _: (Int) -> Int = {a,b,c in 0} var _: (Int, Int) -> Int = {a in 0} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {a, b in a+b} // <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument func r15998821() { func take_closure(_ x : (inout Int) -> ()) { } func test1() { take_closure { (a : inout Int) in a = 42 } } func test2() { take_closure { a in a = 42 } } func withPtr(_ body: (inout Int) -> Int) {} func f() { withPtr { p in return p } } let g = { x in x = 3 } take_closure(g) } // <rdar://problem/22602657> better diagnostics for closures w/o "in" clause var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} // Crash when re-typechecking bodies of non-single expression closures struct CC {} func callCC<U>(_ f: (CC) -> U) -> () {} func typeCheckMultiStmtClosureCrash() { callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }} _ = $0 return 1 } } // SR-832 - both these should be ok func someFunc(_ foo: ((String) -> String)?, bar: @escaping (String) -> String) { let _: (String) -> String = foo != nil ? foo! : bar let _: (String) -> String = foo ?? bar } // SR-1069 - Error diagnostic refers to wrong argument class SR1069_W<T> { func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {} } class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() } struct S<T> { let cs: [SR1069_C<T>] = [] func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable { let wrappedMethod = { (object: AnyObject, value: T) in } // expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}} cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) } } } // Make sure we cannot infer an () argument from an empty parameter list. func acceptNothingToInt (_: () -> Int) {} func testAcceptNothingToInt(ac1: @autoclosure () -> Int) { acceptNothingToInt({ac1($0)}) // expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} } // <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference) struct Thing { init?() {} } // This throws a compiler error let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }} // Commenting out this makes it compile _ = thing return thing } // <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches func r21675896(file : String) { let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }} if true { return "foo" } else { return file } }().pathExtension } // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(_ t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? func uintFunc() -> UInt {} func takeVoidVoidFn(_ a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(_ x: String) {} func f19997471(_ x: Int) {} func someGeneric19997471<T>(_ x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}} // expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}} } } // <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information func f20371273() { let x: [Int] = [1, 2, 3, 4] let y: UInt = 4 x.filter { $0 == y } // expected-error {{binary operator '==' cannot be applied to operands of type 'Int' and 'UInt'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: (UInt, UInt), (Int, Int)}} } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } [0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }} _ in let r = (1,2).0 return r } // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(_ callback: ([String]) -> ()) { } func rdar20868864(_ s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} } } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(_ value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }} print("a") return "hi" } } // Make sure that behavior related to allowing trailing closures to match functions // with Any as a final parameter is the same after the changes made by SR-2505, namely: // that we continue to select function that does _not_ have Any as a final parameter in // presence of other possibilities. protocol SR_2505_Initable { init() } struct SR_2505_II : SR_2505_Initable {} protocol P_SR_2505 { associatedtype T: SR_2505_Initable } extension P_SR_2505 { func test(it o: (T) -> Bool) -> Bool { return o(T.self()) } } class C_SR_2505 : P_SR_2505 { typealias T = SR_2505_II func test(_ o: Any) -> Bool { return false } func call(_ c: C_SR_2505) -> Bool { // Note: no diagnostic about capturing 'self', because this is a // non-escaping closure -- that's how we know we have selected // test(it:) and not test(_) return c.test { o in test(o) } } } let _ = C_SR_2505().call(C_SR_2505()) // <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic extension Collection { func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index { return startIndex } } func fn_r28909024(n: Int) { return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}} _ in true } } // SR-2994: Unexpected ambiguous expression in closure with generics struct S_2994 { var dataOffset: Int } class C_2994<R> { init(arg: (R) -> Void) {} } func f_2994(arg: String) {} func g_2994(arg: Int) -> Double { return 2 } C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}} let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}} let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}} let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}} // https://bugs.swift.org/browse/SR-403 // The () -> T => () -> () implicit conversion was kicking in anywhere // inside a closure result, not just at the top-level. let mismatchInClosureResultType : (String) -> ((Int) -> Void) = { (String) -> ((Int) -> Void) in return { } // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} } // SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS func sr3520_1<T>(_ g: (inout T) -> Int) {} sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) { var x = item update(&x) } var sr3250_arg = 42 sr3520_2(sr3250_arg) { $0 += 3 } // ok // This test makes sure that having closure with inout argument doesn't crash with member lookup struct S_3520 { var number1: Int } func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}} // SR-1976/SR-3073: Inference of inout func sr1976<T>(_ closure: (inout T) -> Void) {} sr1976({ $0 += 2 }) // ok // SR-3073: UnresolvedDotExpr in single expression closure struct SR3073Lense<Whole, Part> { let set: (inout Whole, Part) -> () } struct SR3073 { var number1: Int func lenses() { let _: SR3073Lense<SR3073, Int> = SR3073Lense( set: { $0.number1 = $1 } // ok ) } } // SR-3479: Segmentation fault and other error for closure with inout parameter func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {} func sr3497() { let _ = sr3497_unfold((0, 0)) { s in 0 } // ok } // SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs let _: ((Any?) -> Void) = { (arg: Any!) in } // This example was rejected in 3.0 as well, but accepting it is correct. let _: ((Int?) -> Void) = { (arg: Int!) in } // rdar://30429709 - We should not attempt an implicit conversion from // () -> T to () -> Optional<()>. func returnsArray() -> [Int] { return [] } returnsArray().flatMap { $0 }.flatMap { } // expected-warning@-1 {{expression of type 'Int' is unused}} // expected-warning@-2 {{Please use map instead.}} // expected-warning@-3 {{result of call to 'flatMap' is unused}} // rdar://problem/30271695 _ = ["hi"].flatMap { $0.isEmpty ? nil : $0 }
apache-2.0
e1960a994e7607b3676ee3400f1519f9
34.011538
254
0.638526
3.373356
false
false
false
false
lorentey/swift
test/SourceKit/CursorInfo/use-swift-source-info.swift
3
1524
import Foo func bar() { foo() } // RUN: %empty-directory(%t) // RUN: echo "/// Some doc" >> %t/Foo.swift // RUN: echo "public func foo() { }" >> %t/Foo.swift // RUN: %target-swift-frontend -enable-batch-mode -emit-module -emit-module-doc -emit-module-path %t/Foo.swiftmodule %t/Foo.swift -module-name Foo -emit-module-source-info-path %t/Foo.swiftsourceinfo -emit-module-doc-path %t/Foo.swiftdoc // // Test setting optimize for ide to false // RUN: %sourcekitd-test -req=global-config -for-ide=0 == -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITH %s // // Test setting optimize for ide to true // RUN: %sourcekitd-test -req=global-config -for-ide=1 == -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITHOUT %s // // Test sourcekitd-test's default global configuration request (optimize for ide is true) // RUN: %sourcekitd-test -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITHOUT %s // // Test without sending any global configuration request to check the sevice's default settings (optimize for ide is false) // RUN: %sourcekitd-test -suppress-config-request -req=cursor -pos=3:3 %s -- -I %t -target %target-triple %s | %FileCheck --check-prefixes=BOTH,WITH %s // WITH: source.lang.swift.ref.function.free ({{.*}}/Foo.swift:2:13-2:16) // WITHOUT: source.lang.swift.ref.function.free () // BOTH: foo() // BOTH: s:3Foo3fooyyF // BOTH: () -> () // BOTH: $syycD // BOTH: Foo
apache-2.0
14d35a5106deac98ae7eba5b72f53d24
51.551724
237
0.683727
3.017822
false
true
false
false
aleph7/BrainCore
Source/Snapshot.swift
1
5228
// Copyright © 2016 Venture Media Labs. All rights reserved. // // This file is part of BrainCore. The full BrainCore copyright notice, // including terms governing use, modification, and redistribution, is // contained in the file LICENSE at the root of the source code distribution // tree. import Foundation import Metal /// A data snapshot of a forward-backward pass. open class Snapshot { /// The network definition. open let net: Net var forwardBuffers: [UUID: MTLBuffer] var backwardBuffers: [UUID: MTLBuffer] init(net: Net, forwardBuffers: [UUID: MTLBuffer], backwardBuffers: [UUID: MTLBuffer] = [UUID: MTLBuffer]()) { self.net = net self.forwardBuffers = forwardBuffers self.backwardBuffers = backwardBuffers } func contentsOfForwardBuffer(_ buffer: NetBuffer) -> UnsafeMutableBufferPointer<Float>? { guard let mtlBuffer = forwardBuffers[buffer.id as UUID] else { return nil } return unsafeBufferPointerFromBuffer(mtlBuffer) } func contentsOfBackwardBuffer(_ buffer: NetBuffer) -> UnsafeMutableBufferPointer<Float>? { guard let mtlBuffer = backwardBuffers[buffer.id as UUID] else { return nil } return unsafeBufferPointerFromBuffer(mtlBuffer) } /// Returns a pointer to the forward-pass contents of a network buffer. /// /// - Note: The pointer is short-lived, you should copy any contents that you want preserve. open func contentsOfForwardBuffer(_ ref: Net.BufferID) -> UnsafeMutableBufferPointer<Float>? { guard let buffer = net.buffers[ref] else { return nil } return contentsOfForwardBuffer(buffer) } /// Returns a pointer to the backward-pass contents of a network buffer. /// /// - Note: The pointer is short-lived, you should copy any contents that you want preserve. open func contentsOfBackwardBuffer(_ ref: Net.BufferID) -> UnsafeMutableBufferPointer<Float>? { guard let buffer = net.buffers[ref] else { return nil } return contentsOfBackwardBuffer(buffer) } /// Returns a pointer to the forward-pass output of a layer. /// /// - Note: The pointer is short-lived, you should copy any contents that you want preserve. open func outputOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? { guard let node = net.nodeForLayer(layer), let bufferId = node.outputBuffer?.id, let buffer = forwardBuffers[bufferId] else { return nil } let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size) let count = buffer.length / MemoryLayout<Float>.size - node.outputRange.lowerBound return UnsafeMutableBufferPointer(start: pointer + node.outputRange.lowerBound, count: count) } /// Returns a pointer to the forward-pass input of a layer. /// /// - Note: The pointer is short-lived, you should copy any contents that you want preserve. open func inputOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? { guard let node = net.nodeForLayer(layer), let bufferId = node.inputBuffer?.id, let buffer = forwardBuffers[bufferId] else { return nil } let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size) let count = buffer.length / MemoryLayout<Float>.size - node.inputRange.lowerBound return UnsafeMutableBufferPointer(start: pointer + node.inputRange.lowerBound, count: count) } /// Returns a pointer to the backward-pass input deltas of a layer. /// /// - Note: The pointer is short-lived, you should copy any contents that you want preserve. open func inputDeltasOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? { guard let node = net.nodeForLayer(layer), let bufferId = node.inputBuffer?.id, let buffer = backwardBuffers[bufferId] else { return nil } let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size) let count = buffer.length / MemoryLayout<Float>.size - node.inputRange.lowerBound return UnsafeMutableBufferPointer(start: pointer + node.inputRange.lowerBound, count: count) } /// Returns a pointer to the backward-pass output deltas of a layer. /// /// - Note: The pointer is short-lived, you should copy any contents that you want preserve. open func outputDeltasOfLayer(_ layer: Layer) -> UnsafeMutableBufferPointer<Float>? { guard let node = net.nodeForLayer(layer), let bufferId = node.outputBuffer?.id, let buffer = backwardBuffers[bufferId] else { return nil } let pointer = buffer.contents().bindMemory(to: Float.self, capacity: buffer.length / MemoryLayout<Float>.size) let count = buffer.length / MemoryLayout<Float>.size - node.outputRange.lowerBound return UnsafeMutableBufferPointer(start: pointer + node.outputRange.lowerBound, count: count) } }
mit
d96550d30f62891480684ccc3e60d01f
44.060345
118
0.673809
4.679499
false
false
false
false
aerogear/aerogear-ios-http
AeroGearHttp/Utils.swift
2
1247
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /** Handy extensions and utilities. */ extension String { public func urlEncode() -> String { let str = self return str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! } } public func merge(_ one: [String: String]?, _ two: [String:String]?) -> [String: String]? { var dict: [String: String]? if let one = one { dict = one if let two = two { for (key, value) in two { dict![key] = value } } } else { dict = two } return dict }
apache-2.0
1254d8f746b2b3100e0ccebd41f8581a
26.711111
94
0.655172
4.212838
false
false
false
false
ztolley/VideoStationViewer
VideoStationViewer/CoreDataHelper.swift
1
3513
// // CoreDataHelper.swift // Frazzle // // Created by Zac Tolley on 23/09/2014. // Copyright (c) 2014 Zac Tolley. All rights reserved. // import Foundation import CoreData class CoreDataHelper { static let sharedInstance = CoreDataHelper() let modelName = "Model" let sqlLiteFileName = "VideoStationViewer.sqlite" lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. // This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil); } catch var error as NSError { coordinator = nil NSLog("Unresolved error \(error), \(error)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data stack lazy var applicationCachesDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.scropt.dhfghg" in the application's caches Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() func saveContext () { if let moc = managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } func resetContext() { self.managedObjectContext?.reset() } }
gpl-3.0
2a032854ec06667ea95b5b7695ede804
37.615385
265
0.751494
4.646825
false
false
false
false
mitolog/JINSMEMESampler
JINSMEMESampler/EyeBlink.swift
1
6593
// // EyeBlink.swift // JINSMEMESampler // // Created by Yuhei Miyazato on 12/3/15. // Copyright © 2015 mitolab. All rights reserved. // import Foundation import UIKit class EyeBlinkViewController: UIViewController { var rtmData :MEMERealTimeData? var eyeLid: CAShapeLayer? var lowerEyeLid: CAShapeLayer? var centerEye: CAShapeLayer? var centerEyeInside: CAShapeLayer? var isBlinking: Bool = false var blinkSpeed: CGFloat = 0 var isMovingLeft :Bool = false var isMovingRight :Bool = false override func viewDidLoad() { super.viewDidLoad() let titleViewRect = CGRectMake(0, 0, self.view.frame.width*0.5, 64) let titleLabel = UILabel(frame: titleViewRect) titleLabel.text = "Eye Blink" titleLabel.font = UIFont(name: "NotoSansCJKjp-Bold", size: 14) titleLabel.textAlignment = .Center titleLabel.backgroundColor = UIColor.clearColor() titleLabel.textColor = UIColor.blackColor() self.navigationItem.titleView = titleLabel MEMELibAccess.sharedInstance.changeDataMode(MEME_COM_REALTIME) // debug //NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "timerFired", userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Remove Observer MEMELibAccess.sharedInstance.removeObserver(self, forKeyPath: AppConsts.MEMELibAccess.realtimeDataKey) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Add Observer MEMELibAccess.sharedInstance.addObserver(self, forKeyPath: AppConsts.MEMELibAccess.realtimeDataKey, options: .New, context: nil) } // MARK: - KVO override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { switch keyPath! { case AppConsts.MEMELibAccess.realtimeDataKey: self.rtmData = (object as! MEMELibAccess).realtimeData if (self.rtmData != nil) { blinkSpeed = CGFloat(self.rtmData!.blinkSpeed) self.isBlinking = (blinkSpeed > 0) ? true : false // Comment out if eye moving left/right needed // self.isMovingLeft = (self.rtmData!.eyeMoveLeft > 0) ? true : false // self.isMovingRight = (self.rtmData!.eyeMoveRight > 0) ? true : false if self.isBlinking == true // self.isMovingLeft || self.isMovingRight { self.view.setNeedsLayout() } } default: break } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() //print("blinkSpeed \(self.rtmData?.blinkSpeed)") let origEyeLidSize = CGSizeMake(80, 36) let eyeLidWidth = self.view.frame.width - 20*2 let eyeLidSize = CGSizeMake( eyeLidWidth, (eyeLidWidth * origEyeLidSize.height) / origEyeLidSize.width ) let eyeLidRect = CGRectMake( 20, (CGRectGetHeight(self.view.frame) - eyeLidSize.height)*0.5, eyeLidSize.width, eyeLidSize.height) // まばたき if self.isBlinking { AudioPlayer.sharedInstance.play("click") if self.eyeLid != nil { self.eyeLid?.removeFromSuperlayer() } self.eyeLid = CAShapeLayer.eyeBlinkWithFrame(eyeLidRect, blinkSpeed: (blinkSpeed/1000) * AppConsts.EyeBlink.blinkSpeedMulti) self.view.layer.addSublayer(self.eyeLid!) } // 下まぶた(常時表示) if self.lowerEyeLid == nil { self.lowerEyeLid = CAShapeLayer.lowerEyeWithFrame(eyeLidRect) self.view.layer.addSublayer(self.lowerEyeLid!) } // めんたま (デフォは中心にくるように) if self.centerEye != nil { self.centerEye?.removeFromSuperlayer() self.centerEyeInside?.removeFromSuperlayer() } // // Comment out if needed eye move left/right // if self.isMovingLeft { // self.centerEye = CAShapeLayer.moveTo("left", withFrame: eyeLidRect, speed: 0.7, outside: true) // self.centerEyeInside = CAShapeLayer.moveTo("left", withFrame: eyeLidRect, speed: 0.7, outside: false) // // } else if self.isMovingRight { // self.centerEye = CAShapeLayer.moveTo("right", withFrame: eyeLidRect, speed: 0.7, outside: true) // self.centerEyeInside = CAShapeLayer.moveTo("right", withFrame: eyeLidRect, speed: 0.7, outside: false) // // } else { self.centerEye = CAShapeLayer.centerEyeWithFrame(eyeLidRect, outside: true) self.centerEyeInside = CAShapeLayer.centerEyeWithFrame(eyeLidRect, outside: false) // } // let centerEyeInset:CGFloat = 36 // let centerEyeSize = CGSizeMake( // eyeLidSize.height - centerEyeInset*2, // eyeLidSize.height - centerEyeInset*2 // ) // let centerEyeRect = CGRectMake( // CGRectGetMidX(self.view.frame) - centerEyeSize.width*0.5, // CGRectGetMidY(eyeLidRect) - centerEyeSize.height*0.5, // centerEyeSize.width, centerEyeSize.height) // // self.centerEye = CAShapeLayer() // self.centerEye?.fillColor = UIColor.blackColor().CGColor // self.centerEye?.path = UIBezierPath(ovalInRect: centerEyeRect).CGPath //self.centerEyeInside?.zPosition = CGFloat(-Int.max + 1) self.centerEye?.zPosition = CGFloat(-Int.max) self.view.layer.addSublayer(self.centerEye!) self.view.layer.addSublayer(self.centerEyeInside!) } func timerFired() { // virtually blink self.isBlinking = !self.isBlinking self.isMovingLeft = !self.isMovingLeft self.view.setNeedsLayout() } }
mit
51dc2bca270ce9a56fdfdf257eebbd0d
38.373494
157
0.59134
4.428184
false
false
false
false
kentya6/Fuwari
Fuwari/NSMenu+Extension.swift
1
644
// // NSMenu+Extension.swift // Fuwari // // Created by Kengo Yokoyama on 2018/07/14. // Copyright © 2018年 AppKnop. All rights reserved. // import Cocoa extension NSMenu { func addItem(withTitle title: String, action: Selector? = nil, target: AnyObject? = nil, representedObject: AnyObject? = nil, state: NSControl.StateValue = .off, submenu: NSMenu? = nil) { let menuItem = NSMenuItem(title: title, action: action, keyEquivalent: "") menuItem.target = target menuItem.representedObject = representedObject menuItem.state = state menuItem.submenu = submenu addItem(menuItem) } }
mit
968ed13f9561c30932a524b3c7c9586b
31.05
191
0.675507
4.056962
false
false
false
false
AnthonyMDev/Nimble
Sources/Nimble/Matchers/SatisfyAnyOf.swift
20
3747
import Foundation /// A Nimble matcher that succeeds when the actual value matches with any of the matchers /// provided in the variable list of matchers. public func satisfyAnyOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> { return satisfyAnyOf(predicates) } /// A Nimble matcher that succeeds when the actual value matches with any of the matchers /// provided in the variable list of matchers. public func satisfyAnyOf<T, U>(_ matchers: U...) -> Predicate<T> where U: Matcher, U.ValueType == T { return satisfyAnyOf(matchers.map { $0.predicate }) } internal func satisfyAnyOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> { return Predicate.define { actualExpression in var postfixMessages = [String]() var matches = false for predicate in predicates { let result = try predicate.satisfies(actualExpression) if result.toBoolean(expectation: .toMatch) { matches = true } postfixMessages.append("{\(result.message.expectedMessage)}") } var msg: ExpectationMessage if let actualValue = try actualExpression.evaluate() { msg = .expectedCustomValueTo( "match one of: " + postfixMessages.joined(separator: ", or "), "\(actualValue)" ) } else { msg = .expectedActualValueTo( "match one of: " + postfixMessages.joined(separator: ", or ") ) } return PredicateResult(bool: matches, message: msg) } } public func || <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> { return satisfyAnyOf(left, right) } public func || <T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> Predicate<T> { return satisfyAnyOf(left, right) } public func || <T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> Predicate<T> { return satisfyAnyOf(left, right) } #if canImport(Darwin) extension NMBObjCMatcher { @objc public class func satisfyAnyOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate { return NMBPredicate { actualExpression in if matchers.isEmpty { return NMBPredicateResult( status: NMBPredicateStatus.fail, message: NMBExpectationMessage( fail: "satisfyAnyOf must be called with at least one matcher" ) ) } var elementEvaluators = [Predicate<NSObject>]() for matcher in matchers { let elementEvaluator = Predicate<NSObject> { expression in if let predicate = matcher as? NMBPredicate { // swiftlint:disable:next line_length return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift() } else { let failureMessage = FailureMessage() let success = matcher.matches( // swiftlint:disable:next force_try { try! expression.evaluate() }, failureMessage: failureMessage, location: actualExpression.location ) return PredicateResult(bool: success, message: failureMessage.toExpectationMessage()) } } elementEvaluators.append(elementEvaluator) } return try satisfyAnyOf(elementEvaluators).satisfies(actualExpression).toObjectiveC() } } } #endif
apache-2.0
5a4ab1dc455845d70eaa44f062cfc7a9
38.861702
128
0.566853
5.345221
false
false
false
false
acn001/SwiftJSONModel
SwiftJSONModel/SwiftJSONModelErrorCode.swift
1
2819
// // SwiftJSONModel.swift // SWiftJSONModel // // @version 0.1.1 // @author Zhu Yue([email protected]) // // The MIT License (MIT) // // Copyright (c) 2016 Zhu Yue // // 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 enum SwiftJSONModelErrorCode: Int { // etc. case SwiftJSONModelTypeConvertionErrorOfStringFromCString = -51 // About SwiftJSONModelObjcReflection case SwiftJSONModelObjcPropertyCannotBeReflected = -11 case SwiftJSONModelObjcPropertyNameCannotBeReflected = -12 case SwiftJSONModelObjcPropertyTypeCannotBeReflected = -13 case SwiftJSONModelObjcNotSupportedProperty = -14 // About SwiftJSONModelNetworkHelper case SwiftJSONModelResponseDataStructureError = -101 var description: String { switch self { case .SwiftJSONModelObjcPropertyCannotBeReflected: return "SwiftJSONModelObjcReflection error: some property cannot be reflected. " case .SwiftJSONModelObjcPropertyNameCannotBeReflected: return "SwiftJSONModelObjcReflection error: some property name cannot be reflected. " case .SwiftJSONModelObjcPropertyTypeCannotBeReflected: return "SwiftJSONModelObjcReflection error: some property type cannot be reflected. " case .SwiftJSONModelObjcNotSupportedProperty: return "SwiftJSONModelObjcReflection error: not supported property type found. " case .SwiftJSONModelTypeConvertionErrorOfStringFromCString: return "Convertion error: construct object of String from CSting failed. " case .SwiftJSONModelResponseDataStructureError: return "Response data structure error: " default: return "Current error code has no description with raw value: \(rawValue). " } } }
mit
52655af7263501e1aaa9446c6a5ba2a9
52.188679
464
0.747428
4.818803
false
false
false
false
cbrentharris/swift
test/SILGen/enum.swift
2
6397
// RUN: %target-swift-frontend -parse-as-library -parse-stdlib -emit-silgen %s | FileCheck %s enum Boolish { case falsy case truthy } // CHECK-LABEL: sil hidden @_TF4enum13Boolish_casesFT_T_ func Boolish_cases() { // CHECK: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type // CHECK-NEXT: [[FALSY:%[0-9]+]] = enum $Boolish, #Boolish.falsy!enumelt _ = Boolish.falsy // CHECK-NEXT: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type // CHECK-NEXT: [[TRUTHY:%[0-9]+]] = enum $Boolish, #Boolish.truthy!enumelt _ = Boolish.truthy } struct Int {} enum Optionable { case nought case mere(Int) } // CHECK-LABEL: sil hidden [transparent] @_TFO4enum10Optionable4merefMS0_FVS_3IntS0_ // CHECK: bb0([[ARG:%.*]] : $Int, {{%.*}} : $@thin Optionable.Type): // CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, [[ARG]] : $Int // CHECK-NEXT: return [[RES]] : $Optionable // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_TF4enum16Optionable_casesFVS_3IntT_ func Optionable_cases(x: Int) { // CHECK: [[FN:%.*]] = function_ref @_TFO4enum10Optionable4mereFMS0_FVS_3IntS0_ // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type // CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]]) // CHECK-NEXT: strong_release [[CTOR]] _ = Optionable.mere // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type // CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int _ = Optionable.mere(x) } protocol P {} struct S : P {} enum AddressOnly { case nought case mere(P) case phantom(S) } // CHECK-LABEL: sil hidden [transparent] @_TFO4enum11AddressOnly4merefMS0_FPS_1P_S0_ : $@convention(thin) (@out AddressOnly, @in P, @thin AddressOnly.Type) -> () { // CHECK: bb0([[RET:%.*]] : $*AddressOnly, [[DATA:%.*]] : $*P, {{%.*}} : $@thin AddressOnly.Type): // CHECK-NEXT: [[RET_DATA:%.*]] = init_enum_data_addr [[RET]] : $*AddressOnly, #AddressOnly.mere!enumelt.1 // user: %4 // CHECK-NEXT: copy_addr [take] [[DATA]] to [initialization] [[RET_DATA]] : $*P // CHECK-NEXT: inject_enum_addr [[RET]] : $*AddressOnly, #AddressOnly.mere!enumelt.1 // CHECK: return // CHECK-NEXT: } // CHECK-LABEL: sil hidden @_TF4enum17AddressOnly_casesFVS_1ST_ : $@convention(thin) (S) -> () func AddressOnly_cases(s: S) { // CHECK: [[FN:%.*]] = function_ref @_TFO4enum11AddressOnly4mereFMS0_FPS_1P_S0_ // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]]) // CHECK-NEXT: strong_release [[CTOR]] _ = AddressOnly.mere // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: inject_enum_addr [[NOUGHT]]#1 // CHECK-NEXT: destroy_addr [[NOUGHT]]#1 // CHECK-NEXT: dealloc_stack [[NOUGHT]]#0 _ = AddressOnly.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[MERE:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]#1 // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[PAYLOAD]] // CHECK-NEXT: store %0 to [[PAYLOAD_ADDR]] // CHECK-NEXT: inject_enum_addr [[MERE]]#1 // CHECK-NEXT: destroy_addr [[MERE]]#1 // CHECK-NEXT: dealloc_stack [[MERE]]#0 _ = AddressOnly.mere(s) // Address-only enum vs loadable payload // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type // CHECK-NEXT: [[PHANTOM:%.*]] = alloc_stack $AddressOnly // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr %20#1 : $*AddressOnly, #AddressOnly.phantom!enumelt.1 // CHECK-NEXT: store %0 to [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[PHANTOM]]#1 : $*AddressOnly, #AddressOnly.phantom!enumelt.1 // CHECK-NEXT: destroy_addr [[PHANTOM]]#1 // CHECK-NEXT: dealloc_stack [[PHANTOM]]#0 _ = AddressOnly.phantom(s) // CHECK: return } enum PolyOptionable<T> { case nought case mere(T) } // CHECK-LABEL: sil hidden @_TF4enum20PolyOptionable_casesurFxT_ func PolyOptionable_cases<T>(t: T) { // CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $PolyOptionable<T> // CHECK-NEXT: inject_enum_addr [[NOUGHT]]#1 // CHECK-NEXT: destroy_addr [[NOUGHT]]#1 // CHECK-NEXT: dealloc_stack [[NOUGHT]]#0 _ = PolyOptionable<T>.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type // CHECK-NEXT: [[MERE:%.*]] = alloc_stack $PolyOptionable<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]#1 // CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[MERE]]#1 // CHECK-NEXT: destroy_addr [[MERE]]#1 // CHECK-NEXT: dealloc_stack [[MERE]]#0 _ = PolyOptionable<T>.mere(t) // CHECK-NEXT: destroy_addr %0 // CHECK: return } // The substituted type is loadable and trivial here // CHECK-LABEL: sil hidden @_TF4enum32PolyOptionable_specialized_casesFVS_3IntT_ func PolyOptionable_specialized_cases(t: Int) { // CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.nought!enumelt _ = PolyOptionable<Int>.nought // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type // CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.mere!enumelt.1, %0 _ = PolyOptionable<Int>.mere(t) // CHECK: return } // Regression test for a bug where temporary allocations created as a result of // tuple implosion were not deallocated in enum constructors. struct String { var ptr: Builtin.NativeObject } enum Foo { case A(P, String) } // CHECK-LABEL: sil hidden [transparent] @_TFO4enum3Foo1AfMS0_FTPS_1P_VS_6String_S0_ : $@convention(thin) (@out Foo, @in P, @owned String, @thin Foo.Type) -> () { // CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Foo, #Foo.A!enumelt.1 // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1 // CHECK-NEXT: copy_addr [take] %1 to [initialization] [[LEFT]] : $*P // CHECK-NEXT: store %2 to [[RIGHT]] // CHECK-NEXT: inject_enum_addr %0 : $*Foo, #Foo.A!enumelt.1 // CHECK: return // CHECK-NEXT: }
apache-2.0
e54f038bcfaaad0feecd351f38422ff6
37.769697
163
0.627794
3.079923
false
false
false
false
liuweihaocool/iOS_06_liuwei
新浪微博_swift/新浪微博_swift/class/Main/Compare/View/LWPlaceholdView.swift
1
2159
// // LWPlaceholdView.swift // 新浪微博_swift // // Created by LiuWei on 15/12/5. // Copyright © 2015年 liuwei. All rights reserved. // import UIKit /// 自定义TextView 里面有一个站位文本,当没有内容的时候会显示出来 class LWPlaceholdView: UITextView { /// 提供属性,让别人来设置文本 var placeholder: String? { didSet { placeHolderLabel.text = placeholder placeHolderLabel.font = font } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 实现通知方法 func textDidChange() { placeHolderLabel.hidden = hasText() } override init(frame: CGRect, textContainer: NSTextContainer?) { // 调用父类的init super.init(frame: frame, textContainer: textContainer) // 设置代理 NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self) } /// 移除通知 相当于dealloc deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } /// 懒加载 站位文本 提供label给别人访问,别人可能会做非法操作 private lazy var placeHolderLabel:UILabel = { /// 创建label 设置属性 let label = UILabel() label.textColor = UIColor.lightGrayColor() label.font = self.font /// 添加约束 self.addSubview(label) /// 取消系统的自动约束 label.translatesAutoresizingMaskIntoConstraints = false self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8)) self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5)) label.sizeToFit() return label }() }
apache-2.0
d80fc35111a6cc68cadfff1388145c5d
29.761905
206
0.647575
4.738386
false
false
false
false
crazypoo/PTools
Pods/CollectionViewPagingLayout/Lib/Scale/ScaleTransformViewOptions.Translation3dOptions.swift
1
1328
// // ScaleTransformViewOptions.Translation3dOptions.swift // CollectionViewPagingLayout // // Created by Amir on 27/03/2020. // Copyright © 2020 Amir Khorsandi. All rights reserved. // import UIKit public extension ScaleTransformViewOptions { struct Translation3dOptions { // MARK: Properties /// The translates(x,y,z) ratios /// (translateX = progress * translates.x * targetView.width) /// (translateY = progress * translates.y * targetView.height) /// (translateZ = progress * translates.z * targetView.width) public var translateRatios: (CGFloat, CGFloat, CGFloat) /// The minimum translate ratios public var minTranslateRatios: (CGFloat, CGFloat, CGFloat) /// The maximum translate ratios public var maxTranslateRatios: (CGFloat, CGFloat, CGFloat) // MARK: Lifecycle public init( translateRatios: (CGFloat, CGFloat, CGFloat), minTranslateRatios: (CGFloat, CGFloat, CGFloat), maxTranslateRatios: (CGFloat, CGFloat, CGFloat) ) { self.translateRatios = translateRatios self.minTranslateRatios = minTranslateRatios self.maxTranslateRatios = maxTranslateRatios } } }
mit
e7eaa05bca31d2b0c55dfbbcb0c2afa0
29.860465
70
0.625471
4.825455
false
false
false
false
sergeyzenchenko/react-swift
ReactSwift/ReactSwift/Cartography/Edges.swift
5
2360
// // Edges.swift // Cartography // // Created by Robert Böhnke on 19/06/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif public enum Edges : Compound { case Edges(View) var properties: [Property] { switch (self) { case let .Edges(view): return [ Edge.Top(view), Edge.Leading(view), Edge.Bottom(view), Edge.Trailing(view) ] } } } public func inset(edges: Edges, all: Float) -> Expression<Edges> { return inset(edges, all, all, all, all) } public func inset(edges: Edges, horizontal: Float, vertical: Float) -> Expression<Edges> { return inset(edges, vertical, horizontal, vertical, horizontal) } public func inset(edges: Edges, top: Float, leading: Float, bottom: Float, trailing: Float) -> Expression<Edges> { return Expression(edges, [ Coefficients(1, top), Coefficients(1, leading), Coefficients(1, -bottom), Coefficients(1, -trailing) ]) } // MARK: Equality public func ==(lhs: Edges, rhs: Expression<Edges>) -> [NSLayoutConstraint] { return apply(lhs, coefficients: rhs.coefficients, to: rhs.value) } public func ==(lhs: Expression<Edges>, rhs: Edges) -> [NSLayoutConstraint] { return rhs == lhs } public func ==(lhs: Edges, rhs: Edges) -> [NSLayoutConstraint] { return apply(lhs, to: rhs) } // MARK: Inequality public func <=(lhs: Edges, rhs: Edges) -> [NSLayoutConstraint] { return apply(lhs, to: rhs, relation: NSLayoutRelation.LessThanOrEqual) } public func >=(lhs: Edges, rhs: Edges) -> [NSLayoutConstraint] { return apply(lhs, to: rhs, relation: NSLayoutRelation.GreaterThanOrEqual) } public func <=(lhs: Edges, rhs: Expression<Edges>) -> [NSLayoutConstraint] { return apply(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: NSLayoutRelation.LessThanOrEqual) } public func <=(lhs: Expression<Edges>, rhs: Edges) -> [NSLayoutConstraint] { return rhs >= lhs } public func >=(lhs: Edges, rhs: Expression<Edges>) -> [NSLayoutConstraint] { return apply(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: NSLayoutRelation.GreaterThanOrEqual) } public func >=(lhs: Expression<Edges>, rhs: Edges) -> [NSLayoutConstraint] { return rhs <= lhs }
mit
ff2029bebda60c9f649d61b2fdac1eae
28.111111
134
0.654792
3.834146
false
false
false
false
FabrizioBrancati/BFKit-Swift
Sources/BFKit/Apple/UIKit/UIColor+Extensions.swift
1
16571
// // UIColor+Extensions.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // 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 #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif // MARK: - Global functions /// Create an UIColor or NSColor in format RGBA. /// /// - Parameters: /// - red: Red value. /// - green: Green value. /// - blue: Blue value. /// - alpha: Alpha value. /// - Returns: Returns the created UIColor or NSColor. public func RGBA(_ red: Int, _ green: Int, _ blue: Int, _ alpha: Float) -> Color { #if canImport(UIKit) return Color(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha)) #elseif canImport(AppKit) return Color(calibratedRed: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha)) #endif } /// Create an UIColor or NSColor in format ARGB. /// /// - Parameters: /// - alpha: Alpha value. /// - red: Red value. /// - green: Green value. /// - blue: Blue value. /// - Returns: Returns the created UIColor or NSColor. public func ARGB( _ alpha: Float, _ red: Int, _ green: Int, _ blue: Int) -> Color { RGBA(red, green, blue, alpha) } /// Create an UIColor or NSColor in format RGB. /// /// - Parameters: /// - red: Red value. /// - green: Green value. /// - blue: Blue value. /// - Returns: Returns the created UIColor or NSColor. public func RGB(_ red: Int, _ green: Int, _ blue: Int) -> Color { #if canImport(UIKit) return Color(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) #elseif canImport(AppKit) return Color(calibratedRed: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) #endif } // MARK: - UIColor or NSColor extension /// This extesion adds some useful functions to UIColor or NSColor. public extension Color { // MARK: - Variables #if canImport(UIKit) /// RGB properties: red. var redComponent: CGFloat { guard canProvideRGBComponents(), let component = cgColor.__unsafeComponents else { return 0.0 } return component[0] } /// RGB properties: green. var greenComponent: CGFloat { guard canProvideRGBComponents(), let component = cgColor.__unsafeComponents else { return 0.0 } guard cgColor.colorSpace?.model == CGColorSpaceModel.monochrome else { return component[1] } return component[0] } /// RGB properties: blue. var blueComponent: CGFloat { guard canProvideRGBComponents(), let component = cgColor.__unsafeComponents else { return 0.0 } guard cgColor.colorSpace?.model == CGColorSpaceModel.monochrome else { return component[2] } return component[0] } /// RGB properties: white. var whiteComponent: CGFloat { guard cgColor.colorSpace?.model == CGColorSpaceModel.monochrome, let component = cgColor.__unsafeComponents else { return 0.0 } return component[0] } #endif /// RGB properties: luminance. var luminance: CGFloat { if canProvideRGBComponents() { var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0 #if canImport(UIKit) getRed(&red, green: &green, blue: &blue, alpha: &alpha) #elseif canImport(AppKit) if colorSpace.colorSpaceModel == .rgb { getRed(&red, green: &green, blue: &blue, alpha: &alpha) } else if colorSpace.colorSpaceModel == .gray { var white: CGFloat = 0.0 getWhite(&white, alpha: &alpha) red = white green = white blue = white } #endif return red * 0.2126 + green * 0.7152 + blue * 0.0722 } return 0.0 } /// RGBA properties: alpha. var alpha: CGFloat { return cgColor.alpha } /// HSB properties: hue. var hue: CGFloat { if canProvideRGBComponents() { var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return hue } return 0.0 } /// HSB properties: saturation. var saturation: CGFloat { if canProvideRGBComponents() { var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return saturation } return 0.0 } /// HSB properties: brightness. var brightness: CGFloat { if canProvideRGBComponents() { var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return brightness } return 0.0 } /// Returns the HEX string from UIColor or NSColor. var hex: String { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 0.0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) let redInt = (Int)(red * 255) let greenInt = (Int)(green * 255) let blueInt = (Int)(blue * 255) let rgb: Int = redInt << 16 | greenInt << 8 | blueInt << 0 return String(format: "#%06x", rgb) } // MARK: - Functions /// Create a color from HEX with alpha. /// /// - Parameters: /// - hex: HEX value. /// - alpha: Alpha value. convenience init(hex: Int, alpha: CGFloat = 1.0) { #if canImport(UIKit) self.init(red: CGFloat(((hex & 0xFF0000) >> 16)) / 255.0, green: CGFloat(((hex & 0xFF00) >> 8)) / 255.0, blue: CGFloat((hex & 0xFF)) / 255.0, alpha: alpha) #elseif canImport(AppKit) self.init(calibratedRed: CGFloat(((hex & 0xFF0000) >> 16)) / 255.0, green: CGFloat(((hex & 0xFF00) >> 8)) / 255.0, blue: CGFloat((hex & 0xFF)) / 255.0, alpha: alpha) #endif } /// Create a color from a HEX string. /// It supports the following type: /// - #ARGB, ARGB if alphaFirst is true. #RGBA, RGBA if alphaFirst is false. /// - #ARGB. /// - #RRGGBB. /// - #AARRGGBB, AARRGGBB if alphaFirst is true. #RRGGBBAA, RRGGBBAA if firstIsAlpha is false. /// /// - Parameters: /// - hexString: HEX string. /// - alphaFirst: Set it to true if alpha value is the first in the HEX string. If alpha value is the last one, set it to false. Default is false. convenience init(hex: String, alphaFirst: Bool = false) { let colorString: String = hex.replacingOccurrences(of: "#", with: "").uppercased() var alpha: CGFloat = 1.0, red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0 switch colorString.count { case 3: /// RGB alpha = 1.0 red = Color.colorComponent(fromString: colorString, range: 0..<1) green = Color.colorComponent(fromString: colorString, range: 1..<2) blue = Color.colorComponent(fromString: colorString, range: 2..<3) case 4: /// ARGB if alphaFirst is true, otherwise RGBA. if alphaFirst { alpha = Color.colorComponent(fromString: colorString, range: 0..<1) red = Color.colorComponent(fromString: colorString, range: 1..<2) green = Color.colorComponent(fromString: colorString, range: 2..<3) blue = Color.colorComponent(fromString: colorString, range: 3..<4) } else { red = Color.colorComponent(fromString: colorString, range: 0..<1) green = Color.colorComponent(fromString: colorString, range: 1..<2) blue = Color.colorComponent(fromString: colorString, range: 2..<3) alpha = Color.colorComponent(fromString: colorString, range: 3..<4) } case 6: /// RRGGBB alpha = 1.0 red = Color.colorComponent(fromString: colorString, range: 0..<2) green = Color.colorComponent(fromString: colorString, range: 2..<4) blue = Color.colorComponent(fromString: colorString, range: 4..<6) case 8: /// AARRGGBB if alphaFirst is true, otherwise RRGGBBAA. if alphaFirst { alpha = Color.colorComponent(fromString: colorString, range: 0..<2) red = Color.colorComponent(fromString: colorString, range: 2..<4) green = Color.colorComponent(fromString: colorString, range: 4..<6) blue = Color.colorComponent(fromString: colorString, range: 6..<8) } else { red = Color.colorComponent(fromString: colorString, range: 0..<2) green = Color.colorComponent(fromString: colorString, range: 2..<4) blue = Color.colorComponent(fromString: colorString, range: 4..<6) alpha = Color.colorComponent(fromString: colorString, range: 6..<8) } default: break } #if canImport(UIKit) self.init(red: red, green: green, blue: blue, alpha: alpha) #elseif canImport(AppKit) self.init(calibratedRed: red, green: green, blue: blue, alpha: alpha) #endif } /// A good contrasting color, it will be either black or white. /// /// - Returns: Returns the color. func contrasting() -> Color { luminance > 0.5 ? Color.black : Color.white } /// A complementary color that should look good. /// /// - Returns: Returns the color. func complementary() -> Color? { var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 #if canImport(UIKit) guard getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) else { return nil } #elseif canImport(AppKit) getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) #endif hue += 180 if hue > 360 { hue -= 360 } return Color(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } /// Check if the color is in RGB format. /// /// - Returns: Returns if the color is in RGB format. func canProvideRGBComponents() -> Bool { guard let colorSpace = cgColor.colorSpace else { return false } switch colorSpace.model { case CGColorSpaceModel.rgb, CGColorSpaceModel.monochrome: return true default: return false } } /// Returns the color component from the string. /// /// - Parameters: /// - fromString: String to convert. /// - start: Component start index. /// - lenght: Component lenght. /// - Returns: Returns the color component from the string. private static func colorComponent(fromString string: String, range: Range<Int>) -> CGFloat { let substring: String = string.substring(with: range) let fullHex = (range.upperBound - range.lowerBound) == 2 ? substring : "\(substring)\(substring)" var hexComponent: CUnsignedInt = 0 Scanner(string: fullHex).scanHexInt32(&hexComponent) return CGFloat(hexComponent) / 255.0 } /// Create a random color. /// /// - Parameter alpha: Alpha value. /// - Returns: Returns the UIColor or NSColor instance. static func random(alpha: CGFloat = 1.0) -> Color { let red = Int.random(in: 0...255) let green = Int.random(in: 0...255) let blue = Int.random(in: 0...255) return Color(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha) } /// Create an UIColor or NSColor from a given string. Example: "blue" or hex string. /// /// - Parameter color: String with color. /// - Returns: Returns the created UIColor or NSColor. static func color(string color: String) -> Color { if color.count >= 3 { if Color.responds(to: Selector(color.lowercased() + "Color")) { return convertColor(string: color) } else { return Color(hex: color) } } else { return Color.black } } #if canImport(UIKit) /// Create an UIColor from a given string like "blue" or an hex string. /// /// - Parameter color: String with color. convenience init(string color: String) { if UIColor.responds(to: Selector(color.lowercased() + "Color")) { self.init(cgColor: UIColor.convertColor(string: color).cgColor) } else { self.init(hex: color) } } #elseif canImport(AppKit) /// Create a NSColor from a given string like "blue" or an hex string. /// /// - Parameter color: String with color. convenience init?(string color: String) { if NSColor.responds(to: Selector(color.lowercased() + "Color")) { self.init(cgColor: NSColor.convertColor(string: color).cgColor) } else { self.init(hex: color) } } #endif /// Used the retrive the color from the string color ("blue" or "red"). /// /// - Parameter color: String with the color. /// - Returns: Returns the created UIColor or NSColor. private static func convertColor(string color: String) -> Color { let color = color.lowercased() switch color { case "black": return Color.black case "darkgray": return Color.darkGray case "lightgray": return Color.lightGray case "white": return Color.white case "gray": return Color.gray case "red": return Color.red case "green": return Color.green case "blue": return Color.blue case "cyan": return Color.cyan case "yellow": return Color.yellow case "magenta": return Color.magenta case "orange": return Color.orange case "purple": return Color.purple case "brown": return Color.brown case "clear": return Color.clear default: return Color.clear } } /// Creates and returns a color object that has the same color space and component values as the given color, but has the specified alpha component. /// /// - Parameters: /// - color: UIColor or NSColor value. /// - alpha: Alpha value. /// - Returns: Returns an UIColor or NSColor instance. static func color(color: Color, alpha: CGFloat) -> Color { color.withAlphaComponent(alpha) } }
mit
f163867b8b59fe45cc9faf89533f8d93
35.824444
177
0.583127
4.255521
false
false
false
false
uber/rides-ios-sdk
source/UberCoreTests/UberMocks.swift
1
4792
// // UberMocks.swift // UberCoreTests // // 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. @testable import UberCore class LoginManagerPartialMock: LoginManager { var executeLoginClosure: ((AuthenticationCompletionHandler?) -> ())? @objc public override func login(requestedScopes scopes: [UberScope], presentingViewController: UIViewController? = nil, completion: AuthenticationCompletionHandler? = nil) { executeLoginClosure?(completion) } } @objc class LoginManagingProtocolMock: NSObject, LoginManaging { var loginClosure: (([UberScope], UIViewController?, ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) -> Void)? var openURLClosure: ((UIApplication, URL, String?, Any?) -> Bool)? var didBecomeActiveClosure: (() -> ())? var willEnterForegroundClosure: (() -> ())? var backingManager: LoginManaging? init(loginManaging: LoginManaging? = nil) { backingManager = loginManaging super.init() } func login(requestedScopes scopes: [UberScope], presentingViewController: UIViewController?, completion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?) { if let closure = loginClosure { closure(scopes, presentingViewController, completion) } else if let manager = backingManager { manager.login(requestedScopes: scopes, presentingViewController: presentingViewController, completion: completion) } } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any?) -> Bool { if let closure = openURLClosure { return closure(application, url, sourceApplication, annotation) } else if let manager = backingManager { return manager.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) } else { return false } } @available(iOS 9.0, *) public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String let annotation = options[.annotation] as Any? return application(app, open: url, sourceApplication: sourceApplication, annotation: annotation) } func applicationDidBecomeActive() { if let closure = didBecomeActiveClosure { closure() } else if let manager = backingManager { manager.applicationDidBecomeActive() } } func applicationWillEnterForeground() { if let closure = willEnterForegroundClosure { closure() } else { backingManager?.applicationWillEnterForeground() } } } class RidesNativeAuthenticatorPartialStub: BaseAuthenticator { var consumeResponseCompletionValue: (AccessToken?, NSError?)? override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) { completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1) } } class EatsNativeAuthenticatorPartialStub: BaseAuthenticator { var consumeResponseCompletionValue: (AccessToken?, NSError?)? override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) { completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1) } } class ImplicitAuthenticatorPartialStub: ImplicitGrantAuthenticator { var consumeResponseCompletionValue: (AccessToken?, NSError?)? override func consumeResponse(url: URL, completion: AuthenticationCompletionHandler?) { completion?(consumeResponseCompletionValue?.0, consumeResponseCompletionValue?.1) } }
mit
fc8e4c1a2d607135c41b13327b9103f4
42.563636
178
0.719324
5.225736
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/QuickLookPreview.swift
1
6911
// // QuickLookPreview.swift // Telegram-Mac // // Created by keepcoder on 19/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit import TelegramCore import Postbox import TGUIKit import Quartz import Foundation private class QuickLookPreviewItem : NSObject, QLPreviewItem { let media:Media let path:String init(with media:Media, path:String, ext:String = "txt") { self.path = path + "." + ext self.media = media do { try? FileManager.default.linkItem(atPath: path, toPath: self.path ) } } var previewItemURL: URL! { return URL(fileURLWithPath: path) } var previewItemTitle: String! { if let media = media as? TelegramMediaFile { return media.fileName ?? strings().quickLookPreview } return strings().quickLookPreview } } fileprivate var preview:QuickLookPreview = { return QuickLookPreview() }() class QuickLookPreview : NSObject, QLPreviewPanelDelegate, QLPreviewPanelDataSource { private var panel:QLPreviewPanel! private weak var delegate:InteractionContentViewProtocol? private var item:QuickLookPreviewItem! private var context: AccountContext! private var media:Media! private var ready:Promise<(String?,String?)> = Promise() private let disposable:MetaDisposable = MetaDisposable() private let resourceDisposable:MetaDisposable = MetaDisposable() private var stableId:ChatHistoryEntryId? override init() { super.init() } public func show(context: AccountContext, with media:Media, stableId:ChatHistoryEntryId?, _ delegate:InteractionContentViewProtocol? = nil) { self.context = context self.media = media self.delegate = delegate self.stableId = stableId panel = QLPreviewPanel.shared() var mimeType:String = "image/jpeg" var fileResource:TelegramMediaResource? var fileName:String? = nil var forceExtension: String? = nil let signal:Signal<(String?, String?), NoError> if let file = media as? TelegramMediaFile { fileResource = file.resource mimeType = file.mimeType fileName = file.fileName if let ext = fileName?.nsstring.pathExtension, !ext.isEmpty { forceExtension = ext } signal = copyToDownloads(file, postbox: context.account.postbox) |> map { path in if let path = path { return (Optional(path.nsstring.deletingPathExtension), Optional(path.nsstring.pathExtension)) } else { return (nil, nil) } } } else if let image = media as? TelegramMediaImage { fileResource = largestImageRepresentation(image.representations)?.resource if let fileResource = fileResource { signal = combineLatest(context.account.postbox.mediaBox.resourceData(fileResource), resourceType(mimeType: mimeType)) |> mapToSignal({ (data) -> Signal<(String?,String?), NoError> in return .single((data.0.path, forceExtension ?? data.1)) }) |> deliverOnMainQueue } else { signal = .complete() } } else { signal = .complete() } self.ready.set(signal |> deliverOnMainQueue) disposable.set(ready.get().start(next: { [weak self] (path,ext) in if let strongSelf = self, let path = path { var ext:String? = ext if ext == nil || ext == "*" { ext = fileName?.nsstring.pathExtension } if let ext = ext { let item = QuickLookPreviewItem(with: strongSelf.media, path:path, ext:ext) if ext == "pkpass" || !FastSettings.openInQuickLook(ext) { NSWorkspace.shared.openFile(item.path) return } strongSelf.item = item RunLoop.current.add(Timer.scheduledTimer(timeInterval: 0, target: strongSelf, selector: #selector(strongSelf.openPanelInRunLoop), userInfo: nil, repeats: false), forMode: RunLoop.Mode.modalPanel) } } })) } @objc func openPanelInRunLoop() { panel.updateController() if !isOpened() { panel.makeKeyAndOrderFront(nil) } else { panel.currentPreviewItemIndex = 0 } } func isOpened() -> Bool { return QLPreviewPanel.sharedPreviewPanelExists() && QLPreviewPanel.shared().isVisible } public static var current:QuickLookPreview! { return preview } deinit { disposable.dispose() resourceDisposable.dispose() } func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> QLPreviewItem! { return item } func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int { return 1 } func previewPanel(_ panel: QLPreviewPanel!, handle event: NSEvent!) -> Bool { return true } override class func endPreviewPanelControl(_ panel: QLPreviewPanel!) { var bp = 0 bp += 1 } func previewPanel(_ panel: QLPreviewPanel!, sourceFrameOnScreenFor item: QLPreviewItem!) -> NSRect { if let stableId = stableId { let view:NSView? = delegate?.contentInteractionView(for: stableId, animateIn: false) if let view = view, let window = view.window { // let tframe = view.frame return window.convertToScreen(view.convert(view.bounds, to: nil)) } } return NSZeroRect } func previewPanel(_ panel: QLPreviewPanel!, transitionImageFor item: QLPreviewItem!, contentRect: UnsafeMutablePointer<NSRect>!) -> Any! { if let stableId = stableId { let view:NSView? = delegate?.contentInteractionView(for: stableId, animateIn: true) if let view = view?.copy() as? View, let contents = view.layer?.contents { return NSImage(cgImage: contents as! CGImage, size: view.frame.size) } } return nil //fake } func hide() -> Void { if isOpened() { panel.orderOut(nil) } self.context = nil self.media = nil self.stableId = nil self.disposable.set(nil) self.resourceDisposable.set(nil) } }
gpl-2.0
6eeaae418c75efbf69aef02b61605fce
30.266968
215
0.571056
5.080882
false
false
false
false
BBBInc/AlzPrevent-ios
researchline/AppDelegate.swift
1
9184
// // AppDelegate.swift // // Created by riverleo on 2015. 11. 8.. // Copyright © 2015년 bbb. All rights reserved. // import UIKit import CoreData import Alamofire @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var deviceToken: String? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let deviceToken = Constants.userDefaults.stringForKey("deviceToken") if(deviceToken != nil){ Alamofire.request(.POST, Constants.token, parameters: [ "deviceKey": Constants.deviceKey, "deviceType": Constants.deviceType, "token": deviceToken! ]) .responseJSON { (response) -> Void in debugPrint(response) } } var storyboard = UIStoryboard(name: "TabBar", bundle: nil) self.window?.rootViewController = storyboard.instantiateInitialViewController() if Constants.signKey() == "" || Constants.registerStep() == Constants.STEP_READY { storyboard = UIStoryboard(name: "Welcome", bundle: nil) self.window?.rootViewController = storyboard.instantiateInitialViewController() } else if Constants.registerStep() == Constants.STEP_REGISTER { storyboard = UIStoryboard(name: "Session", bundle: nil) self.window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("AdditionalNavigationController") } else if Constants.registerStep() == Constants.STEP_EMAIL_VERIFICATION { storyboard = UIStoryboard(name: "Session", bundle: nil) self.window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("EmailVerificationNavigationController") } self.window!.makeKeyAndVisible() let settings = UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil) application.registerForRemoteNotifications() application.registerUserNotificationSettings(settings) return true } // MARK: Notification Methods func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let deviceTokenString = "\(deviceToken)" .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString:"<>")) .stringByReplacingOccurrencesOfString(" ", withString: "") self.deviceToken = deviceTokenString print(deviceToken) Constants.userDefaults.setObject(deviceTokenString, forKey: "deviceToken") Alamofire.request(.POST, Constants.token, parameters: [ "deviceKey": Constants.deviceKey, "deviceType": Constants.deviceType, "token": deviceTokenString ]) .responseJSON { (response) -> Void in debugPrint(response) } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { debugPrint(error) } // MARK: Life Cycle Methods func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.bbb.researchline" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("researchline", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this 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. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // 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. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
bsd-3-clause
b39f22ce60a4b1515f1da141c88117f9
50.578652
291
0.685764
6.104388
false
false
false
false
fgengine/quickly
Quickly/Views/Stackbar/QStackbar.swift
1
15581
// // Quickly // open class QStackbar : QView { public enum DisplayMode { case `default` case onlyBottom } public var displayMode: DisplayMode = .default { didSet(oldValue) { if self.displayMode != oldValue { self.setNeedsUpdateConstraints() } } } public var edgeInsets: UIEdgeInsets = UIEdgeInsets() { didSet(oldValue) { if self.edgeInsets != oldValue { self.setNeedsUpdateConstraints() } } } public var contentSize: CGFloat = 50 { didSet(oldValue) { if self.contentSize != oldValue { self.setNeedsUpdateConstraints() } } } public var leftViewsOffset: CGFloat = 0 { didSet(oldValue) { if self.leftViewsOffset != oldValue { self.setNeedsUpdateConstraints() } } } public var leftViewsSpacing: CGFloat { set(value) { self._leftView.spacing = value } get { return self._leftView.spacing } } public var leftViews: [UIView] { set(value) { if self._leftView.views != value { self._leftView.views = value self.setNeedsUpdateConstraints() } } get { return self._leftView.views } } public var centerViewsSpacing: CGFloat { set(value) { self._centerView.spacing = value } get { return self._centerView.spacing } } public var centerViews: [UIView] { set(value) { if self._centerView.views != value { self._centerView.views = value self.setNeedsUpdateConstraints() } } get { return self._centerView.views } } public var rightViewsOffset: CGFloat = 0 { didSet(oldValue) { if self.rightViewsOffset != oldValue { self.setNeedsUpdateConstraints() } } } public var rightViewsSpacing: CGFloat { set(value) { self._rightView.spacing = value } get { return self._rightView.spacing } } public var rightViews: [UIView] { set(value) { if self._rightView.views != value { self._rightView.views = value self.setNeedsUpdateConstraints() } } get { return self._rightView.views } } public var bottomView: UIView? { willSet { guard let view = self.bottomView else { return } view.removeFromSuperview() self.setNeedsUpdateConstraints() } didSet { guard let view = self.bottomView else { return } view.translatesAutoresizingMaskIntoConstraints = false self.insertSubview(view, at: 0) self.setNeedsUpdateConstraints() } } public var backgroundView: UIView? { willSet { guard let view = self.backgroundView else { return } view.removeFromSuperview() self.setNeedsUpdateConstraints() } didSet { guard let view = self.backgroundView else { return } view.translatesAutoresizingMaskIntoConstraints = false self.insertSubview(view, at: 0) self.setNeedsUpdateConstraints() } } public var separatorView: UIView? { willSet { guard let view = self.separatorView else { return } self._separatorConstraint = nil view.removeFromSuperview() self.setNeedsUpdateConstraints() } didSet { guard let view = self.separatorView else { return } view.translatesAutoresizingMaskIntoConstraints = false self.addSubview(view) self._separatorConstraint = NSLayoutConstraint( item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.separatorHeight ) self.setNeedsUpdateConstraints() } } public var separatorHeight: CGFloat = 1 { didSet(oldValue) { if self.separatorHeight != oldValue { if let constraint = self._separatorConstraint { constraint.constant = self.separatorHeight } } } } private var _contentView: UIView! private var _leftView: WrapView! private var _centerView: WrapView! private var _rightView: WrapView! private var _constraints: [NSLayoutConstraint] = [] { willSet { self.removeConstraints(self._constraints) } didSet { self.addConstraints(self._constraints) } } private var _contentConstraints: [NSLayoutConstraint] = [] { willSet { self._contentView.removeConstraints(self._contentConstraints) } didSet { self._contentView.addConstraints(self._contentConstraints) } } private var _separatorConstraint: NSLayoutConstraint? { willSet { guard let view = self.separatorView, let constraint = self._separatorConstraint else { return } view.removeConstraint(constraint) } didSet { guard let view = self.separatorView, let constraint = self._separatorConstraint else { return } view.addConstraint(constraint) } } public required init() { super.init( frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50) ) } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func setup() { super.setup() self.backgroundColor = UIColor.white self._contentView = UIView(frame: self.bounds) self._contentView.translatesAutoresizingMaskIntoConstraints = false self._contentView.backgroundColor = UIColor.clear self.addSubview(self._contentView) self._leftView = WrapView(frame: self.bounds) self._leftView.setContentCompressionResistancePriority(.defaultHigh , for: .horizontal) self._contentView.addSubview(self._leftView) self._centerView = WrapView(frame: self.bounds) self._centerView.setContentCompressionResistancePriority(.defaultLow , for: .horizontal) self._contentView.addSubview(self._centerView) self._rightView = WrapView(frame: self.bounds) self._rightView.setContentCompressionResistancePriority(.defaultHigh , for: .horizontal) self._contentView.addSubview(self._rightView) } open override func updateConstraints() { super.updateConstraints() var constraints: [NSLayoutConstraint] = [] if let backgroundView = self.backgroundView { constraints.append(contentsOf: [ backgroundView.topLayout == self.topLayout, backgroundView.leadingLayout == self.leadingLayout, backgroundView.trailingLayout == self.trailingLayout, backgroundView.bottomLayout == self.bottomLayout ]) } if let separatorView = self.separatorView { constraints.append(contentsOf: [ separatorView.topLayout == self.bottomLayout, separatorView.leadingLayout == self.leadingLayout, separatorView.trailingLayout == self.trailingLayout ]) } switch self.displayMode { case .default: constraints.append(contentsOf: [ self._contentView.topLayout == self.topLayout.offset(self.edgeInsets.top), self._contentView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left), self._contentView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right) ]) if let bottomView = self.bottomView { constraints.append(contentsOf: [ self._contentView.bottomLayout == bottomView.topLayout, bottomView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left), bottomView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right), bottomView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom) ]) } else { constraints.append(contentsOf: [ self._contentView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom) ]) } case .onlyBottom: constraints.append(contentsOf: [ self._contentView.bottomLayout == self.topLayout.offset(-self.edgeInsets.top) ]) if let bottomView = self.bottomView { constraints.append(contentsOf: [ bottomView.topLayout == self.topLayout.offset(self.edgeInsets.top), bottomView.leadingLayout == self.leadingLayout.offset(self.edgeInsets.left), bottomView.trailingLayout == self.trailingLayout.offset(-self.edgeInsets.right), bottomView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom) ]) } else { constraints.append(contentsOf: [ self._contentView.bottomLayout == self.bottomLayout.offset(-self.edgeInsets.bottom) ]) } } self._constraints = constraints var contentConstraints: [NSLayoutConstraint] = [ self._contentView.heightLayout == self.contentSize, self._leftView.topLayout == self._contentView.topLayout, self._leftView.leadingLayout == self._contentView.leadingLayout, self._leftView.bottomLayout == self._contentView.bottomLayout, self._centerView.topLayout == self._contentView.topLayout, self._centerView.bottomLayout == self._contentView.bottomLayout, self._rightView.topLayout == self._contentView.topLayout, self._rightView.trailingLayout == self._contentView.trailingLayout, self._rightView.bottomLayout == self._contentView.bottomLayout ] if self.centerViews.count > 0 { if self.leftViews.count > 0 && self.rightViews.count > 0 { contentConstraints.append(contentsOf: [ self._centerView.leadingLayout >= self._leftView.trailingLayout.offset(self.leftViewsOffset), self._centerView.trailingLayout <= self._rightView.leadingLayout.offset(-self.rightViewsOffset), self._centerView.centerXLayout == self._contentView.centerXLayout ]) } else if self.leftViews.count > 0 { contentConstraints.append(contentsOf: [ self._centerView.leadingLayout >= self._leftView.trailingLayout.offset(self.leftViewsOffset), self._centerView.trailingLayout <= self._contentView.trailingLayout, self._centerView.centerXLayout == self._contentView.centerXLayout ]) } else if self.rightViews.count > 0 { contentConstraints.append(contentsOf: [ self._centerView.leadingLayout >= self._contentView.leadingLayout, self._centerView.trailingLayout <= self._rightView.leadingLayout.offset(-self.rightViewsOffset), self._centerView.centerXLayout == self._contentView.centerXLayout ]) } else { contentConstraints.append(contentsOf: [ self._centerView.leadingLayout == self._contentView.leadingLayout, self._centerView.trailingLayout == self._contentView.trailingLayout, self._centerView.centerXLayout == self._contentView.centerXLayout ]) } } else { if self.leftViews.count > 0 && self.rightViews.count > 0 { contentConstraints.append(contentsOf: [ self._leftView.trailingLayout >= self._rightView.trailingLayout.offset(self.leftViewsOffset + self.rightViewsOffset) ]) } else if self.leftViews.count > 0 { contentConstraints.append(contentsOf: [ self._leftView.trailingLayout <= self._contentView.trailingLayout ]) } else if self.rightViews.count > 0 { contentConstraints.append(contentsOf: [ self._rightView.leadingLayout >= self._contentView.leadingLayout ]) } } self._contentConstraints = contentConstraints } private class WrapView : QInvisibleView { public var spacing: CGFloat = 0 { didSet(oldValue) { if self.spacing != oldValue { self.setNeedsUpdateConstraints() } } } public var views: [UIView] = [] { willSet { for view in self.views { view.removeFromSuperview() } } didSet { for view in self.views { view.translatesAutoresizingMaskIntoConstraints = false view.setContentCompressionResistancePriority(self.contentCompressionResistancePriority(for: .horizontal), for: .horizontal) view.setContentCompressionResistancePriority(self.contentCompressionResistancePriority(for: .vertical), for: .vertical) view.setContentHuggingPriority(self.contentHuggingPriority(for: .horizontal), for: .horizontal) view.setContentHuggingPriority(self.contentHuggingPriority(for: .vertical), for: .vertical) self.addSubview(view) } self.setNeedsUpdateConstraints() } } private var _constraints: [NSLayoutConstraint] = [] { willSet { self.removeConstraints(self._constraints) } didSet { self.addConstraints(self._constraints) } } public override func setup() { super.setup() self.backgroundColor = UIColor.clear self.translatesAutoresizingMaskIntoConstraints = false } public override func updateConstraints() { super.updateConstraints() var constraints: [NSLayoutConstraint] = [] if self.views.count > 0 { var lastView: UIView? = nil for view in self.views { constraints.append(view.topLayout == self.topLayout) if let lastView = lastView { constraints.append(view.leadingLayout == lastView.trailingLayout.offset(self.spacing)) } else { constraints.append(view.leadingLayout == self.leadingLayout) } constraints.append(view.bottomLayout == self.bottomLayout) lastView = view } if let lastView = lastView { constraints.append(lastView.trailingLayout == self.trailingLayout) } } else { constraints.append(self.widthLayout == 0) } self._constraints = constraints } } }
mit
c015e2f902125c2c5346afd3e03b4c3c
39.895013
143
0.578653
5.717798
false
false
false
false
MTR2D2/TIY-Assignments
VenueMenu/VenueMenu/Extensions.swift
1
1357
// // Extensions.swift // VenueMenu // // Created by Michael Reynolds on 12/3/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit extension UIImageView { func downloadImageFrom(imageURL: String) { let formattedImageURL = imageURL.stringByReplacingOccurrencesOfString("\\", withString: "") if let URL = NSURL(string: formattedImageURL) { let task = NSURLSession.sharedSession().dataTaskWithURL(URL, completionHandler: { (imageData, _, error) -> Void in if imageData != nil { if let image = UIImage(data: imageData!) { self.contentMode = .ScaleToFill dispatch_async(dispatch_get_main_queue(), { () -> Void in self.image = image }) } } else { print(error?.localizedDescription) // self.image = UIImage(named: "na.png") } })//.resume() task.resume() } else { print("URL was invalid \(imageURL)") } } }
cc0-1.0
7b90f986e86f084bf22d0e70fd51f954
26.693878
99
0.433628
5.770213
false
false
false
false
JGiola/swift-package-manager
Sources/Utility/Versioning.swift
2
2830
/* 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 Swift project authors */ import clibc /// A Swift version number. /// /// Note that these are *NOT* semantically versioned numbers. public struct SwiftVersion { /// The version number. public var version: (major: Int, minor: Int, patch: Int) /// Whether or not this is a development version. public var isDevelopment: Bool /// Build information, as an unstructured string. public var buildIdentifier: String? /// The major component of the version number. public var major: Int { return version.major } /// The minor component of the version number. public var minor: Int { return version.minor } /// The patch component of the version number. public var patch: Int { return version.patch } /// The version as a readable string. public var displayString: String { var result = "\(major).\(minor).\(patch)" if isDevelopment { result += "-dev" } if let buildIdentifier = self.buildIdentifier { result += " (" + buildIdentifier + ")" } return result } /// The complete product version display string (including the name). public var completeDisplayString: String { var vendorPrefix = String(cString: SPM_VendorNameString()) if !vendorPrefix.isEmpty { vendorPrefix += " " } return vendorPrefix + "Swift Package Manager - Swift " + displayString } /// The list of version specific identifiers to search when attempting to /// load version specific package or version information, in order of /// preference. public var versionSpecificKeys: [String] { return [ "@swift-\(major).\(minor).\(patch)", "@swift-\(major).\(minor)", "@swift-\(major)", ] } } private func getBuildIdentifier() -> String? { let buildIdentifier = String(cString: SPM_BuildIdentifierString()) return buildIdentifier.isEmpty ? nil : buildIdentifier } /// Version support for the package manager. public struct Versioning { /// The current version of the package manager. public static let currentVersion = SwiftVersion( version: (5, 0, 0), isDevelopment: false, buildIdentifier: getBuildIdentifier()) /// The list of version specific "keys" to search when attempting to load /// version specific package or version information, in order of preference. public static let currentVersionSpecificKeys = currentVersion.versionSpecificKeys }
apache-2.0
2baf612815f1b6067a61c384a5d15e01
32.690476
85
0.665371
4.76431
false
false
false
false
phimage/MomXML
Sources/FromXML/MomFetchIndex+FromXML.swift
1
1772
// // MomFetchIndex+FromXML.swift // MomXML // // Created by Eric Marchand on 09/10/2019. // Copyright © 2019 phimage. All rights reserved. // import Foundation extension MomFetchIndex: XMLObject { public init?(xml: XML) { guard let element = xml.element, element.name == "fetchIndex" else { return nil } guard let name = element.attribute(by: "name")?.text else { return nil } self.init(name: name) for child in xml.children { if let entry = MomFetchIndexElement(xml: child) { self.elements.append(entry) } else { MomXML.orphanCallback?(xml, MomFetchIndexElement.self) } } } } extension MomFetchIndexElement: XMLObject { public init?(xml: XML) { guard let element = xml.element, element.name == "fetchIndexElement" else { return nil } guard let typeString = element.attribute(by: "type")?.text, let type = MomFetchIndexElementType(rawValue: typeString.lowercased()), let order = element.attribute(by: "order")?.text else { return nil } if let property = element.attribute(by: "property")?.text { self.init(property: property, type: type, order: order) } else if let expression = element.attribute(by: "expression")?.text, let expressionTypeString = element.attribute(by: "expressionType")?.text, let expressionType = MomAttribute.AttributeType(rawValue: expressionTypeString) { self.init(expression: expression, expressionType: expressionType, type: type, order: order) } else { return nil // unknown type } } }
mit
38e9492552e4347a6e36ee45d26bf5c7
31.2
103
0.595709
4.247002
false
false
false
false
lovehhf/edx-app-ios
Source/CourseOutlineTableSource.swift
1
7187
// // CourseOutlineTableSource.swift // edX // // Created by Akiva Leffert on 4/30/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit protocol CourseOutlineTableControllerDelegate : class { func outlineTableController(controller : CourseOutlineTableController, choseBlock:CourseBlock, withParentID:CourseBlockID) func outlineTableController(controller : CourseOutlineTableController, choseDownloadVideosRootedAtBlock:CourseBlock) } class CourseOutlineTableController : UITableViewController, CourseVideoTableViewCellDelegate, CourseSectionTableViewCellDelegate { weak var delegate : CourseOutlineTableControllerDelegate? private let courseID : String private let headerContainer = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 44)) private let lastAccessedView = CourseOutlineHeaderView(frame: CGRectZero, styles: OEXStyles.sharedStyles(), titleText : OEXLocalizedString("LAST_ACCESSED", nil), subtitleText : "Placeholder") let refreshController = PullRefreshController() init(courseID : String) { self.courseID = courseID super.init(nibName: nil, bundle: nil) } required init!(coder aDecoder: NSCoder!) { fatalError("init(coder:) has not been implemented") } var groups : [CourseOutlineQuerier.BlockGroup] = [] override func viewDidLoad() { tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView(frame: CGRectZero) tableView.registerClass(CourseOutlineHeaderCell.self, forHeaderFooterViewReuseIdentifier: CourseOutlineHeaderCell.identifier) tableView.registerClass(CourseVideoTableViewCell.self, forCellReuseIdentifier: CourseVideoTableViewCell.identifier) tableView.registerClass(CourseHTMLTableViewCell.self, forCellReuseIdentifier: CourseHTMLTableViewCell.identifier) tableView.registerClass(CourseProblemTableViewCell.self, forCellReuseIdentifier: CourseProblemTableViewCell.identifier) tableView.registerClass(CourseUnknownTableViewCell.self, forCellReuseIdentifier: CourseUnknownTableViewCell.identifier) tableView.registerClass(CourseSectionTableViewCell.self, forCellReuseIdentifier: CourseSectionTableViewCell.identifier) headerContainer.addSubview(lastAccessedView) lastAccessedView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self.headerContainer) } refreshController.setupInScrollView(self.tableView) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return groups.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let group = groups[section] return group.children.count } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // Will remove manual heights when dropping iOS7 support and move to automatic cell heights. return 60.0 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let group = groups[section] let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(CourseOutlineHeaderCell.identifier) as! CourseOutlineHeaderCell header.block = group.block return header } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let group = groups[indexPath.section] let nodes = group.children let block = nodes[indexPath.row] switch nodes[indexPath.row].displayType { case .Video: let cell = tableView.dequeueReusableCellWithIdentifier(CourseVideoTableViewCell.identifier, forIndexPath: indexPath) as! CourseVideoTableViewCell cell.block = block cell.localState = OEXInterface.sharedInterface().stateForVideoWithID(block.blockID, courseID : courseID) cell.delegate = self return cell case .HTML(.Base): let cell = tableView.dequeueReusableCellWithIdentifier(CourseHTMLTableViewCell.identifier, forIndexPath: indexPath) as! CourseHTMLTableViewCell cell.block = block return cell case .HTML(.Problem): let cell = tableView.dequeueReusableCellWithIdentifier(CourseProblemTableViewCell.identifier, forIndexPath: indexPath) as! CourseProblemTableViewCell cell.block = block return cell case .Unknown: let cell = tableView.dequeueReusableCellWithIdentifier(CourseUnknownTableViewCell.identifier, forIndexPath: indexPath) as! CourseUnknownTableViewCell cell.block = block return cell case .Outline, .Unit: var cell = tableView.dequeueReusableCellWithIdentifier(CourseSectionTableViewCell.identifier, forIndexPath: indexPath) as! CourseSectionTableViewCell cell.block = nodes[indexPath.row] cell.delegate = self return cell } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let group = groups[indexPath.section] let chosenBlock = group.children[indexPath.row] self.delegate?.outlineTableController(self, choseBlock: chosenBlock, withParentID: group.block.blockID) } override func scrollViewDidScroll(scrollView: UIScrollView) { self.refreshController.scrollViewDidScroll(scrollView) } func videoCellChoseDownload(cell: CourseVideoTableViewCell, block : CourseBlock) { self.delegate?.outlineTableController(self, choseDownloadVideosRootedAtBlock: block) } func sectionCellChoseDownload(cell: CourseSectionTableViewCell, block: CourseBlock) { self.delegate?.outlineTableController(self, choseDownloadVideosRootedAtBlock: block) } func choseViewLastAccessedWithItem(item : CourseLastAccessed) { for group in groups { let childNodes = group.children let currentLastViewedIndex = childNodes.firstIndexMatching({$0.blockID == item.moduleId}) if let matchedIndex = currentLastViewedIndex { self.delegate?.outlineTableController(self, choseBlock: childNodes[matchedIndex], withParentID: group.block.blockID) break } } } /// Shows the last accessed Header from the item as argument. Also, sets the relevant action if the course block exists in the course outline. func showLastAccessedWithItem(item : CourseLastAccessed) { tableView.tableHeaderView = self.headerContainer lastAccessedView.subtitleText = item.moduleName lastAccessedView.setViewButtonAction { [weak self] _ in self?.choseViewLastAccessedWithItem(item) } } func hideLastAccessed() { tableView.tableHeaderView = nil } }
apache-2.0
054d51ef9d4273a3b2c3ab44cc374d71
46.289474
195
0.721302
5.641287
false
false
false
false
firebase/firebase-ios-sdk
FirebaseMessaging/Apps/AdvancedSample/NotificationServiceExtension/NotificationService.swift
2
2113
// Copyright 2020 Google LLC // // 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 UserNotifications import FirebaseMessaging class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { // Modify the notification content here... bestAttemptContent.title = "\(bestAttemptContent.title) 👩🏻‍💻" // Log Delivery signals and export to BigQuery. Messaging.serviceExtension() .exportDeliveryMetricsToBigQuery(withMessageInfo: request.content.userInfo) // Add image, call this last to finish with the content handler. Messaging.serviceExtension() .populateNotificationContent(bestAttemptContent, withContentHandler: contentHandler) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
apache-2.0
d2641b1d576f0a6e7a74fa9e4c096f41
41.897959
135
0.739296
5.417526
false
false
false
false
tarunon/RxExtensions
RxExtensions/Throttle3.swift
1
4562
// // Throttle2.swift // RxExtensions // // Created by Nobuo Saito on 2016/07/22. // Copyright © 2016年 tarunon. All rights reserved. // import Foundation import RxSwift import RxCocoa class Throttle3Sink<O: ObserverType> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType { typealias E = O.E typealias Element = O.E typealias ParentType = Throttle3<Element> typealias DisposeKey = CompositeDisposable.DisposeKey private let _parent: ParentType let _lock = NSRecursiveLock() // state private var _id = 0 as UInt64 private var _value: Element? = nil private var _dropping: Bool = false let cancellable = CompositeDisposable() init(parent: ParentType, observer: O) { _parent = parent super.init(observer: observer) } func run() -> Disposable { let subscription = _parent._source.subscribe(self) return Disposables.create(subscription, cancellable) } func on(_ event: Event<Element>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<Element>) { switch event { case .next(let element): _id = _id &+ 1 let currentId = _id let d = SingleAssignmentDisposable() if let key = self.cancellable.insert(d) { _value = element if _dropping { d.setDisposable(Disposables.create( _parent._scheduler.scheduleRelative((currentId), dueTime: _parent._dueTime, action: self.propagate), _parent._scheduler.scheduleRelative((currentId, key), dueTime: _parent._dueTime, action: self.endDrop) )) } else { _dropping = true d.setDisposable(Disposables.create( _parent._scheduler.scheduleRelative((), dueTime: 0.0, action: self.propagate), _parent._scheduler.scheduleRelative((currentId, key), dueTime: _parent._dueTime, action: self.endDrop) )) } } case .error: _value = nil forwardOn(event) dispose() case .completed: if let value = _value { _value = nil forwardOn(.next(value)) } forwardOn(.completed) dispose() } } func propagate() -> Disposable { _lock.lock(); defer { _lock.unlock() } // { if let value = _value { _value = nil forwardOn(.next(value)) } // } return Disposables.create() } func propagate(currentId: UInt64) -> Disposable { _lock.lock(); defer { _lock.unlock() } // { if let value = _value, currentId == _id { _value = nil forwardOn(.next(value)) } // } return Disposables.create() } func endDrop(currentId: UInt64, key: DisposeKey) -> Disposable { _lock.lock(); defer { _lock.unlock() } // { cancellable.remove(for: key) if currentId == _id { _dropping = false } // } return Disposables.create() } } class Throttle3<Element> : Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _dueTime: RxTimeInterval fileprivate let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) { _source = source _dueTime = dueTime _scheduler = scheduler } override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element { let sink = Throttle3Sink(parent: self, observer: observer) sink.setDisposable(sink.run()) return sink } } extension ObservableType { /** throttle3 is like of throttle2, and send last event after wait dueTime. */ public func throttle3(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Observable<Self.E> { return Throttle3(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler).asObservable() } } extension SharedSequence { /** throttle3 is like of throttle2, and send last event after wait dueTime. */ public func throttle3(_ dueTime: RxTimeInterval) -> SharedSequence { return Throttle3(source: self.asObservable(), dueTime: dueTime, scheduler: MainScheduler.instance).asSharedSequence(onErrorDriveWith: SharedSequence.empty()) } }
mit
77866a3575ba5853bef0103c026dd80f
28.993421
165
0.581268
4.714581
false
false
false
false
spritekitbook/spritekitbook-swift
Chapter 6/Start/SpaceRunner/SpaceRunner/Math.swift
2
1265
// // Math.swift // SpaceRunner // // Created by Jeremy Novak on 8/30/16. // Copyright © 2016 Spritekit Book. All rights reserved. // import SpriteKit func DegreesToRadians(degrees: CGFloat) -> CGFloat { return degrees * CGFloat(M_PI) / 180.0 } func RadiansToDegrees(radians: CGFloat) -> CGFloat { return radians * 180.0 / CGFloat(M_PI) } func Smooth(startPoint: CGFloat, endPoint: CGFloat, percentToMove: CGFloat) -> CGFloat { return (startPoint * (1 - percentToMove)) + endPoint * percentToMove } func AngleBetweenPoints(targetPosition: CGPoint, currentPosition: CGPoint) -> CGFloat { let deltaX = targetPosition.x - currentPosition.x let deltaY = targetPosition.y - currentPosition.y return CGFloat(atan2(Float(deltaY), Float(deltaX))) - DegreesToRadians(degrees: 90) } func DistanceBetweenPoints(firstPoint: CGPoint, secondPoint: CGPoint) -> CGFloat { return CGFloat(hypotf(Float(secondPoint.x - firstPoint.x), Float(secondPoint.y - firstPoint.y))) } func Clamp(value: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { var newMin = min var newMax = max if (min > max) { newMin = max newMax = min } return value < newMin ? newMin : value < newMax ? value : newMax }
apache-2.0
8c41e18c861cc42aa533b5b5d7b9e3b5
27.088889
100
0.682753
3.853659
false
false
false
false
PerfectExamples/staffDirectory
Sources/staffDirectory/handlers/HandlerHelpers.swift
2
1620
// // HandlerHelpers.swift // Perfect-App-Template // // Created by Jonathan Guthrie on 2017-04-01. // // import PerfectHTTP import StORM extension Handlers { static func error(_ request: HTTPRequest, _ response: HTTPResponse, error: String, code: HTTPResponseStatus = .badRequest) { do { response.status = code try response.setBody(json: ["error": "\(error)"]) } catch { print(error) } response.completed() } static func unimplemented(data: [String:Any]) throws -> RequestHandler { return { request, response in response.status = .notImplemented response.completed() } } // Common helper function to dump rows to JSON static func nestedDataDict(_ rows: [StORM]) -> [Any] { var d = [Any]() for i in rows { d.append(i.asDataDict()) } return d } // Used for healthcheck functionality for monitors and load balancers. // Do not remove unless you have an alternate plan static func healthcheck(data: [String:Any]) throws -> RequestHandler { return { request, response in let _ = try? response.setBody(json: ["health": "ok"]) response.completed() } } // Handles psuedo redirects. // Will serve up alternate content, for example if you wish to report an error condition, like missing data. static func redirectRequest(_ request: HTTPRequest, _ response: HTTPResponse, msg: String, template: String, additional: [String:String] = [String:String]()) { var context: [String : Any] = [ "msg": msg ] for i in additional { context[i.0] = i.1 } response.render(template: template, context: context) response.completed() return } }
apache-2.0
7be79cf376a4c7347980ca2cc4018b3e
23.179104
160
0.681481
3.483871
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyerTests/Pipelines/PublicPipelinesViewControllerSpec.swift
1
14310
import XCTest import Quick import Nimble import Fleet import RxSwift @testable import FrequentFlyer class PublicPipelinesViewControllerSpec: QuickSpec { class MockPublicPipelinesDataStreamProducer: PublicPipelinesDataStreamProducer { var pipelinesGroupsSubject = PublishSubject<[PipelineGroupSection]>() var capturedConcourseURL: String? override func openStream(forConcourseWithURL concourseURL: String) -> Observable<[PipelineGroupSection]> { capturedConcourseURL = concourseURL return pipelinesGroupsSubject } } override func spec() { describe("PublicPipelinesViewController"){ var subject: PublicPipelinesViewController! var mockPublicPipelinesDataStreamProducer: MockPublicPipelinesDataStreamProducer! var mockJobsViewController: JobsViewController! var mockTeamsViewController: TeamsViewController! var mockConcourseEntryViewController: ConcourseEntryViewController! beforeEach { let storyboard = UIStoryboard(name: "Main", bundle: nil) subject = storyboard.instantiateViewController(withIdentifier: PublicPipelinesViewController.storyboardIdentifier) as! PublicPipelinesViewController mockJobsViewController = try! storyboard.mockIdentifier(JobsViewController.storyboardIdentifier, usingMockFor: JobsViewController.self) mockTeamsViewController = try! storyboard.mockIdentifier(TeamsViewController.storyboardIdentifier, usingMockFor: TeamsViewController.self) mockConcourseEntryViewController = try! storyboard.mockIdentifier(ConcourseEntryViewController.storyboardIdentifier, usingMockFor: ConcourseEntryViewController.self) subject.concourseURLString = "concourseURL" mockPublicPipelinesDataStreamProducer = MockPublicPipelinesDataStreamProducer() subject.publicPipelinesDataStreamProducer = mockPublicPipelinesDataStreamProducer } describe("After the view has loaded") { beforeEach { _ = Fleet.setInAppWindowRootNavigation(subject) } it("sets the title") { expect(subject.title).to(equal("Pipelines")) } it("sets the data source as the delegate of the table view") { expect(subject.pipelinesTableView?.rx.delegate.forwardToDelegate()).toEventually(beIdenticalTo(subject.publicPipelinesTableViewDataSource)) } it("opens the data stream") { expect(mockPublicPipelinesDataStreamProducer.capturedConcourseURL).to(equal("concourseURL")) } it("has an active loading indicator") { expect(subject.loadingIndicator?.isAnimating).toEventually(beTrue()) expect(subject.loadingIndicator?.isHidden).toEventually(beFalse()) } it("hides the table views row lines while there is no content") { expect(subject.pipelinesTableView?.separatorStyle).toEventually(equal(UITableViewCellSeparatorStyle.none)) } describe("Tapping the gear in the navigation item") { beforeEach { subject.gearBarButtonItem?.tap() } describe("Tapping the 'Log Into a Team' button in the action sheet") { it("sends the app to the \(TeamsViewController.self)") { let actionSheet: () -> UIAlertController? = { return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController } var actionSheetDidAppear = false var didAttemptLogIntoATeamTap = false let assertDidBeginLoggingIntoATeam: () -> Bool = { if !actionSheetDidAppear { if actionSheet() != nil { actionSheetDidAppear = true } return false } if !didAttemptLogIntoATeamTap { actionSheet()!.tapAlertAction(withTitle: "Log Into a Team") didAttemptLogIntoATeamTap = true return false } return Fleet.getApplicationScreen()?.topmostViewController === mockTeamsViewController } expect(assertDidBeginLoggingIntoATeam()).toEventually(beTrue()) } } describe("Tapping the 'Select a Concourse' button in the action sheet") { it("sends the app to the \(ConcourseEntryViewController.self)") { let actionSheet: () -> UIAlertController? = { return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController } var actionSheetDidAppear = false var didAttemptSelectAConcourseTap = false let assertDidBeginSelectingAConcourse: () -> Bool = { if !actionSheetDidAppear { if actionSheet() != nil { actionSheetDidAppear = true } return false } if !didAttemptSelectAConcourseTap { actionSheet()!.tapAlertAction(withTitle: "Select a Concourse") didAttemptSelectAConcourseTap = true return false } return Fleet.getApplicationScreen()?.topmostViewController === mockConcourseEntryViewController } expect(assertDidBeginSelectingAConcourse()).toEventually(beTrue()) } } describe("Tapping the 'Cancel' button in the action sheet") { it("dismisses the action sheet") { let actionSheet: () -> UIAlertController? = { return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController } var actionSheetDidAppear = false var didAttemptLogOutTap = false let assertDidDismissActionSheet: () -> Bool = { if !actionSheetDidAppear { if actionSheet() != nil { actionSheetDidAppear = true } return false } if !didAttemptLogOutTap { actionSheet()!.tapAlertAction(withTitle: "Cancel") didAttemptLogOutTap = true return false } return Fleet.getApplicationScreen()?.topmostViewController === subject } expect(assertDidDismissActionSheet()).toEventually(beTrue()) } } } describe("When the public pipelines data stream spits out some pipelines") { beforeEach { let pipelineOne = Pipeline(name: "pipeline one", isPublic: true, teamName: "cat") let pipelineTwo = Pipeline(name: "pipeline two", isPublic: true, teamName: "turtle") let pipelineThree = Pipeline(name: "pipeline three", isPublic: true, teamName: "dog") var catSection = PipelineGroupSection() catSection.items.append(pipelineOne) var turtleSection = PipelineGroupSection() turtleSection.items.append(pipelineTwo) var dogSection = PipelineGroupSection() dogSection.items.append(pipelineThree) mockPublicPipelinesDataStreamProducer.pipelinesGroupsSubject.onNext([catSection, turtleSection, dogSection]) mockPublicPipelinesDataStreamProducer.pipelinesGroupsSubject.onCompleted() RunLoop.main.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 1)) } it("stops and hides the loading indicator") { expect(subject.loadingIndicator?.isAnimating).toEventually(beFalse()) expect(subject.loadingIndicator?.isHidden).toEventually(beTrue()) } it("shows the table views row lines") { expect(subject.pipelinesTableView?.separatorStyle).toEventually(equal(UITableViewCellSeparatorStyle.singleLine)) } it("creates a cell in each of the rows for each of the pipelines returned") { let cellOne = subject.pipelinesTableView!.fetchCell(at: IndexPath(row: 0, section: 0), asType: PipelineTableViewCell.self) expect(cellOne.nameLabel?.text).to(equal("pipeline one")) let cellTwo = subject.pipelinesTableView!.fetchCell(at: IndexPath(row: 0, section: 1), asType: PipelineTableViewCell.self) expect(cellTwo.nameLabel?.text).to(equal("pipeline two")) } describe("Tapping one of the cells") { beforeEach { subject.pipelinesTableView!.selectRow(at: IndexPath(row: 0, section: 0)) } it("sets up and presents the pipeline's jobs page") { func jobsViewController() -> JobsViewController? { return Fleet.getApplicationScreen()?.topmostViewController as? JobsViewController } expect(jobsViewController()).toEventually(beIdenticalTo(mockJobsViewController)) expect(jobsViewController()?.pipeline).toEventually(equal(Pipeline(name: "pipeline one", isPublic: true, teamName: "cat"))) expect(jobsViewController()?.target).toEventually(beNil()) expect(jobsViewController()?.dataStream).toEventually(beAKindOf(PublicJobsDataStream.self)) expect((jobsViewController()?.dataStream as? PublicJobsDataStream)?.concourseURL).toEventually(equal("concourseURL")) } it("immediately deselects the cell") { let selectedCell = subject.pipelinesTableView?.cellForRow(at: IndexPath(row: 0, section: 0)) expect(selectedCell).toEventuallyNot(beNil()) expect(selectedCell?.isHighlighted).toEventually(beFalse()) expect(selectedCell?.isSelected).toEventually(beFalse()) } } } describe("When the public pipelines data stream emits an error") { beforeEach { mockPublicPipelinesDataStreamProducer.pipelinesGroupsSubject.onError(UnexpectedError("")) RunLoop.main.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 1)) } it("stops and hides the loading indicator") { expect(subject.loadingIndicator?.isAnimating).toEventually(beFalse()) expect(subject.loadingIndicator?.isHidden).toEventually(beTrue()) } it("shows the table views row lines") { expect(subject.pipelinesTableView?.separatorStyle).toEventually(equal(UITableViewCellSeparatorStyle.singleLine)) } it("presents an alert describing the error") { let alert: () -> UIAlertController? = { return Fleet.getApplicationScreen()?.topmostViewController as? UIAlertController } expect(alert()).toEventuallyNot(beNil()) expect(alert()?.title).toEventually(equal("Error")) expect(alert()?.message).toEventually(equal("An unexpected error has occurred. Please try again.")) } describe("Tapping the 'OK' button on the alert") { it("dismisses the alert") { let screen = Fleet.getApplicationScreen() var didTapOK = false let assertOKTappedBehavior = { () -> Bool in if didTapOK { return screen?.topmostViewController === subject } if let alert = screen?.topmostViewController as? UIAlertController { alert.tapAlertAction(withTitle: "OK") didTapOK = true } return false } expect(assertOKTappedBehavior()).toEventually(beTrue()) } } } } } } }
apache-2.0
353027fb1ee30723bd283ff03547bde4
51.226277
181
0.518169
6.876502
false
false
false
false
sfurlani/addsumfun
Add Sum Fun/Add Sum Fun/Game.swift
1
1846
// // Game.swift // Add Sum Fun // // Created by SFurlani on 8/26/15. // Copyright © 2015 Dig-It! Games. All rights reserved. // import Foundation import CoreGraphics protocol GameType { var equations: [EquationType] { get } var answers: [AnswerType] { get } var currentEquation: EquationType? { get } func score() -> CGFloat? mutating func addNewRound() -> () mutating func addNewAnswer(answer: UInt) -> AnswerType? } extension GameType { var currentEquation: EquationType? { guard equations.count > answers.count else { return nil } return equations[answers.count] } func score() -> CGFloat? { guard equations.count == answers.count else { return nil } let correct = answers.reduce(0) { (count: UInt, answer: AnswerType) -> UInt in return count + (answer.isCorrect() ? 1 : 0) } return CGFloat(correct) / CGFloat(equations.count) } } class GameData : GameType { private(set) var equations: [EquationType] private(set) var answers: [AnswerType] let roundSize: UInt init(roundSize: UInt = 5) { self.roundSize = roundSize equations = self.roundSize.repeatMap { (index: UInt) in return Addition() } answers = [AnswerType]() } func addNewRound() { equations = equations + roundSize.repeatMap { (index: UInt) in return Addition() } } func addNewAnswer(answer: UInt) -> AnswerType? { if let equation = currentEquation { let answer = Answer(entered:answer, equation: equation) answers.append(answer) return answer } else { return nil } } }
mit
8b4c1facff73a95108a8a737f09dd1f4
22.961039
86
0.56477
4.310748
false
false
false
false
kleiram/Faker
Source/Classes/Internet.swift
1
9276
// Internet.swift // // Copyright (c) 2014–2015 Apostle (http://apostle.nl) // // 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 class Internet { // MARK: Provider public class Provider { public init() { // noop } func urlFormats() -> [String] { return [ "http://\(Internet.domainName())", "http://www.\(Internet.domainName())", "http://www.\(Internet.domainName())/\(Internet.slug())", "http://www.\(Internet.domainName())/\(Internet.slug())", "https://www.\(Internet.domainName())/\(Internet.slug())", "http://www.\(Internet.domainName())/\(Internet.slug()).html", "http://\(Internet.domainName())/\(Internet.slug())", "http://\(Internet.domainName())/\(Internet.slug())", "http://\(Internet.domainName())/\(Internet.slug()).html", "https://\(Internet.domainName())/\(Internet.slug()).html", ] } func emailFormats() -> [String] { return [ "\(Internet.username())@\(Internet.domainName())", "\(Internet.username())@\(Internet.freeEmailDomain())", "\(Internet.username())@\(Internet.safeEmailDomain())", ] } func usernameFormats() -> [String] { return [ "\(Person.lastName()).\(Person.firstName())", "\(Person.firstName()).\(Person.lastName())", "\(Person.firstName())##", "?\(Person.lastName())", ] } func tlds() -> [String] { return [ "com", "com", "com", "com", "com", "com", "biz", "info", "net", "org" ] } func freeEmailDomains() -> [String] { return [ "gmail.com", "yahoo.com", "hotmail.com", ] } } // MARK: Variables public static var provider : Provider? // MARK: Generators /** Generate a random e-mail address. - note: There is a chance that this e-mail address is actually in use, if you want to send e-mail, use the `safeEmail` method instead. - returns: Returns a random e-mail address. */ public class func email() -> String { return dataProvider().emailFormats().random()! } /** Generate a random safe e-mail address. - returns: Returns a random safe e-mail address. */ public class func safeEmail() -> String { return "\(username())@\(safeEmailDomain())" } /** Generate a random free e-mail address. - note: There is a chance that this e-mail address is actually in use, if you want to send e-mail, use the `safeEmail` method instead. - returns: Returns a random free e-mail address. */ public class func freeEmail() -> String { return "\(username())@\(freeEmailDomain())" } /** Generate a random company e-mail address. - note: There is a chance that this e-mail address is actually in use, if you want to send e-mail, use the `safeEmail` method instead. - returns: Returns a random company e-mail address. */ public class func companyEmail() -> String { return "\(username())@\(domainName())" } /** Generate a random free e-mail domain. - returns: Returns a random free e-mail domain. */ public class func freeEmailDomain() -> String { return dataProvider().freeEmailDomains().random()! } /** Generate a random safe e-mail domain. - returns: Returns a random safe e-mail domain. */ public class func safeEmailDomain() -> String { return [ "example.com", "example.org", "example.net" ].random()! } /** Generate a random username. - returns: Returns a random username. */ public class func username() -> String { let result = dataProvider().usernameFormats().random()! return result.numerify().lexify().lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: ".") } /** Generate a random password of at least `minLength` and at most `maxLength` characters. - parameter minLength: The minimum length of the password. - parameter maxLength: The maximum length of the password. - returns: Returns a password of at least `minLength` and at most `maxLength` characters. */ public class func password(minLength : Int = 6, maxLength : Int = 20) -> String { let format = Array(count: Int.random(minLength, max: maxLength), repeatedValue: "*").joinWithSeparator("") return format.lexify() } /** Generate a random domain name. - returns: Returns a random domain name. */ public class func domainName() -> String { return "\(domainWord()).\(tld())" } /** Generate a random domain word. - returns: Returns a random domain word. */ public class func domainWord() -> String { return "\(Person.lastName())".lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: "-") } /** Generate a random top-level domain (TLD). - returns: Returns a random TLD. */ public class func tld() -> String { return dataProvider().tlds().random()! } /** Generate a random URL. - returns: Returns a random URL. */ public class func url() -> String { return dataProvider().urlFormats().random()! } /** Generate a random slug. - parameter nbWords: The number of words the slug should contain. - parameter variable: If `true`, the number of sentences will vary between +/- 40% of `nbSentences`. - returns: Returns a random slug of `nbWords` words. */ public class func slug(nbWords : Int = 6, variable : Bool = true) -> String { if nbWords <= 0 { return "" } return Lorem.words(variable ? nbWords.randomize(40) : nbWords).joinWithSeparator("-").lowercaseString } /** Generate a random IPv4 address. - returns: Returns a random IPv4 address. */ public class func ipv4() -> String { return [ Int.random(0, max: 255), Int.random(0, max: 255), Int.random(0, max: 255), Int.random(0, max: 255) ].map(String.init).joinWithSeparator(".") } /** Generate a random IPv6 address. - returns: Returns a random IPv6 address. */ public class func ipv6() -> String { let components = (0..<8).map { _ in Int.random(0, max: 65535) } return components.map({ String(format: "%04x", arguments: [ $0 ]) }).joinWithSeparator(":") } /** Generate a random local IPv4 address. - returns: Returns a random local IPv4 address. */ public class func localIpv4() -> String { var prefix : String = "" var components : [String] = [String]() if Int.random(0, max: 1) == 0 { prefix = "10." components = (0..<3).map({ _ in Int.random(0, max: 255) }).map(String.init) } else { prefix = "192.168." components = (0..<2).map({ _ in Int.random(0, max: 255) }).map(String.init) } return prefix + components.joinWithSeparator(".") } /** Generate a random MAC address. - returns: Returns a random MAC address. */ public class func mac() -> String { let components = (0..<6).map { _ in Int.random(0, max: 255) } return components.map({ String(format: "%02X", arguments: [ $0 ]) }).joinWithSeparator(":") } private class func dataProvider() -> Provider { return provider ?? Provider() } }
mit
e3c9bb77eaf037d511e8a73b67d2636c
31.426573
116
0.557257
4.681474
false
false
false
false
lennet/languini
app/LanguageQuiz/LanguageQuiz/ShadowView.swift
1
1201
// // ShadowView.swift // Languini // // Created by Leo Thomas on 03/07/15. // Copyright (c) 2015 Coding Da Vinci. All rights reserved. // import UIKit //@IBDesignable // not supported for iOS 7 class ShadowView: UIView { var color: UIColor = UIColor(red: 0.295, green: 0.695, blue: 0.900, alpha: 0.970) var radius: CGFloat = 1 var opacity: CGFloat = 0.8 var shadowOffset: CGSize = CGSize(width: 2, height: 2) var shadowBrightness: CGFloat = 0.5 func setShadow() { self.backgroundColor = color self.layer.shadowColor = shadowColor() self.layer.shadowOpacity = Float(opacity); self.layer.shadowRadius = radius self.layer.shadowOffset = shadowOffset } func shadowColor() -> CGColorRef { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return UIColor(hue: hue, saturation: saturation, brightness: (brightness * shadowBrightness), alpha: alpha).CGColor } override func awakeFromNib() { setShadow() } }
bsd-2-clause
5c06dacb9452fd4d87e848dd9fc85e25
22.54902
123
0.635304
4.071186
false
false
false
false
kingcos/CS193P_2017
Calculator/Calculator/ViewController.swift
1
4091
// // ViewController.swift // Calculator // // Created by 买明 on 15/02/2017. // Copyright © 2017 买明. All rights reserved. // [Powered by kingcos](https://github.com/kingcos/CS193P_2017) import UIKit class ViewController: UIViewController { @IBOutlet weak var display: UILabel! private var brain = CalculatorBrain() // 存储属性 var userIsInTheMiddleOfTyping = false // 计算属性 var displayValue: Double { get { return Double(display.text!)! } set { display.text = String(newValue) } } @IBAction func touchDigit(_ sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddleOfTyping { let textCurrentlyInDisplay = display.text! display.text = textCurrentlyInDisplay + digit } else { display.text = digit userIsInTheMiddleOfTyping = true } } @IBAction func performOperation(_ sender: UIButton) { if userIsInTheMiddleOfTyping { brain.setOperand(displayValue) userIsInTheMiddleOfTyping = false } if let mathematicalSymbol = sender.currentTitle { brain.performOperation(mathematicalSymbol) } if let result = brain.result { displayValue = result } } // Lecture 12 private func showSizeClasses() { if !userIsInTheMiddleOfTyping { display.textAlignment = .center display.text = "width " + traitCollection.horizontalSizeClass.description + " height " + traitCollection.verticalSizeClass.description } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) showSizeClasses() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (coordinator) in self.showSizeClasses() }, completion: nil) } override func viewDidLoad() { // brain.addUnaryOperation(named: "✅") { (value) -> Double in // return sqrt(value) // } // brain.addUnaryOperation(named: "✅") { // return sqrt($0) // } // brain.addUnaryOperation(named: "✅") { // self.display.textColor = UIColor.green // return sqrt($0) // } // weak // brain.addUnaryOperation(named: "✅") { [weak self] in // // self 为 Optional // self?.display.textColor = UIColor.green // return sqrt($0) // } // // brain.addUnaryOperation(named: "✅") { [weak weakSelf = self] in // weakSelf?.display.textColor = UIColor.green // return sqrt($0) // } // unowned // brain.addUnaryOperation(named: "✅") { [me = self] in // me.display.textColor = UIColor.green // return sqrt($0) // } // // brain.addUnaryOperation(named: "✅") { [unowned me = self] in // me.display.textColor = UIColor.green // return sqrt($0) // } // // brain.addUnaryOperation(named: "✅") { [unowned self = self] in // self.display.textColor = UIColor.green // return sqrt($0) // } brain.addUnaryOperation(named: "✅") { [unowned self] in self.display.textColor = UIColor.green return sqrt($0) } } } // Lecture 12 extension UIUserInterfaceSizeClass: CustomStringConvertible { public var description: String { switch self { case .compact: return "Compact" case .regular: return "Regular" case .unspecified: return "??" } } }
mit
30a47512a785dd0a9c9d8e5e5b0e638f
26.52381
112
0.54004
4.782506
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 1.playgroundbook/Contents/Chapters/Document5.playgroundchapter/Pages/Challenge2.playgroundpage/Sources/Assessments.swift
1
2785
// // Assessments.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // let solution: String? = nil import PlaygroundSupport public func assessmentPoint() -> AssessmentResults { let checker = ContentsChecker(contents: PlaygroundPage.current.text) pageIdentifier = "Boxed_In" var hints = [ "Any tile in the square could have a gem, an open switch, or a closed switch. First, write a function called `checkTile()` to check for each possibility on a single tile.", "You'll need to use your function to check every tile. Is there an easy way to do that?", "Try using a loop that repeats a set of commands to complete one corner of the puzzle each time.", "This puzzle is a **Challenge** and has no provided solution. Strengthen your coding skills by creating your own approach to solve it." ] let customFunction = checker.customFunctions.first ?? "" let success: String if checker.didUseForLoop == false && checker.numberOfStatements > 12 { success = "### Oops! \nYou completed the puzzle, but you forgot to include a [for loop](glossary://for%20loop). You ran \(checker.numberOfStatements) lines of code, but with a for loop, you’d need only 12. \n\nYou can try again or move on. \n\n[**Next Page**](@next)" } else if checker.didUseForLoop == true && checker.didUseConditionalStatement == false { success = "Congrats! \nYou managed to solve the puzzle by using a [for loop](glossary://for%20loop), but you didn’t include [conditional code](glossary://conditional%20code). Using `if` statements makes your code more intelligent and allows it to respond to changes in your environment. \n\nYou can try again or move on. \n\n[**Next Page**](@next)" } else if checker.didUseForLoop == true && checker.didUseConditionalStatement == true && checker.functionCallCount(forName: customFunction) == 0 { success = "### Great work! \nYour solution used both for loops and [conditional code](glossary://conditional%20code), incredible tools that make your code more intelligent and let you avoid repeating the same set of commands many times. However, you can improve your solution by writing your own custom function to check an individual tile for a gem or a closed switch. As an added challenge, try solving the puzzle by writing a custom function. Feel free to move on whenever you are ready. \n\n[**Next Page**](@next)" } else { success = "### Fantastic! \nYour solution is incredible. You've come a long way, learning conditional code and combining your new skills with functions and `for` loops! \n\n[**Next Page**](@next)" } return updateAssessment(successMessage: success, failureHints: hints, solution: solution) }
mit
a0d9c9540ce7eb601bb50d61ec7269b7
65.214286
527
0.710536
4.304954
false
false
false
false
SAP/IssieBoard
EducKeyboard/ConfigItem.swift
1
3833
// // ConfigItem.swift // MasterDetailsHelloWorld // // Created by Sasson, Kobi on 3/14/15. // Copyright (c) 2015 Sasson, Kobi. All rights reserved. // import Foundation import UIKit enum ControlsType { case TextInput case ColorPicker } enum ConfigItemType{ case String case Color case Picker case FontPicker case Templates } class ConfigItem { var UserSettings: NSUserDefaults let key: String let title: String let type: ConfigItemType let defaultValue: AnyObject? var value: AnyObject? { get{ switch self.type{ case .String: if let val = UserSettings.stringForKey(self.key) { return val } else{ return self.defaultValue } case .Color: if let val = UserSettings.stringForKey(self.key) { return UIColor(string: val) } else{ return defaultValue } case .Templates: if let val = UserSettings.stringForKey(self.key) { return val } else { return self.defaultValue } default: if let val = UserSettings.stringForKey(self.key) { return val } else{ return self.defaultValue } } } set { switch self.type{ case .String: UserSettings.setObject(newValue, forKey: self.key) UserSettings.synchronize() case .Color: if let color = (newValue as! UIColor).stringValue { if(self.key == "ISSIE_KEYBOARD_KEYS_COLOR"){ UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET1_KEYS_COLOR") UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET2_KEYS_COLOR") UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET3_KEYS_COLOR") UserSettings.synchronize() } else if(self.key == "ISSIE_KEYBOARD_TEXT_COLOR"){ UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET1_TEXT_COLOR") UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET2_TEXT_COLOR") UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET3_TEXT_COLOR") UserSettings.synchronize() } else { UserSettings.setObject(color, forKey: self.key) UserSettings.synchronize() } } default: UserSettings.setObject(newValue, forKey: self.key) UserSettings.synchronize() } } } init(key:String ,title: String, defaultValue: AnyObject?, type: ConfigItemType ){ UserSettings = NSUserDefaults(suiteName: "group.com.sap.i012387.HashtagPOC")! self.key = key self.title = title self.type = type self.defaultValue = defaultValue switch self.type{ case .String: UserSettings.setObject(defaultValue, forKey: self.key) UserSettings.synchronize() case .Color: if let color = (defaultValue as! UIColor).stringValue { UserSettings.setObject(color, forKey: self.key) UserSettings.synchronize() } default: UserSettings.setObject(defaultValue, forKey: self.key) UserSettings.synchronize() } } }
apache-2.0
c0ea9210b6e51c127bff6690810cca06
32.051724
99
0.515523
5.214966
false
false
false
false
plantain-00/demo-set
swift-demo/NewsCatcher/Ridge/Ridge/PlainTextParser.swift
1
878
// // PlainTextParser.swift // Ridge // // Created by 姚耀 on 15/1/30. // Copyright (c) 2015年 姚耀. All rights reserved. // import Foundation class PlainTextParser: ParserBase { init(strings: [String], index: Int, endIndex: Int, depth: Int) { self.depth = depth super.init(strings: strings, index: index, endIndex: endIndex) } private let depth: Int var plainText: PlainText? override func parse() { var result = StringStatic.empty do { result += strings[index] index++ } while index < endIndex && strings[index] != StringStatic.lessThan let t = result.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if t != StringStatic.empty { plainText = PlainText(text: result, depth: depth) } } }
mit
27c76428553fa8ff2b67243fe4683ec7
23.138889
105
0.612903
4.275862
false
false
false
false
cxpyear/ZSZQApp
spdbapp/spdbapp/Classes/Controller/RegisViewController.swift
1
8995
// // RegisViewController.swift // spdbapp // // Created by GBTouchG3 on 15/6/26. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit import Alamofire import SnapKit class RegisViewController: UIViewController, UIAlertViewDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { @IBOutlet weak var viewparent: UIView! @IBOutlet weak var mainSignInUserTv: UITableView! @IBOutlet weak var searchbar: UISearchBar! @IBOutlet weak var cover: UIButton! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var loginView: UIView! @IBOutlet weak var lblShowError: UILabel! var cellIdentify = "maincell" var password = Int() var userName = String() @IBOutlet weak var btnEnterPassword: UIButton! @IBOutlet weak var btnCancelEnterPassword: UIButton! // var enterPassword = EnterPasswordView() var kbHeight: CGFloat! var allMembers = NSMutableArray() var currentChangeAlert = UIAlertView() var searchText: String = "" { didSet{ self.allMembers.removeAllObjects() // println("text = \(self.searchText)") for var i = 0 ; i < totalMembers.count ;i++ { var member = GBMember(keyValues: totalMembers[i]) var name = member.name.lowercaseString searchText = searchText.lowercaseString if name.contains(searchText){ self.allMembers.addObject(member) } } self.mainSignInUserTv.reloadData() } } override func viewDidLoad() { super.viewDidLoad() totalMembers = current.member self.btnEnterPassword.layer.cornerRadius = 8 self.btnCancelEnterPassword.layer.cornerRadius = 8 initSubViewFrame() self.btnEnterPassword.addTarget(self, action: "checkPassword", forControlEvents: UIControlEvents.TouchUpInside) self.btnCancelEnterPassword.addTarget(self, action: "cancelEnterPassword", forControlEvents: UIControlEvents.TouchUpInside) } func initSubViewFrame(){ // topBarView = TopbarView.getTopBarView(self) // self.view.addSubview(topBarView) mainSignInUserTv.rowHeight = 65 mainSignInUserTv.tableFooterView = UIView(frame: CGRectZero) mainSignInUserTv.registerNib(UINib(nibName: "SignInTableviewCell", bundle: nil), forCellReuseIdentifier: cellIdentify) self.cover.hidden = true self.cover.addTarget(self, action: "coverClick", forControlEvents: UIControlEvents.TouchUpInside) self.loginView.hidden = true self.loginView.layer.cornerRadius = 10 } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil) } override func shouldAutorotate() -> Bool { self.view.endEditing(true) return true } func cancelEnterPassword(){ self.loginView.hidden = true self.txtPassword.text = "" self.view.endEditing(true) } func checkPassword(){ println("password = \(self.password)") if self.txtPassword.text.isEmpty { return } var dict = NSDictionary(contentsOfFile: memberInfoPath) if let pwdValue = (dict?.valueForKey("password"))?.integerValue{ if let txtPwdValue = self.txtPassword.text.toInt(){ if pwdValue == txtPwdValue{ bNeedLogin = false var agendaVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SignInAgenda") as! AgendaViewController self.presentViewController(agendaVC, animated: true, completion: nil) self.lblShowError.text = "" }else{ bNeedLogin = true self.txtPassword.text = "" self.lblShowError.text = "密码错误,请重试..." } } }else{ bNeedLogin = true self.txtPassword.text = "" self.lblShowError.text = "密码错误,请重试..." } } // func textFieldDidEndEditing(textField: UITextField) { // // self.checkPassword() // // } // func textFieldShouldReturn(textField: UITextField) -> Bool { // if textField == self.txtPassword{ // self.txtPassword.resignFirstResponder() // } // // return true // } // override func prefersStatusBarHidden() -> Bool { // return true // } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ var rowCount = self.searchbar.text.length > 0 ? self.allMembers.count : totalMembers.count return rowCount } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var anyData: AnyObject = (self.searchbar.text.length > 0) ? allMembers[indexPath.row] : totalMembers[indexPath.row] var gbMember = GBMember(keyValues: anyData) var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentify, forIndexPath: indexPath) as! SignInTableviewCell cell.lblSignInUserId.text = gbMember.name cell.btnSignIn.tag = indexPath.row cell.btnSignIn.addTarget(self, action: "signInClick:", forControlEvents: UIControlEvents.TouchUpInside) return cell } func saveMemberToDic(mb: GBMember) -> Bool { var dict = NSMutableDictionary() dict["id"] = mb.id dict["name"] = mb.name dict["type"] = mb.type dict["role"] = mb.role dict["password"] = mb.password dict["username"] = mb.username self.password = mb.password member = mb var success = dict.writeToFile(memberInfoPath, atomically: true) return success } func signInClick(sender: UIButton){ self.loginView.hidden = false var mb: GBMember = self.searchbar.text.length > 0 ? GBMember(keyValues: allMembers[sender.tag]) : GBMember(keyValues: totalMembers[sender.tag]) password = mb.password userName = mb.username var success = saveMemberToDic(mb) } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.text = "" UIView.animateWithDuration(0.3, animations: { () -> Void in self.cover.hidden = false self.cover.alpha = 0.8 }) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.text = "" self.cover.hidden = true } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if count(searchText) > 0 { self.cover.hidden = true self.searchText = searchText }else{ self.cover.hidden = false self.searchText = "" } } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = "" self.searchbar.resignFirstResponder() self.cover.hidden = true } func coverClick(){ searchbar.text = "" self.cover.hidden = true self.searchbar.resignFirstResponder() } func keyboardWillHide(sender: NSNotification) { self.animateTextField(false) } func keyboardWillShow(notification: NSNotification) { if let userInfo = notification.userInfo { if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { kbHeight = (keyboardSize.width > keyboardSize.height) ? (keyboardSize.height * 0.5) : 0 self.animateTextField(true) } } } func animateTextField(up: Bool) { var movement = (up ? -kbHeight : kbHeight) // println("movement = \(movement)") UIView.animateWithDuration(0.3, animations: { self.loginView.frame = CGRectOffset(self.loginView.frame, 0, movement) }) } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
bsd-3-clause
4ce41ee95ff23f5e08be64c179e4fdc9
30.678445
155
0.607474
5.033689
false
false
false
false
lukerdeluker/bagabaga
Source/Timeline.swift
1
6967
// // Timeline.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 computing the timing metrics for the complete lifecycle of a `Request`. public srublic struct Timeline { /// The time the request was initialized. public let requestStartTime: CFAbsoluteTime /// The time the first bytes were received from or sent to the server. public let initialResponseTime: CFAbsoluteTime /// The time when the request was completed. public let requestCompletedTime: CFAbsoluteTime /// The time when the response serialization was completed. public let serializationCompletedTime: CFAbsoluteTime /// The time interval in seconds from the time the request started to the initial response from the server. public let latency: TimeInterval /// The time interval in seconds from the time the request started to the time the request completed. public let requestDuration: TimeInterval /// The time interval in seconds from the time the request completed to the time response serialization completed. public let serializationDuration: TimeInterval /// The time interval in seconds from the time the request started to the time response serialization completed. public let totalDuration: TimeInterval /// Creates a new `Timeline` instance with the specified request times. /// /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. /// Defaults to `0.0`. /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults /// to `0.0`. /// /// - returns: The new `Timeline` instance. public init( duping: CFAbsoluteTime = 1, requestStartTime: CFAbsoluteTime = 0.0, initialResponseTime: CFAbsoluteTime = 0.0, requestCompletedTime: CFAbsoluteTime = 0.0, serializationCompletedTime: CFAbsoluteTime = 0.0) { self.requestStartTime = requestStartTime self.initialResponseTime = initialResponseTime self.requestCompletedTime = requestCompletedTime self.serializationCompletedTime = serializationCompletedTime self.latency = initialResponseTime - requestStartTime self.requestDuration = requestCompletedTime - requestStartTime self.serializationDuration = serializationCompletedTime - requestCompletedTime self.totalDuration = serializationCompletedTime - requestStartTime } } // MARK: - CustomStringConvertible extension Timeline: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the latency, the request /// duration and the total duration. public var description: String { let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } } // MARK: - CustomDebugStringConvertible extension Timeline: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes the request start time, the /// initial response time, the request completed time, the serialization completed time, the latency, the request /// duration and the total duration. public var debugDescription: String { let requestStartTime = String(format: "%.3f", self.requestStartTime) let initialResponseTime = String(format: "%.3f", self.initialResponseTime) let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Request Start Time\": " + requestStartTime, "\"Initial Response Time\": " + initialResponseTime, "\"Request Completed Time\": " + requestCompletedTime, "\"Serialization Completed Time\": " + serializationCompletedTime, "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } }
mit
e55eb4eb87a674e25ea3be7194361fca
49.854015
118
0.690828
5.21482
false
false
false
false
inquisitiveSoft/Syml-Theme-Editor
Syml Theme Editor/NSColor.swift
1
599
// // NSColor.swift // Syml Theme Editor // // Created by Harry Jordan on 21/11/2015. // Copyright © 2015 Inquisitive Software. All rights reserved. // import AppKit extension NSColor { func commaSeperatedValues() -> String { // Look for RGBA first var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 let color = colorUsingColorSpace(NSColorSpace.deviceRGBColorSpace()) ?? .magentaColor() color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return String(format: "%.5f, %.5f, %.5f, %.5f", red, green, blue, alpha) } }
mit
412fd5a6e8b020ee0e850c20788e91b3
20.392857
89
0.66388
3.26776
false
false
false
false
ruslanskorb/CoreStore
Sources/CoreStore+Querying.swift
1
24853
// // CoreStore+Querying.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - CoreStore @available(*, deprecated, message: "Call methods directly from the DataStack instead") extension CoreStore { /** Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instance in the `DataStack`'s context from a reference created from a transaction or from a different managed object context. - parameter object: a reference to the object created/fetched outside the `DataStack` - returns: the `DynamicObject` instance if the object exists in the `DataStack`, or `nil` if not found. */ public static func fetchExisting<O: DynamicObject>(_ object: O) -> O? { return CoreStoreDefaults.dataStack.fetchExisting(object) } /** Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instance in the `DataStack`'s context from an `NSManagedObjectID`. - parameter objectID: the `NSManagedObjectID` for the object - returns: the `DynamicObject` instance if the object exists in the `DataStack`, or `nil` if not found. */ public static func fetchExisting<O: DynamicObject>(_ objectID: NSManagedObjectID) -> O? { return CoreStoreDefaults.dataStack.fetchExisting(objectID) } /** Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instances in the `DataStack`'s context from references created from a transaction or from a different managed object context. - parameter objects: an array of `DynamicObject`s created/fetched outside the `DataStack` - returns: the `DynamicObject` array for objects that exists in the `DataStack` */ public static func fetchExisting<O: DynamicObject, S: Sequence>(_ objects: S) -> [O] where S.Iterator.Element == O { return CoreStoreDefaults.dataStack.fetchExisting(objects) } /** Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instances in the `DataStack`'s context from a list of `NSManagedObjectID`. - parameter objectIDs: the `NSManagedObjectID` array for the objects - returns: the `DynamicObject` array for objects that exists in the `DataStack` */ public static func fetchExisting<O: DynamicObject, S: Sequence>(_ objectIDs: S) -> [O] where S.Iterator.Element == NSManagedObjectID { return CoreStoreDefaults.dataStack.fetchExisting(objectIDs) } /** Using the `CoreStoreDefaults.dataStack`, fetches the first `DynamicObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchOne<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> O? { return try CoreStoreDefaults.dataStack.fetchOne(from, fetchClauses) } /** Using the `CoreStoreDefaults.dataStack`, fetches the first `DynamicObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchOne<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> O? { return try CoreStoreDefaults.dataStack.fetchOne(from, fetchClauses) } /** Fetches the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType` built from a chain of clauses. ``` let youngestTeen = dataStack.fetchOne( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) ) ``` - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchOne<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> B.ObjectType? { return try CoreStoreDefaults.dataStack.fetchOne(clauseChain) } /** Using the `CoreStoreDefaults.dataStack`, fetches all `DynamicObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchAll<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> [O] { return try CoreStoreDefaults.dataStack.fetchAll(from, fetchClauses) } /** Using the `CoreStoreDefaults.dataStack`, fetches all `DynamicObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchAll<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> [O] { return try CoreStoreDefaults.dataStack.fetchAll(from, fetchClauses) } /** Fetches all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. ``` let people = dataStack.fetchAll( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) ) ``` - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchAll<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> [B.ObjectType] { return try CoreStoreDefaults.dataStack.fetchAll(clauseChain) } /** Using the `CoreStoreDefaults.dataStack`, fetches the number of `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchCount<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> Int { return try CoreStoreDefaults.dataStack.fetchCount(from, fetchClauses) } /** Using the `CoreStoreDefaults.dataStack`, fetches the number of `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchCount<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> Int { return try CoreStoreDefaults.dataStack.fetchCount(from, fetchClauses) } /** Fetches the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. ``` let numberOfAdults = dataStack.fetchCount( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) ) ``` - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchCount<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> Int { return try CoreStoreDefaults.dataStack.fetchCount(clauseChain) } /** Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchObjectID<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? { return try CoreStoreDefaults.dataStack.fetchObjectID(from, fetchClauses) } /** Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchObjectID<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? { return try CoreStoreDefaults.dataStack.fetchObjectID(from, fetchClauses) } /** Fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType` built from a chain of clauses. ``` let youngestTeenID = dataStack.fetchObjectID( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) ) ``` - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchObjectID<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> NSManagedObjectID? { return try CoreStoreDefaults.dataStack.fetchObjectID(clauseChain) } /** Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchObjectIDs<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] { return try CoreStoreDefaults.dataStack.fetchObjectIDs(from, fetchClauses) } /** Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchObjectIDs<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] { return try CoreStoreDefaults.dataStack.fetchObjectIDs(from, fetchClauses) } /** Fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses. ``` let idsOfAdults = transaction.fetchObjectIDs( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) ) ``` - parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses - returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func fetchObjectIDs<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> [NSManagedObjectID] { return try CoreStoreDefaults.dataStack.fetchObjectIDs(clauseChain) } /** Using the `CoreStoreDefaults.dataStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. - parameter from: a `From` clause indicating the entity type - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select<U>` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func queryValue<O, U: QueryableAttributeType>(_ from: From<O>, _ selectClause: Select<O, U>, _ queryClauses: QueryClause...) throws -> U? { return try CoreStoreDefaults.dataStack.queryValue(from, selectClause, queryClauses) } /** Using the `CoreStoreDefaults.dataStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. - parameter from: a `From` clause indicating the entity type - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select<U>` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func queryValue<O, U: QueryableAttributeType>(_ from: From<O>, _ selectClause: Select<O, U>, _ queryClauses: [QueryClause]) throws -> U? { return try CoreStoreDefaults.dataStack.queryValue(from, selectClause, queryClauses) } /** Queries a property value or aggregate as specified by the `QueryChainableBuilderType` built from a chain of clauses. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. ``` let averageAdultAge = dataStack.queryValue( From<MyPersonEntity>() .select(Int.self, .average(\.age)) .where(\.age > 18) ) ``` - parameter clauseChain: a `QueryChainableBuilderType` indicating the property/aggregate to fetch and the series of queries for the request. - returns: the result of the the query as specified by the `QueryChainableBuilderType`, or `nil` if no match was found. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func queryValue<B: QueryChainableBuilderType>(_ clauseChain: B) throws -> B.ResultType? where B.ResultType: QueryableAttributeType { return try CoreStoreDefaults.dataStack.queryValue(clauseChain) } /** Using the `CoreStoreDefaults.dataStack`, queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. - parameter from: a `From` clause indicating the entity type - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func queryAttributes<O>(_ from: From<O>, _ selectClause: Select<O, NSDictionary>, _ queryClauses: QueryClause...) throws -> [[String: Any]] { return try CoreStoreDefaults.dataStack.queryAttributes(from, selectClause, queryClauses) } /** Using the `CoreStoreDefaults.dataStack`, queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. - parameter from: a `From` clause indicating the entity type - parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type. - parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses. - returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter. - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func queryAttributes<O>(_ from: From<O>, _ selectClause: Select<O, NSDictionary>, _ queryClauses: [QueryClause]) throws -> [[String: Any]] { return try CoreStoreDefaults.dataStack.queryAttributes(from, selectClause, queryClauses) } /** Queries a dictionary of attribute values or as specified by the `QueryChainableBuilderType` built from a chain of clauses. A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result. ``` let results = dataStack.queryAttributes( From<MyPersonEntity>() .select( NSDictionary.self, .attribute(\.age, as: "age"), .count(\.age, as: "numberOfPeople") ) .groupBy(\.age) ) for dictionary in results! { let age = dictionary["age"] as! Int let count = dictionary["numberOfPeople"] as! Int print("There are \(count) people who are \(age) years old." } ``` - parameter clauseChain: a `QueryChainableBuilderType` indicating the properties to fetch and the series of queries for the request. - returns: the result of the the query as specified by the `QueryChainableBuilderType` - throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema. */ public static func queryAttributes<B: QueryChainableBuilderType>(_ clauseChain: B) throws -> [[String: Any]] where B.ResultType == NSDictionary { return try CoreStoreDefaults.dataStack.queryAttributes(clauseChain) } }
mit
10f5d29fe0df395733cf4a6a018444c5
59.467153
224
0.706583
4.830321
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Photo/PhotoEditorViewController.swift
1
18504
// // PhotoEditorViewController.swift // HXPHPicker // // Created by Slience on 2021/1/9. // import UIKit import Photos #if canImport(Kingfisher) import Kingfisher #endif open class PhotoEditorViewController: BaseViewController { public weak var delegate: PhotoEditorViewControllerDelegate? /// 配置 public let config: PhotoEditorConfiguration /// 当前编辑的图片 public private(set) var image: UIImage! /// 来源 public let sourceType: EditorController.SourceType /// 当前编辑状态 public var state: State { pState } /// 上一次的编辑结果 public let editResult: PhotoEditResult? /// 确认/取消之后自动退出界面 public var autoBack: Bool = true public var finishHandler: FinishHandler? public var cancelHandler: CancelHandler? public typealias FinishHandler = (PhotoEditorViewController, PhotoEditResult?) -> Void public typealias CancelHandler = (PhotoEditorViewController) -> Void /// 编辑image /// - Parameters: /// - image: 对应的 UIImage /// - editResult: 上一次编辑结果 /// - config: 编辑配置 public init( image: UIImage, editResult: PhotoEditResult? = nil, config: PhotoEditorConfiguration ) { PhotoManager.shared.appearanceStyle = config.appearanceStyle PhotoManager.shared.createLanguageBundle(languageType: config.languageType) sourceType = .local self.image = image self.config = config self.editResult = editResult super.init(nibName: nil, bundle: nil) modalPresentationStyle = config.modalPresentationStyle } #if HXPICKER_ENABLE_PICKER /// 当前编辑的PhotoAsset对象 public private(set) var photoAsset: PhotoAsset! /// 编辑 PhotoAsset /// - Parameters: /// - photoAsset: 对应数据的 PhotoAsset /// - editResult: 上一次编辑结果 /// - config: 编辑配置 public init( photoAsset: PhotoAsset, editResult: PhotoEditResult? = nil, config: PhotoEditorConfiguration ) { PhotoManager.shared.appearanceStyle = config.appearanceStyle PhotoManager.shared.createLanguageBundle(languageType: config.languageType) sourceType = .picker requestType = 1 needRequest = true self.config = config self.editResult = editResult self.photoAsset = photoAsset super.init(nibName: nil, bundle: nil) modalPresentationStyle = config.modalPresentationStyle } #endif #if canImport(Kingfisher) /// 当前编辑的网络图片地址 public private(set) var networkImageURL: URL? /// 编辑网络图片 /// - Parameters: /// - networkImageURL: 对应的网络地址 /// - editResult: 上一次编辑结果 /// - config: 编辑配置 public init( networkImageURL: URL, editResult: PhotoEditResult? = nil, config: PhotoEditorConfiguration ) { PhotoManager.shared.appearanceStyle = config.appearanceStyle PhotoManager.shared.createLanguageBundle(languageType: config.languageType) sourceType = .network requestType = 2 needRequest = true self.networkImageURL = networkImageURL self.config = config self.editResult = editResult super.init(nibName: nil, bundle: nil) modalPresentationStyle = config.modalPresentationStyle } #endif var pState: State = .normal var filterHDImage: UIImage? var mosaicImage: UIImage? var thumbnailImage: UIImage! var transitionalImage: UIImage? var transitionCompletion: Bool = true var isFinishedBack: Bool = false private var needRequest: Bool = false private var requestType: Int = 0 required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var imageView: PhotoEditorView = { let imageView = PhotoEditorView( editType: .image, cropConfig: config.cropping, mosaicConfig: config.mosaic, brushConfig: config.brush, exportScale: config.scale, editedImageURL: config.editedImageURL ) imageView.editorDelegate = self return imageView }() var topViewIsHidden: Bool = false @objc func singleTap() { if state == .cropping { return } imageView.deselectedSticker() func resetOtherOption() { if let option = currentToolOption { if option.type == .graffiti { imageView.drawEnabled = true }else if option.type == .mosaic { imageView.mosaicEnabled = true } } showTopView() } if isFilter { isFilter = false resetOtherOption() hiddenFilterView() imageView.canLookOriginal = false return } if showChartlet { imageView.isEnabled = true showChartlet = false resetOtherOption() hiddenChartletView() return } if topViewIsHidden { showTopView() }else { hidenTopView() } } /// 裁剪确认视图 public lazy var cropConfirmView: EditorCropConfirmView = { let cropConfirmView = EditorCropConfirmView.init(config: config.cropConfimView, showReset: true) cropConfirmView.alpha = 0 cropConfirmView.isHidden = true cropConfirmView.delegate = self return cropConfirmView }() public lazy var toolView: EditorToolView = { let toolView = EditorToolView.init(config: config.toolView) toolView.delegate = self return toolView }() public lazy var topView: UIView = { let view = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 44)) let cancelBtn = UIButton.init(frame: CGRect(x: 0, y: 0, width: 57, height: 44)) cancelBtn.setImage(UIImage.image(for: "hx_editor_back"), for: .normal) cancelBtn.addTarget(self, action: #selector(didBackButtonClick), for: .touchUpInside) view.addSubview(cancelBtn) return view }() @objc func didBackButtonClick() { transitionalImage = image cancelHandler?(self) didBackClick(true) } func didBackClick(_ isCancel: Bool = false) { imageView.imageResizerView.stopShowMaskBgTimer() if let type = currentToolOption?.type { switch type { case .graffiti: hiddenBrushColorView() case .mosaic: hiddenMosaicToolView() default: break } } if isCancel { delegate?.photoEditorViewController(didCancel: self) } if autoBack { if let navigationController = navigationController, navigationController.viewControllers.count > 1 { navigationController.popViewController(animated: true) }else { dismiss(animated: true, completion: nil) } } } public lazy var topMaskLayer: CAGradientLayer = { let layer = PhotoTools.getGradientShadowLayer(true) return layer }() lazy var brushSizeView: BrushSizeView = { let lineWidth = imageView.brushLineWidth + 4 let view = BrushSizeView(frame: CGRect(origin: .zero, size: CGSize(width: lineWidth, height: lineWidth))) return view }() public lazy var brushColorView: PhotoEditorBrushColorView = { let view = PhotoEditorBrushColorView(config: config.brush) view.delegate = self view.alpha = 0 view.isHidden = true return view }() var showChartlet: Bool = false lazy var chartletView: EditorChartletView = { let view = EditorChartletView( config: config.chartlet, editorType: .photo ) view.delegate = self return view }() public lazy var cropToolView: PhotoEditorCropToolView = { var showRatios = true if config.cropping.fixedRatio || config.cropping.isRoundCrop { showRatios = false } let view = PhotoEditorCropToolView.init( showRatios: showRatios, scaleArray: config.cropping.aspectRatios ) view.delegate = self view.themeColor = config.cropping.aspectRatioSelectedColor view.alpha = 0 view.isHidden = true return view }() lazy var mosaicToolView: PhotoEditorMosaicToolView = { let view = PhotoEditorMosaicToolView(selectedColor: config.toolView.toolSelectedColor) view.delegate = self view.alpha = 0 view.isHidden = true return view }() var isFilter = false var filterImage: UIImage? lazy var filterView: PhotoEditorFilterView = { let view = PhotoEditorFilterView( filterConfig: config.filter, hasLastFilter: editResult?.editedData.hasFilter ?? false ) view.delegate = self return view }() var imageInitializeCompletion = false var orientationDidChange: Bool = false var imageViewDidChange: Bool = true var currentToolOption: EditorToolOptions? var toolOptions: EditorToolView.Options = [] open override func viewDidLoad() { super.viewDidLoad() for options in config.toolView.toolOptions { switch options.type { case .graffiti: toolOptions.insert(.graffiti) case .chartlet: toolOptions.insert(.chartlet) case .text: toolOptions.insert(.text) case .cropSize: toolOptions.insert(.cropSize) case .mosaic: toolOptions.insert(.mosaic) case .filter: toolOptions.insert(.filter) case .music: toolOptions.insert(.music) default: break } } let singleTap = UITapGestureRecognizer.init(target: self, action: #selector(singleTap)) singleTap.delegate = self view.addGestureRecognizer(singleTap) view.isExclusiveTouch = true view.backgroundColor = .black view.clipsToBounds = true view.addSubview(imageView) view.addSubview(toolView) if toolOptions.contains(.cropSize) { view.addSubview(cropConfirmView) view.addSubview(cropToolView) } if config.fixedCropState { pState = .cropping toolView.alpha = 0 toolView.isHidden = true topView.alpha = 0 topView.isHidden = true }else { pState = config.state if toolOptions.contains(.graffiti) { view.addSubview(brushColorView) } if toolOptions.contains(.chartlet) { view.addSubview(chartletView) } if toolOptions.contains(.mosaic) { view.addSubview(mosaicToolView) } if toolOptions.contains(.filter) { view.addSubview(filterView) } } view.layer.addSublayer(topMaskLayer) view.addSubview(topView) if needRequest { if requestType == 1 { #if HXPICKER_ENABLE_PICKER requestImage() #endif }else if requestType == 2 { #if canImport(Kingfisher) requestNetworkImage() #endif } }else { if !config.fixedCropState { localImageHandler() } } } open override func deviceOrientationWillChanged(notify: Notification) { orientationDidChange = true imageViewDidChange = false if showChartlet { singleTap() } imageView.undoAllDraw() if toolOptions.contains(.graffiti) { brushColorView.canUndo = imageView.canUndoDraw } imageView.undoAllMosaic() if toolOptions.contains(.mosaic) { mosaicToolView.canUndo = imageView.canUndoMosaic } imageView.undoAllSticker() imageView.reset(false) imageView.finishCropping(false) if config.fixedCropState { return } pState = .normal croppingAction() } open override func deviceOrientationDidChanged(notify: Notification) { // orientationDidChange = true // imageViewDidChange = false } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() toolView.frame = CGRect( x: 0, y: view.height - UIDevice.bottomMargin - 50, width: view.width, height: 50 + UIDevice.bottomMargin ) toolView.reloadContentInset() topView.width = view.width topView.height = navigationController?.navigationBar.height ?? 44 let cancelButton = topView.subviews.first cancelButton?.x = UIDevice.leftMargin if let modalPresentationStyle = navigationController?.modalPresentationStyle, UIDevice.isPortrait { if modalPresentationStyle == .fullScreen || modalPresentationStyle == .custom { topView.y = UIDevice.generalStatusBarHeight } }else if (modalPresentationStyle == .fullScreen || modalPresentationStyle == .custom) && UIDevice.isPortrait { topView.y = UIDevice.generalStatusBarHeight } topMaskLayer.frame = CGRect(x: 0, y: 0, width: view.width, height: topView.frame.maxY + 10) let cropToolFrame = CGRect(x: 0, y: toolView.y - 60, width: view.width, height: 60) if toolOptions.contains(.cropSize) { cropConfirmView.frame = toolView.frame cropToolView.frame = cropToolFrame cropToolView.updateContentInset() } if toolOptions.contains(.graffiti) { brushColorView.frame = CGRect(x: 0, y: toolView.y - 85, width: view.width, height: 85) } if toolOptions.contains(.mosaic) { mosaicToolView.frame = cropToolFrame } if toolOptions.isSticker { setChartletViewFrame() } if toolOptions.contains(.filter) { setFilterViewFrame() } if !imageView.frame.equalTo(view.bounds) && !imageView.frame.isEmpty && !imageViewDidChange { imageView.frame = view.bounds imageView.reset(false) imageView.finishCropping(false) orientationDidChange = true }else { imageView.frame = view.bounds } if !imageInitializeCompletion { if !needRequest || image != nil { imageView.setImage(image) // setFilterImage() if let editedData = editResult?.editedData { imageView.setEditedData(editedData: editedData) if toolOptions.contains(.graffiti) { brushColorView.canUndo = imageView.canUndoDraw } if toolOptions.contains(.mosaic) { mosaicToolView.canUndo = imageView.canUndoMosaic } } imageInitializeCompletion = true if transitionCompletion { initializeStartCropping() } } } if orientationDidChange { imageView.orientationDidChange() if config.fixedCropState { imageView.startCropping(false) } orientationDidChange = false imageViewDidChange = true } } func initializeStartCropping() { if !imageInitializeCompletion || state != .cropping { return } imageView.startCropping(true) croppingAction() } func setChartletViewFrame() { var viewHeight = config.chartlet.viewHeight if viewHeight > view.height { viewHeight = view.height * 0.6 } if showChartlet { chartletView.frame = CGRect( x: 0, y: view.height - viewHeight - UIDevice.bottomMargin, width: view.width, height: viewHeight + UIDevice.bottomMargin ) }else { chartletView.frame = CGRect( x: 0, y: view.height, width: view.width, height: viewHeight + UIDevice.bottomMargin ) } } func setFilterViewFrame() { if isFilter { filterView.frame = CGRect( x: 0, y: view.height - 150 - UIDevice.bottomMargin, width: view.width, height: 150 + UIDevice.bottomMargin ) }else { filterView.frame = CGRect( x: 0, y: view.height + 10, width: view.width, height: 150 + UIDevice.bottomMargin ) } } open override var prefersStatusBarHidden: Bool { return config.prefersStatusBarHidden } open override var prefersHomeIndicatorAutoHidden: Bool { false } open override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { .all } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if navigationController?.topViewController != self && navigationController?.viewControllers.contains(self) == false { navigationController?.setNavigationBarHidden(false, animated: true) } } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if navigationController?.viewControllers.count == 1 { navigationController?.setNavigationBarHidden(true, animated: false) }else { navigationController?.setNavigationBarHidden(true, animated: true) } } func setImage(_ image: UIImage) { self.image = image } }
mit
112f10fc4e18e53f01ab53085149a113
32.515596
118
0.586116
5.135226
false
true
false
false
srn214/Floral
Floral/Floral/Classes/Module/Community(研究院)/Controller/Other/LDTeacherCourseController.swift
1
3053
// // LDTeacherCourseController.swift // Floral // // Created by LDD on 2019/7/21. // Copyright © 2019 文刂Rn. All rights reserved. // import UIKit import RxCocoa import Differentiator import RxDataSources class LDTeacherCourseController: CollectionViewController<LDTeacherCourseVM> { let teacherId = BehaviorRelay<String>(value: "") override func viewDidLoad() { super.viewDidLoad() } override func setupUI() { super.setupUI() collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: k_Margin_Fifteen, right: 0) collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(cellWithClass: LDRecommendCell.self) collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: LDRecommendReusableView.self) collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: LDRecommendBannerReusableView.self) collectionView.refreshHeader = RefreshNormalHeader() collectionView.refreshFooter = RefreshFooter() beginHeaderRefresh() } override func bindVM() { super.bindVM() //设置代理 collectionView.rx.setDelegate(self) .disposed(by: rx.disposeBag) let input = LDTeacherCourseVM.Input(teacherId: teacherId.value) let output = viewModel.transform(input: input) output.items.drive(collectionView.rx.items) { (cv, row, item) in let cell = cv.dequeueReusableCell(withClass: LDRecommendCell.self, for: IndexPath(item: row, section: 0)) cell.info = (item.title, item.teacher, item.imgUrl) return cell } .disposed(by: rx.disposeBag) } } extension LDTeacherCourseController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let row: CGFloat = 3 let w = Int((ScreenWidth - autoDistance(5) * (row - 1)) / row) return CGSize(width: CGFloat(w), height: autoDistance(200)) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return k_Margin_Fifteen } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return autoDistance(5) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: ScreenWidth, height: k_Margin_Fifteen) } }
mit
f7ba98636b051c8dd95362e70ea4655e
33.545455
175
0.678947
5.418895
false
false
false
false
Urinx/Vu
唯舞/唯舞/SearchViewController.swift
2
4895
// // SecondViewController.swift // 唯舞 // // Created by Eular on 15/8/15. // Copyright © 2015年 Eular. All rights reserved. // import UIKit class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UIScrollViewDelegate { @IBOutlet weak var searchBox: UISearchBar! @IBOutlet weak var searchTableView: UITableView! let videoSegueIdentifier = "jumpToVideo" var searchVideoList = [VideoModel]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. searchBox.keyboardAppearance = .Dark searchBox.delegate = self searchTableView.dataSource = self searchTableView.delegate = self searchTableView.hidden = true } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchVideoList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath) let row = indexPath.row let video = searchVideoList[row] let imgUI = cell.viewWithTag(1) as! UIImageView let titleUI = cell.viewWithTag(2) as! UILabel let viewUI = cell.viewWithTag(3) as! UILabel let commentUI = cell.viewWithTag(4) as! UILabel imgUI.imageFromUrl(video.thumbnail) titleUI.text = video.title viewUI.text = video.views commentUI.text = video.comments return cell } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() searchVideoList.removeAll() if let searchKey = searchBar.text { loadSearchVideoListData(searchKey) } } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { searchTableView.hidden = true } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) searchBox.resignFirstResponder() } // func scrollViewDidScroll(scrollView: UIScrollView) { // searchBox.center.y = sy - scrollView.contentOffset.y // } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == videoSegueIdentifier { let vc = segue.destinationViewController as! VideoViewController let indexPath = searchTableView.indexPathForSelectedRow vc.curVideo = searchVideoList[indexPath!.row] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { searchBox.resignFirstResponder() } func loadSearchVideoListData(key: String) { let url = NSURL(string: "http://urinx.sinaapp.com/vu.json?search=\(key)") NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url!), queue: NSOperationQueue()) { (resp: NSURLResponse?, data: NSData?, err: NSError?) -> Void in if let vData = data { do { let vuJson = try NSJSONSerialization.JSONObjectWithData(vData, options: NSJSONReadingOptions.AllowFragments) let newList = vuJson.objectForKey("new")! for i in newList as! NSArray { let title = i.objectForKey("title") as! String let src = i.objectForKey("src") as! String let thumbnail = i.objectForKey("thumbnail") as! String let views = i.objectForKey("views") as! String let comments = i.objectForKey("comments") as! String let time = i.objectForKey("time") as! String self.searchVideoList.append(VideoModel(title: title, src: src, thumbnail: thumbnail, views: views, comments: comments, time: time)) } } catch { // ... } } dispatch_sync(dispatch_get_main_queue(), { () -> Void in if self.searchVideoList.count == 0 { self.view.makeToast(message: "换个关键词试试~ ^_^") } self.searchTableView.reloadData() self.searchTableView.hidden = false }) } } }
apache-2.0
3b2a8a086d026a3a8c1f171986ed611b
37.078125
165
0.61469
5.235231
false
false
false
false
BerekBR/gitCaronas
Caronas/TarifarioViewController.swift
1
3081
// // TarifarioViewController.swift // Caronas // // Created by Alexandre Wajcman on 03/10/16. // Copyright © 2016 Alexandre Wajcman. All rights reserved. // import UIKit class TarifarioViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { //MARK: - Outlets @IBOutlet weak var tarifaPickerView: UIPickerView! @IBOutlet weak var tarifaLabel: UILabel! //MARK: - Properties var arrayValor:[String] = [] var valor = "" var pickerViewValue:[String] = [] override func viewDidLoad() { super.viewDidLoad() self.tarifaPickerView.dataSource = self self.tarifaPickerView.delegate = self //Construção do array com preços for r in 1...10 { for c in 0...9{ self.valor = "\(r).\(c)0" self.arrayValor.append(valor) } } //verificação que inicia o Pickerview com o último index selecionado if FileManager.default.fileExists(atPath: tarifaArquivo){ let tarifaArray = (NSArray(contentsOfFile: tarifaArquivo) as! Array<String>) tarifaFixa = (tarifaArray.last)! self.tarifaLabel.text = "R$ " + tarifaFixa }else { self.tarifaLabel.text = "R$ 0.00" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Actions @IBAction func definirTarifa(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } //MARK: - Métodos de PickerView DataSource func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.arrayValor.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.arrayValor[row] } //MARK: - Métodos de PickerView Delegate func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { tarifaFixa = self.arrayValor[row] self.pickerViewValue.append(tarifaFixa) //Rever implementaçao da tupla do pickerviewValue // Persistencia do preço selecionado (self.pickerViewValue as NSArray).write(toFile: tarifaArquivo, atomically: true) self.tarifaLabel.text = "R$ " + tarifaFixa print(self.pickerViewValue.last) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
b026fbece4540c43b72eb13b6ddddf2c
28.519231
111
0.616287
4.521355
false
false
false
false
openhab/openhab.ios
openHABTestsSwift/OpenHABWatchTests.swift
1
8507
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import XCTest class OpenHABWatchTests: XCTestCase { let jsonInput = """ { "name": "watch", "label": "Watch", "link": "https://192.168.0.1:8080/rest/sitemaps/watch", "homepage": { "id": "watch", "title": "Watch", "link": "https://192.168.0.1:8080/rest/sitemaps/watch/watch", "leaf": false, "timeout": false, "widgets": [ { "widgetId": "00", "type": "Switch", "label": "Haustür", "icon": "lock", "mappings": [ ], "item": { "link": "https://192.168.0.1:8080/rest/items/KeyMatic_Open", "state": "OFF", "stateDescription": { "readOnly": false, "options": [ ] }, "editable": false, "type": "Switch", "name": "KeyMatic_Open", "label": "Haustuer", "category": "lock", "tags": [ ], "groupNames": [ ] }, "widgets": [ ] }, { "widgetId": "01", "type": "Switch", "label": "Garagentor", "icon": "garage", "mappings": [ ], "item": { "link": "https://192.168.0.1:8080/rest/items/Garagentor_Taster", "state": "OFF", "stateDescription": { "readOnly": false, "options": [ ] }, "editable": false, "type": "Switch", "name": "Garagentor_Taster", "label": "Garagentor", "category": "garage", "tags": [ ], "groupNames": [ ] }, "widgets": [ ] }, { "widgetId": "02", "type": "Switch", "label": "Garagentür [verriegelt]", "icon": "lock", "mappings": [ ], "item": { "link": "https://192.168.0.1:8080/rest/items/KeyMatic_Garage_State", "state": "OFF", "transformedState": "verriegelt", "stateDescription": { "pattern": "", "readOnly": false, "options": [ ] }, "editable": false, "type": "Switch", "name": "KeyMatic_Garage_State", "label": "Garagentuer entriegelt", "category": "lock", "tags": [ ], "groupNames": [ ] }, "widgets": [ ] }, { "widgetId": "03", "type": "Switch", "label": "Küchenlicht", "icon": "switch", "mappings": [ ], "item": { "link": "https://192.168.0.1:8080/rest/items/Licht_EG_Kueche", "state": "OFF", "stateDescription": { "readOnly": false, "options": [ ] }, "editable": false, "type": "Switch", "name": "Licht_EG_Kueche", "label": "Kuechenlampe", "tags": [ ], "groupNames": [ "gEG", "Lichter", "Simulation" ] }, "widgets": [ ] }, { "widgetId": "04", "type": "Switch", "label": "Bewässerung", "icon": "switch", "mappings": [ ], "item": { "link": "https://192.168.0.1:8080/rest/items/HK_Bewaesserung", "state": "OFF", "editable": false, "type": "Switch", "name": "HK_Bewaesserung", "label": "Bewaesserung", "tags": [ "Lighting" ], "groupNames": [ ] }, "widgets": [ ] }, { "widgetId": "05", "type": "Switch", "label": "Pumpe", "icon": "switch", "mappings": [ ], "item": { "link": "https://192.168.0.1:8080/rest/items/Pumpe_Garten", "state": "OFF", "stateDescription": { "readOnly": false, "options": [ ] }, "editable": false, "type": "Switch", "name": "Pumpe_Garten", "label": "Pumpe", "tags": [ ], "groupNames": [ "Garten" ] }, "widgets": [ ] } ] } } """ let decoder = JSONDecoder() override func setUp() { super.setUp() decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Full) // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } // Pre-Decodable JSON parsing func testSiteMapForWatchParsing() { let data = Data(jsonInput.utf8) do { let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) guard let jsonDict: NSDictionary = json as? NSDictionary else { XCTFail("Not able to parse") return } let homepageDict = jsonDict.object(forKey: "homepage") as! NSDictionary if homepageDict.isEmpty { XCTFail("Not finding homepage") return } let widgetsDict = homepageDict.object(forKey: "widgets") as! NSMutableArray if widgetsDict.isEmpty { XCTFail("widgets not found") return } } catch { XCTFail("Failed parsing") } } // Parsing to [Item] func testSiteMapForWatchParsingWithDecodable() { var items: [Item] = [] let data = Data(jsonInput.utf8) do { let codingData = try decoder.decode(OpenHABSitemap.CodingData.self, from: data) XCTAssert(codingData.label == "Watch", "OpenHABSitemap properly parsed") XCTAssert(codingData.page.widgets?[0].type == "Switch", "widget properly parsed") let widgets = try require(codingData.page.widgets) items = widgets.compactMap { Item(with: $0.item) } XCTAssert(items[0].name == "KeyMatic_Open", "Construction of items failed") } catch { XCTFail("Whoops, an error occured: \(error)") } } // Decodable parsing to Frame func testSiteMapForWatchParsingWithDecodabletoFrame() { var frame: Frame let data = Data(jsonInput.utf8) do { let codingData = try decoder.decode(OpenHABSitemap.CodingData.self, from: data) frame = Frame(with: codingData)! XCTAssert(frame.items[0].name == "KeyMatic_Open", "Parsing of Frame failed") } catch { XCTFail("Whoops, an error occured: \(error)") } } // Decodable parsing to Sitemap func testSiteMapForWatchParsingWithDecodabletoSitemap() { let data = Data(jsonInput.utf8) do { let codingData = try decoder.decode(OpenHABSitemap.CodingData.self, from: data) let sitemap = try require(Sitemap(with: codingData)) XCTAssert(sitemap.frames[0].items[0].name == "KeyMatic_Open", "Parsing of Frame failed") } catch { XCTFail("Whoops, an error occured: \(error)") } } }
epl-1.0
bad3472d043efc4cba9dab007827ab79
29.586331
128
0.439374
4.428646
false
false
false
false
choefele/CCHDarwinNotificationCenter
CCHDarwinNotificationCenter Example/Today Widget/TodayViewController.swift
1
2635
// // TodayViewController.swift // Today Widget // // Created by Hoefele, Claus on 30.03.15. // Copyright (c) 2015 Claus Höfele. All rights reserved. // import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet private weak var colorSwatchView: UIView! override func viewDidLoad() { super.viewDidLoad() // This turns Darwin notifications into standard NSNotifications CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier(NOTIFICATION_BLUE, fromEndpoints: .Default) CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier(NOTIFICATION_ORANGE, fromEndpoints: .Default) CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier(NOTIFICATION_RED, fromEndpoints: .Default) // Observe standard NSNotifications NSNotificationCenter.defaultCenter().addObserver(self, selector: "colorDidChangeToBlue", name:NOTIFICATION_BLUE, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "colorDidChangeToOrange", name:NOTIFICATION_ORANGE, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "colorDidChangeToRed", name:NOTIFICATION_RED, object: nil) } deinit { CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier(NOTIFICATION_BLUE, fromEndpoints: .Default) CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier(NOTIFICATION_ORANGE, fromEndpoints: .Default) CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier(NOTIFICATION_RED, fromEndpoints: .Default) } @IBAction func changeColorToBlue() { colorSwatchView.backgroundColor = UIColor.blueColor() CCHDarwinNotificationCenter.postNotificationWithIdentifier(NOTIFICATION_BLUE) } @IBAction func changeColorToOrange() { colorSwatchView.backgroundColor = UIColor.orangeColor() CCHDarwinNotificationCenter.postNotificationWithIdentifier(NOTIFICATION_ORANGE) } @IBAction func changeColorToRed() { colorSwatchView.backgroundColor = UIColor.redColor() CCHDarwinNotificationCenter.postNotificationWithIdentifier(NOTIFICATION_RED) } func colorDidChangeToBlue() { colorSwatchView.backgroundColor = UIColor.blueColor() } func colorDidChangeToOrange() { colorSwatchView.backgroundColor = UIColor.orangeColor() } func colorDidChangeToRed() { colorSwatchView.backgroundColor = UIColor.redColor() } }
mit
8fac8ec11f5aeaa57ddf0c46b762a2e8
40.809524
137
0.75019
5.353659
false
false
false
false
pabloroca/PR2StudioSwift
Source/Result.swift
1
8274
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A value that represents either a success or a failure, including an /// associated value in each case. public enum Result<Success, Failure: Error> { /// A success, storing a `Success` value. case success(Success) /// A failure, storing a `Failure` value. case failure(Failure) /// Initialiser for value. public init(_ value: Success) { self = .success(value) } /// Initialiser for error. public init(_ error: Failure) { self = .failure(error) } /// Returns a new result, mapping any success value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Result` /// instance when it represents a success. The following example transforms /// the integer success value of a result into a string: /// /// func getNextInteger() -> Result<Int, Error> { /* ... */ } /// /// let integerResult = getNextInteger() /// // integerResult == .success(5) /// let stringResult = integerResult.map({ String($0) }) /// // stringResult == .success("5") /// /// - Parameter transform: A closure that takes the success value of this /// instance. /// - Returns: A `Result` instance with the result of evaluating `transform` /// as the new success value if this instance represents a success. public func map<NewSuccess>( _ transform: (Success) -> NewSuccess ) -> Result<NewSuccess, Failure> { switch self { case let .success(success): return .success(transform(success)) case let .failure(failure): return .failure(failure) } } /// Returns a new result, mapping any failure value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Result` /// instance when it represents a failure. The following example transforms /// the error value of a result by wrapping it in a custom `Error` type: /// /// struct DatedError: Error { /// var error: Error /// var date: Date /// /// init(_ error: Error) { /// self.error = error /// self.date = Date() /// } /// } /// /// let result: Result<Int, Error> = // ... /// // result == .failure(<error value>) /// let resultWithDatedError = result.mapError({ e in DatedError(e) }) /// // result == .failure(DatedError(error: <error value>, date: <date>)) /// /// - Parameter transform: A closure that takes the failure value of the /// instance. /// - Returns: A `Result` instance with the result of evaluating `transform` /// as the new failure value if this instance represents a failure. public func mapError<NewFailure>( _ transform: (Failure) -> NewFailure ) -> Result<Success, NewFailure> { switch self { case let .success(success): return .success(success) case let .failure(failure): return .failure(transform(failure)) } } /// Returns a new result, mapping any success value using the given /// transformation and unwrapping the produced result. /// /// - Parameter transform: A closure that takes the success value of the /// instance. /// - Returns: A `Result` instance with the result of evaluating `transform` /// as the new failure value if this instance represents a failure. public func flatMap<NewSuccess>( _ transform: (Success) -> Result<NewSuccess, Failure> ) -> Result<NewSuccess, Failure> { switch self { case let .success(success): return transform(success) case let .failure(failure): return .failure(failure) } } /// Returns a new result, mapping any failure value using the given /// transformation and unwrapping the produced result. /// /// - Parameter transform: A closure that takes the failure value of the /// instance. /// - Returns: A `Result` instance, either from the closure or the previous /// `.success`. public func flatMapError<NewFailure>( _ transform: (Failure) -> Result<Success, NewFailure> ) -> Result<Success, NewFailure> { switch self { case let .success(success): return .success(success) case let .failure(failure): return transform(failure) } } /// Returns the success value as a throwing expression. /// /// Use this method to retrieve the value of this result if it represents a /// success, or to catch the value if it represents a failure. /// /// let integerResult: Result<Int, Error> = .success(5) /// do { /// let value = try integerResult.get() /// print("The value is \(value).") /// } catch error { /// print("Error retrieving the value: \(error)") /// } /// // Prints "The value is 5." /// /// - Returns: The success value, if the instance represents a success. /// - Throws: The failure value, if the instance represents a failure. public func get() throws -> Success { switch self { case let .success(success): return success case let .failure(failure): throw failure } } } public struct AnyError: Error, CustomStringConvertible { /// The underlying error. public let underlyingError: Error public init(_ error: Error) { // If we already have any error, don't nest it. if case let error as AnyError = error { self = error } else { self.underlyingError = error } } public var description: String { return String(describing: underlyingError) } } extension Result: Equatable where Success: Equatable, Failure: Equatable { } extension Result: Hashable where Success: Hashable, Failure: Hashable { } extension Result: CustomStringConvertible { public var description: String { switch self { case .success(let value): return "Result(\(value))" case .failure(let error): return "Result(\(error))" } } } extension Result: Codable where Success: Codable, Failure: Codable { private enum CodingKeys: String, CodingKey { case success, failure } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .success(let value): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .success) try unkeyedContainer.encode(value) case .failure(let error): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .failure) try unkeyedContainer.encode(error) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .success: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let value = try unkeyedValues.decode(Success.self) self = .success(value) case .failure: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let error = try unkeyedValues.decode(Failure.self) self = .failure(error) } } }
mit
dfe9d755bb26096c64d578d53bff08a2
35.773333
133
0.594996
4.736119
false
false
false
false
mlgoogle/viossvc
viossvc/Scenes/ServantPersonalVC.swift
1
16987
// // ServantPersonalVC.swift // HappyTravel // // Created by 陈奕涛 on 16/8/4. // Copyright © 2016年 陈奕涛. All rights reserved. // import Foundation import UIKit import MJRefresh import SVProgressHUD public class ServantPersonalVC : UIViewController,UITableViewDelegate,UITableViewDataSource,ServantPersonalCellDelegate,SendMsgViewDelegate ,GuideViewDelegate { // MARK: - 属性 var personalInfo:UserInfoModel? // 自定义导航条、左右按钮和title var topView:UIView? var leftBtn:UIButton? var rightBtn:UIButton? var topTitle:UILabel? var tableView:UITableView? let header:MJRefreshStateHeader = MJRefreshStateHeader() let footer:MJRefreshAutoStateFooter = MJRefreshAutoStateFooter() // 头视图 var headerView:ServantHeaderView? // 是否关注状态 var follow = false var fansCount = 0 var pageNum:Int = 0 var dataArray = [servantDynamicModel]() var timer:NSTimer? // 刷新用 var offsetY:CGFloat = 0.0 // MARK: - 函数方法 override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if offsetY < 0 { UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true) } } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: false) } override public func viewDidLoad() { super.viewDidLoad() let userDefaults = NSUserDefaults.standardUserDefaults() if userDefaults.floatForKey("guideVersion") < ((NSBundle.mainBundle().infoDictionary! ["CFBundleShortVersionString"])?.floatValue) { loadGuide() } else { initViews() } //接收通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateImageAndName), name: "updateImageAndName", object: nil) } //移除通知 deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //通知实现 func updateImageAndName(notification: NSNotification?) { headerView?.didUpdateUI(CurrentUserHelper.shared.userInfo.head_url!, name: CurrentUserHelper.shared.userInfo.nickname!, star: CurrentUserHelper.shared.userInfo.praise_lv) } func loadGuide() { let guidView:GuidView = GuidView.init(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight)) guidView.delegate = self UIApplication.sharedApplication().keyWindow?.addSubview(guidView) let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setFloat(((NSBundle.mainBundle().infoDictionary! ["CFBundleShortVersionString"])?.floatValue)!, forKey: "guideVersion") } func initViews() { personalInfo = CurrentUserHelper.shared.userInfo addViews() header.performSelector(#selector(MJRefreshHeader.beginRefreshing), withObject: nil, afterDelay: 0.5) let userDefaults = NSUserDefaults.standardUserDefaults() let key = "isShownFiestTime1" let isshownfirsttime = userDefaults.valueForKey(key) if isshownfirsttime == nil { let imageView:UIImageView = UIImageView.init(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight)) imageView.image = UIImage.init(named: "助理端新手引导1") imageView.alpha = 0.5 UIApplication.sharedApplication().keyWindow?.addSubview(imageView) imageView.userInteractionEnabled = true let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.imageTapAction(_:))) imageView.addGestureRecognizer(tap) userDefaults.setValue(true, forKey: key) } } // 加载页面 func addViews() { tableView = UITableView.init(frame: CGRectMake(0, -20, ScreenWidth, ScreenHeight + 20), style: .Grouped) tableView?.backgroundColor = UIColor.init(decR: 242, decG: 242, decB: 242, a: 1) tableView?.autoresizingMask = [.FlexibleWidth,.FlexibleHeight] tableView?.delegate = self tableView?.dataSource = self tableView?.separatorStyle = .None tableView?.estimatedRowHeight = 120 tableView?.rowHeight = UITableViewAutomaticDimension tableView?.separatorStyle = .None tableView?.showsVerticalScrollIndicator = false tableView?.showsHorizontalScrollIndicator = false // 只有一条文字的Cell展示 tableView?.registerClass(ServantOneLabelCell.self, forCellReuseIdentifier: "ServantOneLabelCell") // 只有一张图片的Cell展示 tableView?.registerClass(ServantOnePicCell.self, forCellReuseIdentifier: "ServantOnePicCell") // 复合Cell展示 tableView?.registerClass(ServantPicAndLabelCell.self, forCellReuseIdentifier: "ServantPicAndLabelCell") view.addSubview(tableView!) header.setRefreshingTarget(self, refreshingAction: #selector(ServantPersonalVC.headerRefresh)) footer.setRefreshingTarget(self, refreshingAction: #selector(ServantPersonalVC.footerRefresh)) tableView?.mj_header = header tableView?.mj_footer = footer // 设置顶部 topView topView = UIView.init(frame: CGRectMake(0, 0, ScreenWidth, 64)) topView?.backgroundColor = UIColor.clearColor() view.addSubview(topView!) leftBtn = UIButton.init(frame: CGRectMake(15, 27, 30, 30)) leftBtn!.layer.masksToBounds = true leftBtn!.layer.cornerRadius = 15.0 leftBtn!.setImage(UIImage.init(named: "message-1"), forState: .Normal) topView?.addSubview(leftBtn!) leftBtn!.addTarget(self, action: #selector(ServantPersonalVC.backAction), forControlEvents: .TouchUpInside) rightBtn = UIButton.init(frame: CGRectMake(ScreenWidth - 45, 27, 30, 30)) rightBtn!.layer.masksToBounds = true rightBtn!.layer.cornerRadius = 15.0 rightBtn!.setImage(UIImage.init(named: "sendDynamic-1"), forState: .Normal) topView?.addSubview(rightBtn!) rightBtn!.addTarget(self, action: #selector(ServantPersonalVC.reportAction), forControlEvents: .TouchUpInside) topTitle = UILabel.init(frame: CGRectMake((leftBtn?.Right)! + 10 , (leftBtn?.Top)!, (rightBtn?.Left)! - leftBtn!.Right - 20, (leftBtn?.Height)!)) topView?.addSubview(topTitle!) topTitle?.font = UIFont.systemFontOfSize(17) topTitle?.textAlignment = .Center topTitle?.textColor = UIColor.init(decR: 51, decG: 51, decB: 51, a: 1) } func backAction() { let vc = MyInformationVC() vc.title = "我的消息" vc.hidesBottomBarWhenPushed = true navigationController?.setNavigationBarHidden(false, animated: false) navigationController?.pushViewController(vc, animated: true) } func reportAction() { let sendMsgView:SendMsgViewController = SendMsgViewController() sendMsgView.hidesBottomBarWhenPushed = true sendMsgView.delegate = self navigationController?.pushViewController(sendMsgView, animated: true) } // MARK: - UITableViewDelegate public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row < dataArray.count { let model:servantDynamicModel = dataArray[indexPath.row] let detailText:String = model.dynamic_text! let urlStr = model.dynamic_url let urlArray = urlStr!.componentsSeparatedByString(",") if urlStr?.characters.count == 0 { // 只有文字的Cell let cell = tableView.dequeueReusableCellWithIdentifier("ServantOneLabelCell", forIndexPath: indexPath) as! ServantOneLabelCell cell.delegate = self cell.selectionStyle = .None cell.updateLabelText(model) return cell } else if detailText.characters.count == 0 && urlArray.count == 1 { // 只有一张图片的cell let cell = tableView.dequeueReusableCellWithIdentifier("ServantOnePicCell", forIndexPath: indexPath) as! ServantOnePicCell cell.delegate = self cell.selectionStyle = .None cell.updateImage(model) return cell } else { // 复合cell let cell = tableView.dequeueReusableCellWithIdentifier("ServantPicAndLabelCell", forIndexPath: indexPath) as! ServantPicAndLabelCell cell.delegate = self cell.selectionStyle = .None cell.updateUI(model) return cell } } return UITableViewCell.init() } public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { headerView = ServantHeaderView.init(frame: CGRectMake(0, 0, ScreenWidth, 379)) headerView?.didUpdateUI(CurrentUserHelper.shared.userInfo.head_url!, name: CurrentUserHelper.shared.userInfo.nickname!, star: CurrentUserHelper.shared.userInfo.praise_lv) headerView?.updateFansCount(self.fansCount) return headerView } public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 316 } public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1 } // 滑动的时候改变顶部 topView public func scrollViewDidScroll(scrollView: UIScrollView) { let color:UIColor = UIColor.whiteColor() offsetY = scrollView.contentOffset.y if offsetY < 0 { UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true) topView?.backgroundColor = color.colorWithAlphaComponent(0) topTitle?.text = "" leftBtn?.setImage(UIImage.init(named: "message-1"), forState:.Normal) rightBtn?.setImage(UIImage.init(named: "sendDynamic-1"), forState: .Normal) } else { UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: true) let alpha:CGFloat = 1 - ((128 - offsetY) / 128) topView?.backgroundColor = color.colorWithAlphaComponent(alpha) let titleString = "首页" topTitle?.text = titleString leftBtn?.setImage(UIImage.init(named: "message-2"), forState:.Normal) rightBtn?.setImage(UIImage.init(named: "sendDynamic-2"), forState: .Normal) } } // MARK: 数据 // 刷新数据 func headerRefresh() { footer.state = .Idle pageNum = 0 let servantInfo:ServantInfoModel = ServantInfoModel() servantInfo.page_num = pageNum AppAPIHelper.userAPI().requestDynamicList(servantInfo, complete: { (response) in if let models = response as? [servantDynamicModel] { self.dataArray = models self.endRefresh() } if self.dataArray.count < 10 { self.noMoreData() } // 查询粉丝数 self.updateFollowCount() }, error: { [weak self](error) in self?.endRefresh() }) timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(endRefresh), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) } // 加载数据 func footerRefresh() { pageNum += 1 let servantInfo:ServantInfoModel = ServantInfoModel() servantInfo.page_num = pageNum AppAPIHelper.userAPI().requestDynamicList(servantInfo, complete: { (response) in let models = response as! [servantDynamicModel] self.dataArray += models self.endRefresh() if models.count == 0 { self.noMoreData() } }, error: { [weak self](error) in self?.endRefresh() }) timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(endRefresh), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) } // 停止刷新 func endRefresh() { if header.state == .Refreshing { header.endRefreshing() } if footer.state == .Refreshing { footer.endRefreshing() } if timer != nil { timer?.invalidate() timer = nil } tableView!.reloadData() } func noMoreData() { endRefresh() footer.state = .NoMoreData if dataArray.count == 0 { footer.setTitle("您还未发布任何动态,快去发布吧", forState: .NoMoreData) } else { footer.setTitle("暂无更多动态", forState: .NoMoreData) } } // 查询粉丝数量 func updateFollowCount() { let req = FollowCountRequestModel() req.uid = CurrentUserHelper.shared.uid req.type = 2 AppAPIHelper.userAPI().followCount(req, complete: { (response) in if let model = response as? FollowCountModel { self.headerView?.updateFansCount(model.follow_count) } }, error: nil) } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // 点赞 func servantIsLikedAction(sender: UIButton, model: servantDynamicModel) { let req = ServantThumbUpModel() req.dynamic_id = model.dynamic_id AppAPIHelper.userAPI().servantThumbup(req, complete: { (response) in let result = response as! ServantThumbUpResultModel let likecount = result.dynamic_like_count if result.result == 0 { sender.selected = true sender.setTitle(String(likecount), forState: .Selected) model.is_liked = 1 }else if result.result == 1 { sender.selected = false sender.setTitle(String(likecount), forState: .Normal) model.is_liked = 0 } model.dynamic_like_count = likecount }, error: nil) } // 图片点击放大 func servantImageDidClicked(model: servantDynamicModel, index: Int) { // 解析图片链接 let urlString:String = model.dynamic_url! let imageUrls:NSArray = urlString.componentsSeparatedByString(",") // 显示图片 PhotoBroswerVC.show(self, type: PhotoBroswerVCTypePush , index: UInt(index)) {() -> [AnyObject]! in let photoArray:NSMutableArray = NSMutableArray() let count:Int = imageUrls.count for i in 0..<count { let model: PhotoModel = PhotoModel.init() model.mid = UInt(i) + 1 model.image_HD_U = imageUrls.objectAtIndex(i) as! String photoArray.addObject(model) } return photoArray as [AnyObject] } } // 刷新界面 func sendMsgViewDidSendMessage() { header.performSelector(#selector(MJRefreshHeader.beginRefreshing), withObject: nil, afterDelay: 0.5) } // 新手引导图片点击 func imageTapAction(tap:UITapGestureRecognizer) { let imageView:UIImageView = tap.view as! UIImageView imageView.removeFromSuperview() let userDefaults = NSUserDefaults.standardUserDefaults() let key = "isShownFiestTime1" userDefaults.setValue(true, forKey: key) } // 启动页消失 func guideDidDismissed() { initViews() } }
apache-2.0
42b84b2a15f6cde1af281b001c66395f
36.885845
178
0.618959
5.10899
false
false
false
false
kobe41999/transea-mumble
Source/Classes/NCCU/UserVC/NUserVC.swift
1
3925
// // UserVC.swift // Mumble // // Created by 賴昱榮 on 2017/4/24. // // import Foundation import UIKit class UserVC: UIViewController { @IBOutlet var imgHead: UIImageView! @IBOutlet var labelName: UILabel! @IBOutlet var switchAvailable: UISwitch! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let currentUser = PFUser.current() let userID: String = currentUser!.username! print("userid=\(userID)") if (currentUser != nil) { let array: [Any] = userID.components(separatedBy: "@") labelName.text = array[0] as! String } } @IBAction func testBid(_ sender: Any) { let serverURL: String = "http://162.243.49.105:8888/bid" let currentUser = PFUser.current() let userID: String = currentUser!.username! print("userid=\(userID)") if !(currentUser != nil) { return } var resultsDictionary: [AnyHashable: Any] // 返回的 JSON 数据 let starter: String = "starter" let bid = Int(20) let userData: [AnyHashable: Any] = [ "userid" : userID, "starter" : starter, "bid" : bid ] let mainJson: [AnyHashable: Any] = [ "data" : userData, "type" : "bid" ] var error: Error? let jsonData: Data? = try? JSONSerialization.data(withJSONObject: mainJson, options: JSONSerialization.WritingOptions.prettyPrinted) let post = String(data: jsonData!, encoding: String.Encoding.utf8) print("\(post)") //NSString *queryString = [NSString stringWithFormat:@"http://example.com/username.php?name=%@", [self.txtName text]]; var theRequest = NSMutableURLRequest(url: URL(string: serverURL)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 60.0) theRequest.httpMethod = "POST" theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") // should check for and handle errors here but we aren't theRequest.httpBody = jsonData NSURLConnection.sendAsynchronousRequest(theRequest as URLRequest, queue: OperationQueue.main, completionHandler: {(_ response: URLResponse, _ data: Data, _ error: Error?) -> Void in if error != nil { //do something with error print("\(error?.localizedDescription)") } else { var responseText = String(describing:(data, encoding: String.Encoding.ascii)) print("Response: \(responseText)") let newLineStr: String = "\n" responseText = responseText.replacingOccurrences(of: "<br />", with: newLineStr) } } as! (URLResponse?, Data?, Error?) -> Void) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onSwitch(_ sender: Any) { let currentUser = PFUser.current() if switchAvailable.isOn { print("ON") currentUser?["AVAILABLE"] = Int(true) } else { print("OFF") currentUser?["AVAILABLE"] = Int(false) } currentUser?.saveInBackground(block: {(_ succeeded: Bool, _ error: Error?) -> Void in }) } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ deinit { } } import ParseFacebookUtilsV4
bsd-3-clause
9925323b72b3459fd800cbc6e6fb0868
35.877358
189
0.595037
4.772894
false
false
false
false
stephentyrone/swift
stdlib/public/core/UnicodeScalarProperties.swift
1
59369
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Exposes advanced properties of Unicode.Scalar defined by the Unicode // Standard. //===----------------------------------------------------------------------===// import SwiftShims extension Unicode.Scalar { /// A value that provides access to properties of a Unicode scalar that are /// defined by the Unicode standard. public struct Properties { @usableFromInline internal var _scalar: Unicode.Scalar internal init(_ scalar: Unicode.Scalar) { self._scalar = scalar } // Provide the value as UChar32 to make calling the ICU APIs cleaner internal var icuValue: __swift_stdlib_UChar32 { return __swift_stdlib_UChar32(bitPattern: self._scalar._value) } } /// Properties of this scalar defined by the Unicode standard. /// /// Use this property to access the Unicode properties of a Unicode scalar /// value. The following code tests whether a string contains any math /// symbols: /// /// let question = "Which is larger, 3 * 3 * 3 or 10 + 10 + 10?" /// let hasMathSymbols = question.unicodeScalars.contains(where: { /// $0.properties.isMath /// }) /// // hasMathSymbols == true public var properties: Properties { return Properties(self) } } /// Boolean properties that are defined by the Unicode Standard (i.e., not /// ICU-specific). extension Unicode.Scalar.Properties { internal func _hasBinaryProperty( _ property: __swift_stdlib_UProperty ) -> Bool { return __swift_stdlib_u_hasBinaryProperty(icuValue, property) != 0 } /// A Boolean value indicating whether the scalar is alphabetic. /// /// Alphabetic scalars are the primary units of alphabets and/or syllabaries. /// /// This property corresponds to the "Alphabetic" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isAlphabetic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ALPHABETIC) } /// A Boolean value indicating whether the scalar is an ASCII character /// commonly used for the representation of hexadecimal numbers. /// /// The only scalars for which this property is `true` are: /// /// * U+0030...U+0039: DIGIT ZERO...DIGIT NINE /// * U+0041...U+0046: LATIN CAPITAL LETTER A...LATIN CAPITAL LETTER F /// * U+0061...U+0066: LATIN SMALL LETTER A...LATIN SMALL LETTER F /// /// This property corresponds to the "ASCII_Hex_Digit" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isASCIIHexDigit: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ASCII_HEX_DIGIT) } /// A Boolean value indicating whether the scalar is a format control /// character that has a specific function in the Unicode Bidrectional /// Algorithm. /// /// This property corresponds to the "Bidi_Control" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isBidiControl: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_CONTROL) } /// A Boolean value indicating whether the scalar is mirrored in /// bidirectional text. /// /// This property corresponds to the "Bidi_Mirrored" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isBidiMirrored: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_MIRRORED) } /// A Boolean value indicating whether the scalar is a punctuation /// symbol explicitly called out as a dash in the Unicode Standard or a /// compatibility equivalent. /// /// This property corresponds to the "Dash" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDash: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DASH) } /// A Boolean value indicating whether the scalar is a default-ignorable /// code point. /// /// Default-ignorable code points are those that should be ignored by default /// in rendering (unless explicitly supported). They have no visible glyph or /// advance width in and of themselves, although they may affect the display, /// positioning, or adornment of adjacent or surrounding characters. /// /// This property corresponds to the "Default_Ignorable_Code_Point" property /// in the [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDefaultIgnorableCodePoint: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DEFAULT_IGNORABLE_CODE_POINT) } /// A Boolean value indicating whether the scalar is deprecated. /// /// Scalars are never removed from the Unicode Standard, but the usage of /// deprecated scalars is strongly discouraged. /// /// This property corresponds to the "Deprecated" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDeprecated: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DEPRECATED) } /// A Boolean value indicating whether the scalar is a diacritic. /// /// Diacritics are scalars that linguistically modify the meaning of another /// scalar to which they apply. Scalars for which this property is `true` are /// frequently, but not always, combining marks or modifiers. /// /// This property corresponds to the "Diacritic" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isDiacritic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_DIACRITIC) } /// A Boolean value indicating whether the scalar's principal function is /// to extend the value or shape of a preceding alphabetic scalar. /// /// Typical extenders are length and iteration marks. /// /// This property corresponds to the "Extender" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isExtender: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EXTENDER) } /// A Boolean value indicating whether the scalar is excluded from /// composition when performing Unicode normalization. /// /// This property corresponds to the "Full_Composition_Exclusion" property in /// the [Unicode Standard](http://www.unicode.org/versions/latest/). public var isFullCompositionExclusion: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_FULL_COMPOSITION_EXCLUSION) } /// A Boolean value indicating whether the scalar is a grapheme base. /// /// A grapheme base can be thought of as a space-occupying glyph above or /// below which other non-spacing modifying glyphs can be applied. For /// example, when the character `é` is represented in its decomposed form, /// the grapheme base is "e" (U+0065 LATIN SMALL LETTER E) and it is followed /// by a single grapheme extender, U+0301 COMBINING ACUTE ACCENT. /// /// The set of scalars for which `isGraphemeBase` is `true` is disjoint by /// definition from the set for which `isGraphemeExtend` is `true`. /// /// This property corresponds to the "Grapheme_Base" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isGraphemeBase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_BASE) } /// A Boolean value indicating whether the scalar is a grapheme extender. /// /// A grapheme extender can be thought of primarily as a non-spacing glyph /// that is applied above or below another glyph. For example, when the /// character `é` is represented in its decomposed form, the grapheme base is /// "e" (U+0065 LATIN SMALL LETTER E) and it is followed by a single grapheme /// extender, U+0301 COMBINING ACUTE ACCENT. /// /// The set of scalars for which `isGraphemeExtend` is `true` is disjoint by /// definition from the set for which `isGraphemeBase` is `true`. /// /// This property corresponds to the "Grapheme_Extend" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isGraphemeExtend: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_EXTEND) } /// A Boolean value indicating whether the scalar is one that is commonly /// used for the representation of hexadecimal numbers or a compatibility /// equivalent. /// /// This property is `true` for all scalars for which `isASCIIHexDigit` is /// `true` as well as for their CJK halfwidth and fullwidth variants. /// /// This property corresponds to the "Hex_Digit" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isHexDigit: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_HEX_DIGIT) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a non-starting position in a /// programming language identifier. /// /// Applications that store identifiers in NFKC normalized form should instead /// use `isXIDContinue` to check whether a scalar is a valid identifier /// character. /// /// This property corresponds to the "ID_Continue" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDContinue: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_CONTINUE) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a starting position in a /// programming language identifier. /// /// Applications that store identifiers in NFKC normalized form should instead /// use `isXIDStart` to check whether a scalar is a valid identifier /// character. /// /// This property corresponds to the "ID_Start" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDStart: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_START) } /// A Boolean value indicating whether the scalar is considered to be a /// CJKV (Chinese, Japanese, Korean, and Vietnamese) or other siniform /// (Chinese writing-related) ideograph. /// /// This property roughly defines the class of "Chinese characters" and does /// not include characters of other logographic scripts such as Cuneiform or /// Egyptian Hieroglyphs. /// /// This property corresponds to the "Ideographic" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIdeographic: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDEOGRAPHIC) } /// A Boolean value indicating whether the scalar is an ideographic /// description character that determines how the two ideographic characters /// or ideographic description sequences that follow it are to be combined to /// form a single character. /// /// Ideographic description characters are technically printable characters, /// but advanced rendering engines may use them to approximate ideographs that /// are otherwise unrepresentable. /// /// This property corresponds to the "IDS_Binary_Operator" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDSBinaryOperator: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_BINARY_OPERATOR) } /// A Boolean value indicating whether the scalar is an ideographic /// description character that determines how the three ideographic characters /// or ideographic description sequences that follow it are to be combined to /// form a single character. /// /// Ideographic description characters are technically printable characters, /// but advanced rendering engines may use them to approximate ideographs that /// are otherwise unrepresentable. /// /// This property corresponds to the "IDS_Trinary_Operator" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isIDSTrinaryOperator: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_TRINARY_OPERATOR) } /// A Boolean value indicating whether the scalar is a format control /// character that has a specific function in controlling cursive joining and /// ligation. /// /// There are two scalars for which this property is `true`: /// /// * When U+200C ZERO WIDTH NON-JOINER is inserted between two characters, it /// directs the rendering engine to render them separately/disconnected when /// it might otherwise render them as a ligature. For example, a rendering /// engine might display "fl" in English as a connected glyph; inserting the /// zero width non-joiner would force them to be rendered as disconnected /// glyphs. /// /// * When U+200D ZERO WIDTH JOINER is inserted between two characters, it /// directs the rendering engine to render them as a connected glyph when it /// would otherwise render them independently. The zero width joiner is also /// used to construct complex emoji from sequences of base emoji characters. /// For example, the various "family" emoji are encoded as sequences of man, /// woman, or child emoji that are interleaved with zero width joiners. /// /// This property corresponds to the "Join_Control" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isJoinControl: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_JOIN_CONTROL) } /// A Boolean value indicating whether the scalar requires special handling /// for operations involving ordering, such as sorting and searching. /// /// This property applies to a small number of spacing vowel letters occurring /// in some Southeast Asian scripts like Thai and Lao, which use a visual /// order display model. Such letters are stored in text ahead of /// syllable-initial consonants. /// /// This property corresponds to the "Logical_Order_Exception" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isLogicalOrderException: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_LOGICAL_ORDER_EXCEPTION) } /// A Boolean value indicating whether the scalar's letterform is /// considered lowercase. /// /// This property corresponds to the "Lowercase" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isLowercase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_LOWERCASE) } /// A Boolean value indicating whether the scalar is one that naturally /// appears in mathematical contexts. /// /// The set of scalars for which this property is `true` includes mathematical /// operators and symbols as well as specific Greek and Hebrew letter /// variants that are categorized as symbols. Notably, it does _not_ contain /// the standard digits or Latin/Greek letter blocks; instead, it contains the /// mathematical Latin, Greek, and Arabic letters and numbers defined in the /// Supplemental Multilingual Plane. /// /// This property corresponds to the "Math" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isMath: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_MATH) } /// A Boolean value indicating whether the scalar is permanently reserved /// for internal use. /// /// This property corresponds to the "Noncharacter_Code_Point" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isNoncharacterCodePoint: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_NONCHARACTER_CODE_POINT) } /// A Boolean value indicating whether the scalar is one that is used in /// writing to surround quoted text. /// /// This property corresponds to the "Quotation_Mark" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isQuotationMark: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_QUOTATION_MARK) } /// A Boolean value indicating whether the scalar is a radical component of /// CJK characters, Tangut characters, or Yi syllables. /// /// These scalars are often the components of ideographic description /// sequences, as defined by the `isIDSBinaryOperator` and /// `isIDSTrinaryOperator` properties. /// /// This property corresponds to the "Radical" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isRadical: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_RADICAL) } /// A Boolean value indicating whether the scalar has a "soft dot" that /// disappears when a diacritic is placed over the scalar. /// /// For example, "i" is soft dotted because the dot disappears when adding an /// accent mark, as in "í". /// /// This property corresponds to the "Soft_Dotted" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isSoftDotted: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_SOFT_DOTTED) } /// A Boolean value indicating whether the scalar is a punctuation symbol /// that typically marks the end of a textual unit. /// /// This property corresponds to the "Terminal_Punctuation" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isTerminalPunctuation: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_TERMINAL_PUNCTUATION) } /// A Boolean value indicating whether the scalar is one of the unified /// CJK ideographs in the Unicode Standard. /// /// This property is false for CJK punctuation and symbols, as well as for /// compatibility ideographs (which canonically decompose to unified /// ideographs). /// /// This property corresponds to the "Unified_Ideograph" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isUnifiedIdeograph: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_UNIFIED_IDEOGRAPH) } /// A Boolean value indicating whether the scalar's letterform is /// considered uppercase. /// /// This property corresponds to the "Uppercase" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isUppercase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_UPPERCASE) } /// A Boolean value indicating whether the scalar is a whitespace /// character. /// /// This property is `true` for scalars that are spaces, separator characters, /// and other control characters that should be treated as whitespace for the /// purposes of parsing text elements. /// /// This property corresponds to the "White_Space" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isWhitespace: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_WHITE_SPACE) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a non-starting position in a /// programming language identifier, with adjustments made for NFKC normalized /// form. /// /// The set of scalars `[:XID_Continue:]` closes the set `[:ID_Continue:]` /// under NFKC normalization by removing any scalars whose normalized form is /// not of the form `[:ID_Continue:]*`. /// /// This property corresponds to the "XID_Continue" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isXIDContinue: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_CONTINUE) } /// A Boolean value indicating whether the scalar is one which is /// recommended to be allowed to appear in a starting position in a /// programming language identifier, with adjustments made for NFKC normalized /// form. /// /// The set of scalars `[:XID_Start:]` closes the set `[:ID_Start:]` under /// NFKC normalization by removing any scalars whose normalized form is not of /// the form `[:ID_Start:] [:ID_Continue:]*`. /// /// This property corresponds to the "XID_Start" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isXIDStart: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_START) } /// A Boolean value indicating whether the scalar is a punctuation mark /// that generally marks the end of a sentence. /// /// This property corresponds to the "Sentence_Terminal" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isSentenceTerminal: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_S_TERM) } /// A Boolean value indicating whether the scalar is a variation selector. /// /// Variation selectors allow rendering engines that support them to choose /// different glyphs to display for a particular code point. /// /// This property corresponds to the "Variation_Selector" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isVariationSelector: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_VARIATION_SELECTOR) } /// A Boolean value indicating whether the scalar is recommended to have /// syntactic usage in patterns represented in source code. /// /// This property corresponds to the "Pattern_Syntax" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isPatternSyntax: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_SYNTAX) } /// A Boolean value indicating whether the scalar is recommended to be /// treated as whitespace when parsing patterns represented in source code. /// /// This property corresponds to the "Pattern_White_Space" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isPatternWhitespace: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_WHITE_SPACE) } /// A Boolean value indicating whether the scalar is considered to be /// either lowercase, uppercase, or titlecase. /// /// Though similar in name, this property is *not* equivalent to /// `changesWhenCaseMapped`. The set of scalars for which `isCased` is `true` /// is a superset of those for which `changesWhenCaseMapped` is `true`. For /// example, the Latin small capitals that are used by the International /// Phonetic Alphabet have a case, but do not change when they are mapped to /// any of the other cases. /// /// This property corresponds to the "Cased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isCased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CASED) } /// A Boolean value indicating whether the scalar is ignored for casing /// purposes. /// /// This property corresponds to the "Case_Ignorable" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var isCaseIgnorable: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CASE_IGNORABLE) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the `lowercaseMapping` of each constituent scalar. /// /// This property corresponds to the "Changes_When_Lowercased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenLowercased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_LOWERCASED) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the `uppercaseMapping` of each constituent scalar. /// /// This property corresponds to the "Changes_When_Uppercased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenUppercased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_UPPERCASED) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the `titlecaseMapping` of each constituent scalar. /// /// This property corresponds to the "Changes_When_Titlecased" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenTitlecased: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_TITLECASED) } /// A Boolean value indicating whether the scalar's normalized form differs /// from the case-fold mapping of each constituent scalar. /// /// This property corresponds to the "Changes_When_Casefolded" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenCaseFolded: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEFOLDED) } /// A Boolean value indicating whether the scalar may change when it /// undergoes case mapping. /// /// This property is `true` whenever one or more of `changesWhenLowercased`, /// `changesWhenUppercased`, or `changesWhenTitlecased` are `true`. /// /// This property corresponds to the "Changes_When_Casemapped" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenCaseMapped: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEMAPPED) } /// A Boolean value indicating whether the scalar is one that is not /// identical to its NFKC case-fold mapping. /// /// This property corresponds to the "Changes_When_NFKC_Casefolded" property /// in the [Unicode Standard](http://www.unicode.org/versions/latest/). public var changesWhenNFKCCaseFolded: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // FIXME: These properties were introduced in ICU 57, but Ubuntu 16.04 comes // with ICU 55 so the values won't be correct there. Exclude them on // non-Darwin platforms for now; bundling ICU with the toolchain would resolve // this and other inconsistencies (https://bugs.swift.org/browse/SR-6076). /// A Boolean value indicating whether the scalar has an emoji /// presentation, whether or not it is the default. /// /// This property is true for scalars that are rendered as emoji by default /// and also for scalars that have a non-default emoji rendering when followed /// by U+FE0F VARIATION SELECTOR-16. This includes some scalars that are not /// typically considered to be emoji: /// /// let scalars: [Unicode.Scalar] = ["😎", "$", "0"] /// for s in scalars { /// print(s, "-->", s.properties.isEmoji) /// } /// // 😎 --> true /// // $ --> false /// // 0 --> true /// /// The final result is true because the ASCII digits have non-default emoji /// presentations; some platforms render these with an alternate appearance. /// /// Because of this behavior, testing `isEmoji` alone on a single scalar is /// insufficient to determine if a unit of text is rendered as an emoji; a /// correct test requires inspecting multiple scalars in a `Character`. In /// addition to checking whether the base scalar has `isEmoji == true`, you /// must also check its default presentation (see `isEmojiPresentation`) and /// determine whether it is followed by a variation selector that would modify /// the presentation. /// /// This property corresponds to the "Emoji" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmoji: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI) } /// A Boolean value indicating whether the scalar is one that should be /// rendered with an emoji presentation, rather than a text presentation, by /// default. /// /// Scalars that have default to emoji presentation can be followed by /// U+FE0E VARIATION SELECTOR-15 to request the text presentation of the /// scalar instead. Likewise, scalars that default to text presentation can /// be followed by U+FE0F VARIATION SELECTOR-16 to request the emoji /// presentation. /// /// This property corresponds to the "Emoji_Presentation" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiPresentation: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_PRESENTATION) } /// A Boolean value indicating whether the scalar is one that can modify /// a base emoji that precedes it. /// /// The Fitzpatrick skin types are examples of emoji modifiers; they change /// the appearance of the preceding emoji base (that is, a scalar for which /// `isEmojiModifierBase` is true) by rendering it with a different skin tone. /// /// This property corresponds to the "Emoji_Modifier" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiModifier: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER) } /// A Boolean value indicating whether the scalar is one whose appearance /// can be changed by an emoji modifier that follows it. /// /// This property corresponds to the "Emoji_Modifier_Base" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmojiModifierBase: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER_BASE) } #endif } /// Case mapping properties. extension Unicode.Scalar.Properties { // The type of ICU case conversion functions. internal typealias _U_StrToX = ( /* dest */ UnsafeMutablePointer<__swift_stdlib_UChar>, /* destCapacity */ Int32, /* src */ UnsafePointer<__swift_stdlib_UChar>, /* srcLength */ Int32, /* locale */ UnsafePointer<Int8>, /* pErrorCode */ UnsafeMutablePointer<__swift_stdlib_UErrorCode> ) -> Int32 /// Applies the given ICU string mapping to the scalar. /// /// This function attempts first to write the mapping into a stack-based /// UTF-16 buffer capable of holding 16 code units, which should be enough for /// all current case mappings. In the event more space is needed, it will be /// allocated on the heap. internal func _applyMapping(_ u_strTo: _U_StrToX) -> String { // Allocate 16 code units on the stack. var fixedArray = _FixedArray16<UInt16>(allZeros: ()) let count: Int = fixedArray.withUnsafeMutableBufferPointer { buf in return _scalar.withUTF16CodeUnits { utf16 in var err = __swift_stdlib_U_ZERO_ERROR let correctSize = u_strTo( buf.baseAddress._unsafelyUnwrappedUnchecked, Int32(buf.count), utf16.baseAddress._unsafelyUnwrappedUnchecked, Int32(utf16.count), "", &err) guard err.isSuccess else { fatalError("Unexpected error case-converting Unicode scalar.") } return Int(correctSize) } } if _fastPath(count <= 16) { fixedArray.count = count return fixedArray.withUnsafeBufferPointer { String._uncheckedFromUTF16($0) } } // Allocate `count` code units on the heap. let array = Array<UInt16>(unsafeUninitializedCapacity: count) { buf, initializedCount in _scalar.withUTF16CodeUnits { utf16 in var err = __swift_stdlib_U_ZERO_ERROR let correctSize = u_strTo( buf.baseAddress._unsafelyUnwrappedUnchecked, Int32(buf.count), utf16.baseAddress._unsafelyUnwrappedUnchecked, Int32(utf16.count), "", &err) guard err.isSuccess else { fatalError("Unexpected error case-converting Unicode scalar.") } _internalInvariant(count == correctSize, "inconsistent ICU behavior") initializedCount = count } } return array.withUnsafeBufferPointer { String._uncheckedFromUTF16($0) } } /// The lowercase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the character "İ" (U+0130 LATIN CAPITAL LETTER I /// WITH DOT ABOVE) becomes two scalars (U+0069 LATIN SMALL LETTER I, U+0307 /// COMBINING DOT ABOVE) when converted to lowercase. /// /// This property corresponds to the "Lowercase_Mapping" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var lowercaseMapping: String { return _applyMapping(__swift_stdlib_u_strToLower) } /// The titlecase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the ligature "fi" (U+FB01 LATIN SMALL LIGATURE FI) /// becomes "Fi" (U+0046 LATIN CAPITAL LETTER F, U+0069 LATIN SMALL LETTER I) /// when converted to titlecase. /// /// This property corresponds to the "Titlecase_Mapping" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var titlecaseMapping: String { return _applyMapping { ptr, cap, src, len, locale, err in return __swift_stdlib_u_strToTitle(ptr, cap, src, len, nil, locale, err) } } /// The uppercase mapping of the scalar. /// /// This property is a `String`, not a `Unicode.Scalar` or `Character`, /// because some mappings may transform a scalar into multiple scalars or /// graphemes. For example, the German letter "ß" (U+00DF LATIN SMALL LETTER /// SHARP S) becomes "SS" (U+0053 LATIN CAPITAL LETTER S, U+0053 LATIN CAPITAL /// LETTER S) when converted to uppercase. /// /// This property corresponds to the "Uppercase_Mapping" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var uppercaseMapping: String { return _applyMapping(__swift_stdlib_u_strToUpper) } } extension Unicode { /// A version of the Unicode Standard represented by its major and minor /// components. public typealias Version = (major: Int, minor: Int) } extension Unicode.Scalar.Properties { /// The earliest version of the Unicode Standard in which the scalar was /// assigned. /// /// This value is `nil` for code points that have not yet been assigned. /// /// This property corresponds to the "Age" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var age: Unicode.Version? { var versionInfo: __swift_stdlib_UVersionInfo = (0, 0, 0, 0) withUnsafeMutablePointer(to: &versionInfo) { tuplePtr in tuplePtr.withMemoryRebound(to: UInt8.self, capacity: 4) { versionInfoPtr in __swift_stdlib_u_charAge(icuValue, versionInfoPtr) } } guard versionInfo.0 != 0 else { return nil } return (major: Int(versionInfo.0), minor: Int(versionInfo.1)) } } extension Unicode { /// The most general classification of a Unicode scalar. /// /// The general category of a scalar is its "first-order, most usual /// categorization". It does not attempt to cover multiple uses of some /// scalars, such as the use of letters to represent Roman numerals. public enum GeneralCategory { /// An uppercase letter. /// /// This value corresponds to the category `Uppercase_Letter` (abbreviated /// `Lu`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case uppercaseLetter /// A lowercase letter. /// /// This value corresponds to the category `Lowercase_Letter` (abbreviated /// `Ll`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case lowercaseLetter /// A digraph character whose first part is uppercase. /// /// This value corresponds to the category `Titlecase_Letter` (abbreviated /// `Lt`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case titlecaseLetter /// A modifier letter. /// /// This value corresponds to the category `Modifier_Letter` (abbreviated /// `Lm`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case modifierLetter /// Other letters, including syllables and ideographs. /// /// This value corresponds to the category `Other_Letter` (abbreviated /// `Lo`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherLetter /// A non-spacing combining mark with zero advance width (abbreviated Mn). /// /// This value corresponds to the category `Nonspacing_Mark` (abbreviated /// `Mn`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case nonspacingMark /// A spacing combining mark with positive advance width. /// /// This value corresponds to the category `Spacing_Mark` (abbreviated `Mc`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case spacingMark /// An enclosing combining mark. /// /// This value corresponds to the category `Enclosing_Mark` (abbreviated /// `Me`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case enclosingMark /// A decimal digit. /// /// This value corresponds to the category `Decimal_Number` (abbreviated /// `Nd`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case decimalNumber /// A letter-like numeric character. /// /// This value corresponds to the category `Letter_Number` (abbreviated /// `Nl`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case letterNumber /// A numeric character of another type. /// /// This value corresponds to the category `Other_Number` (abbreviated `No`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherNumber /// A connecting punctuation mark, like a tie. /// /// This value corresponds to the category `Connector_Punctuation` /// (abbreviated `Pc`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case connectorPunctuation /// A dash or hyphen punctuation mark. /// /// This value corresponds to the category `Dash_Punctuation` (abbreviated /// `Pd`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case dashPunctuation /// An opening punctuation mark of a pair. /// /// This value corresponds to the category `Open_Punctuation` (abbreviated /// `Ps`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case openPunctuation /// A closing punctuation mark of a pair. /// /// This value corresponds to the category `Close_Punctuation` (abbreviated /// `Pe`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case closePunctuation /// An initial quotation mark. /// /// This value corresponds to the category `Initial_Punctuation` /// (abbreviated `Pi`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case initialPunctuation /// A final quotation mark. /// /// This value corresponds to the category `Final_Punctuation` (abbreviated /// `Pf`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case finalPunctuation /// A punctuation mark of another type. /// /// This value corresponds to the category `Other_Punctuation` (abbreviated /// `Po`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherPunctuation /// A symbol of mathematical use. /// /// This value corresponds to the category `Math_Symbol` (abbreviated `Sm`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case mathSymbol /// A currency sign. /// /// This value corresponds to the category `Currency_Symbol` (abbreviated /// `Sc`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case currencySymbol /// A non-letterlike modifier symbol. /// /// This value corresponds to the category `Modifier_Symbol` (abbreviated /// `Sk`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case modifierSymbol /// A symbol of another type. /// /// This value corresponds to the category `Other_Symbol` (abbreviated /// `So`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case otherSymbol /// A space character of non-zero width. /// /// This value corresponds to the category `Space_Separator` (abbreviated /// `Zs`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case spaceSeparator /// A line separator, which is specifically (and only) U+2028 LINE /// SEPARATOR. /// /// This value corresponds to the category `Line_Separator` (abbreviated /// `Zl`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case lineSeparator /// A paragraph separator, which is specifically (and only) U+2029 PARAGRAPH /// SEPARATOR. /// /// This value corresponds to the category `Paragraph_Separator` /// (abbreviated `Zp`) in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case paragraphSeparator /// A C0 or C1 control code. /// /// This value corresponds to the category `Control` (abbreviated `Cc`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case control /// A format control character. /// /// This value corresponds to the category `Format` (abbreviated `Cf`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case format /// A surrogate code point. /// /// This value corresponds to the category `Surrogate` (abbreviated `Cs`) in /// the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case surrogate /// A private-use character. /// /// This value corresponds to the category `Private_Use` (abbreviated `Co`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case privateUse /// A reserved unassigned code point or a non-character. /// /// This value corresponds to the category `Unassigned` (abbreviated `Cn`) /// in the /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values). case unassigned internal init(rawValue: __swift_stdlib_UCharCategory) { switch rawValue { case __swift_stdlib_U_UNASSIGNED: self = .unassigned case __swift_stdlib_U_UPPERCASE_LETTER: self = .uppercaseLetter case __swift_stdlib_U_LOWERCASE_LETTER: self = .lowercaseLetter case __swift_stdlib_U_TITLECASE_LETTER: self = .titlecaseLetter case __swift_stdlib_U_MODIFIER_LETTER: self = .modifierLetter case __swift_stdlib_U_OTHER_LETTER: self = .otherLetter case __swift_stdlib_U_NON_SPACING_MARK: self = .nonspacingMark case __swift_stdlib_U_ENCLOSING_MARK: self = .enclosingMark case __swift_stdlib_U_COMBINING_SPACING_MARK: self = .spacingMark case __swift_stdlib_U_DECIMAL_DIGIT_NUMBER: self = .decimalNumber case __swift_stdlib_U_LETTER_NUMBER: self = .letterNumber case __swift_stdlib_U_OTHER_NUMBER: self = .otherNumber case __swift_stdlib_U_SPACE_SEPARATOR: self = .spaceSeparator case __swift_stdlib_U_LINE_SEPARATOR: self = .lineSeparator case __swift_stdlib_U_PARAGRAPH_SEPARATOR: self = .paragraphSeparator case __swift_stdlib_U_CONTROL_CHAR: self = .control case __swift_stdlib_U_FORMAT_CHAR: self = .format case __swift_stdlib_U_PRIVATE_USE_CHAR: self = .privateUse case __swift_stdlib_U_SURROGATE: self = .surrogate case __swift_stdlib_U_DASH_PUNCTUATION: self = .dashPunctuation case __swift_stdlib_U_START_PUNCTUATION: self = .openPunctuation case __swift_stdlib_U_END_PUNCTUATION: self = .closePunctuation case __swift_stdlib_U_CONNECTOR_PUNCTUATION: self = .connectorPunctuation case __swift_stdlib_U_OTHER_PUNCTUATION: self = .otherPunctuation case __swift_stdlib_U_MATH_SYMBOL: self = .mathSymbol case __swift_stdlib_U_CURRENCY_SYMBOL: self = .currencySymbol case __swift_stdlib_U_MODIFIER_SYMBOL: self = .modifierSymbol case __swift_stdlib_U_OTHER_SYMBOL: self = .otherSymbol case __swift_stdlib_U_INITIAL_PUNCTUATION: self = .initialPunctuation case __swift_stdlib_U_FINAL_PUNCTUATION: self = .finalPunctuation default: fatalError("Unknown general category \(rawValue)") } } } } // Internal helpers extension Unicode.GeneralCategory { internal var _isSymbol: Bool { switch self { case .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol: return true default: return false } } internal var _isPunctuation: Bool { switch self { case .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation, .initialPunctuation, .finalPunctuation, .otherPunctuation: return true default: return false } } } extension Unicode.Scalar.Properties { /// The general category (most usual classification) of the scalar. /// /// This property corresponds to the "General_Category" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var generalCategory: Unicode.GeneralCategory { let rawValue = __swift_stdlib_UCharCategory( __swift_stdlib_UCharCategory.RawValue( __swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_GENERAL_CATEGORY))) return Unicode.GeneralCategory(rawValue: rawValue) } } extension Unicode.Scalar.Properties { internal func _scalarName( _ choice: __swift_stdlib_UCharNameChoice ) -> String? { var err = __swift_stdlib_U_ZERO_ERROR let count = Int(__swift_stdlib_u_charName(icuValue, choice, nil, 0, &err)) guard count > 0 else { return nil } // ICU writes a trailing null, so we have to save room for it as well. var array = Array<UInt8>(repeating: 0, count: count + 1) return array.withUnsafeMutableBufferPointer { bufPtr in var err = __swift_stdlib_U_ZERO_ERROR let correctSize = __swift_stdlib_u_charName( icuValue, choice, UnsafeMutableRawPointer(bufPtr.baseAddress._unsafelyUnwrappedUnchecked) .assumingMemoryBound(to: Int8.self), Int32(bufPtr.count), &err) guard err.isSuccess else { fatalError("Unexpected error case-converting Unicode scalar.") } _internalInvariant(count == correctSize, "inconsistent ICU behavior") return String._fromASCII( UnsafeBufferPointer(rebasing: bufPtr[..<count])) } } /// The published name of the scalar. /// /// Some scalars, such as control characters, do not have a value for this /// property in the Unicode Character Database. For such scalars, this /// property is `nil`. /// /// This property corresponds to the "Name" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var name: String? { return _scalarName(__swift_stdlib_U_UNICODE_CHAR_NAME) } /// The normative formal alias of the scalar. /// /// The name of a scalar is immutable and never changed in future versions of /// the Unicode Standard. The `nameAlias` property is provided to issue /// corrections if a name was issued erroneously. For example, the `name` of /// U+FE18 is "PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET" /// (note that "BRACKET" is misspelled). The `nameAlias` property then /// contains the corrected name. /// /// If a scalar has no alias, this property is `nil`. /// /// This property corresponds to the "Name_Alias" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var nameAlias: String? { return _scalarName(__swift_stdlib_U_CHAR_NAME_ALIAS) } } extension Unicode { /// The classification of a scalar used in the Canonical Ordering Algorithm /// defined by the Unicode Standard. /// /// Canonical combining classes are used by the ordering algorithm to /// determine if two sequences of combining marks should be considered /// canonically equivalent (that is, identical in interpretation). Two /// sequences are canonically equivalent if they are equal when sorting the /// scalars in ascending order by their combining class. /// /// For example, consider the sequence `"\u{0041}\u{0301}\u{0316}"` (LATIN /// CAPITAL LETTER A, COMBINING ACUTE ACCENT, COMBINING GRAVE ACCENT BELOW). /// The combining classes of these scalars have the numeric values 0, 230, and /// 220, respectively. Sorting these scalars by their combining classes yields /// `"\u{0041}\u{0316}\u{0301}"`, so two strings that differ only by the /// ordering of those scalars would compare as equal: /// /// let aboveBeforeBelow = "\u{0041}\u{0301}\u{0316}" /// let belowBeforeAbove = "\u{0041}\u{0316}\u{0301}" /// print(aboveBeforeBelow == belowBeforeAbove) /// // Prints "true" /// /// Named and Unnamed Combining Classes /// =================================== /// /// Canonical combining classes are defined in the Unicode Standard as /// integers in the range `0...254`. For convenience, the standard assigns /// symbolic names to a subset of these combining classes. /// /// The `CanonicalCombiningClass` type conforms to `RawRepresentable` with a /// raw value of type `UInt8`. You can create instances of the type by using /// the static members named after the symbolic names, or by using the /// `init(rawValue:)` initializer. /// /// let overlayClass = Unicode.CanonicalCombiningClass(rawValue: 1) /// let overlayClassIsOverlay = overlayClass == .overlay /// // overlayClassIsOverlay == true public struct CanonicalCombiningClass: Comparable, Hashable, RawRepresentable { /// Base glyphs that occupy their own space and do not combine with others. public static let notReordered = CanonicalCombiningClass(rawValue: 0) /// Marks that overlay a base letter or symbol. public static let overlay = CanonicalCombiningClass(rawValue: 1) /// Diacritic nukta marks in Brahmi-derived scripts. public static let nukta = CanonicalCombiningClass(rawValue: 7) /// Combining marks that are attached to hiragana and katakana to indicate /// voicing changes. public static let kanaVoicing = CanonicalCombiningClass(rawValue: 8) /// Diacritic virama marks in Brahmi-derived scripts. public static let virama = CanonicalCombiningClass(rawValue: 9) /// Marks attached at the bottom left. public static let attachedBelowLeft = CanonicalCombiningClass(rawValue: 200) /// Marks attached directly below. public static let attachedBelow = CanonicalCombiningClass(rawValue: 202) /// Marks attached directly above. public static let attachedAbove = CanonicalCombiningClass(rawValue: 214) /// Marks attached at the top right. public static let attachedAboveRight = CanonicalCombiningClass(rawValue: 216) /// Distinct marks at the bottom left. public static let belowLeft = CanonicalCombiningClass(rawValue: 218) /// Distinct marks directly below. public static let below = CanonicalCombiningClass(rawValue: 220) /// Distinct marks at the bottom right. public static let belowRight = CanonicalCombiningClass(rawValue: 222) /// Distinct marks to the left. public static let left = CanonicalCombiningClass(rawValue: 224) /// Distinct marks to the right. public static let right = CanonicalCombiningClass(rawValue: 226) /// Distinct marks at the top left. public static let aboveLeft = CanonicalCombiningClass(rawValue: 228) /// Distinct marks directly above. public static let above = CanonicalCombiningClass(rawValue: 230) /// Distinct marks at the top right. public static let aboveRight = CanonicalCombiningClass(rawValue: 232) /// Distinct marks subtending two bases. public static let doubleBelow = CanonicalCombiningClass(rawValue: 233) /// Distinct marks extending above two bases. public static let doubleAbove = CanonicalCombiningClass(rawValue: 234) /// Greek iota subscript only (U+0345 COMBINING GREEK YPOGEGRAMMENI). public static let iotaSubscript = CanonicalCombiningClass(rawValue: 240) /// The raw integer value of the canonical combining class. public let rawValue: UInt8 /// Creates a new canonical combining class with the given raw integer /// value. /// /// - Parameter rawValue: The raw integer value of the canonical combining /// class. public init(rawValue: UInt8) { self.rawValue = rawValue } public static func == ( lhs: CanonicalCombiningClass, rhs: CanonicalCombiningClass ) -> Bool { return lhs.rawValue == rhs.rawValue } public static func < ( lhs: CanonicalCombiningClass, rhs: CanonicalCombiningClass ) -> Bool { return lhs.rawValue < rhs.rawValue } public var hashValue: Int { return rawValue.hashValue } public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } } } extension Unicode.Scalar.Properties { /// The canonical combining class of the scalar. /// /// This property corresponds to the "Canonical_Combining_Class" property in /// the [Unicode Standard](http://www.unicode.org/versions/latest/). public var canonicalCombiningClass: Unicode.CanonicalCombiningClass { let rawValue = UInt8(__swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_CANONICAL_COMBINING_CLASS)) return Unicode.CanonicalCombiningClass(rawValue: rawValue) } } extension Unicode { /// The numeric type of a scalar. /// /// Scalars with a non-nil numeric type include numbers, fractions, numeric /// superscripts and subscripts, and circled or otherwise decorated number /// glyphs. /// /// Some letterlike scalars used in numeric systems, such as Greek or Latin /// letters, do not have a non-nil numeric type, in order to prevent programs /// from incorrectly interpreting them as numbers in non-numeric contexts. public enum NumericType { /// A digit that is commonly understood to form base-10 numbers. /// /// Specifically, scalars have this numeric type if they occupy a contiguous /// range of code points representing numeric values `0...9`. case decimal /// A digit that does not meet the requirements of the `decimal` numeric /// type. /// /// Scalars with this numeric type are often those that represent a decimal /// digit but would not typically be used to write a base-10 number, such /// as "④" (U+2463 CIRCLED DIGIT FOUR). /// /// As of Unicode 6.3, any new scalars that represent numbers but do not /// meet the requirements of `decimal` will have numeric type `numeric`, /// and programs can treat `digit` and `numeric` equivalently. case digit /// A digit that does not meet the requirements of the `decimal` numeric /// type or a non-digit numeric value. /// /// This numeric type includes fractions such as "⅕" (U+2155 VULGAR /// FRACITON ONE FIFTH), numerical CJK ideographs like "兆" (U+5146 CJK /// UNIFIED IDEOGRAPH-5146), and other scalars that are not decimal digits /// used positionally in the writing of base-10 numbers. /// /// As of Unicode 6.3, any new scalars that represent numbers but do not /// meet the requirements of `decimal` will have numeric type `numeric`, /// and programs can treat `digit` and `numeric` equivalently. case numeric internal init?(rawValue: __swift_stdlib_UNumericType) { switch rawValue { case __swift_stdlib_U_NT_NONE: return nil case __swift_stdlib_U_NT_DECIMAL: self = .decimal case __swift_stdlib_U_NT_DIGIT: self = .digit case __swift_stdlib_U_NT_NUMERIC: self = .numeric default: fatalError("Unknown numeric type \(rawValue)") } } } } /// Numeric properties of scalars. extension Unicode.Scalar.Properties { /// The numeric type of the scalar. /// /// For scalars that represent a number, `numericType` is the numeric type /// of the scalar. For all other scalars, this property is `nil`. /// /// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"] /// for scalar in scalars { /// print(scalar, "-->", scalar.properties.numericType) /// } /// // 4 --> Optional(Swift.Unicode.NumericType.decimal) /// // ④ --> Optional(Swift.Unicode.NumericType.digit) /// // ⅕ --> Optional(Swift.Unicode.NumericType.numeric) /// // X --> nil /// /// This property corresponds to the "Numeric_Type" property in the /// [Unicode Standard](http://www.unicode.org/versions/latest/). public var numericType: Unicode.NumericType? { let rawValue = __swift_stdlib_UNumericType( __swift_stdlib_UNumericType.RawValue( __swift_stdlib_u_getIntPropertyValue( icuValue, __swift_stdlib_UCHAR_NUMERIC_TYPE))) return Unicode.NumericType(rawValue: rawValue) } /// The numeric value of the scalar. /// /// For scalars that represent a numeric value, `numericValue` is the whole /// or fractional value. For all other scalars, this property is `nil`. /// /// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"] /// for scalar in scalars { /// print(scalar, "-->", scalar.properties.numericValue) /// } /// // 4 --> Optional(4.0) /// // ④ --> Optional(4.0) /// // ⅕ --> Optional(0.2) /// // X --> nil /// /// This property corresponds to the "Numeric_Value" property in the [Unicode /// Standard](http://www.unicode.org/versions/latest/). public var numericValue: Double? { let icuNoNumericValue: Double = -123456789 let result = __swift_stdlib_u_getNumericValue(icuValue) return result != icuNoNumericValue ? result : nil } }
apache-2.0
6e7ed8a16b32405e9290f8b49a55e69d
40.608696
86
0.692116
4.307368
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/ConversationList/ZMConversationListDirectoryTests+Teams.swift
1
4459
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // 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 final class ZMConversationListDirectoryTests_Teams: ZMBaseManagedObjectTest { var team: Team! var otherTeam: Team! var teamConversation1: ZMConversation! var teamConversation2: ZMConversation! var archivedTeamConversation: ZMConversation! var clearedTeamConversation: ZMConversation! var otherTeamConversation: ZMConversation! var otherTeamArchivedConversation: ZMConversation! var conversationWithoutTeam: ZMConversation! override func setUp() { super.setUp() team = Team.insertNewObject(in: uiMOC) team.remoteIdentifier = .create() otherTeam = Team.insertNewObject(in: uiMOC) otherTeam.remoteIdentifier = .create() teamConversation1 = createGroupConversation(in: team) teamConversation2 = createGroupConversation(in: team) otherTeamConversation = createGroupConversation(in: otherTeam) archivedTeamConversation = createGroupConversation(in: team, archived: true) otherTeamArchivedConversation = createGroupConversation(in: otherTeam, archived: true) clearedTeamConversation = createGroupConversation(in: team, archived: true) clearedTeamConversation.clearedTimeStamp = clearedTeamConversation.lastServerTimeStamp conversationWithoutTeam = createGroupConversation(in: nil) } override func tearDown() { team = nil otherTeam = nil teamConversation1 = nil teamConversation2 = nil archivedTeamConversation = nil clearedTeamConversation = nil otherTeamConversation = nil otherTeamArchivedConversation = nil conversationWithoutTeam = nil super.tearDown() } func testThatItReturnsConversationsInATeam() { // given let sut = uiMOC.conversationListDirectory() // when let conversations = sut.conversationsIncludingArchived // then XCTAssertEqual(conversations.setValue, [teamConversation1, teamConversation2, archivedTeamConversation, conversationWithoutTeam, otherTeamConversation, otherTeamArchivedConversation]) } func testThatItReturnsArchivedConversationsInATeam() { // given let sut = uiMOC.conversationListDirectory() // when let conversations = sut.archivedConversations // then XCTAssertEqual(conversations.setValue, [archivedTeamConversation, otherTeamArchivedConversation]) } func testThatItReturnsClearedConversationsInATeam() { // given let sut = uiMOC.conversationListDirectory() // when let conversations = sut.clearedConversations // then XCTAssertEqual(conversations.setValue, [clearedTeamConversation]) } func testThatItDoesNotIncludeClearedConversationsInConversationsIncludingArchived() { // given let sut = uiMOC.conversationListDirectory() // when let conversations = sut.conversationsIncludingArchived // then XCTAssertFalse(conversations.setValue.contains(clearedTeamConversation)) } // MARK: - Helper func createGroupConversation(in team: Team?, archived: Bool = false) -> ZMConversation { let conversation = ZMConversation.insertNewObject(in: uiMOC) conversation.lastServerTimeStamp = Date() conversation.lastReadServerTimeStamp = conversation.lastServerTimeStamp conversation.remoteIdentifier = .create() conversation.team = team conversation.isArchived = archived conversation.conversationType = .group return conversation } } fileprivate extension ZMConversationList { var setValue: Set<ZMConversation> { return Set(self as! [ZMConversation]) } }
gpl-3.0
faed72fffa710f0a7c15c9894ee5f955
33.835938
191
0.715631
5.385266
false
false
false
false
sha05301239/SHA_DYZB
SHA_DYZB/SHA_DYZB/Classes/Main/View/PageTitleView.swift
1
6540
// // PageTitleView.swift // SHA_DYZB // // Created by sha0530 on 17/2/7. // Copyright © 2017年 鼎. All rights reserved. // import UIKit //代理定义协议 protocol PageTitleViewDelegate : class{ func pageTitleView(_ titleView : PageTitleView, selectedIndex index : Int) } //定义常量 private let kScrollerLineH : CGFloat = 2 private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85) private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0) //MARK: - 定义类 class PageTitleView: UIView { //定义属性 fileprivate var titles:[String] fileprivate var currentIndex : Int = 0 weak var delegate : PageTitleViewDelegate? //MARK: - 懒加载属性 fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() //MARK: - 懒加载存放Label的数组 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() //MARK: - 懒加载底部滚动线条 fileprivate 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) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI界面 extension PageTitleView{ func setupUI(){ //1.添加scrollView addSubview(scrollView) scrollView.frame = bounds //2.添加title对应的Label setipTitleLabels() //3.设置label底部线条和滑块 setupbottomMenuAndScrollLine() } private func setipTitleLabels(){ let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kScrollerLineH let labelY : CGFloat = 0 for (index,title) in titles.enumerated(){ //1.创建label let label = UILabel() //2.设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textAlignment = .center label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) //3.设置label的frame let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //4.将label添加到scrollerView上 scrollView.addSubview(label) titleLabels.append(label) //5.给label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action:#selector(self.titleLabelClick(_:))) label.addGestureRecognizer(tapGes) } } private func setupbottomMenuAndScrollLine(){ //添加底线 let bottonLine = UIView() bottonLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottonLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottonLine) //2.添加scrollerLine //2.1获取第一个label guard let firstLabel = titleLabels.first else{ return } firstLabel.textColor = UIColor.orange //2.2设置scrollerLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollerLineH, width: firstLabel.frame.width, height: kScrollerLineH) } } //mark - 监听label点击 extension PageTitleView{ @objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer){ //1.获取当前label下表值 guard let currentLabel = tapGes.view as? UILabel else {return} //2.获取之前的label let oldLabel = titleLabels[currentIndex] //3.切换文字颜色 oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) //4.保存最新label currentIndex = currentLabel.tag //5.滚动条位置发生改变 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.12) { self.scrollLine.frame.origin.x = scrollLineX } //6.通知代理做事情 delegate?.pageTitleView(self, selectedIndex: currentIndex) } } //MARK: - 对外公开方法,改变title选中状态 extension PageTitleView{ func setTitleWithProgress(progress : CGFloat,sourceIndex: Int,targetIndex: Int){ //1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] //2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) //4.记录最新的index currentIndex = targetIndex } }
mit
63b399a7702e345a27ae122a27b5645f
22.864341
174
0.587624
4.736154
false
false
false
false
mnisn/zhangchu
zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendTodayCell.swift
1
4324
// // RecommendTodayCell.swift // zhangchu // // Created by 苏宁 on 2016/10/27. // Copyright © 2016年 suning. All rights reserved. // import UIKit class RecommendTodayCell: UITableViewCell { var clickClosure:RecipClickClosure? var listModle:RecipeRecommendWidgetList? { didSet{ showData() } } func showData() { if listModle?.widget_data?.count > 0 { for i in 0 ..< 3 { //图片 if i * 4 < listModle?.widget_data?.count { let imgData = listModle?.widget_data![i * 4] if imgData?.type == "image" { let tmpView = contentView.viewWithTag(100 + i) if tmpView?.isKindOfClass(UIImageView) == true { let imgView = tmpView as! UIImageView imgView.kf_setImageWithURL(NSURL(string: (imgData?.content)!), placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } } //标题 if i * 4 + 2 < listModle?.widget_data?.count { let textTitleData = listModle?.widget_data![i * 4 + 2] if textTitleData!.type == "text" { let tmpView = contentView.viewWithTag(200 + i) if tmpView?.isKindOfClass(UILabel) == true { let textTitleLabel = tmpView as! UILabel textTitleLabel.text = textTitleData?.content } } } //内容 if i * 4 + 3 < listModle?.widget_data?.count { let textConData = listModle?.widget_data![i * 4 + 3] if textConData!.type == "text" { let tmpView = contentView.viewWithTag(300 + i) if tmpView?.isKindOfClass(UILabel) == true { let textConLabel = tmpView as! UILabel textConLabel.text = textConData?.content } } } } } } //点击进入详情 @IBAction func btnClick(sender: UIButton) { let index = sender.tag - 400 if index * 4 < listModle?.widget_data?.count { let imgData = listModle?.widget_data![index * 4] if imgData?.type == "image" { if clickClosure != nil && imgData?.link != nil { clickClosure!((imgData?.link)!) } } } } //点击播放视频 @IBAction func playBtnClick(sender: UIButton) { let index = sender.tag - 500 if index * 4 + 1 < listModle?.widget_data?.count { let videoData = listModle?.widget_data![index * 4 + 1] if videoData?.type == "video" { if clickClosure != nil && videoData?.content != nil { clickClosure!((videoData?.content)!) } } } } //创建cell class func createTodayCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, listModel:RecipeRecommendWidgetList?) ->RecommendTodayCell { let cellID = "recommendTodayCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommendTodayCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("RecommendTodayCell", owner: nil, options: nil).last as? RecommendTodayCell } cell?.listModle = listModel! return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
af67f8e5cde0fbc6b814eff4df49ac3b
31.401515
203
0.470657
5.190534
false
false
false
false
bignerdranch/Deferred
Tests/DeferredTests/FutureAsyncTests.swift
1
1096
// // FutureAsyncTests.swift // Deferred // // Created by Zachary Waldowski on 6/3/18. // Copyright © 2018 Big Nerd Ranch. Licensed under MIT. // import XCTest import Dispatch import Deferred class FutureAsyncTests: XCTestCase { static let allTests: [(String, (FutureAsyncTests) -> () throws -> Void)] = [ ("testThatPeekingBeforeStartingReturnsNil", testThatPeekingBeforeStartingReturnsNil) ] private var queue: DispatchQueue! override func setUp() { super.setUp() queue = DispatchQueue(label: "FutureAsyncTests") queue.suspend() } override func tearDown() { queue = nil super.tearDown() } func testThatPeekingBeforeStartingReturnsNil() { let future = Future<Int>.async(upon: queue) { 1 } XCTAssertNil(future.peek()) queue.resume() let expect = expectation(description: "future fulfils") future.upon(queue) { (result) in XCTAssertEqual(result, 1) expect.fulfill() } wait(for: [ expect ], timeout: shortTimeout) } }
mit
2c17cf9816d77461cfb605a93e53f94c
21.8125
92
0.628311
4.433198
false
true
false
false
sebk/BeaconMonitor
BeaconMonitor/BeaconSender.swift
1
2157
// // BeaconSender.swift // BeaconMonitor // // Created by Sebastian Kruschwitz on 16.09.15. // Copyright © 2015 seb. All rights reserved. // import Foundation import CoreLocation import CoreBluetooth public class BeaconSender: NSObject { public static let sharedInstance = BeaconSender() fileprivate var _region: CLBeaconRegion? fileprivate var _peripheralManager: CBPeripheralManager! fileprivate var _uuid = "" fileprivate var _identifier = "" public func startSending(uuid: String, majorID: CLBeaconMajorValue, minorID: CLBeaconMinorValue, identifier: String) { _uuid = uuid _identifier = identifier stopSending() //stop sending when it's active // create the region that will be used to send _region = CLBeaconRegion( proximityUUID: UUID(uuidString: uuid)!, major: majorID, minor: minorID, identifier: identifier) _peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } open func stopSending() { _peripheralManager?.stopAdvertising() } } //MARK: - CBPeripheralManagerDelegate extension BeaconSender: CBPeripheralManagerDelegate { public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { if peripheral.state == .poweredOn { let data = ((_region?.peripheralData(withMeasuredPower: nil))! as NSDictionary) as! Dictionary<String, Any> peripheral.startAdvertising(data) print("Powered On -> start advertising") } else if peripheral.state == .poweredOff { peripheral.stopAdvertising() print("Powered Off -> stop advertising") } } public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { if let error = error { print("Error starting advertising: \(error)") } else { print("Did start advertising") } } }
mit
595edbe2526b753ca3f55b4e63d72f1c
26.641026
122
0.608998
5.556701
false
false
false
false
larryhou/swift
QRCode/QRCode/AztecImageView.swift
1
1236
// // AztecImageView.swift // QRCode // // Created by larryhou on 23/12/2015. // Copyright © 2015 larryhou. All rights reserved. // import Foundation import UIKit @IBDesignable class AztecImageView: GeneratorImageView { @IBInspectable var inputMessage: String = "larryhou" { didSet { drawAztecImage() } } @IBInspectable var inputCompactStyle: Bool = false { didSet { drawAztecImage() } } @IBInspectable var inputCorrectionLevel: Float = 50.0 // 23.0[5.0,95.0] { didSet { drawAztecImage() } } @IBInspectable var inputLayers: Float = 1.0 // 0.0[1.0,32.0] { didSet { drawAztecImage() } } func drawAztecImage() { let filter = CIFilter(name: "CIAztecCodeGenerator") let data = inputMessage.data(using: .utf8) filter?.setValue(data, forKey: "inputMessage") // filter?.setValue(inputLayers, forKey: "inputLayers") // filter?.setValue(inputCompactStyle, forKey: "inputCompactStyle") filter?.setValue(inputCorrectionLevel, forKey: "inputCorrectionLevel") self.image = stripOutputImage(of: filter) } override func prepareForInterfaceBuilder() { drawAztecImage() } }
mit
5741ced55d4012d926e4c157fa0fd519
23.215686
78
0.640486
4.130435
false
false
false
false
xedin/swift
test/decl/subscript/subscripting.swift
2
14153
// RUN: %target-typecheck-verify-swift struct X { } // expected-note * {{did you mean 'X'?}} // Simple examples struct X1 { var stored : Int subscript (i : Int) -> Int { get { return stored } mutating set { stored = newValue } } } struct X2 { var stored : Int subscript (i : Int) -> Int { get { return stored + i } set(v) { stored = v - i } } } struct X3 { var stored : Int subscript (_ : Int) -> Int { get { return stored } set(v) { stored = v } } } struct X4 { var stored : Int subscript (i : Int, j : Int) -> Int { get { return stored + i + j } set(v) { stored = v + i - j } } } struct X5 { static var stored : Int = 1 static subscript (i : Int) -> Int { get { return stored + i } set { stored = newValue - i } } } class X6 { static var stored : Int = 1 class subscript (i : Int) -> Int { get { return stored + i } set { stored = newValue - i } } } protocol XP1 { subscript (i : Int) -> Int { get set } static subscript (i : Int) -> Int { get set } } // Semantic errors struct Y1 { var x : X subscript(i: Int) -> Int { get { return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}} } set { x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}} } } } struct Y2 { subscript(idx: Int) -> TypoType { // expected-error {{use of undeclared type 'TypoType'}} get { repeat {} while true } set {} } } class Y3 { subscript(idx: Int) -> TypoType { // expected-error {{use of undeclared type 'TypoType'}} get { repeat {} while true } set {} } } class Y4 { var x = X() static subscript(idx: Int) -> X { get { return x } // expected-error {{instance member 'x' cannot be used on type 'Y4'}} set {} } } class Y5 { static var x = X() subscript(idx: Int) -> X { get { return x } // expected-error {{static member 'x' cannot be used on instance of type 'Y5'}} set {} } } protocol ProtocolGetSet0 { subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}} } protocol ProtocolGetSet1 { subscript(i: Int) -> Int { get } } protocol ProtocolGetSet2 { subscript(i: Int) -> Int { set } // expected-error {{subscript with a setter must also have a getter}} } protocol ProtocolGetSet3 { subscript(i: Int) -> Int { get set } } protocol ProtocolGetSet4 { subscript(i: Int) -> Int { set get } } protocol ProtocolWillSetDidSet1 { subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } protocol ProtocolWillSetDidSet2 { subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } protocol ProtocolWillSetDidSet3 { subscript(i: Int) -> Int { willSet didSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } protocol ProtocolWillSetDidSet4 { subscript(i: Int) -> Int { didSet willSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}} } class DidSetInSubscript { subscript(_: Int) -> Int { didSet { // expected-error {{'didSet' is not allowed in subscripts}} print("eek") } get {} } } class WillSetInSubscript { subscript(_: Int) -> Int { willSet { // expected-error {{'willSet' is not allowed in subscripts}} print("eek") } get {} } } subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}} get {} } func f() { // expected-note * {{did you mean 'f'?}} subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}} get {} } } struct NoSubscript { } struct OverloadedSubscript { subscript(i: Int) -> Int { get { return i } set {} } subscript(i: Int, j: Int) -> Int { get { return i } set {} } } struct RetOverloadedSubscript { subscript(i: Int) -> Int { // expected-note {{found this candidate}} get { return i } set {} } subscript(i: Int) -> Float { // expected-note {{found this candidate}} get { return Float(i) } set {} } } struct MissingGetterSubscript1 { subscript (i : Int) -> Int { } // expected-error {{subscript must have accessors specified}} } struct MissingGetterSubscript2 { subscript (i : Int, j : Int) -> Int { set {} // expected-error{{subscript with a setter must also have a getter}} } } func test_subscript(_ x2: inout X2, i: Int, j: Int, value: inout Int, no: NoSubscript, ovl: inout OverloadedSubscript, ret: inout RetOverloadedSubscript) { no[i] = value // expected-error{{value of type 'NoSubscript' has no subscripts}} value = x2[i] x2[i] = value value = ovl[i] ovl[i] = value value = ovl[i, j] ovl[i, j] = value value = ovl[(i, j, i)] // expected-error{{cannot convert value of type '(Int, Int, Int)' to expected argument type 'Int'}} ret[i] // expected-error{{ambiguous use of 'subscript(_:)'}} value = ret[i] ret[i] = value X5[i] = value value = X5[i] } func test_proto_static<XP1Type: XP1>( i: Int, value: inout Int, existential: inout XP1, generic: inout XP1Type ) { existential[i] = value value = existential[i] type(of: existential)[i] = value value = type(of: existential)[i] generic[i] = value value = generic[i] XP1Type[i] = value value = XP1Type[i] } func subscript_rvalue_materialize(_ i: inout Int) { i = X1(stored: 0)[i] } func subscript_coerce(_ fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {} func test_subscript_coerce() { subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] }) } struct no_index { subscript () -> Int { return 42 } func test() -> Int { return self[] } } struct tuple_index { subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) } func test() -> (Int, Int) { return self[123, 456] } } struct MutableComputedGetter { var value: Int subscript(index: Int) -> Int { value = 5 // expected-error{{cannot assign to property: 'self' is immutable}} return 5 } var getValue : Int { value = 5 // expected-error {{cannot assign to property: 'self' is immutable}} return 5 } } struct MutableSubscriptInGetter { var value: Int subscript(index: Int) -> Int { get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} value = 5 // expected-error{{cannot assign to property: 'self' is immutable}} return 5 } } } protocol Protocol {} protocol RefinedProtocol: Protocol {} class SuperClass {} class SubClass: SuperClass {} class SubSubClass: SubClass {} class ClassConformingToProtocol: Protocol {} class ClassConformingToRefinedProtocol: RefinedProtocol {} struct GenSubscriptFixitTest { subscript<T>(_ arg: T) -> Bool { return true } // expected-note {{declared here}} } func testGenSubscriptFixit(_ s0: GenSubscriptFixitTest) { _ = s0.subscript("hello") // expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{27-28=]}} } struct SubscriptTest1 { subscript(keyword:String) -> Bool { return true } // expected-note@-1 4 {{found this candidate}} subscript(keyword:String) -> String? {return nil } // expected-note@-1 4 {{found this candidate}} subscript(arg: SubClass) -> Bool { return true } // expected-note {{declared here}} subscript(arg: Protocol) -> Bool { return true } // expected-note 2 {{declared here}} subscript(arg: (foo: Bool, bar: (Int, baz: SubClass)), arg2: String) -> Bool { return true } // expected-note@-1 2 {{declared here}} } func testSubscript1(_ s1 : SubscriptTest1) { let _ : Int = s1["hello"] // expected-error {{ambiguous subscript with base type 'SubscriptTest1' and index type 'String'}} if s1["hello"] {} _ = s1.subscript((true, (5, SubClass())), "hello") // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{52-53=]}} _ = s1.subscript((true, (5, baz: SubSubClass())), "hello") // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{60-61=]}} _ = s1.subscript((fo: true, (5, baz: SubClass())), "hello") // expected-error@-1 {{cannot convert value of type '(fo: Bool, (Int, baz: SubClass))' to expected argument type '(foo: Bool, bar: (Int, baz: SubClass))'}} _ = s1.subscript(SubSubClass()) // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{33-34=]}} _ = s1.subscript(ClassConformingToProtocol()) // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{47-48=]}} _ = s1.subscript(ClassConformingToRefinedProtocol()) // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{54-55=]}} _ = s1.subscript(true) // expected-error@-1 {{cannot invoke 'subscript' with an argument list of type '(Bool)'}} // expected-note@-2 {{overloads for 'subscript' exist with these partially matching parameter lists: (Protocol), (String), (SubClass)}} _ = s1.subscript(SuperClass()) // expected-error@-1 {{cannot invoke 'subscript' with an argument list of type '(SuperClass)'}} // expected-note@-2 {{overloads for 'subscript' exist with these partially matching parameter lists: (Protocol), (String), (SubClass)}} _ = s1.subscript("hello") // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} _ = s1.subscript("hello" // expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} // expected-note@-2 {{to match this opening '('}} let _ = s1["hello"] // expected-error@-1 {{ambiguous use of 'subscript(_:)'}} // expected-error@-2 {{expected ')' in expression list}} } struct SubscriptTest2 { subscript(a : String, b : Int) -> Int { return 0 } // expected-note@-1 {{declared here}} subscript(a : String, b : String) -> Int { return 0 } } func testSubscript1(_ s2 : SubscriptTest2) { _ = s2["foo"] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an argument of type 'String'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}} let a = s2["foo", 1.0] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an argument of type '(String, Double)'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}} _ = s2.subscript("hello", 6) // expected-error@-1 {{value of type 'SubscriptTest2' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{30-31=]}} let b = s2[1, "foo"] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} // rdar://problem/27449208 let v: (Int?, [Int]?) = (nil [17]) // expected-error {{cannot subscript a nil literal value}} } // sr-114 & rdar://22007370 class Foo { subscript(key: String) -> String { // expected-note {{'subscript(_:)' previously declared here}} get { a } // expected-error {{use of unresolved identifier 'a'}} set { b } // expected-error {{use of unresolved identifier 'b'}} } subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript(_:)'}} get { _ = 0; a } // expected-error {{use of unresolved identifier 'a'}} set { b } // expected-error {{use of unresolved identifier 'b'}} } } // <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please protocol r23952125 { associatedtype ItemType var count: Int { get } subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get <#set#> \}}} var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-14= { get <#set#> \}}} } // SR-2575 struct SR2575 { subscript() -> Int { // expected-note {{declared here}} return 1 } } SR2575().subscript() // expected-error@-1 {{value of type 'SR2575' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{20-21=]}} // SR-7890 struct InOutSubscripts { subscript(x1: inout Int) -> Int { return 0 } // expected-error@-1 {{'inout' must not be used on subscript parameters}} subscript(x2: inout Int, y2: inout Int) -> Int { return 0 } // expected-error@-1 2{{'inout' must not be used on subscript parameters}} subscript(x3: (inout Int) -> ()) -> Int { return 0 } // ok subscript(x4: (inout Int, inout Int) -> ()) -> Int { return 0 } // ok subscript(inout x5: Int) -> Int { return 0 } // expected-error@-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} // expected-error@-2 {{'inout' must not be used on subscript parameters}} }
apache-2.0
73842fe267fbaefdb7c7bcdc37c34b1c
30.174009
198
0.626864
3.600356
false
true
false
false
guoc/spi
SPiKeyboard/TastyImitationKeyboard/KeyboardKeyBackground.swift
2
10545
// // KeyboardKeyBackground.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/19/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // This class does not actually draw its contents; rather, it generates bezier curves for others to use. // (You can still move it around, resize it, and add subviews to it. It just won't display the curve assigned to it.) class KeyboardKeyBackground: UIView, Connectable { var fillPath: UIBezierPath? var underPath: UIBezierPath? var edgePaths: [UIBezierPath]? // do not set this manually var cornerRadius: CGFloat var underOffset: CGFloat var startingPoints: [CGPoint] var segmentPoints: [(CGPoint, CGPoint)] var arcCenters: [CGPoint] var arcStartingAngles: [CGFloat] var dirty: Bool var attached: Direction? { didSet { self.dirty = true self.setNeedsLayout() } } var hideDirectionIsOpposite: Bool { didSet { self.dirty = true self.setNeedsLayout() } } init(cornerRadius: CGFloat, underOffset: CGFloat) { attached = nil hideDirectionIsOpposite = false dirty = false startingPoints = [] segmentPoints = [] arcCenters = [] arcStartingAngles = [] startingPoints.reserveCapacity(4) segmentPoints.reserveCapacity(4) arcCenters.reserveCapacity(4) arcStartingAngles.reserveCapacity(4) for _ in 0..<4 { startingPoints.append(CGPoint.zero) segmentPoints.append((CGPoint.zero, CGPoint.zero)) arcCenters.append(CGPoint.zero) arcStartingAngles.append(0) } self.cornerRadius = cornerRadius self.underOffset = underOffset super.init(frame: CGRect.zero) self.isUserInteractionEnabled = false } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } var oldBounds: CGRect? override func layoutSubviews() { if !self.dirty { if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && self.bounds.equalTo(oldBounds!) { return } } oldBounds = self.bounds super.layoutSubviews() self.generatePointsForDrawing(self.bounds) self.dirty = false } let floatPi = CGFloat(M_PI) let floatPiDiv2 = CGFloat(M_PI/2.0) let floatPiDivNeg2 = -CGFloat(M_PI/2.0) func generatePointsForDrawing(_ bounds: CGRect) { let segmentWidth = bounds.width let segmentHeight = bounds.height - CGFloat(underOffset) // base, untranslated corner points self.startingPoints[0] = CGPoint(x: 0, y: segmentHeight) self.startingPoints[1] = CGPoint(x: 0, y: 0) self.startingPoints[2] = CGPoint(x: segmentWidth, y: 0) self.startingPoints[3] = CGPoint(x: segmentWidth, y: segmentHeight) self.arcStartingAngles[0] = floatPiDiv2 self.arcStartingAngles[2] = floatPiDivNeg2 self.arcStartingAngles[1] = floatPi self.arcStartingAngles[3] = 0 //// actual coordinates for each edge, including translation //self.segmentPoints.removeAll(keepCapacity: true) // //// actual coordinates for arc centers for each corner //self.arcCenters.removeAll(keepCapacity: true) // //self.arcStartingAngles.removeAll(keepCapacity: true) for i in 0 ..< self.startingPoints.count { let currentPoint = self.startingPoints[i] let nextPoint = self.startingPoints[(i + 1) % self.startingPoints.count] var floatXCorner: CGFloat = 0 var floatYCorner: CGFloat = 0 if (i == 1) { floatXCorner = cornerRadius } else if (i == 3) { floatXCorner = -cornerRadius } if (i == 0) { floatYCorner = -cornerRadius } else if (i == 2) { floatYCorner = cornerRadius } let p0 = CGPoint( x: currentPoint.x + (floatXCorner), y: currentPoint.y + underOffset + (floatYCorner)) let p1 = CGPoint( x: nextPoint.x - (floatXCorner), y: nextPoint.y + underOffset - (floatYCorner)) self.segmentPoints[i] = (p0, p1) let c = CGPoint( x: p0.x - (floatYCorner), y: p0.y + (floatXCorner)) self.arcCenters[i] = c } // order of edge drawing: left edge, down edge, right edge, up edge // We need to have separate paths for all the edges so we can toggle them as needed. // Unfortunately, it doesn't seem possible to assemble the connected fill path // by simply using CGPathAddPath, since it closes all the subpaths, so we have to // duplicate the code a little bit. let fillPath = UIBezierPath() var edgePaths: [UIBezierPath] = [] var prevPoint: CGPoint? for i in 0..<4 { var edgePath: UIBezierPath? let segmentPoint = self.segmentPoints[i] if self.attached != nil && (self.hideDirectionIsOpposite ? self.attached!.rawValue != i : self.attached!.rawValue == i) { // do nothing // TODO: quick hack if !self.hideDirectionIsOpposite { continue } } else { edgePath = UIBezierPath() // TODO: figure out if this is ncessary if prevPoint == nil { prevPoint = segmentPoint.0 fillPath.move(to: prevPoint!) } fillPath.addLine(to: segmentPoint.0) fillPath.addLine(to: segmentPoint.1) edgePath!.move(to: segmentPoint.0) edgePath!.addLine(to: segmentPoint.1) prevPoint = segmentPoint.1 } let shouldDrawArcInOppositeMode = (self.attached != nil ? (self.attached!.rawValue == i) || (self.attached!.rawValue == ((i + 1) % 4)) : false) if (self.attached != nil && (self.hideDirectionIsOpposite ? !shouldDrawArcInOppositeMode : self.attached!.rawValue == ((i + 1) % 4))) { // do nothing } else { edgePath = (edgePath == nil ? UIBezierPath() : edgePath) if prevPoint == nil { prevPoint = segmentPoint.1 fillPath.move(to: prevPoint!) } let startAngle = self.arcStartingAngles[(i + 1) % 4] let endAngle = startAngle + floatPiDiv2 let arcCenter = self.arcCenters[(i + 1) % 4] fillPath.addLine(to: prevPoint!) fillPath.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) edgePath!.move(to: prevPoint!) edgePath!.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) prevPoint = self.segmentPoints[(i + 1) % 4].0 } edgePath?.apply(CGAffineTransform(translationX: 0, y: -self.underOffset)) if edgePath != nil { edgePaths.append(edgePath!) } } fillPath.close() fillPath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset)) let underPath = { () -> UIBezierPath in let underPath = UIBezierPath() underPath.move(to: self.segmentPoints[2].1) var startAngle = self.arcStartingAngles[3] var endAngle = startAngle + CGFloat(M_PI/2.0) underPath.addArc(withCenter: self.arcCenters[3], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLine(to: self.segmentPoints[3].1) startAngle = self.arcStartingAngles[0] endAngle = startAngle + CGFloat(M_PI/2.0) underPath.addArc(withCenter: self.arcCenters[0], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLine(to: CGPoint(x: self.segmentPoints[0].0.x, y: self.segmentPoints[0].0.y - self.underOffset)) startAngle = self.arcStartingAngles[1] endAngle = startAngle - CGFloat(M_PI/2.0) underPath.addArc(withCenter: CGPoint(x: self.arcCenters[0].x, y: self.arcCenters[0].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.addLine(to: CGPoint(x: self.segmentPoints[2].1.x - self.cornerRadius, y: self.segmentPoints[2].1.y + self.cornerRadius - self.underOffset)) startAngle = self.arcStartingAngles[0] endAngle = startAngle - CGFloat(M_PI/2.0) underPath.addArc(withCenter: CGPoint(x: self.arcCenters[3].x, y: self.arcCenters[3].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.close() return underPath }() self.fillPath = fillPath self.edgePaths = edgePaths self.underPath = underPath } func attachmentPoints(_ direction: Direction) -> (CGPoint, CGPoint) { let returnValue = ( self.segmentPoints[direction.clockwise().rawValue].0, self.segmentPoints[direction.counterclockwise().rawValue].1) return returnValue } func attachmentDirection() -> Direction? { return self.attached } func attach(_ direction: Direction?) { self.attached = direction } }
bsd-3-clause
d0638bf10cf49e4724c68d37fa79f480
36
216
0.556662
5.009501
false
false
false
false
paoloiulita/AbstractNumericStepper
AbstractNumericStepper/Classes/AbstractNumericStepper.swift
1
4069
// // AbstractNumericStepper.swift // Pods // // Created by Paolo Iulita on 03/05/16. // // import Foundation import UIKit @objc public protocol AbstractNumericStepperDelegate: NSObjectProtocol { func numericStepper(numericStepper: AbstractNumericStepper, valueChanged value: Double) } /// Contains methods for easily creating a numeric stepper public class AbstractNumericStepper: UIView, UITextFieldDelegate { // MARK: initializers public override func awakeFromNib() { textField.delegate = self textField.keyboardType = .DecimalPad let numberToolbar: UIToolbar = UIToolbar() numberToolbar.barStyle = .Default numberToolbar.items = [ UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil), UIBarButtonItem(title: "Done", style: .Plain, target: self, action: #selector(onDone)) ] numberToolbar.sizeToFit() textField.inputAccessoryView = numberToolbar } // MARK: outlets @IBOutlet weak var increment: UIButton! @IBOutlet weak var decrement: UIButton! @IBOutlet weak var textField: UITextField! // MARK: actions /** change the model by adding a defined step value - Parameter sender: The UIButton invoking */ @IBAction func onIncrement(sender: UIButton) { value += step } /** change the model by subtracting a defined step value - Parameter sender: The UIButton invoking */ @IBAction func onDecrement(sender: UIButton) { value -= step } // MARK: properties /// The object implementing the method called when value changes public var delegate: AbstractNumericStepperDelegate? /// The actual value of the numeric stepper public var value: Double = 0 { didSet { let isInt = floor(value) == value if !canShowDecimalValues { value = round(value) } else if shouldRoundToHalfDecimal && !isInt { var fValue: Double = floor(value) if (value - fValue) > 0.5 { fValue += 1 } else { fValue += 0.5 } value = fValue } value = Swift.min(value, max) value = Swift.max(value, min) decrement.enabled = value >= min increment.enabled = value <= max updateTextField() if value != oldValue { delegate?.numericStepper(self, valueChanged: value) } } } /// The minimum value allowed to be set public var min: Double = 0 { didSet { value = Swift.max(value, min) } } /// The maximum value allowed to be set public var max: Double = 10 { didSet { value = Swift.min(value, max) } } /// The quantity to be added or subtracted on each button press public var step: Double = 1 /// Defines if the numeric stepper should or not show only integers public var canShowDecimalValues: Bool = false { didSet { updateTextField() } } /// The symbol that can be placed after the value public var currencySymbol: String = "" { didSet { if currencySymbol != "" { updateTextField() } } } /// Defines if the value should be rounded at the neares half decimal (0.5) point public var shouldRoundToHalfDecimal: Bool = false /// Defines if the UITextField shoul be interactive public var canDirectInputValues: Bool = true { didSet { if canDirectInputValues { textField.delegate = self } else { textField.delegate = nil } textField.userInteractionEnabled = canDirectInputValues } } // MARK: private methods private func updateTextField() { var valueToString = "" if !canShowDecimalValues { valueToString = "\(Int(value))" } else { valueToString = String(value) } if currencySymbol != "" { textField.text = "\(valueToString) \(currencySymbol)" } else { textField.text = valueToString } } private func updateValue() { if let tValue = textField.text { value = Double(tValue) ?? min } } @objc private func onDone() { textField.resignFirstResponder() } // MARK: UITextFieldDelegate public func textFieldDidEndEditing(textField: UITextField) { updateValue() } public func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
3a5b7406765e0ba9b9b36c8d8fae5f0b
22.119318
89
0.693045
3.73989
false
false
false
false
davidstump/SwiftPhoenixClient
Tests/SwiftPhoenixClientTests/SocketSpec.swift
1
33460
// // SocketSpec.swift // SwiftPhoenixClient // // Created by Daniel Rees on 2/10/18. // import Quick import Nimble @testable import SwiftPhoenixClient @available(iOS 13, *) class SocketSpec: QuickSpec { let encode = Defaults.encode let decode = Defaults.decode override func spec() { describe("constructor") { it("sets defaults", closure: { let socket = Socket("wss://localhost:4000/socket") expect(socket.channels).to(haveCount(0)) expect(socket.sendBuffer).to(haveCount(0)) expect(socket.ref).to(equal(0)) expect(socket.endPoint).to(equal("wss://localhost:4000/socket")) expect(socket.stateChangeCallbacks.open).to(beEmpty()) expect(socket.stateChangeCallbacks.close).to(beEmpty()) expect(socket.stateChangeCallbacks.error).to(beEmpty()) expect(socket.stateChangeCallbacks.message).to(beEmpty()) expect(socket.timeout).to(equal(Defaults.timeoutInterval)) expect(socket.heartbeatInterval).to(equal(Defaults.heartbeatInterval)) expect(socket.logger).to(beNil()) expect(socket.reconnectAfter(1)).to(equal(0.010)) // 10ms expect(socket.reconnectAfter(2)).to(equal(0.050)) // 50ms expect(socket.reconnectAfter(3)).to(equal(0.100)) // 100ms expect(socket.reconnectAfter(4)).to(equal(0.150)) // 150ms expect(socket.reconnectAfter(5)).to(equal(0.200)) // 200ms expect(socket.reconnectAfter(6)).to(equal(0.250)) // 250ms expect(socket.reconnectAfter(7)).to(equal(0.500)) // 500ms expect(socket.reconnectAfter(8)).to(equal(1.000)) // 1_000ms (1s) expect(socket.reconnectAfter(9)).to(equal(2.000)) // 2_000ms (2s) expect(socket.reconnectAfter(10)).to(equal(5.00)) // 5_000ms (5s) expect(socket.reconnectAfter(11)).to(equal(5.00)) // 5_000ms (5s) }) it("overrides some defaults", closure: { let socket = Socket("wss://localhost:4000/socket", paramsClosure: { ["one": 2] }) socket.timeout = 40000 socket.heartbeatInterval = 60000 socket.logger = { _ in } socket.reconnectAfter = { _ in return 10 } expect(socket.timeout).to(equal(40000)) expect(socket.heartbeatInterval).to(equal(60000)) expect(socket.logger).toNot(beNil()) expect(socket.reconnectAfter(1)).to(equal(10)) expect(socket.reconnectAfter(2)).to(equal(10)) }) // it("sets queue for underlying transport", closure: { // let socket = Socket(endPoint: "wss://localhost:4000/socket", transport: { (url) -> WebSocketClient in // let webSocket = WebSocket(url: url) // webSocket.callbackQueue = DispatchQueue(label: "test_queue") // return webSocket // }) // socket.timeout = 40000 // socket.heartbeatInterval = 60000 // socket.logger = { _ in } // socket.reconnectAfter = { _ in return 10 } // socket.connect() // expect(socket.connection).to(beAKindOf(Transport.self)) // expect((socket.connection as! WebSocket).callbackQueue.label).to(equal("test_queue")) // }) it("should construct a valid URL", closure: { // test vsn expect(Socket("http://localhost:4000/socket/websocket", paramsClosure: { ["token": "abc123"] }, vsn: "1.0.0") .endPointUrl .absoluteString) .to(equal("http://localhost:4000/socket/websocket?vsn=1.0.0&token=abc123")) // test params expect(Socket("http://localhost:4000/socket/websocket", paramsClosure: { ["token": "abc123"] }) .endPointUrl .absoluteString) .to(equal("http://localhost:4000/socket/websocket?vsn=2.0.0&token=abc123")) expect(Socket("ws://localhost:4000/socket/websocket", paramsClosure: { ["token": "abc123", "user_id": 1] }) .endPointUrl .absoluteString) .to(satisfyAnyOf( // absoluteString does not seem to return a string with the params in a deterministic order equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&token=abc123&user_id=1"), equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&user_id=1&token=abc123") ) ) // test params with spaces expect(Socket("ws://localhost:4000/socket/websocket", paramsClosure: { ["token": "abc 123", "user_id": 1] }) .endPointUrl .absoluteString) .to(satisfyAnyOf( // absoluteString does not seem to return a string with the params in a deterministic order equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&token=abc%20123&user_id=1"), equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&user_id=1&token=abc%20123") ) ) }) it("should not introduce any retain cycles", closure: { // Must remain as a weak var in order to deallocate the socket. This tests that the // reconnect timer does not old on to the Socket causing a memory leak. weak var socket = Socket("http://localhost:4000/socket/websocket") expect(socket).to(beNil()) }) } describe("params") { it("changes dynamically with a closure") { var authToken = "abc123" let socket = Socket("ws://localhost:4000/socket/websocket", paramsClosure: { ["token": authToken] }) expect(socket.params?["token"] as? String).to(equal("abc123")) authToken = "xyz987" expect(socket.params?["token"] as? String).to(equal("xyz987")) } } describe("websocketProtocol") { it("returns wss when protocol is https", closure: { let socket = Socket("https://example.com/") expect(socket.websocketProtocol).to(equal("wss")) }) it("returns wss when protocol is wss", closure: { let socket = Socket("wss://example.com/") expect(socket.websocketProtocol).to(equal("wss")) }) it("returns ws when protocol is http", closure: { let socket = Socket("http://example.com/") expect(socket.websocketProtocol).to(equal("ws")) }) it("returns ws when protocol is ws", closure: { let socket = Socket("ws://example.com/") expect(socket.websocketProtocol).to(equal("ws")) }) it("returns empty if there is no scheme", closure: { let socket = Socket("example.com/") expect(socket.websocketProtocol).to(beEmpty()) }) } // describe("endPointUrl") { // it("does nothing with the url", closure: { // let socket = Socket("http://example.com/websocket") // expect(socket.endPointUrl.absoluteString).to(equal("http://example.com/websocket")) // }) // // it("appends /websocket correctly", closure: { // let socketA = Socket("wss://example.org/chat/") // expect(socketA.endPointUrl.absoluteString).to(equal("wss://example.org/chat/websocket")) // // let socketB = Socket("ws://example.org/chat") // expect(socketB.endPointUrl.absoluteString).to(equal("ws://example.org/chat/websocket")) // }) // } describe("connect with Websocket") { // Mocks var mockWebSocket: PhoenixTransportMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) socket.skipHeartbeat = true } it("establishes websocket connection with endpoint", closure: { socket.connect() expect(socket.connection).toNot(beNil()) }) it("set callbacks for connection", closure: { var open = 0 socket.onOpen { open += 1 } var close = 0 socket.onClose { close += 1 } var lastError: Error? socket.onError(callback: { (error) in lastError = error }) var lastMessage: Message? socket.onMessage(callback: { (message) in lastMessage = message }) mockWebSocket.readyState = .closed socket.connect() mockWebSocket.delegate?.onOpen() expect(open).to(equal(1)) mockWebSocket.delegate?.onClose(code: 1000) expect(close).to(equal(1)) mockWebSocket.delegate?.onError(error: TestError.stub) expect(lastError).toNot(beNil()) let data: [Any] = ["2", "6", "topic", "event", ["response": ["go": true], "status": "ok"]] let text = toWebSocketText(data: data) mockWebSocket.delegate?.onMessage(message: text) expect(lastMessage?.payload["go"] as? Bool).to(beTrue()) }) it("removes callbacks", closure: { var open = 0 socket.onOpen { open += 1 } var close = 0 socket.onClose { close += 1 } var lastError: Error? socket.onError(callback: { (error) in lastError = error }) var lastMessage: Message? socket.onMessage(callback: { (message) in lastMessage = message }) mockWebSocket.readyState = .closed socket.releaseCallbacks() socket.connect() mockWebSocket.delegate?.onOpen() expect(open).to(equal(0)) mockWebSocket.delegate?.onClose(code: 1000) expect(close).to(equal(0)) mockWebSocket.delegate?.onError(error: TestError.stub) expect(lastError).to(beNil()) let data: [Any] = ["2", "6", "topic", "event", ["response": ["go": true], "status": "ok"]] let text = toWebSocketText(data: data) mockWebSocket.delegate?.onMessage(message: text) expect(lastMessage).to(beNil()) }) it("does not connect if already connected", closure: { mockWebSocket.readyState = .open socket.connect() socket.connect() expect(mockWebSocket.connectCallsCount).to(equal(1)) }) } describe("disconnect") { // Mocks var mockWebSocket: PhoenixTransportMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) } it("removes existing connection", closure: { socket.connect() socket.disconnect() expect(socket.connection).to(beNil()) expect(mockWebSocket.disconnectCodeReasonReceivedArguments?.code) .to(equal(Socket.CloseCode.normal.rawValue)) }) it("flags the socket as closed cleanly", closure: { expect(socket.closeStatus).to(equal(.unknown)) socket.disconnect() expect(socket.closeStatus).to(equal(.clean)) }) it("calls callback", closure: { var callCount = 0 socket.connect() socket.disconnect(code: .goingAway) { callCount += 1 } expect(mockWebSocket.disconnectCodeReasonCalled).to(beTrue()) expect(mockWebSocket.disconnectCodeReasonReceivedArguments?.reason).to(beNil()) expect(mockWebSocket.disconnectCodeReasonReceivedArguments?.code) .to(equal(Socket.CloseCode.goingAway.rawValue)) expect(callCount).to(equal(1)) }) it("calls onClose for all state callbacks", closure: { var callCount = 0 socket.onClose { callCount += 1 } socket.disconnect() expect(callCount).to(equal(1)) }) it("invalidates and invalidates the heartbeat timer", closure: { var timerCalled = 0 let queue = DispatchQueue(label: "test.heartbeat") let timer = HeartbeatTimer(timeInterval: 10, queue: queue) timer.start { timerCalled += 1 } socket.heartbeatTimer = timer socket.disconnect() expect(socket.heartbeatTimer?.isValid).to(beFalse()) timer.fire() expect(timerCalled).to(equal(0)) }) it("does nothing if not connected", closure: { socket.disconnect() expect(mockWebSocket.disconnectCodeReasonCalled).to(beFalse()) }) } describe("channel") { var socket: Socket! beforeEach { socket = Socket("/socket") } it("returns channel with given topic and params", closure: { let channel = socket.channel("topic", params: ["one": "two"]) socket.ref = 1006 // No deep equal, so hack it expect(channel.socket?.ref).to(equal(socket.ref)) expect(channel.topic).to(equal("topic")) expect(channel.params["one"] as? String).to(equal("two")) }) it("adds channel to sockets channel list", closure: { expect(socket.channels).to(beEmpty()) let channel = socket.channel("topic", params: ["one": "two"]) expect(socket.channels).to(haveCount(1)) expect(socket.channels[0].topic).to(equal(channel.topic)) }) } describe("remove") { var socket: Socket! beforeEach { socket = Socket("/socket") } it("removes given channel from channels", closure: { let channel1 = socket.channel("topic-1") let channel2 = socket.channel("topic-2") channel1.joinPush.ref = "1" channel2.joinPush.ref = "2" socket.remove(channel1) expect(socket.channels).to(haveCount(1)) expect(socket.channels[0].topic).to(equal(channel2.topic)) }) } describe("push") { // Mocks var mockWebSocket: PhoenixTransportMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) } it("sends data to connection when connected", closure: { mockWebSocket.readyState = .open socket.connect() socket.push(topic: "topic", event: "event", payload: ["one": "two"], ref: "6", joinRef: "2") expect(mockWebSocket.sendDataCalled).to(beTrue()) let json = self.decode(mockWebSocket.sendDataReceivedData!) as! [Any] expect(json[0] as? String).to(equal("2")) expect(json[1] as? String).to(equal("6")) expect(json[2] as? String).to(equal("topic")) expect(json[3] as? String).to(equal("event")) expect(json[4] as? [String: String]).to(equal(["one": "two"])) expect(String(data: mockWebSocket.sendDataReceivedData!, encoding: .utf8)) .to(equal("[\"2\",\"6\",\"topic\",\"event\",{\"one\":\"two\"}]")) }) it("excludes ref information if not passed", closure: { mockWebSocket.readyState = .open socket.connect() socket.push(topic: "topic", event: "event", payload: ["one": "two"]) let json = self.decode(mockWebSocket.sendDataReceivedData!) as! [Any?] expect(json[0] as? String).to(beNil()) expect(json[1] as? String).to(beNil()) expect(json[2] as? String).to(equal("topic")) expect(json[3] as? String).to(equal("event")) expect(json[4] as? [String: String]).to(equal(["one": "two"])) expect(String(data: mockWebSocket.sendDataReceivedData!, encoding: .utf8)) .to(equal("[null,null,\"topic\",\"event\",{\"one\":\"two\"}]")) }) it("buffers data when not connected", closure: { mockWebSocket.readyState = .closed socket.connect() expect(socket.sendBuffer).to(beEmpty()) socket.push(topic: "topic1", event: "event1", payload: ["one": "two"]) expect(mockWebSocket.sendDataCalled).to(beFalse()) expect(socket.sendBuffer).to(haveCount(1)) socket.push(topic: "topic2", event: "event2", payload: ["one": "two"]) expect(mockWebSocket.sendDataCalled).to(beFalse()) expect(socket.sendBuffer).to(haveCount(2)) socket.sendBuffer.forEach( { try? $0.callback() } ) expect(mockWebSocket.sendDataCalled).to(beTrue()) expect(mockWebSocket.sendDataCallsCount).to(equal(2)) }) } describe("makeRef") { var socket: Socket! beforeEach { socket = Socket("/socket") } it("returns next message ref", closure: { expect(socket.ref).to(equal(0)) expect(socket.makeRef()).to(equal("1")) expect(socket.ref).to(equal(1)) expect(socket.makeRef()).to(equal("2")) expect(socket.ref).to(equal(2)) }) it("resets to 0 if it hits max int", closure: { socket.ref = UInt64.max expect(socket.makeRef()).to(equal("0")) expect(socket.ref).to(equal(0)) }) } describe("sendHeartbeat v1") { // Mocks var mockWebSocket: PhoenixTransportMock! // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() socket = Socket("/socket") socket.connection = mockWebSocket } it("closes socket when heartbeat is not ack'd within heartbeat window", closure: { mockWebSocket.readyState = .open socket.sendHeartbeat() expect(mockWebSocket.disconnectCodeReasonCalled).to(beFalse()) expect(socket.pendingHeartbeatRef).toNot(beNil()) socket.sendHeartbeat() expect(mockWebSocket.disconnectCodeReasonCalled).to(beTrue()) expect(socket.pendingHeartbeatRef).to(beNil()) }) it("pushes heartbeat data when connected", closure: { mockWebSocket.readyState = .open socket.sendHeartbeat() expect(socket.pendingHeartbeatRef).to(equal(String(socket.ref))) expect(mockWebSocket.sendDataCalled).to(beTrue()) let json = self.decode(mockWebSocket.sendDataReceivedData!) as? [Any?] expect(json?[0] as? String).to(beNil()) expect(json?[1] as? String).to(equal(socket.pendingHeartbeatRef)) expect(json?[2] as? String).to(equal("phoenix")) expect(json?[3] as? String).to(equal("heartbeat")) expect(json?[4] as? [String: String]).to(beEmpty()) expect(String(data: mockWebSocket.sendDataReceivedData!, encoding: .utf8)) .to(equal("[null,\"1\",\"phoenix\",\"heartbeat\",{}]")) }) it("does nothing when not connected", closure: { mockWebSocket.readyState = .closed socket.sendHeartbeat() expect(mockWebSocket.disconnectCodeReasonCalled).to(beFalse()) expect(mockWebSocket.sendDataCalled).to(beFalse()) }) } describe("flushSendBuffer") { // Mocks var mockWebSocket: PhoenixTransportMock! // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() socket = Socket("/socket") socket.connection = mockWebSocket } it("calls callbacks in buffer when connected", closure: { var oneCalled = 0 socket.sendBuffer.append(("0", { oneCalled += 1 })) var twoCalled = 0 socket.sendBuffer.append(("1", { twoCalled += 1 })) let threeCalled = 0 mockWebSocket.readyState = .open socket.flushSendBuffer() expect(oneCalled).to(equal(1)) expect(twoCalled).to(equal(1)) expect(threeCalled).to(equal(0)) }) it("empties send buffer", closure: { socket.sendBuffer.append((nil, { })) mockWebSocket.readyState = .open socket.flushSendBuffer() expect(socket.sendBuffer).to(beEmpty()) }) } describe("removeFromSendBuffer") { // Mocks var mockWebSocket: PhoenixTransportMock! // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() socket = Socket("/socket") socket.connection = mockWebSocket } it("removes a callback with a matching ref", closure: { var oneCalled = 0 socket.sendBuffer.append(("0", { oneCalled += 1 })) var twoCalled = 0 socket.sendBuffer.append(("1", { twoCalled += 1 })) let threeCalled = 0 mockWebSocket.readyState = .open socket.removeFromSendBuffer(ref: "0") socket.flushSendBuffer() expect(oneCalled).to(equal(0)) expect(twoCalled).to(equal(1)) expect(threeCalled).to(equal(0)) }) } describe("onConnectionOpen") { // Mocks var mockWebSocket: PhoenixTransportMock! var mockTimeoutTimer: TimeoutTimerMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() mockTimeoutTimer = TimeoutTimerMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) socket.reconnectAfter = { _ in return 10 } socket.reconnectTimer = mockTimeoutTimer socket.skipHeartbeat = true mockWebSocket.readyState = .open socket.connect() } it("flushes the send buffer", closure: { var oneCalled = 0 socket.sendBuffer.append(("0", { oneCalled += 1 })) socket.onConnectionOpen() expect(oneCalled).to(equal(1)) expect(socket.sendBuffer).to(beEmpty()) }) it("resets reconnectTimer", closure: { socket.onConnectionOpen() expect(mockTimeoutTimer.resetCalled).to(beTrue()) }) it("triggers onOpen callbacks", closure: { var oneCalled = 0 socket.onOpen { oneCalled += 1 } var twoCalled = 0 socket.onOpen { twoCalled += 1 } var threeCalled = 0 socket.onClose { threeCalled += 1 } socket.onConnectionOpen() expect(oneCalled).to(equal(1)) expect(twoCalled).to(equal(1)) expect(threeCalled).to(equal(0)) }) } describe("resetHeartbeat") { // Mocks var mockWebSocket: PhoenixTransportMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) } it("clears any pending heartbeat", closure: { socket.pendingHeartbeatRef = "1" socket.resetHeartbeat() expect(socket.pendingHeartbeatRef).to(beNil()) }) it("does not schedule heartbeat if skipHeartbeat == true", closure: { socket.skipHeartbeat = true socket.resetHeartbeat() expect(socket.heartbeatTimer).to(beNil()) }) it("creates a timer and sends a heartbeat", closure: { mockWebSocket.readyState = .open socket.connect() socket.heartbeatInterval = 1 expect(socket.heartbeatTimer).to(beNil()) socket.resetHeartbeat() expect(socket.heartbeatTimer).toNot(beNil()) expect(socket.heartbeatTimer?.timeInterval).to(equal(1)) // Fire the timer socket.heartbeatTimer?.fire() expect(mockWebSocket.sendDataCalled).to(beTrue()) let json = self.decode(mockWebSocket.sendDataReceivedData!) as? [Any?] expect(json?[0] as? String).to(beNil()) expect(json?[1] as? String).to(equal(String(socket.ref))) expect(json?[2] as? String).to(equal("phoenix")) expect(json?[3] as? String).to(equal(ChannelEvent.heartbeat)) expect(json?[4] as? [String: Any]).to(beEmpty()) }) it("should invalidate an old timer and create a new one", closure: { mockWebSocket.readyState = .open let queue = DispatchQueue(label: "test.heartbeat") let timer = HeartbeatTimer(timeInterval: 1000, queue: queue) var timerCalled = 0 timer.start { timerCalled += 1 } socket.heartbeatTimer = timer expect(timer.isValid).to(beTrue()) socket.resetHeartbeat() expect(timer.isValid).to(beFalse()) expect(socket.heartbeatTimer).toNot(equal(timer)) }) } describe("onConnectionClosed") { // Mocks var mockWebSocket: PhoenixTransportMock! var mockTimeoutTimer: TimeoutTimerMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() mockTimeoutTimer = TimeoutTimerMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) // socket.reconnectAfter = { _ in return 10 } socket.reconnectTimer = mockTimeoutTimer // socket.skipHeartbeat = true } it("schedules reconnectTimer timeout if normal close", closure: { socket.onConnectionClosed(code: Socket.CloseCode.normal.rawValue) expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beTrue()) }) it("does not schedule reconnectTimer timeout if normal close after explicit disconnect", closure: { socket.disconnect() expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beFalse()) }) it("schedules reconnectTimer timeout if not normal close", closure: { socket.onConnectionClosed(code: 1001) expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beTrue()) }) it("schedules reconnectTimer timeout if connection cannot be made after a previous clean disconnect", closure: { socket.disconnect() socket.connect() socket.onConnectionClosed(code: 1001) expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beTrue()) }) it("triggers channel error if joining", closure: { let channel = socket.channel("topic") var errorCalled = false channel.on(ChannelEvent.error, callback: { _ in errorCalled = true }) channel.join() expect(channel.state).to(equal(.joining)) socket.onConnectionClosed(code: 1001) expect(errorCalled).to(beTrue()) }) it("triggers channel error if joined", closure: { let channel = socket.channel("topic") var errorCalled = false channel.on(ChannelEvent.error, callback: { _ in errorCalled = true }) channel.join().trigger("ok", payload: [:]) expect(channel.state).to(equal(.joined)) socket.onConnectionClosed(code: 1001) expect(errorCalled).to(beTrue()) }) it("does not trigger channel error after leave", closure: { let channel = socket.channel("topic") var errorCalled = false channel.on(ChannelEvent.error, callback: { _ in errorCalled = true }) channel.join().trigger("ok", payload: [:]) channel.leave() expect(channel.state).to(equal(.closed)) socket.onConnectionClosed(code: 1001) expect(errorCalled).to(beFalse()) }) it("triggers onClose callbacks", closure: { var oneCalled = 0 socket.onClose { oneCalled += 1 } var twoCalled = 0 socket.onClose { twoCalled += 1 } var threeCalled = 0 socket.onOpen { threeCalled += 1 } socket.onConnectionClosed(code: 1000) expect(oneCalled).to(equal(1)) expect(twoCalled).to(equal(1)) expect(threeCalled).to(equal(0)) }) } describe("onConnectionError") { // Mocks var mockWebSocket: PhoenixTransportMock! var mockTimeoutTimer: TimeoutTimerMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() mockTimeoutTimer = TimeoutTimerMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) socket.reconnectAfter = { _ in return 10 } socket.reconnectTimer = mockTimeoutTimer socket.skipHeartbeat = true mockWebSocket.readyState = .open socket.connect() } it("triggers onClose callbacks", closure: { var lastError: Error? socket.onError(callback: { (error) in lastError = error }) socket.onConnectionError(TestError.stub) expect(lastError).toNot(beNil()) }) it("triggers channel error if joining", closure: { let channel = socket.channel("topic") var errorCalled = false channel.on(ChannelEvent.error, callback: { _ in errorCalled = true }) channel.join() expect(channel.state).to(equal(.joining)) socket.onConnectionError(TestError.stub) expect(errorCalled).to(beTrue()) }) it("triggers channel error if joined", closure: { let channel = socket.channel("topic") var errorCalled = false channel.on(ChannelEvent.error, callback: { _ in errorCalled = true }) channel.join().trigger("ok", payload: [:]) expect(channel.state).to(equal(.joined)) socket.onConnectionError(TestError.stub) expect(errorCalled).to(beTrue()) }) it("does not trigger channel error after leave", closure: { let channel = socket.channel("topic") var errorCalled = false channel.on(ChannelEvent.error, callback: { _ in errorCalled = true }) channel.join().trigger("ok", payload: [:]) channel.leave() expect(channel.state).to(equal(.closed)) socket.onConnectionError(TestError.stub) expect(errorCalled).to(beFalse()) }) } describe("onConnectionMessage") { // Mocks var mockWebSocket: PhoenixTransportMock! var mockTimeoutTimer: TimeoutTimerMock! let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket } // UUT var socket: Socket! beforeEach { mockWebSocket = PhoenixTransportMock() mockTimeoutTimer = TimeoutTimerMock() socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport) socket.reconnectAfter = { _ in return 10 } socket.reconnectTimer = mockTimeoutTimer socket.skipHeartbeat = true mockWebSocket.readyState = .open socket.connect() } it("parses raw message and triggers channel event", closure: { let targetChannel = socket.channel("topic") let otherChannel = socket.channel("off-topic") var targetMessage: Message? targetChannel.on("event", callback: { (msg) in targetMessage = msg }) var otherMessage: Message? otherChannel.on("event", callback: { (msg) in otherMessage = msg }) let data: [Any?] = [nil, nil, "topic", "event", ["status": "ok", "response": ["one": "two"]]] let rawMessage = toWebSocketText(data: data) socket.onConnectionMessage(rawMessage) expect(targetMessage?.topic).to(equal("topic")) expect(targetMessage?.event).to(equal("event")) expect(targetMessage?.payload["one"] as? String).to(equal("two")) expect(otherMessage).to(beNil()) }) it("triggers onMessage callbacks", closure: { var message: Message? socket.onMessage(callback: { (msg) in message = msg }) let data: [Any?] = [nil, nil, "topic", "event", ["status": "ok", "response": ["one": "two"]]] let rawMessage = toWebSocketText(data: data) socket.onConnectionMessage(rawMessage) expect(message?.topic).to(equal("topic")) expect(message?.event).to(equal("event")) expect(message?.payload["one"] as? String).to(equal("two")) }) it("clears pending heartbeat", closure: { socket.pendingHeartbeatRef = "5" let rawMessage = "[null,\"5\",\"phoenix\",\"phx_reply\",{\"response\":{},\"status\":\"ok\"}]" socket.onConnectionMessage(rawMessage) expect(socket.pendingHeartbeatRef).to(beNil()) }) } } }
mit
f4a6e4b0bc28068d89a029603e4424e8
33.709544
118
0.585117
4.388197
false
false
false
false
SparkAppStudio/SparkKit
SparkKit/BasicButton.swift
1
1238
// // Copyright © 2017 Spark App Studio. All rights reserved. // import UIKit @IBDesignable class BasicButton: UIButton { let rounded: CGFloat = 12 override init(frame: CGRect) { super.init(frame: frame) sharedInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInit() } func sharedInit() { titleLabel?.textColor = UIColor.white } override func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext()! let inset = rect.insetBy(dx: 1, dy: 1) let rounded = UIBezierPath(roundedRect: inset, cornerRadius: self.rounded) UIColor.blue.setFill() ctx.addPath(rounded.cgPath) ctx.fillPath() UIColor.orange.setStroke() ctx.addPath(rounded.cgPath) ctx.strokePath() } override var intrinsicContentSize: CGSize { if let string = titleLabel?.text as NSString? { let stringSize = string.size(withAttributes: [.font: titleLabel!.font]) return CGSize(width: rounded * 2 + ceil(stringSize.width), height: rounded * 2 + ceil(stringSize.height)) } return super.intrinsicContentSize } }
mit
3c2f4aee6e6a2d535ab4357c731c8fa6
22.788462
117
0.616006
4.531136
false
false
false
false
RajmohanKathiresan/emotiphor_ios
Emotiphor/ViewController/CreatorViewController.swift
1
5875
// // CreatorViewController.swift // Emotiphor // // Created by Rajmohan Kathiresan on 13/09/16. // Copyright © 2016 Rajmohan Kathiresan. All rights reserved. // import UIKit import EmotCore class CreatorViewController : UIViewController { static let kStoryboardName = "Creator" static let kControllerIdentifier = "CreatorViewController" @IBOutlet weak var emoticonView: UIImageView! @IBOutlet weak var historyCollectionView: UICollectionView! @IBOutlet weak var backBarButton: UIBarButtonItem! var history:[RMEmoji] = [RMEmoji]() override func viewDidLoad() { super.viewDidLoad() self.title = "Collage" self.applyTheme() self.backBarButton.target = self self.backBarButton.action = #selector(self.backAction(_:)) let searchButton = UIBarButtonItem(image: UIImage(named:"search"), style: .plain, target: self, action: #selector(CreatorViewController.searchTapAction(_:))) searchButton.tintColor = UIColor.white self.navigationItem.rightBarButtonItem = searchButton self.emoticonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CreatorViewController.changeEmojiAction(gesture:)))) } @objc fileprivate func backAction(_ sender:AnyObject?) { _ = self.navigationController?.popViewController(animated: true) } fileprivate func applyTheme() { self.historyCollectionView.backgroundColor = UIColor.white let navigationBar = self.navigationController?.navigationBar navigationBar?.backgroundColor = ApplicationTheme.color() navigationBar?.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] self.emoticonView.tintColor = UIColor.lightGray } fileprivate func addToHistory(emoji:RMEmoji) { history.insert(emoji, at: 0) historyCollectionView.reloadData() //Save tp Disk // saveToDisk(emoji) } fileprivate func randomizeColor() { let redValue:CGFloat = CGFloat(arc4random()%255)/255.0 let blueValue:CGFloat = CGFloat(arc4random()%255)/255.0 let greenValue:CGFloat = CGFloat(arc4random()%255)/255.0 let randomColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) self.emoticonView.backgroundColor = randomColor } /// TODO: Need Refinements fileprivate func getImageFromView() -> UIImage { let scale = UIScreen.main.nativeScale print(scale) let actualSize = self.emoticonView.bounds.size print("\(actualSize.width):\(actualSize.height)") UIGraphicsBeginImageContextWithOptions(actualSize, false, scale) self.emoticonView.drawHierarchy(in: self.emoticonView.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } fileprivate func saveToDisk(_ emoticon:RMEmoji) { let image = getImageFromView() let filemanager = FileManager.default let path = filemanager.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first! print(path) let directoryName = "emotiphor" let directoryPath = path.appendingPathComponent(directoryName) print(directoryPath.path) do { try filemanager.createDirectory(atPath: directoryPath.path, withIntermediateDirectories:false, attributes: nil) } catch { print("Folder already exists") } let filename = emoticon.unicode + ".png" let fileurl = directoryPath.appendingPathComponent("\(filename)") print(fileurl.path) do { try UIImagePNGRepresentation(image)!.write(to: URL(fileURLWithPath: fileurl.path), options: NSData.WritingOptions.atomic) } catch { print("Issues writing to file") } } func searchTapAction(_:UIBarButtonItem) { self.searchEmoji() } func changeEmojiAction(gesture:UITapGestureRecognizer) { if gesture.state == .ended { self.searchEmoji() } } private func searchEmoji() { let searchVC = UIViewController.GetViewController(instoryboard: SearchEmojiViewController.kStoryboardName, withController: SearchEmojiViewController.kControllerIdentifier) as! SearchEmojiViewController searchVC.delegate = self self.present(searchVC, animated: true, completion: nil) } } extension CreatorViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return history.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmojiCell.kIdentifier, for: indexPath) as! EmojiCell cell.setContent(withEmoji: history[(indexPath as NSIndexPath).row]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 40.0,height: 40.0) } } extension CreatorViewController : SearchEmojiDelegate { func searchEmojiDidCancel(sender: AnyObject?) { //TODO: } func searchEmojiDidSelectEmoji(emoji: RMEmoji, sender: AnyObject?) { self.addToHistory(emoji: emoji) self.emoticonView.image = UIImage(named: emoji.unicode) } }
mpl-2.0
8f21c5dc3ef0ad259a7e331ed76e0566
37.900662
209
0.693905
5.130131
false
false
false
false
billdonner/sheetcheats9
sc9/InterAppCommunications.swift
1
2067
// // InterAppCommunications // stories // // Created by bill donner on 7/18/15. // Copyright © 2015 shovelreadyapps. All rights reserved. // import Foundation //typealias ExternalStory = Dictionary<String,String> typealias ExternalTile = [String:String] typealias ExTilePayload = [ExternalTile] let SuiteNameForDataModel = "group.com.midnightrambler.stories" enum IACommunications:Error { case generalFailure case restoreFailure } class InterAppCommunications { class var shared: InterAppCommunications { struct Singleton { static let sharedAppConfiguration = InterAppCommunications() } return Singleton.sharedAppConfiguration } // the data sent to watch or "messages" extension var version: String = "0.0.1" var name: String // typically matches section name var items: ExTilePayload // the small tile data // init() { name = ""; items = [] } class func make(_ name:String ,items:ExTilePayload){ InterAppCommunications.shared.name = name InterAppCommunications.shared.items = items } //put in special NSUserDefaults which can be shared class func restore () throws { if let defaults: UserDefaults = UserDefaults(suiteName: SuiteNameForDataModel), let name = (defaults.object(forKey: "name") as? String), let items = (defaults.object(forKey: "items") as? ExTilePayload) { // version check goes here InterAppCommunications.make(name,items:items) return } else {throw IACommunications.restoreFailure} } class func save (_ name:String,items:ExTilePayload) {// aka send to other device/panel InterAppCommunications.make(name,items:items) let defaults: UserDefaults = UserDefaults(suiteName:SuiteNameForDataModel)! defaults.set( InterAppCommunications.shared.version, forKey: "version") defaults.set( name, forKey: "name") defaults.set( items, forKey: "items") } }
apache-2.0
15b7e05e0f1a710a840778c33eac48d9
31.28125
90
0.666021
4.313152
false
false
false
false
jopamer/swift
test/Generics/protocol_requirement_signatures.swift
1
3319
// RUN: %target-typecheck-verify-swift // RUN: %target-typecheck-verify-swift -debug-generic-signatures > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump // CHECK-LABEL: .P1@ // CHECK-NEXT: Requirement signature: <Self> // CHECK-NEXT: Canonical requirement signature: <τ_0_0> protocol P1 {} // CHECK-LABEL: .P2@ // CHECK-NEXT: Requirement signature: <Self> // CHECK-NEXT: Canonical requirement signature: <τ_0_0> protocol P2 {} // CHECK-LABEL: .P3@ // CHECK-NEXT: Requirement signature: <Self> // CHECK-NEXT: Canonical requirement signature: <τ_0_0> protocol P3 {} // basic protocol // CHECK-LABEL: .Q1@ // CHECK-NEXT: Requirement signature: <Self where Self.X : P1> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.X : P1> protocol Q1 { associatedtype X: P1 // expected-note {{declared here}} } // inheritance // CHECK-LABEL: .Q2@ // CHECK-NEXT: Requirement signature: <Self where Self : Q1> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q1> protocol Q2: Q1 {} // inheritance without any new requirements // CHECK-LABEL: .Q3@ // CHECK-NEXT: Requirement signature: <Self where Self : Q1> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q1> protocol Q3: Q1 { associatedtype X } // inheritance adding a new conformance // CHECK-LABEL: .Q4@ // CHECK-NEXT: Requirement signature: <Self where Self : Q1, Self.X : P2> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q1, τ_0_0.X : P2> protocol Q4: Q1 { associatedtype X: P2 // expected-warning{{redeclaration of associated type 'X'}} // expected-note@-1 2{{'X' declared here}} } // multiple inheritance // CHECK-LABEL: .Q5@ // CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0 : Q3, τ_0_0 : Q4> protocol Q5: Q2, Q3, Q4 {} // multiple inheritance without any new requirements // CHECK-LABEL: .Q6@ // CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0 : Q3, τ_0_0 : Q4> protocol Q6: Q2, // expected-note{{conformance constraint 'Self.X': 'P1' implied here}} Q3, Q4 { associatedtype X: P1 // expected-warning{{redundant conformance constraint 'Self.X': 'P1'}} // expected-warning@-1{{redeclaration of associated type 'X' from protocol 'Q4' is}} } // multiple inheritance with a new conformance // CHECK-LABEL: .Q7@ // CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4, Self.X : P3> // CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0 : Q3, τ_0_0 : Q4, τ_0_0.X : P3> protocol Q7: Q2, Q3, Q4 { associatedtype X: P3 // expected-warning{{redeclaration of associated type 'X'}} } // SR-5945 class SomeBaseClass {} // CHECK-DAG: .P4@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.BType.AType, Self.BType : P5, Self.Native : SomeBaseClass> protocol P4 { associatedtype Native : SomeBaseClass associatedtype BType : P5 where BType.AType == Self } // CHECK-DAG: .P5@ // CHECK-NEXT: <Self where Self == Self.AType.BType, Self.AType : P4> protocol P5 { associatedtype AType : P4 where AType.BType == Self }
apache-2.0
f0c2e0245ae98ace24cdd39024105651
36.011236
121
0.675774
3.010969
false
false
false
false
networkextension/SFSocket
SFSocket/tcp/ProxyConnector.swift
1
7690
// // ProxyConnector.swift // Surf // // Created by yarshure on 16/1/7. // Copyright © 2016年 yarshure. All rights reserved. // import Foundation import AxLogger import NetworkExtension import Security public class ProxyConnector: NWTCPSocket,NWTCPConnectionAuthenticationDelegate { var proxy:SFProxy var tlsSupport:Bool = false var targetHost:String = "" var targetPort:UInt16 = 0 var tlsEvaluate:Bool = false #if os(iOS) let acceptableCipherSuites:Set<NSNumber> = [ NSNumber(value: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256), NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA), NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA), NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA), NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), NSNumber(value: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA), NSNumber(value: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384), NSNumber(value: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384), NSNumber(value: TLS_RSA_WITH_AES_256_GCM_SHA384), NSNumber(value: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384), NSNumber(value: TLS_DH_RSA_WITH_AES_256_GCM_SHA384) // public var TLS_RSA_WITH_AES_256_GCM_SHA384: SSLCipherSuite { get } // public var TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: SSLCipherSuite { get } // public var TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: SSLCipherSuite { get } // public var TLS_DH_RSA_WITH_AES_128_GCM_SHA256: SSLCipherSuite { get } // public var TLS_DH_RSA_WITH_AES_256_GCM_SHA384: SSLCipherSuite { get } ] #else let acceptableCipherSuites:Set<NSNumber> = [ NSNumber(value: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256), NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA), NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA), NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA), NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), NSNumber(value: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA) ] #endif var pFrontAddress:String = "" var pFrontPort:UInt16 = 0 init(p:SFProxy) { proxy = p super.init() //cIDFunc() } override public func start() { guard let port = Int(proxy.serverPort) else { return } if proxy.type == .SS { if !proxy.serverIP.isEmpty{ //by pass dns resolv try! self.connectTo(proxy.serverIP, port: port, enableTLS: false, tlsSettings: nil) }else { try! self.connectTo(proxy.serverAddress, port: port, enableTLS: false, tlsSettings: nil) } }else { try! self.connectTo(proxy.serverAddress, port: port, enableTLS: proxy.tlsEnable, tlsSettings: nil) } } override public func connectTo(_ host: String, port: Int, enableTLS: Bool, tlsSettings: [NSObject : AnyObject]?) throws { if enableTLS { let endpoint = NWHostEndpoint(hostname: host, port: "\(port)") let tlsParameters = NWTLSParameters() if let tlsSettings = tlsSettings as? [String: AnyObject] { tlsParameters.setValuesForKeys(tlsSettings) }else { tlsParameters.sslCipherSuites = acceptableCipherSuites } let v = SSLProtocol.tlsProtocol12 tlsParameters.minimumSSLProtocolVersion = Int(v.rawValue) guard let c = RawSocketFactory.TunnelProvider?.createTCPConnection(to: endpoint, enableTLS: enableTLS, tlsParameters: tlsParameters, delegate: nil) else { // This should only happen when the extension is already stoped and `RawSocketFactory.TunnelProvider` is set to `nil`. return } connection = c connection!.addObserver(self, forKeyPath: "state", options: [.initial, .new], context: nil) }else { do { try super.connectTo(host, port: port, enableTLS: false, tlsSettings: tlsSettings) }catch let e as NSError{ throw e } } } @nonobjc public func shouldEvaluateTrustForConnection(connection: NWTCPConnection) -> Bool{ return true } @nonobjc public func evaluateTrustForConnection(connection: NWTCPConnection, peerCertificateChain: [AnyObject], completionHandler completion: @escaping (SecTrust) -> Void){ let myPolicy = SecPolicyCreateSSL(true, nil)//proxy.serverAddress var possibleTrust: SecTrust? let x = SecTrustCreateWithCertificates(peerCertificateChain.first!, myPolicy, &possibleTrust) guard let remoteAddress = connection.remoteAddress as? NWHostEndpoint else { completion(possibleTrust!) return } AxLogger.log("debug :\(remoteAddress.hostname)", level: .Debug) if x != 0 { AxLogger.log("debug :\(remoteAddress.hostname) \(x)", level: .Debug) } if let trust = possibleTrust { //let's do test by ourself first var trustResult : SecTrustResultType = .invalid let r = SecTrustEvaluate(trust, &trustResult) if r != 0{ AxLogger.log("debug :\(remoteAddress.hostname) error code:\(r)", level: .Debug) } if trustResult == .proceed { AxLogger.log("debug :\(remoteAddress.hostname) Proceed", level: .Debug) }else { AxLogger.log("debug :\(remoteAddress.hostname) Proceed error", level: .Debug) } //print(trustResult) // the result is 5, is it //kSecTrustResultRecoverableTrustFailure? completion(trust) }else { AxLogger.log("debug :\(remoteAddress.hostname) error", level: .Debug) } } // override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { // let x = connection.endpoint as! NWHostEndpoint // if keyPath == "state" { // // // var stateString = "" // switch connection.state { // case .Connected: // stateString = "Connected" // if proxy.tlsEnable == true && proxy.type != .SS { // AxLogger.log("\(cIDString) host:\(x) tls handshake passed", level: .Debug) // } // queueCall { // self.socketConnectd() // } // // case .Disconnected: // stateString = "Disconnected" // cancel() // case .Cancelled: // stateString = "Cancelled" // queueCall { // let delegate = self.delegate // self.delegate = nil // delegate?.didDisconnect(self) // // } // case .Connecting: // stateString = "Connecting" // case .Waiting: // stateString = "Waiting" // case .Invalid: // stateString = "Invalid" // // } // AxLogger.log("\(cIDString) host:\(x) " + stateString, level: .Debug) // } // // } }
bsd-3-clause
dbdf441c3b42a9aff9b0d9b9e69426c4
37.823232
176
0.567712
4.071504
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift
1
16960
// // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !os(watchOS) #if os(macOS) import AppKit #else import UIKit #endif extension KingfisherWrapper where Base: KFCrossPlatformImageView { // MARK: Setting Image /// Sets an image to the image view with a `Source`. /// /// - Parameters: /// - source: The `Source` object defines data information from network or a data provider. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: /// /// ``` /// // Set image from a network source. /// let url = URL(string: "https://example.com/image.png")! /// imageView.kf.setImage(with: .network(url)) /// /// // Or set image from a data provider. /// let provider = LocalFileImageDataProvider(fileURL: fileURL) /// imageView.kf.setImage(with: .provider(provider)) /// ``` /// /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code /// above is equivalent to: /// /// ``` /// imageView.kf.setImage(with: url) /// imageView.kf.setImage(with: provider) /// ``` /// /// Internally, this method will use `KingfisherManager` to get the source. /// Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with source: Source?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { var mutatingSelf = self guard let source = source else { mutatingSelf.placeholder = placeholder mutatingSelf.taskIdentifier = nil completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) return nil } var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet { // Always set placeholder while there is no image/placeholder yet. mutatingSelf.placeholder = placeholder } let maybeIndicator = indicator maybeIndicator?.startAnimatingView() let issuedIdentifier = Source.Identifier.next() mutatingSelf.taskIdentifier = issuedIdentifier if base.shouldPreloadAllAnimation() { options.preloadAllAnimationData = true } if let block = progressBlock { options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] } if let provider = ImageProgressiveProvider(options, refresh: { image in self.base.image = image }) { options.onDataReceived = (options.onDataReceived ?? []) + [provider] } options.onDataReceived?.forEach { $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } } let task = KingfisherManager.shared.retrieveImage( with: source, options: options, completionHandler: { result in CallbackQueue.mainCurrentOrAsync.execute { maybeIndicator?.stopAnimatingView() guard issuedIdentifier == self.taskIdentifier else { let reason: KingfisherError.ImageSettingErrorReason do { let value = try result.get() reason = .notCurrentSourceTask(result: value, error: nil, source: source) } catch { reason = .notCurrentSourceTask(result: nil, error: error, source: source) } let error = KingfisherError.imageSettingError(reason: reason) completionHandler?(.failure(error)) return } mutatingSelf.imageTask = nil mutatingSelf.taskIdentifier = nil switch result { case .success(let value): guard self.needsTransition(options: options, cacheType: value.cacheType) else { mutatingSelf.placeholder = nil self.base.image = value.image completionHandler?(result) return } self.makeTransition(image: value.image, transition: options.transition) { completionHandler?(result) } case .failure: if let image = options.onFailureImage { self.base.image = image } completionHandler?(result) } } } ) mutatingSelf.imageTask = task return task } /// Sets an image to the image view with a requested resource. /// /// - Parameters: /// - resource: The `Resource` object contains information about the resource. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// - Note: /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this: /// /// ``` /// let url = URL(string: "https://example.com/image.png")! /// imageView.kf.setImage(with: url) /// ``` /// /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache /// or network. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with resource: Resource?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: resource.map { .network($0) }, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /// Sets an image to the image view with a data provider. /// /// - Parameters: /// - provider: The `ImageDataProvider` object contains information about the data. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. /// - completionHandler: Called when the image retrieved and set finished. /// - Returns: A task represents the image downloading. /// /// Internally, this method will use `KingfisherManager` to get the image data, from either cache /// or the data provider. Since this method will perform UI changes, you must call it from the main thread. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. /// @discardableResult public func setImage( with provider: ImageDataProvider?, placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask? { return setImage( with: provider.map { .provider($0) }, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } // MARK: Cancelling Downloading Task /// Cancels the image download task of the image view if it is running. /// Nothing will happen if the downloading has already finished. public func cancelDownloadTask() { imageTask?.cancel() } private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool { switch options.transition { case .none: return false #if !os(macOS) default: if options.forceTransition { return true } if cacheType == .none { return true } return false #endif } } private func makeTransition(image: KFCrossPlatformImage, transition: ImageTransition, done: @escaping () -> Void) { #if !os(macOS) // Force hiding the indicator without transition first. UIView.transition( with: self.base, duration: 0.0, options: [], animations: { self.indicator?.stopAnimatingView() }, completion: { _ in var mutatingSelf = self mutatingSelf.placeholder = nil UIView.transition( with: self.base, duration: transition.duration, options: [transition.animationOptions, .allowUserInteraction], animations: { transition.animations?(self.base, image) }, completion: { finished in transition.completion?(finished) done() } ) } ) #else done() #endif } } // MARK: - Associated Object private var taskIdentifierKey: Void? private var indicatorKey: Void? private var indicatorTypeKey: Void? private var placeholderKey: Void? private var imageTaskKey: Void? extension KingfisherWrapper where Base: KFCrossPlatformImageView { // MARK: Properties public private(set) var taskIdentifier: Source.Identifier.Value? { get { let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey) return box?.value } set { let box = newValue.map { Box($0) } setRetainedAssociatedObject(base, &taskIdentifierKey, box) } } /// Holds which indicator type is going to be used. /// Default is `.none`, means no indicator will be shown while downloading. public var indicatorType: IndicatorType { get { return getAssociatedObject(base, &indicatorTypeKey) ?? .none } set { switch newValue { case .none: indicator = nil case .activity: indicator = ActivityIndicator() case .image(let data): indicator = ImageIndicator(imageData: data) case .custom(let anIndicator): indicator = anIndicator } setRetainedAssociatedObject(base, &indicatorTypeKey, newValue) } } /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `indicatorType` is `.none`. public private(set) var indicator: Indicator? { get { let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey) return box?.value } set { // Remove previous if let previousIndicator = indicator { previousIndicator.view.removeFromSuperview() } // Add new if let newIndicator = newValue { // Set default indicator layout let view = newIndicator.view base.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false view.centerXAnchor.constraint( equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true view.centerYAnchor.constraint( equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true newIndicator.view.isHidden = true } // Save in associated object // Wrap newValue with Box to workaround an issue that Swift does not recognize // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872 setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init)) } } private var imageTask: DownloadTask? { get { return getAssociatedObject(base, &imageTaskKey) } set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} } /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while /// it is downloading an image. public private(set) var placeholder: Placeholder? { get { return getAssociatedObject(base, &placeholderKey) } set { if let previousPlaceholder = placeholder { previousPlaceholder.remove(from: base) } if let newPlaceholder = newValue { newPlaceholder.add(to: base) } else { base.image = nil } setRetainedAssociatedObject(base, &placeholderKey, newValue) } } } @objc extension KFCrossPlatformImageView { func shouldPreloadAllAnimation() -> Bool { return true } } extension KingfisherWrapper where Base: KFCrossPlatformImageView { /// Gets the image URL bound to this image view. @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.") public private(set) var webURL: URL? { get { return nil } set { } } } #endif
mit
1c847a5e10a055225e3eade78d1bb839
40.670762
120
0.608667
5.387548
false
false
false
false
ssmali1505/Web-service-call-in-swift
WebServiceCalls/WebServiceCalls/APIHelper.swift
1
8737
// // APIHelper.swift // WebServiceCalls // // Created by SANDY on 02/01/15. // Copyright (c) 2015 Evgeny Nazarov. All rights reserved. // import Foundation @objc protocol APIHelperDelegate { /// This will return response from webservice if request successfully done to server func apiHelperResponseSuccess(apihelper:APIHelper) /// This is for Fail request or server give any error optional func apiHelperResponseFail(connection: NSURLConnection?,error: NSError) } public class APIHelper: NSObject,NSURLConnectionDelegate { public enum MethodType : Int{ case GET = 1 case POST = 2 case JSON = 3 case IMAGE = 4 } let timeinterval:Int = 239 private var objConnection:NSURLConnection? private var objURL:NSString! private var objParameter:NSMutableDictionary? private var objUtility:APIUtilityHelper! public var responseData:NSMutableData! var delegate:APIHelperDelegate? public var ApiIdentifier:NSString!="" override init() { super.init(); objUtility=APIUtilityHelper() } // MARK: Method Web API /// Call GET request webservice (urlMethodOrFile, parameters:,apiIdentifier,delegate) func APIHelperAPI_GET(urlMethodOrFile:NSString, parameters:NSMutableDictionary?,apiIdentifier:NSString,delegate:APIHelperDelegate!) { self.objParameter=parameters self.ApiIdentifier=apiIdentifier self.delegate=delegate var strParam :NSString? = objUtility!.JSONStringify(objParameter!) if (strParam != "") { strParam = "?" + strParam! } var strURL:String = "\(urlMethodOrFile)" + strParam! self.objURL=strURL self.CallURL(nil, methodtype: MethodType.GET) } /// Call POST request webservice (urlMethodOrFile, parameters,apiIdentifier,delegate) func APIHelperAPI_POST(urlMethodOrFile:NSString, parameters:NSMutableDictionary?,apiIdentifier:NSString,delegate:APIHelperDelegate!) { self.objParameter=parameters self.ApiIdentifier=apiIdentifier self.delegate=delegate var strParam :NSString? = objUtility!.JSONStringify(objParameter!) println("wenservice Post Input >>> \(strParam)") var strURL:String = (urlMethodOrFile) self.objURL=strURL self.CallURL(strParam?.dataUsingEncoding(NSUTF8StringEncoding), methodtype: MethodType.POST); } /// Upload file and text data through webservice (urlMethodOrFile, parameters,parametersImage(dictionary of NSData),apiIdentifier,delegate) func APIHelperAPI_FileUpload(urlMethodOrFile:NSString, parameters:NSMutableDictionary?,parametersImage:NSMutableDictionary?,apiIdentifier:NSString,delegate:APIHelperDelegate!) { self.objParameter=parameters self.ApiIdentifier=apiIdentifier self.delegate=delegate var strParam :NSString? = objUtility!.JSONStringify(self.objParameter!) var strURL:String = (urlMethodOrFile) self.objURL=strURL var body : NSMutableData?=NSMutableData() var dicParam:NSDictionary = parameters! var dicImageParam:NSDictionary = parametersImage! var boundary:NSString? = "---------------------------14737809831466499882746641449" // process text parameters for (key, value) in dicParam { body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); body?.appendData(("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); } //process images parameters var i:Int=0 for (key, value) in dicImageParam { body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); body?.appendData(("Content-Disposition: file; name=\"\(key)\"; filename=\"image.png\(i)\"\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); body?.appendData(("Content-Type: application/octet-stream\r\n\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); body?.appendData(value as NSData); body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); } body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!); self.CallURL(body!, methodtype: MethodType.IMAGE); } /// Call JSON webservice (urlMethodOrFile,json,apiIdentifier,delegate) func APIHelperAPI_JSON(urlMethodOrFile:NSString, json:NSString?,apiIdentifier:NSString,delegate:APIHelperDelegate!) { self.ApiIdentifier=apiIdentifier self.delegate=delegate var strParam :NSString? = json var strURL:String = urlMethodOrFile self.objURL=strURL self.CallURL(strParam?.dataUsingEncoding(NSUTF8StringEncoding),methodtype: MethodType.JSON) } private func CallURL(dataParam:NSData?,methodtype:MethodType) { //println(self.objURL) if(!self.objUtility.isInternetAvailable()) { println("INTERNET NOT AVAILABLE") var error :NSError=NSError(domain: "INTERNET NOT AVAILABLE", code: 404, userInfo: nil) delegate?.apiHelperResponseFail?(nil, error: error) return; } var objurl = NSURL(string: self.objURL) var request:NSMutableURLRequest = NSMutableURLRequest(URL:objurl!) if(methodtype == MethodType.GET) {//if simple GET method -- here we are not using strParam as it concenate with url already request.timeoutInterval = NSTimeInterval(self.timeinterval) request.HTTPMethod = "GET"; } if(methodtype == MethodType.POST) {//if simple POST method // request.addValue("\(strParam?.length)", forHTTPHeaderField: "Content-length") request.timeoutInterval = NSTimeInterval(self.timeinterval) request.HTTPMethod = "POST"; request.HTTPBody=dataParam } if(methodtype == MethodType.JSON) {//if JSON type webservice called request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") // request.addValue("\(strParam?.length)", forHTTPHeaderField: "Content-length") request.timeoutInterval = NSTimeInterval(self.timeinterval) request.HTTPMethod = "POST"; request.HTTPBody=dataParam } if(methodtype == MethodType.IMAGE) {//if webservice with Image Uploading var boundary:NSString? = "---------------------------14737809831466499882746641449" var contentType:NSString? = "multipart/form-data; boundary=\(boundary)" request.addValue(contentType, forHTTPHeaderField: "Content-Type") request.timeoutInterval = NSTimeInterval(self.timeinterval) request.HTTPMethod = "POST"; request.HTTPBody=dataParam } self.objConnection = NSURLConnection(request: request, delegate: self, startImmediately: true) self.responseData=NSMutableData() } // MARK: NSURLConnection func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { //println("response") } func connection(connection: NSURLConnection, didReceiveData data: NSData) { self.responseData.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection) { //println(NSDate().timeIntervalSince1970) // println("json : \(NSString(data: self.responseData!, encoding: NSUTF8StringEncoding))") delegate?.apiHelperResponseSuccess(self) } public func connection(connection: NSURLConnection, didFailWithError error: NSError) { println("error iHelperClass: \(error)"); delegate?.apiHelperResponseFail?(connection, error: error) } }
apache-2.0
b7e8b854a0d0c7e8dc4230b5d0d1e0e2
34.958848
179
0.62985
5.050289
false
false
false
false
forbidden404/FSOhanaAlert
FSOhanaAlert/FSOhanaCustomAlert.swift
1
6417
// // FSOhanaCustomAlert.swift // FSOhanaAlert // // Created by Francisco Soares on 26/10/17. // Copyright © 2017 Francisco Soares. All rights reserved. // import UIKit public class FSOhanaCustomAlert: UIView { @IBOutlet weak var ohanaImageView: UIImageView! @IBOutlet weak var textLabel: UILabel! @IBOutlet weak var leftButton: UIButton! @IBOutlet weak var rightButton: UIButton! @IBOutlet weak var buttonStackView: UIStackView! @IBOutlet weak var okButton: UIButton! var hasOkButton: Bool = false { willSet { okButton.isHidden = !newValue okButton.isUserInteractionEnabled = newValue okButton.tintColor = FSOhanaButtonType.standard.color() okButton.titleLabel?.font = FSOhanaButtonType.standard.font() } } var completion: ((Any?, Error?) -> Void)? { didSet { leftButton.isHidden = false rightButton.isHidden = false leftButton.isUserInteractionEnabled = true rightButton.isUserInteractionEnabled = true hasOkButton = false } } let nibName = "FSOhanaCustomAlert" var contentView: UIView! // MARK: Set Up View public override init(frame: CGRect) { super.init(frame: frame) setUpView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpView() } public override func layoutSubviews() { self.layoutIfNeeded() if completion == nil && !hasOkButton { self.buttonStackView.removeFromSuperview() self.contentView.frame = CGRect(x: self.contentView.frame.origin.x, y: self.contentView.frame.origin.y, width: self.contentView.frame.size.width, height: self.contentView.frame.size.height - (self.buttonStackView.bounds.size.height/2.0)) } // If there is no Ok Button if !hasOkButton { self.okButton.removeFromSuperview() } // Shadow self.contentView.backgroundColor = UIColor.clear for subview in self.contentView.subviews { subview.backgroundColor = UIColor.clear } let shadowPath = UIBezierPath(rect: self.contentView.bounds) self.contentView.layer.shadowColor = UIColor.black.cgColor self.contentView.layer.shadowOffset = CGSize(width: 0.0, height: 5.0) self.contentView.layer.shadowOpacity = 0.5 self.contentView.layer.shadowPath = shadowPath.cgPath // Corner let border = UIView() border.frame = self.contentView.bounds border.layer.masksToBounds = true border.clipsToBounds = true border.layer.cornerRadius = 10 border.layer.backgroundColor = UIColor.white.cgColor self.contentView.addSubview(border) self.contentView.sendSubview(toBack: border) } public override func didMoveToSuperview() { self.contentView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) UIView.animate(withDuration: 0.15, animations: { self.contentView.alpha = 1.0 self.contentView.transform = CGAffineTransform.identity }) { _ in if self.completion == nil && !self.hasOkButton { let when = DispatchTime.now() + 3 DispatchQueue.main.asyncAfter(deadline: when) { UIView.animate(withDuration: 0.20, delay: 0, options: .curveEaseOut, animations: { self.contentView.alpha = 0.0 self.contentView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) }) { _ in self.removeFromSuperview() } } } } } private func setUpView() { let bundle = Bundle(for: self.classForCoder) let nib = UINib(nibName: self.nibName, bundle: bundle) self.contentView = nib.instantiate(withOwner: self, options: nil).first as! UIView contentView.frame = aspectRatio() addSubview(contentView) contentView.center = self.center contentView.autoresizingMask = [] contentView.translatesAutoresizingMaskIntoConstraints = true contentView.alpha = 0.0 textLabel.text = "" textLabel.autoresizingMask = [.flexibleHeight, .flexibleWidth] leftButton.isHidden = true leftButton.autoresizingMask = [.flexibleHeight, .flexibleWidth] rightButton.isHidden = true rightButton.autoresizingMask = [.flexibleHeight, .flexibleWidth] hasOkButton = false okButton.autoresizingMask = [.flexibleHeight, .flexibleWidth] } private func aspectRatio() -> CGRect { var frame = self.contentView.frame while frame.width > self.frame.width { frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width / 1.2, height: frame.height / 1.2) } return frame } public func set(image: UIImage) { self.ohanaImageView.image = image } public func set(text: String) { self.textLabel.text = text self.textLabel.adjustsFontSizeToFitWidth = true } public func set(completion: @escaping ((Any?, Error?) -> Void), with titles: [String] = ["Cancel", "Take"], and types: [FSOhanaButtonType] = [.cancel, .standard]) { self.completion = completion leftButton.tintColor = types[0].color() rightButton.tintColor = types[1].color() leftButton.titleLabel?.font = types[0].font() rightButton.titleLabel?.font = types[1].font() leftButton.setTitle(titles[0], for: .normal) rightButton.setTitle(titles[1], for: .normal) } public func has(okButton: Bool) { self.hasOkButton = okButton } @IBAction func leftButtonPressed(_ sender: UIButton) { guard let completion = completion else { return } completion(nil, FSError.LeftButton) } @IBAction func rightButtonPressed(_ sender: UIButton) { guard let completion = completion else { return } completion(self, FSError.RightButton) } @IBAction func okButtonPressed(_ sender: UIButton) { self.removeFromSuperview() } }
mit
ca8e2ddaf6ea55d10cbf562c8b1ddef0
34.447514
246
0.612843
4.82406
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/Pods/Log/Source/Extensions/Themes.swift
4
2525
// // Themes.swift // // Copyright (c) 2015-2016 Damien (http://delba.io) // // 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. // extension Themes { public static let `default` = Theme( trace: "#C8C8C8", debug: "#0000FF", info: "#00FF00", warning: "#FFFB00", error: "#FF0000" ) public static let dusk = Theme( trace: "#FFFFFF", debug: "#526EDA", info: "#93C96A", warning: "#D28F5A", error: "#E44347" ) public static let midnight = Theme( trace: "#FFFFFF", debug: "#527EFF", info: "#08FA95", warning: "#EB905A", error: "#FF4647" ) public static let tomorrow = Theme( trace: "#4D4D4C", debug: "#4271AE", info: "#718C00", warning: "#EAB700", error: "#C82829" ) public static let tomorrowNight = Theme( trace: "#C5C8C6", debug: "#81A2BE", info: "#B5BD68", warning: "#F0C674", error: "#CC6666" ) public static let tomorrowNightEighties = Theme( trace: "#CCCCCC", debug: "#6699CC", info: "#99CC99", warning: "#FFCC66", error: "#F2777A" ) public static let tomorrowNightBright = Theme( trace: "#EAEAEA", debug: "#7AA6DA", info: "#B9CA4A", warning: "#E7C547", error: "#D54E53" ) }
mit
7c0520ffad7c57e8f772c79a2f26e95a
30.17284
81
0.593663
3.81997
false
false
false
false
srosskopf/Geschmacksbildung
Geschmacksbildung/Geschmacksbildung/GlossaryTableController.swift
1
4080
// // GlossaryTableController.swift // Geschmacksbildung // // Created by Sebastian Roßkopf on 01.07.16. // Copyright © 2016 sebastian rosskopf. All rights reserved. // import UIKit protocol GlossaryTableControllerDelegate { func termSelected(term: String) } class GlossaryTableController: UITableViewController { var delegate: GlossaryTableControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) if let text = cell?.textLabel?.text { print("selected row: \(text)") if let delegate = delegate { if text.characters.count > 1 { delegate.termSelected(text) } } } } // MARK: - Table view data source // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // #warning Incomplete implementation, return the number of sections // return 0 // } // // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // // #warning Incomplete implementation, return the number of rows // return 0 // } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. 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 to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d6c579c4283a4aa717a4f301d5de2b5a
31.110236
157
0.653016
5.518268
false
false
false
false
tache/SwifterSwift
Sources/Extensions/UIKit/UITableViewExtensions.swift
1
5222
// // UITableViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/22/16. // Copyright © 2016 SwifterSwift // #if os(iOS) || os(tvOS) import UIKit // MARK: - Properties public extension UITableView { /// SwifterSwift: Index path of last row in tableView. public var indexPathForLastRow: IndexPath? { return indexPathForLastRow(inSection: lastSection) } /// SwifterSwift: Index of last section in tableView. public var lastSection: Int { return numberOfSections > 0 ? numberOfSections - 1 : 0 } } // MARK: - Methods public extension UITableView { /// SwifterSwift: Number of all rows in all sections of tableView. /// /// - Returns: The count of all rows in the tableView. public func numberOfRows() -> Int { var section = 0 var rowCount = 0 while section < numberOfSections { rowCount += numberOfRows(inSection: section) section += 1 } return rowCount } /// SwifterSwift: IndexPath for last row in section. /// /// - Parameter section: section to get last row in. /// - Returns: optional last indexPath for last row in section (if applicable). public func indexPathForLastRow(inSection section: Int) -> IndexPath? { guard section >= 0 else { return nil } guard numberOfRows(inSection: section) > 0 else { return IndexPath(row: 0, section: section) } return IndexPath(row: numberOfRows(inSection: section) - 1, section: section) } /// Reload data with a completion handler. /// /// - Parameter completion: completion handler to run after reloadData finishes. public func reloadData(_ completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } /// SwifterSwift: Remove TableFooterView. public func removeTableFooterView() { tableFooterView = nil } /// SwifterSwift: Remove TableHeaderView. public func removeTableHeaderView() { tableHeaderView = nil } /// SwifterSwift: Scroll to bottom of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). public func scrollToBottom(animated: Bool = true) { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) setContentOffset(bottomOffset, animated: animated) } /// SwifterSwift: Scroll to top of TableView. /// /// - Parameter animated: set true to animate scroll (default is true). public func scrollToTop(animated: Bool = true) { setContentOffset(CGPoint.zero, animated: animated) } /// SwifterSwift: Dequeue reusable UITableViewCell using class name /// /// - Parameter name: UITableViewCell type /// - Returns: UITableViewCell object with associated class name (optional value) public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T? { return dequeueReusableCell(withIdentifier: String(describing: name)) as? T } /// SwiferSwift: Dequeue reusable UITableViewCell using class name for indexPath /// /// - Parameters: /// - name: UITableViewCell type. /// - indexPath: location of cell in tableView. /// - Returns: UITableViewCell object with associated class name. public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T? { return dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T } /// SwiferSwift: Dequeue reusable UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type /// - Returns: UITableViewHeaderFooterView object with associated class name (optional value) public func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T? { return dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameters: /// - nib: Nib file used to create the header or footer view. /// - name: UITableViewHeaderFooterView type. public func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) { register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewHeaderFooterView using class name /// /// - Parameter name: UITableViewHeaderFooterView type public func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) { register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameter name: UITableViewCell type public func register<T: UITableViewCell>(cellWithClass name: T.Type) { register(T.self, forCellReuseIdentifier: String(describing: name)) } /// SwifterSwift: Register UITableViewCell using class name /// /// - Parameters: /// - nib: Nib file used to create the tableView cell. /// - name: UITableViewCell type. public func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) { register(nib, forCellReuseIdentifier: String(describing: name)) } } #endif
mit
5d22c7dd46f8bb6837b808d8cc54314a
33.348684
111
0.71289
4.454778
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/ChatItems/QuoteChatItem.swift
1
1379
// // QuoteChatItem.swift // Rocket.Chat // // Created by Filipe Alvarenga on 03/10/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation import DifferenceKit import RocketChatViewController import RealmSwift final class QuoteChatItem: BaseTextAttachmentChatItem, ChatItem, Differentiable { var relatedReuseIdentifier: String { return hasText ? QuoteCell.identifier : QuoteMessageCell.identifier } let identifier: String let purpose: String let title: String let text: String? let hasText: Bool init(identifier: String, purpose: String, title: String, text: String?, collapsed: Bool, hasText: Bool, user: UnmanagedUser?, message: UnmanagedMessage?) { self.identifier = identifier self.purpose = purpose self.title = title self.text = text self.hasText = hasText super.init( collapsed: collapsed, user: user, message: message ) } var differenceIdentifier: String { return identifier } func isContentEqual(to source: QuoteChatItem) -> Bool { return title == source.title && text == source.text && collapsed == source.collapsed && purpose.isEmpty == source.purpose.isEmpty } }
mit
85750b9b169d43b7e7273f8d4fd736dd
23.175439
81
0.618287
4.835088
false
false
false
false
brave/browser-ios
ThirdParty/SQLiteSwift/Tests/SQLiteTests/RowTests.swift
4
2890
import XCTest @testable import SQLite class RowTests : XCTestCase { public func test_get_value() { let row = Row(["\"foo\"": 0], ["value"]) let result = try! row.get(Expression<String>("foo")) XCTAssertEqual("value", result) } public func test_get_value_subscript() { let row = Row(["\"foo\"": 0], ["value"]) let result = row[Expression<String>("foo")] XCTAssertEqual("value", result) } public func test_get_value_optional() { let row = Row(["\"foo\"": 0], ["value"]) let result = try! row.get(Expression<String?>("foo")) XCTAssertEqual("value", result) } public func test_get_value_optional_subscript() { let row = Row(["\"foo\"": 0], ["value"]) let result = row[Expression<String?>("foo")] XCTAssertEqual("value", result) } public func test_get_value_optional_nil() { let row = Row(["\"foo\"": 0], [nil]) let result = try! row.get(Expression<String?>("foo")) XCTAssertNil(result) } public func test_get_value_optional_nil_subscript() { let row = Row(["\"foo\"": 0], [nil]) let result = row[Expression<String?>("foo")] XCTAssertNil(result) } public func test_get_type_mismatch_throws_unexpected_null_value() { let row = Row(["\"foo\"": 0], ["value"]) XCTAssertThrowsError(try row.get(Expression<Int>("foo"))) { error in if case QueryError.unexpectedNullValue(let name) = error { XCTAssertEqual("\"foo\"", name) } else { XCTFail("unexpected error: \(error)") } } } public func test_get_type_mismatch_optional_returns_nil() { let row = Row(["\"foo\"": 0], ["value"]) let result = try! row.get(Expression<Int?>("foo")) XCTAssertNil(result) } public func test_get_non_existent_column_throws_no_such_column() { let row = Row(["\"foo\"": 0], ["value"]) XCTAssertThrowsError(try row.get(Expression<Int>("bar"))) { error in if case QueryError.noSuchColumn(let name, let columns) = error { XCTAssertEqual("\"bar\"", name) XCTAssertEqual(["\"foo\""], columns) } else { XCTFail("unexpected error: \(error)") } } } public func test_get_ambiguous_column_throws() { let row = Row(["table1.\"foo\"": 0, "table2.\"foo\"": 1], ["value"]) XCTAssertThrowsError(try row.get(Expression<Int>("foo"))) { error in if case QueryError.ambiguousColumn(let name, let columns) = error { XCTAssertEqual("\"foo\"", name) XCTAssertEqual(["table1.\"foo\"", "table2.\"foo\""], columns.sorted()) } else { XCTFail("unexpected error: \(error)") } } } }
mpl-2.0
9ee6a26ed73343d57dd60760d3c22cbc
31.840909
86
0.5391
4.158273
false
true
false
false
newtonstudio/cordova-plugin-device
imgly-sdk-ios-master/imglyKit/Backend/IMGLYFontImporter.swift
1
1459
// // IMGLYFontImporter.swift // imglyKit // // Created by Carsten Przyluczky on 09/03/15. // Copyright (c) 2015 9elements GmbH. All rights reserved. // import Foundation import CoreGraphics import CoreText /** Provides functions to import font added as resource. It also registers them, so that the application can load them like any other pre-installed font. */ public class IMGLYFontImporter { private static var fontsRegistered = false /** Imports all fonts added as resource. Supported formats are TTF and OTF. */ public func importFonts() { if !IMGLYFontImporter.fontsRegistered { importFontsWithExtension("ttf") importFontsWithExtension("otf") IMGLYFontImporter.fontsRegistered = true } } private func importFontsWithExtension(ext: String) { let paths = NSBundle(forClass: self.dynamicType).pathsForResourcesOfType(ext, inDirectory: nil) for fontPath in paths as! [String] { let data: NSData? = NSFileManager.defaultManager().contentsAtPath(fontPath) var error: Unmanaged<CFError>? var provider = CGDataProviderCreateWithCFData(data as! CFDataRef) var font = CGFontCreateWithDataProvider(provider) if (!CTFontManagerRegisterGraphicsFont(font, &error)) { println("Failed to register font, error: \(error)") return } } } }
apache-2.0
04e8d685c9958d5e17a47737accc78fe
32.181818
103
0.662097
4.815182
false
false
false
false
wqhiOS/WeiBo
WeiBo/WeiBo/Classes/Controller/Home/HomePopoverViewController/HomePresentationController.swift
1
1293
// // HomePresentationController.swift // WeiBo // // Created by wuqh on 2017/6/13. // Copyright © 2017年 吴启晗. All rights reserved. // import UIKit class HomePresentationController: UIPresentationController { var presentedFrame: CGRect = CGRect.zero fileprivate lazy var coverView: UIView = UIView() override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() // 设置弹出view 的尺寸 presentedView?.frame = presentedFrame // 添加蒙版 setupCoverView() } } // MARK: - UI extension HomePresentationController { fileprivate func setupCoverView() { containerView?.insertSubview(coverView, belowSubview: presentedView!) coverView.backgroundColor = UIColor.black coverView.alpha = 0.4 coverView.frame = containerView?.bounds ?? CGRect.zero coverView.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(coverViewClick)) coverView.addGestureRecognizer(tapGes) } } // MARK: - Action extension HomePresentationController { @objc fileprivate func coverViewClick() { presentedViewController.dismiss(animated: true, completion: nil) } }
mit
7a8fd81e8f90637cb745102ce51fd99f
25.851064
92
0.68859
5.193416
false
false
false
false
macfeteria/JKNotificationPanel
Pod/Classes/JKSubtitleView.swift
1
5343
//// //// JKSubtitleView.swift //// Pods //// //// Created by Ter on 9/24/16. //// //// // import UIKit open class JKSubtitleView: UIView { private let verticalSpace:CGFloat = 8 private let horizontalSpace:CGFloat = 8 private let iconSize:CGFloat = 26 private let titleLableHeight:CGFloat = 22 private let subtitleLabelHeight:CGFloat = 18 var imageIcon:UIImageView! var textLabel:UILabel! var subtitleLabel:UILabel! var baseView:UIView! override init (frame : CGRect) { super.init(frame : frame) imageIcon = UIImageView(frame: CGRect(x: verticalSpace, y: horizontalSpace, width: iconSize, height: iconSize)) imageIcon.backgroundColor = UIColor.clear let textLabelX = verticalSpace + iconSize + verticalSpace textLabel = UILabel(frame: CGRect(x: textLabelX, y: 0, width: frame.width - textLabelX - horizontalSpace, height: titleLableHeight)) textLabel.isUserInteractionEnabled = true textLabel.textColor = UIColor.white let subtitleLableY = textLabel.frame.origin.y + titleLableHeight subtitleLabel = UILabel(frame: CGRect(x: textLabelX, y: subtitleLableY, width: frame.width - textLabelX - horizontalSpace, height: subtitleLabelHeight)) subtitleLabel.font = UIFont.systemFont(ofSize: 12) subtitleLabel.isUserInteractionEnabled = true subtitleLabel.textColor = UIColor.white baseView = UIView(frame: frame) baseView.backgroundColor = UIColor(red: 35.0/255.0, green: 160.0/255.0, blue: 73.0/255.0, alpha: 1) baseView.addSubview(imageIcon) baseView.addSubview(textLabel) baseView.addSubview(subtitleLabel) self.addSubview(baseView) } open func transitionTo(size:CGSize) { let x = verticalSpace + iconSize + verticalSpace self.frame.size = CGSize(width: size.width, height: self.frame.height) textLabel.frame.size = CGSize(width: size.width - x - horizontalSpace, height: titleLableHeight) subtitleLabel.frame.size = CGSize(width: size.width - x - horizontalSpace, height: subtitleLabelHeight) baseView.frame.size = CGSize(width: size.width, height: baseView.frame.height) // adjust text label self.setTitle(textLabel.text) self.setMessage(subtitleLabel.text) } open func setImage(_ icon:UIImage) { imageIcon.image = icon } open func setColor(_ color:UIColor) { self.baseView.backgroundColor = color } open func setTitle(_ text:String?) { guard (text != nil) else { return } textLabel.lineBreakMode = NSLineBreakMode.byWordWrapping textLabel.text = text textLabel.numberOfLines = 0 textLabel.sizeToFit() textLabel.frame.origin.y = 2 let height = textLabel.frame.height var frameHeight = (verticalSpace * 2) + height if frameHeight < 44 { frameHeight = 44 } self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: frameHeight) baseView.frame = self.frame } open func setMessage(_ text:String?) { guard (text != nil) else { return } // Subtitle subtitleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping subtitleLabel.text = text subtitleLabel.numberOfLines = 0 subtitleLabel.sizeToFit() subtitleLabel.frame.origin.y = textLabel.frame.origin.y + textLabel.frame.height let subHeight = subtitleLabel.frame.height + 2 let subFrameHeight = (textLabel.frame.origin.y + textLabel.frame.height) + subHeight self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: subFrameHeight) baseView.frame = self.frame } func loadImageBundle(named imageName:String) ->UIImage? { let podBundle = Bundle(for: self.classForCoder) if let bundleURL = podBundle.url(forResource: "JKNotificationPanel", withExtension: "bundle") { let imageBundel = Bundle(url:bundleURL ) let image = UIImage(named: imageName, in: imageBundel, compatibleWith: nil) return image } return nil } open func setPanelStatus(_ status:JKStatus) { switch (status) { case .success: imageIcon.image = loadImageBundle(named: "success-icon") textLabel.text = "Success" baseView.backgroundColor = UIColor(red: 35.0/255.0, green: 160.0/255.0, blue: 73.0/255.0, alpha: 1) case .warning: imageIcon.image = loadImageBundle(named: "warning-icon") textLabel.text = "Warning" baseView.backgroundColor = UIColor(red: 249.0/255.0, green: 169.0/255.0, blue: 69.0/255.0, alpha: 1) case .failed: imageIcon.image = loadImageBundle(named: "fail-icon") textLabel.text = "Failed" baseView.backgroundColor = UIColor(red: 67.0/255.0, green: 69.0/255.0, blue: 80.0/255.0, alpha: 1) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
a76ee65caee7d2fc623d5607926551fd
35.101351
160
0.634662
4.445092
false
false
false
false
laszlokorte/reform-swift
ReformExpression/ReformExpression/ExpressionParser.swift
1
11412
// // MyParser.swift // ExpressionEngine // // Created by Laszlo Korte on 08.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import Foundation struct BinaryOperatorDefinition { let op : BinaryOperator.Type let precedence : Precedence let associativity : Associativity init(_ op: BinaryOperator.Type, _ precedence : Precedence, _ assoc : Associativity) { self.op = op self.precedence = precedence self.associativity = assoc } } struct UnaryOperatorDefinition { let op : UnaryOperator.Type let precedence : Precedence let associativity : Associativity init(_ op: UnaryOperator.Type, _ precedence : Precedence, _ assoc : Associativity) { self.op = op self.precedence = precedence self.associativity = assoc } } final public class ExpressionParserDelegate : ShuntingYardDelegate { public typealias NodeType = Expression private let sheet : Sheet public init(sheet: Sheet) { self.sheet = sheet } let binaryOperators : [String : BinaryOperatorDefinition] = [ "^" : BinaryOperatorDefinition(BinaryExponentiation.self, Precedence(50), .right), "*" : BinaryOperatorDefinition(BinaryMultiplication.self, Precedence(40), .left), "/" : BinaryOperatorDefinition(BinaryDivision.self, Precedence(40), .left), "%" : BinaryOperatorDefinition(BinaryModulo.self, Precedence(40), .left), "+" : BinaryOperatorDefinition(BinaryAddition.self, Precedence(30), .left), "-" : BinaryOperatorDefinition(BinarySubtraction.self, Precedence(30), .left), "<": BinaryOperatorDefinition(LessThanRelation.self, Precedence(20), .left), "<=": BinaryOperatorDefinition(LessThanOrEqualRelation.self, Precedence(20), .left), ">": BinaryOperatorDefinition(GreaterThanRelation.self, Precedence(20), .left), ">=": BinaryOperatorDefinition(GreaterThanOrEqualRelation.self, Precedence(20), .left), "==": BinaryOperatorDefinition(StrictEqualRelation.self, Precedence(10), .left), "!=": BinaryOperatorDefinition(StrictNotEqualRelation.self, Precedence(10), .left), "&&": BinaryOperatorDefinition(BinaryLogicAnd.self, Precedence(8), .left), "||": BinaryOperatorDefinition(BinaryLogicOr.self, Precedence(5), .left), ] let unaryOperators : [String : UnaryOperatorDefinition] = [ "+" : UnaryOperatorDefinition(UnaryPlus.self, Precedence(45), .left), "-" : UnaryOperatorDefinition(UnaryMinus.self, Precedence(45), .left), "~" : UnaryOperatorDefinition(UnaryLogicNegation.self, Precedence(45), .left), ] let constants : [String : Value] = [ "PI" : Value.doubleValue(value: Double.pi), "E" : Value.doubleValue(value: M_E), ] let functions : [String : Function.Type] = [ "sin" : Sinus.self, "asin" : ArcusSinus.self, "cos" : Cosinus.self, "acos" : ArcusCosinus.self, "tan" : Tangens.self, "atan" : ArcusTangens.self, "atan2" : ArcusTangens.self, "exp" : Exponential.self, "pow" : Power.self, "ln" : NaturalLogarithm.self, "log10" : DecimalLogarithm.self, "log2" : BinaryLogarithm.self, "sqrt" : SquareRoot.self, "round" : Round.self, "ceil" : Ceil.self, "floor" : Floor.self, "abs" : Absolute.self, "max" : Maximum.self, "min" : Minimum.self, "count" : Count.self, "avg" : Average.self, "sum" : Sum.self, "random" : Random.self, "int" : IntCast.self, "double" : DoubleCast.self, "bool" : BoolCast.self, "string" : StringCast.self, "rgb" : RGBConstructor.self, "rgba" : RGBAConstructor.self ] let matchingPairs : [String:String] = ["(":")"] public func isMatchingPair(_ left : Token<ShuntingYardTokenType>, right : Token<ShuntingYardTokenType>) -> Bool { return matchingPairs[left.value] == right.value } public func variableTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> Expression { if let definition = sheet.definitionWithName(token.value) { return .reference(id: definition.id) } else { throw ShuntingYardError.unexpectedToken(token: token, message: "unknown identifier") } } public func constantTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> Expression { if let val = constants[token.value] { return Expression.namedConstant(token.value, val) } else { throw ShuntingYardError.unexpectedToken(token: token, message: "") } } public func emptyNode() throws -> Expression { return Expression.constant(.intValue(value: 0)) } public func unaryOperatorToNode(_ op : Token<ShuntingYardTokenType>, operand : Expression) throws -> Expression { if let o = unaryOperators[op.value] { return Expression.unary(o.op.init(), operand) } else { throw ShuntingYardError.unknownOperator(token: op, arity: OperatorArity.unary) } } public func binaryOperatorToNode(_ op : Token<ShuntingYardTokenType>, leftHand : Expression, rightHand : Expression) throws -> Expression { if let o = binaryOperators[op.value] { return Expression.binary(o.op.init(), leftHand, rightHand) } else { throw ShuntingYardError.unknownOperator(token: op, arity: OperatorArity.binary) } } public func functionTokenToNode(_ function : Token<ShuntingYardTokenType>, args : [Expression]) throws -> Expression { if let f = functions[function.value] { let arity = f.arity switch(arity) { case .fix(let count) where count == args.count: return .call(f.init(), args) case .variadic where args.count > 0: return .call(f.init(), args) default: throw ShuntingYardError.unknownFunction(token: function, parameters: args.count) } } else { throw ShuntingYardError.unknownFunction(token: function, parameters: args.count) } } public func hasBinaryOperator(_ op : Token<ShuntingYardTokenType>) -> Bool { return binaryOperators.keys.contains(op.value) } public func hasUnaryOperator(_ op : Token<ShuntingYardTokenType>) -> Bool { return unaryOperators.keys.contains(op.value) } public func hasFunctionOfName(_ function : Token<ShuntingYardTokenType>) -> Bool { return functions.keys.contains(function.value) } public func hasConstantOfName(_ token : Token<ShuntingYardTokenType>) -> Bool { return constants.keys.contains(token.value) } public func literalTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> Expression { if token.value == "true" { return Expression.constant(Value.boolValue(value: true)) } else if token.value == "false" { return Expression.constant(Value.boolValue(value: false)) } else if let range = token.value.range(of: "\\A\"([^\"]*)\"\\Z", options: .regularExpression) { let string = token.value[range] let subString = string[string.index(after: string.startIndex)..<string.index(before: string.endIndex)] return Expression.constant(Value.stringValue(value: String(subString))) } else if let range = token.value.range(of: "\\A#[0-9a-z]{6}\\Z", options: .regularExpression) { let string = String(token.value[range].dropFirst()) let digits = string.utf16.map(parseHexDigits) if let r1 = digits[0], let r2 = digits[1], let g1 = digits[2], let g2 = digits[3], let b1 = digits[4], let b2 = digits[5] { let r = r1<<4 | r2 let g = g1<<4 | g2 let b = b1<<4 | b2 return Expression.constant(Value.colorValue(r: r, g:g, b: b, a: 255)) } else { throw ShuntingYardError.unexpectedToken(token: token, message: "") } } else if let range = token.value.range(of: "\\A#[0-9a-z]{8}\\Z", options: .regularExpression) { let string = String(token.value[range].dropFirst()) let digits = string.utf16.map(parseHexDigits) if let r1 = digits[0], let r2 = digits[1], let g1 = digits[2], let g2 = digits[3], let b1 = digits[4], let b2 = digits[5], let a1 = digits[6], let a2 = digits[7] { let r = r1<<4 | r2 let g = g1<<4 | g2 let b = b1<<4 | b2 let a = a1<<4 | a2 return Expression.constant(Value.colorValue(r: r, g:g, b: b, a: a)) } else { throw ShuntingYardError.unexpectedToken(token: token, message: "") } } else if let int = Int(token.value) { return Expression.constant(Value.intValue(value: int)) } else if let double = Double(token.value) { return Expression.constant(Value.doubleValue(value: double)) } else { throw ShuntingYardError.unexpectedToken(token: token, message: "") } } private func parseHexDigits(_ char: UTF16.CodeUnit) -> UInt8? { let zero = 0x30 let nine = 0x39 let lowerA = 0x61 let lowerF = 0x66 let upperA = 0x41 let upperF = 0x46 let value = Int(char) switch (value) { case zero...nine: return UInt8(value - zero) case lowerA...lowerF: return UInt8(value - lowerA + 10) case upperA...upperF: return UInt8(value - upperA + 10) default: return nil } } public func assocOfOperator(_ token : Token<ShuntingYardTokenType>) -> Associativity? { return binaryOperators[token.value]?.associativity } public func precedenceOfOperator(_ token : Token<ShuntingYardTokenType>, unary : Bool) -> Precedence? { if(unary) { return unaryOperators[token.value]?.precedence } else { return binaryOperators[token.value]?.precedence } } func uniqueNameFor(_ wantedName: String, definition: Definition? = nil) -> String { var testName = wantedName var postfix = 0 var otherDef = sheet.definitionWithName(testName) while (otherDef?.id != nil && otherDef?.id != definition?.id || functions.keys.contains(testName) || constants.keys.contains(testName)) { postfix += 1 testName = "\(wantedName)\(postfix)" otherDef = sheet.definitionWithName(testName) } if (postfix > 0) { return testName } else { return wantedName } } }
mit
f6605b89be5b2eb1a9ed8253dab8ec3f
36.660066
143
0.58058
4.301168
false
false
false
false
sundance2000/LegoDimensionsCalculator
LegoDimensionsCalculator/Figure.swift
1
713
// // Figure.swift // LegoDimensionsCalculator // // Created by Christian Oberdörfer on 04.05.16. // Copyright © 2016 sundance. All rights reserved. // class Figure: CustomStringConvertible, Hashable { let name: String /// All abilities of all versions of the figure var abilities: Set<Ability> var description: String { get { return self.name } } var hashValue: Int { get { return self.name.hashValue } } init(let name: String, abilities: Set<Ability>) { self.name = name self.abilities = abilities } } func ==(lhs: Figure, rhs: Figure) -> Bool { return lhs.name == rhs.name }
mit
66027e48a9f7e9ae118e661306c3ab91
19.911765
53
0.585091
3.972067
false
false
false
false
xu6148152/binea_project_for_ios
Trax MapKit Swift 1.2/Trax/GPXViewController.swift
1
4388
// // GPXViewController.swift // Trax // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit import MapKit class GPXViewController: UIViewController, MKMapViewDelegate { // MARK: - Outlets @IBOutlet weak var mapView: MKMapView! { didSet { mapView.mapType = .Satellite mapView.delegate = self } } // MARK: - Public API var gpxURL: NSURL? { didSet { clearWaypoints() if let url = gpxURL { GPX.parse(url) { if let gpx = $0 { self.handleWaypoints(gpx.waypoints) } } } } } // MARK: - Waypoints private func clearWaypoints() { if mapView?.annotations != nil { mapView.removeAnnotations(mapView.annotations as! [MKAnnotation]) } } private func handleWaypoints(waypoints: [GPX.Waypoint]) { mapView.addAnnotations(waypoints) mapView.showAnnotations(waypoints, animated: true) } // MARK: - MKMapViewDelegate func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.AnnotationViewReuseIdentifier) if view == nil { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.AnnotationViewReuseIdentifier) view.canShowCallout = true } else { view.annotation = annotation } view.leftCalloutAccessoryView = nil view.rightCalloutAccessoryView = nil if let waypoint = annotation as? GPX.Waypoint { if waypoint.thumbnailURL != nil { view.leftCalloutAccessoryView = UIImageView(frame: Constants.LeftCalloutFrame) } if waypoint.imageURL != nil { view.rightCalloutAccessoryView = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton } } return view } func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) { if let waypoint = view.annotation as? GPX.Waypoint { if let thumbnailImageView = view.leftCalloutAccessoryView as? UIImageView { if let imageData = NSData(contentsOfURL: waypoint.thumbnailURL!) { // blocks main thread! if let image = UIImage(data: imageData) { thumbnailImageView.image = image } } } } } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { performSegueWithIdentifier(Constants.ShowImageSegue, sender: view) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Constants.ShowImageSegue { if let waypoint = (sender as? MKAnnotationView)?.annotation as? GPX.Waypoint { if let ivc = segue.destinationViewController as? ImageViewController { ivc.imageURL = waypoint.imageURL ivc.title = waypoint.name } } } } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() // sign up to hear about GPX files arriving let center = NSNotificationCenter.defaultCenter() let queue = NSOperationQueue.mainQueue() let appDelegate = UIApplication.sharedApplication().delegate center.addObserverForName(GPXURL.Notification, object: appDelegate, queue: queue) { notification in if let url = notification?.userInfo?[GPXURL.Key] as? NSURL { self.gpxURL = url } } // gpxURL = NSURL(string: "http://cs193p.stanford.edu/Vacation.gpx") // for demo/debug/testing } // MARK: - Constants private struct Constants { static let LeftCalloutFrame = CGRect(x: 0, y: 0, width: 59, height: 59) static let AnnotationViewReuseIdentifier = "waypoint" static let ShowImageSegue = "Show Image" } }
mit
1859a925e1e2fac3caf9ccaf65d3c7a9
32.242424
130
0.599134
5.519497
false
false
false
false
xeo-it/contacts-sample
totvs-contacts-test/Services/SpinerLayer.swift
6
1589
import UIKit class SpinerLayer: CAShapeLayer { var spinnerColor = UIColor.whiteColor() { didSet { strokeColor = spinnerColor.CGColor } } init(frame:CGRect) { super.init() let radius:CGFloat = (frame.height / 2) * 0.5 self.frame = CGRectMake(0, 0, frame.height, frame.height) let center = CGPointMake(frame.height / 2, bounds.center.y) let startAngle = 0 - M_PI_2 let endAngle = M_PI * 2 - M_PI_2 let clockwise: Bool = true self.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).CGPath self.fillColor = nil self.strokeColor = spinnerColor.CGColor self.lineWidth = 1 self.strokeEnd = 0.4 self.hidden = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animation() { self.hidden = false let rotate = CABasicAnimation(keyPath: "transform.rotation.z") rotate.fromValue = 0 rotate.toValue = M_PI * 2 rotate.duration = 0.4 rotate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) rotate.repeatCount = HUGE rotate.fillMode = kCAFillModeForwards rotate.removedOnCompletion = false self.addAnimation(rotate, forKey: rotate.keyPath) } func stopAnimation() { self.hidden = true self.removeAllAnimations() } }
mit
814c4d8354edc29346aa9e6491242163
28.444444
158
0.611076
4.646199
false
false
false
false
Cocoastudies/CocoaCast
PodcastApp/PodcastApp/AppDelegate.swift
1
6099
// // AppDelegate.swift // PodcastApp // // Created by Bruno Da luz on 09/05/16. // Copyright © 2016 cocoastudies. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "io.studies.PodcastApp" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("PodcastApp", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this 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. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // 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. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
442b2f43db88bd902c7520780b973331
53.936937
291
0.719744
5.880424
false
false
false
false
AlvinL33/TownHunt
TownHunt-1.1 (LoginScreen)/TownHunt/AccountInfoPageViewController.swift
1
2231
// // AccountInfoPageViewController.swift // TownHunt // // Created by Alvin Lee on 18/02/2017. // Copyright © 2017 LeeTech. All rights reserved. // import UIKit class AccountInfoPageViewController: UIViewController { @IBOutlet weak var menuOpenNavBarButton: UIBarButtonItem! @IBOutlet weak var userIDInfoLabel: UILabel! @IBOutlet weak var usernameInfoLabel: UILabel! @IBOutlet weak var emailInfoLabel: UILabel! @IBOutlet weak var noPacksPlayedInfoLabel: UILabel! @IBOutlet weak var noPacksCreatedInfoLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() menuOpenNavBarButton.target = self.revealViewController() menuOpenNavBarButton.action = #selector(SWRevealViewController.revealToggle(_:)) UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "accountInfoBackgroundImage")?.draw(in: self.view.bounds) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() self.view.backgroundColor = UIColor(patternImage: image) loadAccountDetails() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func LogoutButtonTapped(_ sender: Any) { UserDefaults.standard.set(false, forKey: "isUserLoggedIn") UserDefaults.standard.removeObject(forKey: "UserID") UserDefaults.standard.removeObject(forKey: "Username") UserDefaults.standard.removeObject(forKey: "UserEmail") UserDefaults.standard.synchronize() self.performSegue(withIdentifier: "loginViewAfterLogout", sender: self) } private func loadAccountDetails(){ userIDInfoLabel.text = "User ID: \(UserDefaults.standard.string(forKey: "UserID")!)" usernameInfoLabel.text = "Username: \(UserDefaults.standard.string(forKey: "Username")!)" emailInfoLabel.text = "Email: \(UserDefaults.standard.string(forKey: "UserEmail")!)" noPacksPlayedInfoLabel.text = "No Of Packs Played: 0" noPacksCreatedInfoLabel.text = "No Of Packs Created: 0" } }
apache-2.0
2955aecc4f2f05ea598ed64c59296560
35.557377
97
0.695516
5.022523
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/KMSearchListViewController.swift
1
15088
// // KMGroupListViewController.swift // Komikan // // Created by Seth on 2016-02-14. // import Cocoa class KMSearchListViewController: NSViewController { /// The visual effect view for the background of the window @IBOutlet weak var backgroundVisualEffectView: NSVisualEffectView! /// The table view for the search list @IBOutlet weak var searchListTableView: NSTableView! /// When we click the "Filter" button... @IBAction func filterButtonPressed(_ sender: AnyObject) { // Apply the search filter applyFilter(); } /// When we click the "Select All" button... @IBAction func selectAllButtonPressed(_ sender: AnyObject) { // For every search list item... for(_, currentSearchListItem) in searchListItems.enumerated() { // Set the current search list item to be selected currentSearchListItem.checked = true; } // Reload the table view searchListTableView.reloadData(); } /// When we click the "Deselect All" button... @IBAction func deselectAllButtonPressed(_ sender: AnyObject) { // For every search list item... for(_, currentSearchListItem) in searchListItems.enumerated() { // Set the current search list item to be deselected currentSearchListItem.checked = false; } // Reload the table view searchListTableView.reloadData(); } /// The search list items for the search list table view var searchListItems : [KMSearchListItemData] = []; override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Style the window styleWindow(); // Load the items loadItems(); // Deselect all the items // For every search list item... for(_, currentSearchListItem) in searchListItems.enumerated() { // Set the current search list item to be deselected currentSearchListItem.checked = false; } // Reload the table view searchListTableView.reloadData(); } func loadItems() { // Remove all the group items searchListItems.removeAll(); // For every series the user has in the manga grid... for(_, currentSeries) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allSeries().enumerated() { // Add the current series to the search list items searchListItems.append(KMSearchListItemData(name: currentSeries, type: KMPropertyType.series)); // Set the items count to the amount of times it's series appears searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfSeries(currentSeries); } // For every artist the user has in the manga grid... for(_, currentArtist) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allArtists().enumerated() { // Add the current artist to the search list items searchListItems.append(KMSearchListItemData(name: currentArtist, type: KMPropertyType.artist)); // Set the items count to the amount of times it's artist appears searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfArtist(currentArtist); } // For every writer the user has in the manga grid... for(_, currentWriter) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allWriters().enumerated() { // Add the current writer to the search list items searchListItems.append(KMSearchListItemData(name: currentWriter, type: KMPropertyType.writer)); // Set the items count to the amount of times it's writer appears searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfWriter(currentWriter); } // For every tag the user has in the manga grid... for(_, currentTag) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allTags().enumerated() { // Add the current tag to the search list items searchListItems.append(KMSearchListItemData(name: currentTag, type: KMPropertyType.tags)); // Set the items count to the amount of times it's tag appears searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfTag(currentTag); } // For every group the user has in the manga grid... for(_, currentGroup) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allGroups().enumerated() { // Add the current group to the search list items searchListItems.append(KMSearchListItemData(name: currentGroup, type: KMPropertyType.group)); // Set the items count to the amount of times it's group appears searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfGroup(currentGroup); } // Reload the table view searchListTableView.reloadData(); } /// Takes everything we checked/unchecked and filters by them func applyFilter() { /// The string we will search by var searchString : String = ""; /// Is this the first series search item? var firstOfSeriesSearch : Bool = true; /// Is this the first artist search item? var firstOfArtistSearch : Bool = true; /// Is this the first writer search item? var firstOfWriterSearch : Bool = true; /// Is this the first tags search item? var firstOfTagsSearch : Bool = true; /// Is this the first group search item? var firstOfGroupSearch : Bool = true; // For every item in the search list items... for(_, currentItem) in searchListItems.enumerated() { // If the current item is checked... if(currentItem.checked) { // If the current item is for a series... if(currentItem.type == .series) { // If this is the first series search term... if(firstOfSeriesSearch) { // Add the series search group marker searchString += "s:\""; // Say this is no longer the first series search term firstOfSeriesSearch = false; } // Add the current series to the search string searchString += currentItem.name + ", "; } // If the current item is for an artist... else if(currentItem.type == .artist) { // If this is the first artist search term... if(firstOfArtistSearch) { // If the search string isnt blank... if(searchString != "") { // Remove the extra ", " from the search string searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex))); // Add the "" a:"" to the search string to denote a new search type searchString += "\" a:\""; } else { // Add the artist search group marker searchString += "a:\""; } // Say this is no longer the first artist search term firstOfArtistSearch = false; } // Add the current artist to the search string searchString += currentItem.name + ", "; } // If the current item is for a writer... else if(currentItem.type == .writer) { // If this is the first writer search term... if(firstOfWriterSearch) { // If the search string isnt blank... if(searchString != "") { // Remove the extra ", " from the search string searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex))); // Add the "" w:"" to the search string to denote a new search type searchString += "\" w:\""; } else { // Add the writer search group marker searchString += "w:\""; } // Say this is no longer the first writer search term firstOfWriterSearch = false; } // Add the current artist to the search string searchString += currentItem.name + ", "; } // If the current item is for tags... else if(currentItem.type == .tags) { // If this is the first tag search term... if(firstOfTagsSearch) { // If the search string isnt blank... if(searchString != "") { // Remove the extra ", " from the search string searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex))); // Add the "" tg:"" to the search string to denote a new search type searchString += "\" tg:\""; } else { // Add the tags search group marker searchString += "tg:\""; } // Say this is no longer the first tags search term firstOfTagsSearch = false; } // Add the current artist to the search string searchString += currentItem.name + ", "; } // If the current item is for a group... else if(currentItem.type == .group) { // If this is the first group search term... if(firstOfGroupSearch) { // If the search string isnt blank... if(searchString != "") { // Remove the extra ", " from the search string searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex))); // Add the "" g:"" to the search string to denote a new search type searchString += "\" g:\""; } else { // Add the group search group marker searchString += "g:\""; } // Say this is no longer the first group search term firstOfGroupSearch = false; } // Add the current artist to the search string searchString += currentItem.name + ", "; } } } // If the search string isnt blank... if(searchString != "") { // Remove the extra ", " from the search string searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex))); // Add the """ at the end of the search string to denote the end of the final search term searchString += "\""; } // Set the search fields value to the search string we created (NSApplication.shared().delegate as! AppDelegate).searchTextField.stringValue = searchString; // Search for the search string (NSApplication.shared().delegate as! AppDelegate).mangaGridController.searchFor(searchString); } /// Styles the window func styleWindow() { // Set the background to be more vibrant backgroundVisualEffectView.material = NSVisualEffectMaterial.dark; } } extension KMSearchListViewController: NSTableViewDelegate { func numberOfRows(in aTableView: NSTableView) -> Int { // Return the amount of search list items return self.searchListItems.count; } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { /// The cell view it is asking us about for the data let cellView : NSTableCellView = tableView.make(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView; // If the column is the Main Column... if(tableColumn!.identifier == "Main Column") { /// This items search list data let searchListItemData = self.searchListItems[row]; // Set the label's string value to the search list items name cellView.textField!.stringValue = searchListItemData.name; // Set the checkbox to be checked/unchecked based on if the cell view item is checked (cellView as? KMSearchListTableViewCell)?.checkbox.state = Int(searchListItemData.checked as NSNumber); // Set the type label's string value to be this item's type with the count at the end in parenthesis (cellView as? KMSearchListTableViewCell)?.typeLabel.stringValue = KMEnumUtilities().propertyTypeToString(searchListItemData.type!) + "(" + String(searchListItemData.count) + ")"; // Set the cell views data so it can update it as it is changed (cellView as? KMSearchListTableViewCell)?.data = searchListItemData; // Return the modified cell view return cellView; } // Return the unmodified cell view, we didnt need to do anything to this one return cellView; } } extension KMSearchListViewController: NSTableViewDataSource { }
gpl-3.0
b1c5a065165b62d5bbe3030a6aecf61c
45.712074
190
0.544008
5.798616
false
false
false
false
LeoMobileDeveloper/MDTable
MDTableExample/SystemCellController.swift
1
2450
// // SystemCellController.swift // MDTableExample // // Created by Leo on 2017/6/15. // Copyright © 2017年 Leo Huang. All rights reserved. // import UIKit import MDTable class SystemCellController: UIViewController { var tableManager:TableManager! var customSwitchValue = true override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "System cell" let tableView = UITableView(frame: view.bounds, style: .grouped) view.addSubview(tableView) let section0 = buildSection0() tableView.manager = TableManager(sections: [section0]) } func buildSection0()->Section{ let row0 = Row(title: "Basic", rowHeight: 40.0, accessoryType: .none) let row1 = Row(title: "Custom Color", rowHeight: 40.0, accessoryType: .detailDisclosureButton) row1.onRender { (cell,isInital) in cell.textLabel?.textColor = UIColor.orange cell.textLabel?.font = UIFont.systemFont(ofSize: 14) }.onDidSelected { (tableView, indexPath) in tableView.deselectRow(at: indexPath, animated: true) } let row2 = Row(title: "Title", image: UIImage(named: "avatar"), detailTitle: "Detail Title", rowHeight: 60.0, accessoryType: .disclosureIndicator); row2.cellStyle = .value1 let row3 = Row(title: "Title", image: UIImage(named: "avatar"), detailTitle: "Sub Title", rowHeight: 60.0, accessoryType: .checkmark); row3.cellStyle = .subtitle let row4 = Row(title: "Title", image: UIImage(named: "avatar"), detailTitle: "Sub Title", rowHeight: 60.0, accessoryType: .checkmark); row4.onRender { (cell,isInital) in if isInital{ let customSwitch = UISwitch() cell.accessoryView = customSwitch } } row4.reuseIdentifier = "Cell With Switch" let section = Section(rows: [row0,row1,row2,row3,row4]) section.heightForHeader = 10.0 section.heightForFooter = 0.0 return section } }
mit
4a93689837efa087a8955df22d13cc46
34.985294
102
0.536575
4.78865
false
false
false
false
OscarSwanros/swift
stdlib/public/SDK/Intents/INSetDefrosterSettingsInCarIntent.swift
27
936
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) @available(iOS 10.0, *) extension INSetDefrosterSettingsInCarIntent { @nonobjc public convenience init( enable: Bool? = nil, defroster: INCarDefroster = .unknown ) { self.init(__enable: enable.map { NSNumber(value: $0) }, defroster: defroster) } @nonobjc public final var enable: Bool? { return __enable?.boolValue } } #endif
apache-2.0
ca2b5eabc0cd1a4dd3f5b209d578dbad
28.25
80
0.587607
4.436019
false
false
false
false
litoarias/HAPlayerView
HAPlayerView/HABackgroundPlayerView.swift
1
3439
import UIKit import AVFoundation @IBDesignable public class HABackgroundPlayerView: UIView { var player: AVPlayer? var avPlayerLayer: AVPlayerLayer! var videoURL: NSURL = NSURL() var cView: UIView = UIView() let screenSize = UIScreen.main.bounds @IBInspectable public var name: String = "test" { didSet { inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha) } } @IBInspectable public var mime: String = "mp4" { didSet { inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha) } } @IBInspectable public var repeats: Bool = true { didSet { inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha) } } @IBInspectable public var muted: Bool = true { didSet { inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha) } } @IBInspectable public var layerAlpha: CGFloat = 0.5 { didSet { inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha) } } public override init(frame: CGRect) { super.init(frame: frame) inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha) } func inits(resource: String, extensionFormat: String, repeats: Bool, muted: Bool, alpha: CGFloat) { setLayer() guard let video = Bundle.main.url(forResource: resource, withExtension: extensionFormat) else { return } videoURL = video as NSURL if (player == nil) { player = AVPlayer(url: videoURL as URL) player?.actionAtItemEnd = .none player?.isMuted = muted avPlayerLayer = AVPlayerLayer(player: player) avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill avPlayerLayer.zPosition = -1 avPlayerLayer.frame = screenSize player?.play() layer.addSublayer(avPlayerLayer) } if repeats { NotificationCenter.default.addObserver(self, selector: #selector(loopVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem) } } @objc func loopVideo() { player?.seek(to: CMTime.zero) player?.play() } func setLayer() { if cView.isDescendant(of: self) { cView.removeFromSuperview() } else { cView = UIView.init(frame: screenSize) cView.backgroundColor = UIColor.black cView.alpha = layerAlpha; cView.layer.zPosition = 0; self.addSubview(cView) } } }
mit
af80686f3a88bed5e6ad250606c72791
30.550459
107
0.548415
5.187029
false
false
false
false
alblue/swift
test/SILGen/conditional_conformance.swift
2
3515
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s protocol P1 { func normal() func generic<T: P3>(_: T) } protocol P2 {} protocol P3 {} protocol P4 { associatedtype AT } struct Conformance<A> {} extension Conformance: P1 where A: P2 { func normal() {} func generic<T: P3>(_: T) {} } // CHECK-LABEL: sil_witness_table hidden <A where A : P2> Conformance<A>: P1 module conditional_conformance { // CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$s23conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> Conformance<A> // CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$s23conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> Conformance<A> // CHECK-NEXT: conditional_conformance (A: P2): dependent // CHECK-NEXT: } struct ConformanceAssoc<A> {} extension ConformanceAssoc: P1 where A: P4, A.AT: P2 { func normal() {} func generic<T: P3>(_: T) {} } // CHECK-LABEL: sil_witness_table hidden <A where A : P4, A.AT : P2> ConformanceAssoc<A>: P1 module conditional_conformance { // CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$s23conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> ConformanceAssoc<A> // CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$s23conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> ConformanceAssoc<A> // CHECK-NEXT: conditional_conformance (A: P4): dependent // CHECK-NEXT: conditional_conformance (A.AT: P2): dependent // CHECK-NEXT: } /* FIXME: same type constraints are modelled incorrectly. struct SameTypeConcrete<B> {} extension SameTypeConcrete: P1 where B == Int { func normal() {} func generic<T: P3>(_: T) {} } struct SameTypeGeneric<C, D> {} extension SameTypeGeneric: P1 where C == D { func normal() {} func generic<T: P3>(_: T) {} } struct SameTypeGenericConcrete<E, F> {} extension SameTypeGenericConcrete: P1 where E == [F] { func normal() {} func generic<T: P3>(_: T) {} } struct Everything<G, H, I, J, K, L> {} extension Everything: P1 where G: P2, H == Int, I == J, K == [L] { func normal() {} func generic<T: P3>(_: T) {} } */ struct IsP2: P2 {} struct IsNotP2 {} class Base<A> {} extension Base: P1 where A: P2 { func normal() {} func generic<T: P3>(_: T) {} } // CHECK-LABEL: sil_witness_table hidden <A where A : P2> Base<A>: P1 module conditional_conformance { // CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$s23conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> Base<A> // CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$s23conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> Base<A> // CHECK-NEXT: conditional_conformance (A: P2): dependent // CHECK-NEXT: } // These don't get separate witness tables, but shouldn't crash anything. class SubclassGood: Base<IsP2> {} class SubclassBad: Base<IsNotP2> {}
apache-2.0
028338b08a382d945e86065726c2cd4b
42.9375
288
0.687055
3.011997
false
false
false
false
scottrhoyt/Jolt
Jolt/Source/FloatingTypeExtensions/FloatingTypeOperationsExtensions.swift
1
1486
// // FloatingTypeOperationsExtensions.swift // Jolt // // Created by Scott Hoyt on 9/8/15. // Copyright © 2015 Scott Hoyt. All rights reserved. // import Accelerate extension Double : VectorOperations { public static func magnitude(x: [Double]) -> Double { return cblas_dnrm2(Int32(x.count), x, 1) } public static func unit(x: [Double]) -> [Double] { // FIXME: Can a vecLib function like vSnorm2 be used? return Double.div(x, [Double](count: x.count, repeatedValue:magnitude(x))) } public static func dot(x: [Double], _ y: [Double]) -> Double { precondition(x.count == y.count, "Vectors must have equal count") var result: Double = 0.0 vDSP_dotprD(x, 1, y, 1, &result, vDSP_Length(x.count)) return result } } extension Float : VectorOperations { public static func magnitude(x: [Float]) -> Float { return cblas_snrm2(Int32(x.count), x, 1) } public static func unit(x: [Float]) -> [Float] { // FIXME: Can a vecLib function like vSnorm2 be used? return Float.div(x, [Float](count: x.count, repeatedValue:magnitude(x))) } public static func dot(x: [Float], _ y: [Float]) -> Float { precondition(x.count == y.count, "Vectors must have equal count") var result: Float = 0.0 vDSP_dotpr(x, 1, y, 1, &result, vDSP_Length(x.count)) return result } }
mit
34e064c86f1e841d3ce31d315d4732f4
26.518519
82
0.584512
3.648649
false
false
false
false
alblue/swift
test/SILGen/dynamic.swift
2
27440
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift | %FileCheck %s // RUN: %target-swift-emit-sil(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -verify // REQUIRES: objc_interop import Foundation import gizmo class Foo: Proto { // Not objc or dynamic, so only a vtable entry init(native: Int) {} func nativeMethod() {} var nativeProp: Int = 0 subscript(native native: Int) -> Int { get { return native } set {} } // @objc, so it has an ObjC entry point but can also be dispatched // by vtable @objc init(objc: Int) {} @objc func objcMethod() {} @objc var objcProp: Int = 0 @objc subscript(objc objc: AnyObject) -> Int { get { return 0 } set {} } // dynamic, so it has only an ObjC entry point @objc dynamic init(dynamic: Int) {} @objc dynamic func dynamicMethod() {} @objc dynamic var dynamicProp: Int = 0 @objc dynamic subscript(dynamic dynamic: Int) -> Int { get { return dynamic } set {} } func overriddenByDynamic() {} @NSManaged var managedProp: Int } protocol Proto { func nativeMethod() var nativeProp: Int { get set } subscript(native native: Int) -> Int { get set } func objcMethod() var objcProp: Int { get set } subscript(objc objc: AnyObject) -> Int { get set } func dynamicMethod() var dynamicProp: Int { get set } subscript(dynamic dynamic: Int) -> Int { get set } } // ObjC entry points for @objc and dynamic entry points // normal and @objc initializing ctors can be statically dispatched // CHECK-LABEL: sil hidden @$s7dynamic3FooC{{.*}}tcfC // CHECK: function_ref @$s7dynamic3FooC{{.*}}tcfc // CHECK-LABEL: sil hidden @$s7dynamic3FooC{{.*}}tcfC // CHECK: function_ref @$s7dynamic3FooC{{.*}}tcfc // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTo // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC10objcMethod{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC8objcPropSivgTo // CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC8objcPropSivsTo // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC4objcSiyXl_tcigTo // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC4objcSiyXl_tcisTo // TODO: dynamic initializing ctor must be objc dispatched // CHECK-LABEL: sil hidden @$s7dynamic3{{[_0-9a-zA-Z]*}}fC // CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTD // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTD // CHECK: objc_method {{%.*}} : $Foo, #Foo.init!initializer.1.foreign : // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTo // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC0A4PropSivgTo // CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC0A4PropSivsTo // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooCAAS2i_tcigTo // CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooCAAS2i_tcisTo // Protocol witnesses use best appropriate dispatch // Native witnesses use vtable dispatch: // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP12nativeMethod{{[_0-9a-zA-Z]*}}FTW // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP10nativePropSivgTW // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP10nativePropSivsTW // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcigTW // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcisTW // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // @objc witnesses use vtable dispatch: // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP10objcMethod{{[_0-9a-zA-Z]*}}FTW // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP8objcPropSivgTW // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP8objcPropSivsTW // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcigTW // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcisTW // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // Dynamic witnesses use objc dispatch: // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP0A6Method{{[_0-9a-zA-Z]*}}FTW // CHECK: function_ref @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD // CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP0A4PropSivgTW // CHECK: function_ref @$s7dynamic3FooC0A4PropSivgTD // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooC0A4PropSivgTD // CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP0A4PropSivsTW // CHECK: function_ref @$s7dynamic3FooC0A4PropSivsTD // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooC0A4PropSivsTD // CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDPAAS2i_tcigTW // CHECK: function_ref @$s7dynamic3FooCAAS2i_tcigTD // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooCAAS2i_tcigTD // CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign : // CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDPAAS2i_tcisTW // CHECK: function_ref @$s7dynamic3FooCAAS2i_tcisTD // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooCAAS2i_tcisTD // CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign : // Superclass dispatch class Subclass: Foo { // Native and objc methods can directly reference super members override init(native: Int) { super.init(native: native) } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fC // CHECK: function_ref @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc override func nativeMethod() { super.nativeMethod() } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC12nativeMethod{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$s7dynamic3FooC12nativeMethodyyF : $@convention(method) (@guaranteed Foo) -> () override var nativeProp: Int { get { return super.nativeProp } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC10nativePropSivg // CHECK: function_ref @$s7dynamic3FooC10nativePropSivg : $@convention(method) (@guaranteed Foo) -> Int set { super.nativeProp = newValue } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC10nativePropSivs // CHECK: function_ref @$s7dynamic3FooC10nativePropSivs : $@convention(method) (Int, @guaranteed Foo) -> () } override subscript(native native: Int) -> Int { get { return super[native: native] } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC6nativeS2i_tcig // CHECK: function_ref @$s7dynamic3FooC6nativeS2i_tcig : $@convention(method) (Int, @guaranteed Foo) -> Int set { super[native: native] = newValue } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC6nativeS2i_tcis // CHECK: function_ref @$s7dynamic3FooC6nativeS2i_tcis : $@convention(method) (Int, Int, @guaranteed Foo) -> () } override init(objc: Int) { super.init(objc: objc) } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC4objcACSi_tcfc // CHECK: function_ref @$s7dynamic3FooC4objcACSi_tcfc : $@convention(method) (Int, @owned Foo) -> @owned Foo override func objcMethod() { super.objcMethod() } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC10objcMethod{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$s7dynamic3FooC10objcMethodyyF : $@convention(method) (@guaranteed Foo) -> () override var objcProp: Int { get { return super.objcProp } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC8objcPropSivg // CHECK: function_ref @$s7dynamic3FooC8objcPropSivg : $@convention(method) (@guaranteed Foo) -> Int set { super.objcProp = newValue } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC8objcPropSivs // CHECK: function_ref @$s7dynamic3FooC8objcPropSivs : $@convention(method) (Int, @guaranteed Foo) -> () } override subscript(objc objc: AnyObject) -> Int { get { return super[objc: objc] } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC4objcSiyXl_tcig // CHECK: function_ref @$s7dynamic3FooC4objcSiyXl_tcig : $@convention(method) (@guaranteed AnyObject, @guaranteed Foo) -> Int set { super[objc: objc] = newValue } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC4objcSiyXl_tcis // CHECK: function_ref @$s7dynamic3FooC4objcSiyXl_tcis : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> () } // Dynamic methods are super-dispatched by objc_msgSend override init(dynamic: Int) { super.init(dynamic: dynamic) } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc // CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign : override func dynamicMethod() { super.dynamicMethod() } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC0A6Method{{[_0-9a-zA-Z]*}}F // CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign : override var dynamicProp: Int { get { return super.dynamicProp } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC0A4PropSivg // CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign : set { super.dynamicProp = newValue } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassC0A4PropSivs // CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign : } override subscript(dynamic dynamic: Int) -> Int { get { return super[dynamic: dynamic] } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassCAAS2i_tcig // CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign : set { super[dynamic: dynamic] = newValue } // CHECK-LABEL: sil hidden @$s7dynamic8SubclassCAAS2i_tcis // CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign : } @objc dynamic override func overriddenByDynamic() {} } class SubclassWithInheritedInits: Foo { // CHECK-LABEL: sil hidden @$s7dynamic26SubclassWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc // CHECK: objc_super_method {{%.*}} : $SubclassWithInheritedInits, #Foo.init!initializer.1.foreign : } class GrandchildWithInheritedInits: SubclassWithInheritedInits { // CHECK-LABEL: sil hidden @$s7dynamic28GrandchildWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc // CHECK: objc_super_method {{%.*}} : $GrandchildWithInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign : } class GrandchildOfInheritedInits: SubclassWithInheritedInits { // Dynamic methods are super-dispatched by objc_msgSend override init(dynamic: Int) { super.init(dynamic: dynamic) } // CHECK-LABEL: sil hidden @$s7dynamic26GrandchildOfInheritedInitsC{{[_0-9a-zA-Z]*}}fc // CHECK: objc_super_method {{%.*}} : $GrandchildOfInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign : } // CHECK-LABEL: sil hidden @$s7dynamic20nativeMethodDispatchyyF : $@convention(thin) () -> () func nativeMethodDispatch() { // CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC let c = Foo(native: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @$s7dynamic18objcMethodDispatchyyF : $@convention(thin) () -> () func objcMethodDispatch() { // CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC let c = Foo(objc: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[objc: 0 as NSNumber] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[objc: 0 as NSNumber] = y } // CHECK-LABEL: sil hidden @$s7dynamic0A14MethodDispatchyyF : $@convention(thin) () -> () func dynamicMethodDispatch() { // CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC let c = Foo(dynamic: 0) // CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @$s7dynamic15managedDispatchyyAA3FooCF func managedDispatch(_ c: Foo) { // CHECK: objc_method {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign let x = c.managedProp // CHECK: objc_method {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @$s7dynamic21foreignMethodDispatchyyF func foreignMethodDispatch() { // CHECK: function_ref @$sSo9GuisemeauC{{[_0-9a-zA-Z]*}}fC let g = Guisemeau()! // CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign g.frob() // CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign let x = g.count // CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign g.count = x // CHECK: objc_method {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign let y: Any! = g[0] // CHECK: objc_method {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign g[0] = y // CHECK: objc_method {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign _ = g.description } extension Gizmo { // CHECK-LABEL: sil hidden @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC // CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign convenience init(convenienceInExtension: Int) { self.init(bellsOn: convenienceInExtension) } // CHECK-LABEL: sil hidden @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC // CHECK: objc_method {{%.*}} : $@objc_metatype Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassFactory x: Int) { self.init(stuff: x) } // CHECK-LABEL: sil hidden @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC // CHECK: objc_method {{%.*}} : $@objc_metatype Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassExactFactory x: Int) { self.init(exactlyStuff: x) } @objc func foreignObjCExtension() { } @objc dynamic func foreignDynamicExtension() { } } // CHECK-LABEL: sil hidden @$s7dynamic24foreignExtensionDispatchyySo5GizmoCF // CHECK: bb0([[ARG:%.*]] : @guaranteed $Gizmo): func foreignExtensionDispatch(_ g: Gizmo) { // CHECK: objc_method [[ARG]] : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : (Gizmo) g.foreignObjCExtension() // CHECK: objc_method [[ARG]] : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign g.foreignDynamicExtension() } // CHECK-LABEL: sil hidden @$s7dynamic33nativeMethodDispatchFromOtherFileyyF : $@convention(thin) () -> () func nativeMethodDispatchFromOtherFile() { // CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC let c = FromOtherFile(native: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @$s7dynamic31objcMethodDispatchFromOtherFileyyF : $@convention(thin) () -> () func objcMethodDispatchFromOtherFile() { // CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC let c = FromOtherFile(objc: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[objc: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[objc: 0] = y } // CHECK-LABEL: sil hidden @$s7dynamic0A27MethodDispatchFromOtherFileyyF : $@convention(thin) () -> () func dynamicMethodDispatchFromOtherFile() { // CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC let c = FromOtherFile(dynamic: 0) // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @$s7dynamic28managedDispatchFromOtherFileyyAA0deF0CF func managedDispatchFromOtherFile(_ c: FromOtherFile) { // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign let x = c.managedProp // CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @$s7dynamic0A16ExtensionMethodsyyAA13ObjCOtherFileCF func dynamicExtensionMethods(_ obj: ObjCOtherFile) { // CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign obj.extensionMethod() // CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign _ = obj.extensionProp // CHECK: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type // CHECK-NEXT: objc_method {{%.*}} : $@objc_metatype ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign _ = type(of: obj).extensionClassProp // CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign obj.dynExtensionMethod() // CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign _ = obj.dynExtensionProp // CHECK: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type // CHECK-NEXT: objc_method {{%.*}} : $@objc_metatype ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign _ = type(of: obj).dynExtensionClassProp } public class Base { @objc dynamic var x: Bool { return false } } public class Sub : Base { // CHECK-LABEL: sil hidden @$s7dynamic3SubC1xSbvg : $@convention(method) (@guaranteed Sub) -> Bool { // CHECK: bb0([[SELF:%.*]] : @guaranteed $Sub): // CHECK: [[AUTOCLOSURE:%.*]] = function_ref @$s7dynamic3SubC1xSbvgSbyKXKfu_ : $@convention(thin) (@guaranteed Sub) -> (Bool, @error Error) // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: = partial_apply [callee_guaranteed] [[AUTOCLOSURE]]([[SELF_COPY]]) // CHECK: return {{%.*}} : $Bool // CHECK: } // end sil function '$s7dynamic3SubC1xSbvg' // CHECK-LABEL: sil private [transparent] @$s7dynamic3SubC1xSbvgSbyKXKfu_ : $@convention(thin) (@guaranteed Sub) -> (Bool, @error Error) { // CHECK: bb0([[VALUE:%.*]] : @guaranteed $Sub): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK: [[CAST_VALUE_COPY:%.*]] = upcast [[VALUE_COPY]] // CHECK: [[BORROWED_CAST_VALUE_COPY:%.*]] = begin_borrow [[CAST_VALUE_COPY]] // CHECK: [[DOWNCAST_FOR_SUPERMETHOD:%.*]] = unchecked_ref_cast [[BORROWED_CAST_VALUE_COPY]] // CHECK: [[SUPER:%.*]] = objc_super_method [[DOWNCAST_FOR_SUPERMETHOD]] : $Sub, #Base.x!getter.1.foreign : (Base) -> () -> Bool, $@convention(objc_method) (Base) -> ObjCBool // CHECK: = apply [[SUPER]]([[BORROWED_CAST_VALUE_COPY]]) // CHECK: end_borrow [[BORROWED_CAST_VALUE_COPY]] // CHECK: destroy_value [[CAST_VALUE_COPY]] // CHECK: } // end sil function '$s7dynamic3SubC1xSbvgSbyKXKfu_' override var x: Bool { return false || super.x } } public class BaseExt : NSObject {} extension BaseExt { @objc public var count: Int { return 0 } } public class SubExt : BaseExt { public override var count: Int { return 1 } } public class GenericBase<T> { public func method(_: T) {} } public class ConcreteDerived : GenericBase<Int> { @objc public override dynamic func method(_: Int) {} } // The dynamic override has a different calling convention than the base, // so after re-abstracting the signature we must dispatch to the dynamic // thunk. // CHECK-LABEL: sil private @$s7dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed ConcreteDerived) -> () // CHECK: bb0(%0 : @trivial $*Int, %1 : @guaranteed $ConcreteDerived): // CHECK-NEXT: [[VALUE:%.*]] = load [trivial] %0 : $*Int // CHECK: [[DYNAMIC_THUNK:%.*]] = function_ref @$s7dynamic15ConcreteDerivedC6methodyySiFTD : $@convention(method) (Int, @guaranteed ConcreteDerived) -> () // CHECK-NEXT: apply [[DYNAMIC_THUNK]]([[VALUE]], %1) : $@convention(method) (Int, @guaranteed ConcreteDerived) -> () // CHECK: return // Vtable contains entries for native and @objc methods, but not dynamic ones // CHECK-LABEL: sil_vtable Foo { // CHECK-NEXT: #Foo.init!allocator.1: {{.*}} : @$s7dynamic3FooC6nativeACSi_tcfC // CHECK-NEXT: #Foo.nativeMethod!1: {{.*}} : @$s7dynamic3FooC12nativeMethodyyF // CHECK-NEXT: #Foo.nativeProp!getter.1: {{.*}} : @$s7dynamic3FooC10nativePropSivg // dynamic.Foo.nativeProp.getter : Swift.Int // CHECK-NEXT: #Foo.nativeProp!setter.1: {{.*}} : @$s7dynamic3FooC10nativePropSivs // dynamic.Foo.nativeProp.setter : Swift.Int // CHECK-NEXT: #Foo.nativeProp!modify.1: // CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : @$s7dynamic3FooC6nativeS2i_tcig // dynamic.Foo.subscript.getter : (native: Swift.Int) -> Swift.Int // CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : @$s7dynamic3FooC6nativeS2i_tcis // dynamic.Foo.subscript.setter : (native: Swift.Int) -> Swift.Int // CHECK-NEXT: #Foo.subscript!modify.1: // CHECK-NEXT: #Foo.init!allocator.1: {{.*}} : @$s7dynamic3FooC4objcACSi_tcfC // CHECK-NEXT: #Foo.objcMethod!1: {{.*}} : @$s7dynamic3FooC10objcMethodyyF // CHECK-NEXT: #Foo.objcProp!getter.1: {{.*}} : @$s7dynamic3FooC8objcPropSivg // dynamic.Foo.objcProp.getter : Swift.Int // CHECK-NEXT: #Foo.objcProp!setter.1: {{.*}} : @$s7dynamic3FooC8objcPropSivs // dynamic.Foo.objcProp.setter : Swift.Int // CHECK-NEXT: #Foo.objcProp!modify.1: // CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : @$s7dynamic3FooC4objcSiyXl_tcig // dynamic.Foo.subscript.getter : (objc: Swift.AnyObject) -> Swift.Int // CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : @$s7dynamic3FooC4objcSiyXl_tcis // dynamic.Foo.subscript.setter : (objc: Swift.AnyObject) -> Swift.Int // CHECK-NEXT: #Foo.subscript!modify.1: // CHECK-NEXT: #Foo.overriddenByDynamic!1: {{.*}} : @$s7dynamic3FooC19overriddenByDynamic{{[_0-9a-zA-Z]*}} // CHECK-NEXT: #Foo.deinit!deallocator.1: {{.*}} // CHECK-NEXT: } // Vtable uses a dynamic thunk for dynamic overrides // CHECK-LABEL: sil_vtable Subclass { // CHECK: #Foo.overriddenByDynamic!1: {{.*}} : public @$s7dynamic8SubclassC19overriddenByDynamic{{[_0-9a-zA-Z]*}}FTD // CHECK: } // Check vtables for implicitly-inherited initializers // CHECK-LABEL: sil_vtable SubclassWithInheritedInits { // CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26SubclassWithInheritedInitsC6nativeACSi_tcfC // CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26SubclassWithInheritedInitsC4objcACSi_tcfC // CHECK-NOT: .init! // CHECK: } // CHECK-LABEL: sil_vtable GrandchildWithInheritedInits { // CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic28GrandchildWithInheritedInitsC6nativeACSi_tcfC // CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic28GrandchildWithInheritedInitsC4objcACSi_tcfC // CHECK-NOT: .init! // CHECK: } // CHECK-LABEL: sil_vtable GrandchildOfInheritedInits { // CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26GrandchildOfInheritedInitsC6nativeACSi_tcfC // CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26GrandchildOfInheritedInitsC4objcACSi_tcfC // CHECK-NOT: .init! // CHECK: } // No vtable entry for override of @objc extension property // CHECK-LABEL: sil_vtable [serialized] SubExt { // CHECK-NEXT: #SubExt.deinit!deallocator.1: @$s7dynamic6SubExtCfD // dynamic.SubExt.__deallocating_deinit // CHECK-NEXT: } // Dynamic thunk + vtable re-abstraction // CHECK-LABEL: sil_vtable [serialized] ConcreteDerived { // CHECK-NEXT: #GenericBase.method!1: <T> (GenericBase<T>) -> (T) -> () : public @$s7dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV [override] // vtable thunk for dynamic.GenericBase.method(A) -> () dispatching to dynamic.ConcreteDerived.method(Swift.Int) -> () // CHECK-NEXT: #GenericBase.init!allocator.1: <T> (GenericBase<T>.Type) -> () -> GenericBase<T> : @$s7dynamic15ConcreteDerivedCACycfC [override] // CHECK-NEXT: #ConcreteDerived.deinit!deallocator.1: @$s7dynamic15ConcreteDerivedCfD // dynamic.ConcreteDerived.__deallocating_deinit // CHECK-NEXT: }
apache-2.0
db6642878493367d3ff01b1cdc3fbb2c
48.352518
280
0.679592
3.484444
false
false
false
false
hardikdevios/HKKit
Pod/Classes/HKExtensions/UIKit+Extensions/UIColor+Extension.swift
1
1634
// // UIColor+Extension.swift // HKCustomization // // Created by Hardik on 10/18/15. // Copyright © 2015 . All rights reserved. // import UIKit extension UIColor { convenience public init(hexString:String) { let r, g, b : CGFloat if hexString.hasPrefix("#") { let start = hexString.index(hexString.startIndex, offsetBy: 1) let hexColor = String(hexString[start...]) if hexColor.count <= 8 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff0000) >> 16) / 255 g = CGFloat((hexNumber & 0xff00) >> 8) / 255 b = CGFloat(hexNumber & 0xff) / 255 self.init(red: r, green: g, blue: b, alpha: 1) return } } } self.init(red: 0, green: 0, blue: 0, alpha: 1) } public class func getRandomColor() -> UIColor{ let randomRed:CGFloat = CGFloat(drand48()) let randomGreen:CGFloat = CGFloat(drand48()) let randomBlue:CGFloat = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } convenience public init(clearRed:CGFloat,clearGreen:CGFloat,clearBlue:CGFloat){ self.init(red: clearRed/255.0, green: clearGreen/255.0, blue: clearBlue/255, alpha: 1) } }
mit
840fa5bd2bd80a8dd14c4fe1d0f62ae0
28.160714
94
0.514391
4.523546
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/Swift4Semanas (7.0).playground/Pages/S2 - Tuplas.xcplaygroundpage/Contents.swift
1
566
//: [Anterior: Optionals](@previous) // Playground - noun: a place where people can play import UIKit let compra = (5, "KG", "Maça") // (Int, String, String) let (quantidade, unidade, mercadoria) = compra print("Você comprou \(quantidade) \(unidade) de \(mercadoria).") let (_,_,produto) = compra print("\(produto) foi adicionada ao seu carrinho :-)") print("\(compra.2) foi adicionada ao seu carrinho.") let minhaCompra = (quantidade: 2, unidade: "KG", mercadoria: "Laranja") let meuProduto = minhaCompra.mercadoria //: [Próximo: Funções](@next)
mit
f7dc4a3e4007c874188bcf196bcc3ff4
20.576923
71
0.679144
2.621495
false
false
false
false
ZekeSnider/Jared
Pods/Telegraph/Sources/Protocols/WebSockets/Models/HTTPMessage+WebSocket.swift
1
2790
// // HTTPMessage+WebSocket.swift // Telegraph // // Created by Yvo van Beek on 2/16/17. // Copyright © 2017 Building42. All rights reserved. // import Foundation extension HTTPMessage { public static let webSocketMagicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" public static let webSocketProtocol = "websocket" public static let webSocketVersion = "13" /// Is this an upgrade to the WebSocket protocol? var isWebSocketUpgrade: Bool { return headers.upgrade?.caseInsensitiveCompare(HTTPMessage.webSocketProtocol) == .orderedSame } } extension HTTPRequest { /// Creates a websocket handshake request. static func webSocketHandshake(host: String, port: Int = 80, protocolName: String? = nil) -> HTTPRequest { let request = HTTPRequest() request.webSocketHandshake(host: host, port: port, protocolName: protocolName) return request } /// Decorates a request with websocket handshake headers. func webSocketHandshake(host: String, port: Int = 80, protocolName: String? = nil) { method = .GET setHostHeader(host: host, port: port) headers.connection = "Upgrade" headers.upgrade = HTTPMessage.webSocketProtocol headers.webSocketKey = Data(randomNumberOfBytes: 16).base64EncodedString() headers.webSocketVersion = HTTPMessage.webSocketVersion // Only send the 'Sec-WebSocket-Protocol' if it has a value (according to spec) if let protocolName = protocolName, !protocolName.isEmpty { headers.webSocketProtocol = protocolName } } } public extension HTTPResponse { /// Creates a websocket handshake response. static func webSocketHandshake(key: String, protocolName: String? = nil) -> HTTPResponse { let response = HTTPResponse() response.webSocketHandshake(key: key, protocolName: protocolName) return response } /// Decorates a response with websocket handshake headers. func webSocketHandshake(key: String, protocolName: String? = nil) { // Take the incoming key, append the static GUID and return a base64 encoded SHA-1 hash let webSocketKey = key.appending(HTTPMessage.webSocketMagicGUID) let webSocketAccept = SHA1.hash(webSocketKey).base64EncodedString() status = .switchingProtocols headers.connection = "Upgrade" headers.upgrade = HTTPMessage.webSocketProtocol headers.webSocketAccept = webSocketAccept // Only send the 'Sec-WebSocket-Protocol' if it has a value (according to spec) if let protocolName = protocolName, !protocolName.isEmpty { headers.webSocketProtocol = protocolName } } // Returns a boolean indicating if the response is a websocket handshake. var isWebSocketHandshake: Bool { return status == .switchingProtocols && isWebSocketUpgrade && headers.webSocketAccept?.isEmpty == false } }
apache-2.0
74a8caa19b0b4d8872301631be65933e
35.220779
108
0.738257
4.412975
false
false
false
false
jihun-kang/ios_a2big_sdk
A2bigSDK/NoticeData.swift
1
750
// // NoticeData.swift // nextpage // // Created by a2big on 2016. 11. 7.. // Copyright © 2016년 a2big. All rights reserved. // //import SwiftyJSON public class NoticeData{ public var notice_no: String! public var start_date: String! public var end_date: String! public var notice_title: String! public var notice_ment: String! public var flag: String! required public init(json: JSON) { notice_no = json["notice_no"].stringValue start_date = json["start_date"].stringValue end_date = json["end_date"].stringValue notice_title = json["notice_title"].stringValue notice_ment = json["notice_ment"].stringValue flag = json["flag"].stringValue } }
apache-2.0
2773cfd0f64a17c0e0e2e78570bb952e
25.678571
55
0.631861
3.870466
false
false
false
false
khizkhiz/swift
test/ClangModules/optional.swift
1
2519
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -emit-silgen -o - %s | FileCheck %s // REQUIRES: objc_interop import ObjectiveC import Foundation import objc_ext import TestProtocols class A { @objc func foo() -> String? { return "" } // CHECK-LABEL: sil hidden [thunk] @_TToFC8optional1A3foofT_GSqSS_ : $@convention(objc_method) (A) -> @autoreleased Optional<NSString> // CHECK: [[T0:%.*]] = function_ref @_TFC8optional1A3foofT_GSqSS_ // CHECK-NEXT: [[T1:%.*]] = apply [[T0]](%0) // CHECK-NEXT: strong_release // CHECK: [[T2:%.*]] = select_enum [[T1]] // CHECK-NEXT: cond_br [[T2]] // Something branch: project value, translate, inject into result. // CHECK: [[STR:%.*]] = unchecked_enum_data [[T1]] // CHECK: [[T0:%.*]] = function_ref @swift_StringToNSString // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[STR]]) // CHECK-NEXT: enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // CHECK: enum $Optional<NSString>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<NSString>): // CHECK-NEXT: return [[T0]] @objc func bar(x x : String?) {} // CHECK-LABEL: sil hidden [thunk] @_TToFC8optional1A3barfT1xGSqSS__T_ : $@convention(objc_method) (Optional<NSString>, A) -> () // CHECK: [[T1:%.*]] = select_enum %0 // CHECK-NEXT: cond_br [[T1]] // Something branch: project value, translate, inject into result. // CHECK: [[NSSTR:%.*]] = unchecked_enum_data %0 // CHECK: [[T0:%.*]] = function_ref @swift_NSStringToString // Make a temporary initialized string that we're going to clobber as part of the conversion process (?). // CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]]) // CHECK-NEXT: enum $Optional<String>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // CHECK: enum $Optional<String>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : $Optional<String>): // CHECK: [[T1:%.*]] = function_ref @_TFC8optional1A3barfT1xGSqSS__T_ // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], %1) // CHECK-NEXT: strong_release %1 // CHECK-NEXT: return [[T2]] : $() } // rdar://15144951 class TestWeak : NSObject { weak var b : WeakObject? = nil } class WeakObject : NSObject {}
apache-2.0
d729ab2865490e8a73b9978bd58f890f
40.295082
137
0.626042
3.200762
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusionBenchmarks/Pose2SLAM.swift
1
2035
// Copyright 2020 The SwiftFusion Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Benchmarks Pose2SLAM solutions. import _Differentiation import Benchmark import SwiftFusion let pose2SLAM = BenchmarkSuite(name: "Pose2SLAM") { suite in let intelDataset = try! G2OReader.G2OFactorGraph(g2oFile2D: try! cachedDataset("input_INTEL_g2o.txt")) check( intelDataset.graph.error(at: intelDataset.initialGuess), near: 0.5 * 73565.64, accuracy: 1e-2) // Uses `FactorGraph` on the Intel dataset. // The solvers are configured to run for a constant number of steps. // The nonlinear solver is 10 iterations of Gauss-Newton. // The linear solver is 500 iterations of CGLS. suite.benchmark( "FactorGraph, Intel, 10 Gauss-Newton steps, 500 CGLS steps", settings: Iterations(1), TimeUnit(.ms) ) { var x = intelDataset.initialGuess var graph = intelDataset.graph graph.store(PriorFactor(TypedID(0), Pose2(0, 0, 0))) for _ in 0..<10 { let linearized = graph.linearized(at: x) var dx = x.tangentVectorZeros var optimizer = GenericCGLS(precision: 0, max_iteration: 500) optimizer.optimize(gfg: linearized, initial: &dx) x.move(along: dx) } check(graph.error(at: x), near: 0.5 * 0.987, accuracy: 1e-2) } } func check(_ actual: Double, near expected: Double, accuracy: Double) { if abs(actual - expected) > accuracy { print("ERROR: \(actual) != \(expected) (accuracy \(accuracy))") fatalError() } }
apache-2.0
1649b19820fca8032b9fd2568760c7c6
34.086207
87
0.702211
3.627451
false
false
false
false
stebojan/Calculator
Calculator/ViewController.swift
1
1546
// // ViewController.swift // Calculator // // Created by Bojan Stevanovic on 6/28/15. // Copyright (c) 2015 Bojan Stevanovic. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var display: UILabel! var userIsInTheMiddleOfTypingANumber = false var brain = CalculatorBrain() @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddleOfTypingANumber { display.text = display.text! + digit } else { display.text = digit userIsInTheMiddleOfTypingANumber = true } } @IBAction func operate(sender: UIButton) { if userIsInTheMiddleOfTypingANumber { enter() } if let operation = sender.currentTitle { if let result = brain.performOperation(operation) { displayValue = result } else { displayValue = 0 } } } @IBAction func enter() { userIsInTheMiddleOfTypingANumber = false if let result = brain.pushOperand(displayValue) { displayValue = result } else { displayValue = 0 } } var displayValue: Double { get { return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { display.text = "\(newValue)" userIsInTheMiddleOfTypingANumber = false } } }
mit
5737e72b3403fe31d3ffd3244a93dc92
22.074627
83
0.566624
5.405594
false
false
false
false
anirudh24seven/wikipedia-ios
Wikipedia/Code/WMFWelcomeIntroductionAnimationView.swift
1
5356
import Foundation public class WMFWelcomeIntroductionAnimationView : WMFWelcomeAnimationView { lazy var tubeImgView: UIImageView = { let tubeRotationPoint = CGPointMake(0.576, 0.38) let initialTubeRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(0.0) let rectCorrectingForRotation = CGRectMake( self.bounds.origin.x - (self.bounds.size.width * (0.5 - tubeRotationPoint.x)), self.bounds.origin.y - (self.bounds.size.height * (0.5 - tubeRotationPoint.y)), self.bounds.size.width, self.bounds.size.height ) let imgView = UIImageView(frame: rectCorrectingForRotation) imgView.image = UIImage(named: "ftux-telescope-tube") imgView.contentMode = UIViewContentMode.ScaleAspectFit imgView.layer.zPosition = 101 imgView.layer.transform = initialTubeRotationTransform imgView.layer.anchorPoint = tubeRotationPoint return imgView }() lazy var baseImgView: UIImageView = { let imgView = UIImageView(frame: self.bounds) imgView.image = UIImage(named: "ftux-telescope-base") imgView.contentMode = UIViewContentMode.ScaleAspectFit imgView.layer.zPosition = 101 imgView.layer.transform = CATransform3DIdentity return imgView }() lazy var dashedCircle: WelcomeCircleShapeLayer = { return WelcomeCircleShapeLayer( unitRadius: 0.304, unitOrigin: CGPointMake(0.521, 0.531), referenceSize: self.frame.size, isDashed: true, transform: self.wmf_scaleZeroTransform, opacity:0.0 ) }() lazy var solidCircle: WelcomeCircleShapeLayer = { return WelcomeCircleShapeLayer( unitRadius: 0.32, unitOrigin: CGPointMake(0.625, 0.55), referenceSize: self.frame.size, isDashed: false, transform: self.wmf_scaleZeroTransform, opacity:0.0 ) }() lazy var plus1: WelcomePlusShapeLayer = { return WelcomePlusShapeLayer( unitOrigin: CGPointMake(0.033, 0.219), unitWidth: 0.05, referenceSize: self.frame.size, transform: self.wmf_scaleZeroTransform, opacity: 0.0 ) }() lazy var plus2: WelcomePlusShapeLayer = { return WelcomePlusShapeLayer( unitOrigin: CGPointMake(0.11, 0.16), unitWidth: 0.05, referenceSize: self.frame.size, transform: self.wmf_scaleZeroTransform, opacity: 0.0 ) }() lazy var line1: WelcomeLineShapeLayer = { return WelcomeLineShapeLayer( unitOrigin: CGPointMake(0.91, 0.778), unitWidth: 0.144, referenceSize: self.frame.size, transform: self.wmf_scaleZeroAndRightTransform, opacity: 0.0 ) }() lazy var line2: WelcomeLineShapeLayer = { return WelcomeLineShapeLayer( unitOrigin: CGPointMake(0.836, 0.81), unitWidth: 0.06, referenceSize: self.frame.size, transform: self.wmf_scaleZeroAndRightTransform, opacity: 0.0 ) }() lazy var line3: WelcomeLineShapeLayer = { return WelcomeLineShapeLayer( unitOrigin: CGPointMake(0.907, 0.81), unitWidth: 0.0125, referenceSize: self.frame.size, transform: self.wmf_scaleZeroAndRightTransform, opacity: 0.0 ) }() override public func addAnimationElementsScaledToCurrentFrameSize(){ removeExistingSubviewsAndSublayers() self.addSubview(self.baseImgView) self.addSubview(self.tubeImgView) _ = [ self.solidCircle, self.dashedCircle, self.plus1, self.plus2, self.line1, self.line2, self.line3 ].map({ (layer: CALayer) -> () in self.layer.addSublayer(layer) }) } override public func beginAnimations() { CATransaction.begin() let tubeOvershootRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(15.0) let tubeFinalRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(-2.0) tubeImgView.layer.wmf_animateToOpacity(1.0, transform:tubeOvershootRotationTransform, delay: 0.8, duration: 0.9 ) tubeImgView.layer.wmf_animateToOpacity(1.0, transform:tubeFinalRotationTransform, delay: 1.8, duration: 0.9 ) self.solidCircle.wmf_animateToOpacity(0.09, transform: CATransform3DIdentity, delay: 0.3, duration: 1.0 ) let animate = { (layer: CALayer) -> () in layer.wmf_animateToOpacity(0.15, transform: CATransform3DIdentity, delay: 0.3, duration: 1.0 ) } _ = [ self.dashedCircle, self.plus1, self.plus2, self.line1, self.line2, self.line3 ].map(animate) CATransaction.commit() } }
mit
96b408a65eb2c258be0e003986e420fd
31.26506
97
0.581031
4.56607
false
false
false
false
jkereako/LoginView
Source/BubblePresentationAnimator.swift
1
3652
// // BubblePresentationAnimator.swift // // Created by Andrea Mazzini on 04/04/15. // Copyright (c) 2015 Fancy Pixel. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Andrea Mazzini // // 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 final class BubblePresentationAnimator: NSObject { let origin: CGPoint let backgroundColor: UIColor init(origin: CGPoint = .zero, backgroundColor: UIColor = .clear) { self.origin = origin self.backgroundColor = backgroundColor } } // MARK: - UIViewControllerAnimatedTransitioning extension BubblePresentationAnimator: UIViewControllerAnimatedTransitioning { private func frameForBubble(originalCenter: CGPoint, size originalSize: CGSize, start: CGPoint) -> CGRect { let lengthX = fmax(start.x, originalSize.width - start.x); let lengthY = fmax(start.y, originalSize.height - start.y) let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2; let size = CGSize(width: offset, height: offset) return CGRect(origin: .zero, size: size) } func transitionDuration( using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let to = transitionContext.view(forKey: UITransitionContextViewKey.to) let originalCenter = to?.center ?? .zero let originalSize = to?.frame.size ?? .zero let bubble = UIView() bubble.frame = frameForBubble( originalCenter: originalCenter, size: originalSize, start: .zero ) bubble.layer.cornerRadius = bubble.frame.size.height / 2 bubble.center = origin bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) bubble.backgroundColor = backgroundColor transitionContext.containerView.addSubview(bubble) to?.center = origin to?.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) to?.alpha = 0 transitionContext.containerView.addSubview(to ?? UIView()) UIView.animate( withDuration: 0.5, animations: { bubble.transform = .identity to?.transform = .identity to?.alpha = 1 to?.center = originalCenter }, completion: { (done: Bool) in transitionContext.completeTransition(true) } ) } }
mit
2f5def51ed906621420b25948e3daee2
38.268817
91
0.663472
4.837086
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-16/ImageMetalling-16/Classes/Common/IMPFilterView.swift
1
8786
// // IMPCanvasView.swift // ImageMetalling-16 // // Created by denis svinarchuk on 21.06.2018. // Copyright © 2018 ImageMetalling. All rights reserved. // import Cocoa import MetalKit import IMProcessing import IMProcessingUI open class IMPFilterView: MTKView { public var name:String? public var debug:Bool = false public var placeHolderColor:NSColor? { didSet{ if let color = placeHolderColor{ __placeHolderColor = color.rgba } else { __placeHolderColor = float4(0.5) } } } open weak var filter:IMPFilter? = nil { willSet{ filter?.removeObserver(destinationUpdated: destinationObserver) filter?.removeObserver(newSource: sourceObserver) } didSet { filter?.addObserver(destinationUpdated: destinationObserver) filter?.addObserver(newSource: sourceObserver) } } public var image:IMPImageProvider? { return _image } public override init(frame frameRect: CGRect, device: MTLDevice?=nil) { super.init(frame: frameRect, device: device ?? MTLCreateSystemDefaultDevice()) configure() } public required init(coder: NSCoder) { super.init(coder: coder) device = MTLCreateSystemDefaultDevice() configure() } open override var frame: NSRect { didSet{ self.filter?.dirty = true } } open override func setNeedsDisplay(_ invalidRect: NSRect) { super.setNeedsDisplay(invalidRect) self.filter?.dirty = true } open func configure() { delegate = self isPaused = false enableSetNeedsDisplay = false framebufferOnly = true postsBoundsChangedNotifications = true postsFrameChangedNotifications = true clearColor = MTLClearColorMake(0, 0, 0, 0) } private var _image:IMPImageProvider? { didSet{ refreshQueue.async(flags: [.barrier]) { self.__source = self.image if self.image == nil /*&& self.__placeHolderColor == nil*/ { return } if self.isPaused { self.draw() } } } } private var __source:IMPImageProvider? private var __placeHolderColor = float4(1) private lazy var destinationObserver:IMPFilter.UpdateHandler = { let handler:IMPFilter.UpdateHandler = { (destination) in if self.isPaused { self._image = destination self.needProcessing = true } } return handler }() private lazy var sourceObserver:IMPFilter.SourceUpdateHandler = { let handler:IMPFilter.SourceUpdateHandler = { (source) in self.needProcessing = true } return handler }() private var needProcessing = true private lazy var commandQueue:MTLCommandQueue = self.device!.makeCommandQueue(maxCommandBufferCount: IMPFilterView.maxFrames)! private static let maxFrames = 1 private let mutex = DispatchSemaphore(value: IMPFilterView.maxFrames) private var framesTimeout:UInt64 = 5 fileprivate func refresh(){ self.filter?.context.runOperation(.async, { if let filter = self.filter, filter.dirty || self.needProcessing { self.__source = filter.destination self.needProcessing = false if self.debug { Swift.print("View[\((self.name ?? "-"))] filter = \(filter, self.__source, self.__source?.size)") } } else { return } guard let pipeline = ((self.__source?.texture == nil) ? self.placeHolderPipeline : self.pipeline), let commandBuffer = self.commandQueue.makeCommandBuffer() else { return } if !self.isPaused { guard self.mutex.wait(timeout: DispatchTime(uptimeNanoseconds: 1000000000 * self.framesTimeout)) == .success else { return } } self.render(commandBuffer: commandBuffer, texture: self.__source?.texture, with: pipeline){ if !self.isPaused { self.mutex.signal() } } }) } fileprivate func render(commandBuffer:MTLCommandBuffer, texture:MTLTexture?, with pipeline: MTLRenderPipelineState, complete: @escaping () -> Void) { commandBuffer.label = "Frame command buffer" commandBuffer.addCompletedHandler{ commandBuffer in complete() return } if let currentDrawable = self.currentDrawable, let renderPassDescriptor = currentRenderPassDescriptor, let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor){ renderEncoder.label = "IMPProcessingView" renderEncoder.setRenderPipelineState(pipeline) renderEncoder.setVertexBuffer(vertexBuffer, offset:0, index:0) if let texture = texture { renderEncoder.setFragmentTexture(texture, index:0) } else { renderEncoder.setFragmentBytes(&__placeHolderColor, length: MemoryLayout.size(ofValue: __placeHolderColor), index: 0) } renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart:0, vertexCount:4, instanceCount:1) renderEncoder.endEncoding() commandBuffer.present(currentDrawable) commandBuffer.commit() commandBuffer.waitUntilCompleted() } else { complete() } } private static var library = MTLCreateSystemDefaultDevice()!.makeDefaultLibrary()! private lazy var fragment = IMPFilterView.library.makeFunction(name: "fragment_passview") private lazy var fragmentPlaceHolder = IMPFilterView.library.makeFunction(name: "fragment_placeHolderView") private lazy var vertex = IMPFilterView.library.makeFunction(name: "vertex_passview") private lazy var pipeline:MTLRenderPipelineState? = { do { let descriptor = MTLRenderPipelineDescriptor() descriptor.colorAttachments[0].pixelFormat = self.colorPixelFormat descriptor.vertexFunction = self.vertex descriptor.fragmentFunction = self.fragment return try self.device!.makeRenderPipelineState(descriptor: descriptor) } catch let error as NSError { NSLog("IMPView error: \(error)") return nil } }() private lazy var placeHolderPipeline:MTLRenderPipelineState? = { do { let descriptor = MTLRenderPipelineDescriptor() descriptor.colorAttachments[0].pixelFormat = self.colorPixelFormat descriptor.vertexFunction = self.vertex descriptor.fragmentFunction = self.fragmentPlaceHolder return try self.device!.makeRenderPipelineState(descriptor: descriptor) } catch let error as NSError { NSLog("IMPView error: \(error)") return nil } }() private static let viewVertexData:[Float] = [ -1.0, -1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, ] private lazy var vertexBuffer:MTLBuffer? = { let v = self.device?.makeBuffer(bytes: IMPFilterView.viewVertexData, length: MemoryLayout<Float>.size*IMPFilterView.viewVertexData.count, options: []) v?.label = "Vertices" return v }() public var refreshQueue = DispatchQueue(label: String(format: "com.dehancer.metal.view.refresh-%08x%08x", arc4random(), arc4random())) } extension IMPFilterView: MTKViewDelegate { public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} public func draw(in view: MTKView) { self.refresh() } }
mit
9bf49ab2fb1bfd59df3517a1654375e4
33.182879
158
0.55868
5.439628
false
false
false
false
huangboju/Moots
UICollectionViewLayout/uicollectionview-layouts-kit-master/insta-grid/Core/Cell/InstagridCollectionViewCell.swift
1
1573
// // InstagridCollectionViewCell.swift // insta-grid // // Created by Astemir Eleev on 18/04/2018. // Copyright © 2018 Astemir Eleev. All rights reserved. // import UIKit class InstagridCollectionViewCell: UICollectionViewCell { // MARK: - Static properties static let reusableId = "image-cell" // MARK: - Properties var imageName: String = "" { didSet { imageView.image = UIImage(named: imageName) } } // MARK: - Outlets @IBOutlet weak var imageView: UIImageView! // MARK: - Overrides // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) prepare() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } // MARK: - Methods override func awakeFromNib() { super.awakeFromNib() imageView.contentMode = .scaleAspectFill } override class var requiresConstraintBasedLayout: Bool { return true } override func prepareForReuse() { contentView.backgroundColor = .black imageView.image = nil } // MARK: - Helpers private func prepare() { contentView.layer.cornerRadius = 5.0 contentView.layer.borderColor = UIColor.white.cgColor contentView.layer.borderWidth = 1.0 contentView.layer.shouldRasterize = true contentView.layer.rasterizationScale = UIScreen.main.scale contentView.clipsToBounds = true } }
mit
8ac79aa362f43a2178759fcf917a5d05
21.457143
66
0.605598
4.763636
false
false
false
false
mightydeveloper/swift
test/SILGen/writeback.swift
10
8295
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s struct Foo { mutating // used to test writeback. func foo() {} subscript(x: Int) -> Foo { get { return Foo() } set {} } } var x: Foo { get { return Foo() } set {} } var y: Foo { get { return Foo() } set {} } var z: Foo { get { return Foo() } set {} } var readonly: Foo { get { return Foo() } } func bar(inout x x: Foo) {} func bas(inout x x: Foo)(inout y: Foo) {} func zim(inout x x: Foo)(inout y: Foo) -> (inout z: Foo) -> () { return { (inout z: Foo) in } } // Writeback to value type 'self' argument x.foo() // CHECK: [[FOO:%.*]] = function_ref @_TFV9writeback3Foo3foo{{.*}} : $@convention(method) (@inout Foo) -> () // CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo // CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo // CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo // CHECK: store [[X]] to [[X_TEMP]]#1 // CHECK: apply [[FOO]]([[X_TEMP]]#1) : $@convention(method) (@inout Foo) -> () // CHECK: [[X1:%.*]] = load [[X_TEMP]]#1 : $*Foo // CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> () // CHECK: dealloc_stack [[X_TEMP]]#0 : $*@local_storage Foo // Writeback to inout argument bar(x: &x) // CHECK: [[BAR:%.*]] = function_ref @_TF9writeback3barFT1xRVS_3Foo_T_ : $@convention(thin) (@inout Foo) -> () // CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo // CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo // CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo // CHECK: store [[X]] to [[X_TEMP]]#1 : $*Foo // CHECK: apply [[BAR]]([[X_TEMP]]#1) : $@convention(thin) (@inout Foo) -> () // CHECK: [[X1:%.*]] = load [[X_TEMP]]#1 : $*Foo // CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> () // CHECK: dealloc_stack [[X_TEMP]]#0 : $*@local_storage Foo // Writeback to curried arguments bas(x: &x)(y: &y) // CHECK: [[BAS:%.*]] = function_ref @_TF9writeback3basfT1xRVS_3Foo_FT1yRS0__T_ : $@convention(thin) (@inout Foo, @inout Foo) -> () // CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo // CHECK: {{%.*}} = apply [[GET_X]]() : $@convention(thin) () -> Foo // CHECK: [[GET_Y:%.*]] = function_ref @_TF9writebackg1yVS_3Foo : $@convention(thin) () -> Foo // CHECK: {{%.*}} = apply [[GET_Y]]() : $@convention(thin) () -> Foo // CHECK: apply [[BAS]]({{%.*}}, {{%.*}}) : $@convention(thin) (@inout Foo, @inout Foo) -> () // CHECK: [[SET_Y:%.*]] = function_ref @_TF9writebacks1yVS_3Foo : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_Y]]({{%.*}}) : $@convention(thin) (Foo) -> () // CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_X]]({{%.*}}) : $@convention(thin) (Foo) -> () // Writeback to curried arguments to function that returns a function zim(x: &x)(y: &y)(z: &z) // CHECK: [[ZIM:%.*]] = function_ref @_TF9writeback3zimfT1xRVS_3Foo_FT1yRS0__FT1zRS0__T_ : $@convention(thin) (@inout Foo, @inout Foo) -> @owned @callee_owned (@inout Foo) -> () // CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo // CHECK: {{%.*}} = apply [[GET_X]]() : $@convention(thin) () -> Foo // CHECK: [[GET_Y:%.*]] = function_ref @_TF9writebackg1yVS_3Foo : $@convention(thin) () -> Foo // CHECK: {{%.*}} = apply [[GET_Y]]() : $@convention(thin) () -> Foo // CHECK: [[ZIM2:%.*]] = apply [[ZIM]]({{%.*}}, {{%.*}}) : $@convention(thin) (@inout Foo, @inout Foo) -> @owned @callee_owned (@inout Foo) -> () // CHECK: [[SET_Y:%.*]] = function_ref @_TF9writebacks1yVS_3Foo : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_Y]]({{%.*}}) : $@convention(thin) (Foo) -> () // CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_X]]({{%.*}}) : $@convention(thin) (Foo) -> () // CHECK: [[GET_Z:%.*]] = function_ref @_TF9writebackg1zVS_3Foo : $@convention(thin) () -> Foo // CHECK: {{%.*}} = apply [[GET_Z]]() : $@convention(thin) () -> Foo // CHECK: apply [[ZIM2]]({{%.*}}) : $@callee_owned (@inout Foo) -> () // CHECK: [[SET_Z:%.*]] = function_ref @_TF9writebacks1zVS_3Foo : $@convention(thin) (Foo) -> () // CHECK: apply [[SET_Z]]({{%.*}}) : $@convention(thin) (Foo) -> () func zang(x x: Foo) {} // No writeback for pass-by-value argument zang(x: x) // CHECK: function_ref @_TF9writeback4zangFT1xVS_3Foo_T_ : $@convention(thin) (Foo) -> () // CHECK-NOT: @_TF9writebacks1xVS_3Foo zang(x: readonly) // CHECK: function_ref @_TF9writeback4zangFT1xVS_3Foo_T_ : $@convention(thin) (Foo) -> () // CHECK-NOT: @_TF9writebacks8readonlyVS_3Foo func zung() -> Int { return 0 } // Ensure that subscripts are only evaluated once. bar(x: &x[zung()]) // CHECK: [[BAR:%.*]] = function_ref @_TF9writeback3barFT1xRVS_3Foo_T_ : $@convention(thin) (@inout Foo) -> () // CHECK: [[ZUNG:%.*]] = function_ref @_TF9writeback4zungFT_Si : $@convention(thin) () -> Int // CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int // CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo // CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @_TFV9writeback3Foog9subscript{{.*}} : $@convention(method) (Int, Foo) -> Foo // CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo // CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> () // CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @_TFV9writeback3Foos9subscript{{.*}} : $@convention(method) (Foo, Int, @inout Foo) -> () // CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> () // CHECK: function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> () protocol Fungible {} extension Foo : Fungible {} var addressOnly: Fungible { get { return Foo() } set {} } func funge(inout x x: Fungible) {} funge(x: &addressOnly) // CHECK: [[FUNGE:%.*]] = function_ref @_TF9writeback5fungeFT1xRPS_8Fungible__T_ : $@convention(thin) (@inout Fungible) -> () // CHECK: [[TEMP:%.*]] = alloc_stack $Fungible // CHECK: [[GET:%.*]] = function_ref @_TF9writebackg11addressOnlyPS_8Fungible_ : $@convention(thin) (@out Fungible) -> () // CHECK: apply [[GET]]([[TEMP]]#1) : $@convention(thin) (@out Fungible) -> () // CHECK: apply [[FUNGE]]([[TEMP]]#1) : $@convention(thin) (@inout Fungible) -> () // CHECK: [[SET:%.*]] = function_ref @_TF9writebacks11addressOnlyPS_8Fungible_ : $@convention(thin) (@in Fungible) -> () // CHECK: apply [[SET]]([[TEMP]]#1) : $@convention(thin) (@in Fungible) -> () // CHECK: dealloc_stack [[TEMP]]#0 : $*@local_storage Fungible // Test that writeback occurs with generic properties. // <rdar://problem/16525257> protocol Runcible { typealias Frob: Frobable var frob: Frob { get set } } protocol Frobable { typealias Anse var anse: Anse { get set } } // CHECK-LABEL: sil hidden @_TF9writeback12test_generic // CHECK: witness_method $Runce, #Runcible.frob!materializeForSet.1 // CHECK: witness_method $Runce.Frob, #Frobable.anse!setter.1 func test_generic<Runce: Runcible>(inout runce runce: Runce, anse: Runce.Frob.Anse) { runce.frob.anse = anse } // We should *not* write back when referencing decls or members as rvalues. // <rdar://problem/16530235> // CHECK-LABEL: sil hidden @_TF9writeback15loadAddressOnlyFT_PS_8Fungible_ : $@convention(thin) (@out Fungible) -> () { func loadAddressOnly() -> Fungible { // CHECK: function_ref writeback.addressOnly.getter // CHECK-NOT: function_ref writeback.addressOnly.setter return addressOnly } // CHECK-LABEL: sil hidden @_TF9writeback10loadMember // CHECK: witness_method $Runce, #Runcible.frob!getter.1 // CHECK: witness_method $Runce.Frob, #Frobable.anse!getter.1 // CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter.1 // CHECK-NOT: witness_method $Runce, #Runcible.frob!setter.1 func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse { return runce.frob.anse }
apache-2.0
6865f661e05e81f91c23648c80b9d8fe
42.429319
177
0.594575
3.092841
false
false
false
false
ryanbaldwin/Restivus
Sources/HTTPURLResponse+Extensions.swift
1
1689
// // HTTPURLResponse+Extensions.swift // Restivus // // Created by Ryan Baldwin on 2017-08-21. // Copyright © 2017 bunnyhug.me. All rights governed under the Apache 2 License Agreement // import Foundation extension HTTPURLResponse { /// A textual representation of this instance, suitable for debugging. open override var debugDescription: String { var fields: [String] = ["\nResponse:", "==============="] fields.append("Response Code: \(self.statusCode)") if allHeaderFields.count > 0 { fields.append("Headers:") allHeaderFields.forEach { (key, val) in fields.append("\t\(key): \(val)") } } return fields.joined(separator: "\n") } /// True if this response code is a member of the 1xx Informational set of codes; otherwise false public var isInformational: Bool { return 100...199 ~= statusCode } /// True if this response code is a member of the 2xx Success response codes; otherwise false public var isSuccess: Bool { return 200...299 ~= statusCode } /// True if this response code is a member of the 3xx Redirection response codes; otherwise false public var isRedirection: Bool { return 300...399 ~= statusCode } /// True if this response code is a member of the 4xx Client Error response codes; otherwise false public var isClientError: Bool { return 400...499 ~= statusCode } /// True if this response code is a member of the 5xx Server Error response codes; otherwise false public var isServerError: Bool { return 500...599 ~= statusCode } }
apache-2.0
a78d43008c69d3272e0c663278df8ce9
32.098039
102
0.634479
4.715084
false
false
false
false