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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lorentey/swift | test/Generics/conditional_conformances.swift | 10 | 18138 | // RUN: %target-typecheck-verify-swift
// RUN: %target-typecheck-verify-swift -debug-generic-signatures > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
protocol P1 {}
protocol P2 {}
protocol P3 {}
protocol P4: P1 {}
protocol P5: P2 {}
protocol P6: P2 {}
protocol Assoc { associatedtype AT }
func takes_P2<X: P2>(_: X) {}
func takes_P5<X: P5>(_: X) {}
// Skip the first generic signature declcontext dump
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Free
struct Free<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Free
// CHECK-NEXT: (normal_conformance type=Free<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
extension Free: P2 where T: P1 {}
// expected-note@-1 {{requirement from conditional conformance of 'Free<U>' to 'P2'}}
// expected-note@-2 {{requirement from conditional conformance of 'Free<T>' to 'P2'}}
func free_good<U: P1>(_: U) {
takes_P2(Free<U>())
}
func free_bad<U>(_: U) {
takes_P2(Free<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P1'}}
}
struct Constrained<T: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Constrained
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Constrained
// CHECK-NEXT: (normal_conformance type=Constrained<T> protocol=P2
// CHECK-NEXT: conforms_to: T P3)
extension Constrained: P2 where T: P3 {} // expected-note {{requirement from conditional conformance of 'Constrained<U>' to 'P2'}}
func constrained_good<U: P1 & P3>(_: U) {
takes_P2(Constrained<U>())
}
func constrained_bad<U: P1>(_: U) {
takes_P2(Constrained<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P3'}}
}
struct RedundantSame<T: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSame
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSame
// CHECK-NEXT: (normal_conformance type=RedundantSame<T> protocol=P2)
extension RedundantSame: P2 where T: P1 {}
struct RedundantSuper<T: P4> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSuper
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundantSuper
// CHECK-NEXT: (normal_conformance type=RedundantSuper<T> protocol=P2)
extension RedundantSuper: P2 where T: P1 {}
struct OverlappingSub<T: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=OverlappingSub
// CHECK-LABEL: ExtensionDecl line={{.*}} base=OverlappingSub
// CHECK-NEXT: (normal_conformance type=OverlappingSub<T> protocol=P2
// CHECK-NEXT: conforms_to: T P4)
extension OverlappingSub: P2 where T: P4 {} // expected-note {{requirement from conditional conformance of 'OverlappingSub<U>' to 'P2'}}
func overlapping_sub_good<U: P4>(_: U) {
takes_P2(OverlappingSub<U>())
}
func overlapping_sub_bad<U: P1>(_: U) {
takes_P2(OverlappingSub<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P4'}}
}
struct SameType<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameType
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameType
// CHECK-NEXT: (normal_conformance type=SameType<T> protocol=P2
// CHECK-NEXT: same_type: T Int)
extension SameType: P2 where T == Int {}
// expected-note@-1 {{requirement from conditional conformance of 'SameType<U>' to 'P2'}}
// expected-note@-2 {{requirement from conditional conformance of 'SameType<Float>' to 'P2'}}
func same_type_good() {
takes_P2(SameType<Int>())
}
func same_type_bad<U>(_: U) {
takes_P2(SameType<U>()) // expected-error{{global function 'takes_P2' requires the types 'U' and 'Int' be equivalent}}
takes_P2(SameType<Float>()) // expected-error{{global function 'takes_P2' requires the types 'Float' and 'Int' be equivalent}}
}
struct SameTypeGeneric<T, U> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameTypeGeneric
// CHECK-LABEL: ExtensionDecl line={{.*}} base=SameTypeGeneric
// CHECK-NEXT: (normal_conformance type=SameTypeGeneric<T, U> protocol=P2
// CHECK-NEXT: same_type: T U)
extension SameTypeGeneric: P2 where T == U {}
// expected-note@-1 {{requirement from conditional conformance of 'SameTypeGeneric<U, Int>' to 'P2'}}
// expected-note@-2 {{requirement from conditional conformance of 'SameTypeGeneric<Int, Float>' to 'P2'}}
// expected-note@-3 {{requirement from conditional conformance of 'SameTypeGeneric<U, V>' to 'P2'}}
func same_type_generic_good<U, V>(_: U, _: V)
where U: Assoc, V: Assoc, U.AT == V.AT
{
takes_P2(SameTypeGeneric<Int, Int>())
takes_P2(SameTypeGeneric<U, U>())
takes_P2(SameTypeGeneric<U.AT, V.AT>())
}
func same_type_bad<U, V>(_: U, _: V) {
takes_P2(SameTypeGeneric<U, V>())
// expected-error@-1{{global function 'takes_P2' requires the types 'U' and 'V' be equivalent}}
takes_P2(SameTypeGeneric<U, Int>())
// expected-error@-1{{global function 'takes_P2' requires the types 'U' and 'Int' be equivalent}}
takes_P2(SameTypeGeneric<Int, Float>())
// expected-error@-1{{global function 'takes_P2' requires the types 'Int' and 'Float' be equivalent}}
}
struct Infer<T, U> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Infer
// CHECK-LABEL: ExtensionDecl line={{.*}} base=Infer
// CHECK-NEXT: (normal_conformance type=Infer<T, U> protocol=P2
// CHECK-NEXT: same_type: T Constrained<U>
// CHECK-NEXT: conforms_to: U P1)
extension Infer: P2 where T == Constrained<U> {}
// expected-note@-1 2 {{requirement from conditional conformance of 'Infer<Constrained<U>, V>' to 'P2'}}
func infer_good<U: P1>(_: U) {
takes_P2(Infer<Constrained<U>, U>())
}
func infer_bad<U: P1, V>(_: U, _: V) {
takes_P2(Infer<Constrained<U>, V>())
// expected-error@-1{{global function 'takes_P2' requires the types 'Constrained<U>' and 'Constrained<V>' be equivalent}}
// expected-error@-2{{global function 'takes_P2' requires that 'V' conform to 'P1'}}
takes_P2(Infer<Constrained<V>, V>())
// expected-error@-1{{type 'V' does not conform to protocol 'P1'}}
}
struct InferRedundant<T, U: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InferRedundant
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InferRedundant
// CHECK-NEXT: (normal_conformance type=InferRedundant<T, U> protocol=P2
// CHECK-NEXT: same_type: T Constrained<U>)
extension InferRedundant: P2 where T == Constrained<U> {}
func infer_redundant_good<U: P1>(_: U) {
takes_P2(InferRedundant<Constrained<U>, U>())
}
func infer_redundant_bad<U: P1, V>(_: U, _: V) {
takes_P2(InferRedundant<Constrained<U>, V>())
// expected-error@-1{{type 'V' does not conform to protocol 'P1'}}
takes_P2(InferRedundant<Constrained<V>, V>())
// expected-error@-1{{type 'V' does not conform to protocol 'P1'}}
}
class C1 {}
class C2: C1 {}
class C3: C2 {}
struct ClassFree<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassFree
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassFree
// CHECK-NEXT: (normal_conformance type=ClassFree<T> protocol=P2
// CHECK-NEXT: superclass: T C1)
extension ClassFree: P2 where T: C1 {} // expected-note {{requirement from conditional conformance of 'ClassFree<U>' to 'P2'}}
func class_free_good<U: C1>(_: U) {
takes_P2(ClassFree<U>())
}
func class_free_bad<U>(_: U) {
takes_P2(ClassFree<U>())
// expected-error@-1{{global function 'takes_P2' requires that 'U' inherit from 'C1'}}
}
struct ClassMoreSpecific<T: C1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassMoreSpecific
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassMoreSpecific
// CHECK-NEXT: (normal_conformance type=ClassMoreSpecific<T> protocol=P2
// CHECK-NEXT: superclass: T C3)
extension ClassMoreSpecific: P2 where T: C3 {} // expected-note {{requirement from conditional conformance of 'ClassMoreSpecific<U>' to 'P2'}}
func class_more_specific_good<U: C3>(_: U) {
takes_P2(ClassMoreSpecific<U>())
}
func class_more_specific_bad<U: C1>(_: U) {
takes_P2(ClassMoreSpecific<U>())
// expected-error@-1{{global function 'takes_P2' requires that 'U' inherit from 'C3'}}
}
struct ClassLessSpecific<T: C3> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassLessSpecific
// CHECK-LABEL: ExtensionDecl line={{.*}} base=ClassLessSpecific
// CHECK-NEXT: (normal_conformance type=ClassLessSpecific<T> protocol=P2)
extension ClassLessSpecific: P2 where T: C1 {}
// Inherited conformances:
class Base<T> {}
extension Base: P2 where T: C1 {}
class SubclassGood: Base<C1> {}
func subclass_good() {
takes_P2(SubclassGood())
}
class SubclassBad: Base<Int> {} // expected-note {{requirement from conditional conformance of 'SubclassBad' to 'P2'}}
func subclass_bad() {
takes_P2(SubclassBad())
// expected-error@-1{{global function 'takes_P2' requires that 'Int' inherit from 'C1'}}
}
// Inheriting conformances:
struct InheritEqual<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
extension InheritEqual: P2 where T: P1 {} // expected-note {{requirement from conditional conformance of 'InheritEqual<U>' to 'P2'}}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritEqual
// CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P5
// CHECK-NEXT: (normal_conformance type=InheritEqual<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
// CHECK-NEXT: conforms_to: T P1)
extension InheritEqual: P5 where T: P1 {} // expected-note {{requirement from conditional conformance of 'InheritEqual<U>' to 'P5'}}
func inheritequal_good<U: P1>(_: U) {
takes_P2(InheritEqual<U>())
takes_P5(InheritEqual<U>())
}
func inheritequal_bad<U>(_: U) {
takes_P2(InheritEqual<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P1'}}
takes_P5(InheritEqual<U>()) // expected-error{{global function 'takes_P5' requires that 'U' conform to 'P1'}}
}
struct InheritLess<T> {}
extension InheritLess: P2 where T: P1 {}
extension InheritLess: P5 {} // expected-error{{type 'T' does not conform to protocol 'P1'}}
// expected-error@-1{{'P5' requires that 'T' conform to 'P1'}}
// expected-note@-2{{requirement specified as 'T' : 'P1'}}
// expected-note@-3{{requirement from conditional conformance of 'InheritLess<T>' to 'P2'}}
struct InheritMore<T> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
extension InheritMore: P2 where T: P1 {} // expected-note {{requirement from conditional conformance of 'InheritMore<U>' to 'P2'}}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-LABEL: ExtensionDecl line={{.*}} base=InheritMore
// CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P5
// CHECK-NEXT: (normal_conformance type=InheritMore<T> protocol=P2
// CHECK-NEXT: conforms_to: T P1)
// CHECK-NEXT: conforms_to: T P4)
extension InheritMore: P5 where T: P4 {} // expected-note 2 {{requirement from conditional conformance of 'InheritMore<U>' to 'P5'}}
func inheritequal_good_good<U: P4>(_: U) {
takes_P2(InheritMore<U>())
takes_P5(InheritMore<U>())
}
func inheritequal_good_bad<U: P1>(_: U) {
takes_P2(InheritMore<U>())
takes_P5(InheritMore<U>()) // expected-error{{global function 'takes_P5' requires that 'U' conform to 'P4'}}
}
func inheritequal_bad_bad<U>(_: U) {
takes_P2(InheritMore<U>()) // expected-error{{global function 'takes_P2' requires that 'U' conform to 'P1'}}
takes_P5(InheritMore<U>()) // expected-error{{global function 'takes_P5' requires that 'U' conform to 'P4'}}
}
struct InheritImplicitOne<T> {}
// This shouldn't give anything implicit since we disallow implication for
// conditional conformances (in many cases, the implied bounds are
// incorrect/insufficiently general).
extension InheritImplicitOne: P5 where T: P1 {}
// expected-error@-1{{conditional conformance of type 'InheritImplicitOne<T>' to protocol 'P5' does not imply conformance to inherited protocol 'P2'}}
// expected-note@-2{{did you mean to explicitly state the conformance like 'extension InheritImplicitOne: P2 where ...'?}}
struct InheritImplicitTwo<T> {}
// Even if we relax the rule about implication, this double-up should still be
// an error, because either conformance could imply InheritImplicitTwo: P2.
extension InheritImplicitTwo: P5 where T: P1 {}
// expected-error@-1{{conditional conformance of type 'InheritImplicitTwo<T>' to protocol 'P5' does not imply conformance to inherited protocol 'P2'}}
// expected-note@-2{{did you mean to explicitly state the conformance like 'extension InheritImplicitTwo: P2 where ...'?}}
extension InheritImplicitTwo: P6 where T: P1 {}
// However, if there's a non-conditional conformance that implies something, we
// can imply from that one.
struct InheritImplicitGood1<T> {}
extension InheritImplicitGood1: P5 {}
extension InheritImplicitGood1: P6 where T: P1 {}
func inheritimplicitgood1<T>(_ : T) {
takes_P2(InheritImplicitGood1<T>()) // unconstrained!
takes_P2(InheritImplicitGood1<Int>())
}
struct InheritImplicitGood2<T> {}
extension InheritImplicitGood2: P6 where T: P1 {}
extension InheritImplicitGood2: P5 {}
func inheritimplicitgood2<T>(_: T) {
takes_P2(InheritImplicitGood2<T>()) // unconstrained!
takes_P2(InheritImplicitGood2<Int>())
}
struct InheritImplicitGood3<T>: P5 {}
extension InheritImplicitGood3: P6 where T: P1 {}
func inheritimplicitgood3<T>(_: T) {
takes_P2(InheritImplicitGood3<T>()) // unconstrained!
takes_P2(InheritImplicitGood3<Int>())
}
// "Multiple conformances" from SE0143
struct TwoConformances<T> {}
extension TwoConformances: P2 where T: P1 {}
// expected-note@-1{{'TwoConformances<T>' declares conformance to protocol 'P2' here}}
extension TwoConformances: P2 where T: P3 {}
// expected-error@-1{{conflicting conformance of 'TwoConformances<T>' to protocol 'P2'; there cannot be more than one conformance, even with different conditional bounds}}
struct TwoDisjointConformances<T> {}
extension TwoDisjointConformances: P2 where T == Int {}
// expected-note@-1{{'TwoDisjointConformances<T>' declares conformance to protocol 'P2' here}}
extension TwoDisjointConformances: P2 where T == String {}
// expected-error@-1{{conflicting conformance of 'TwoDisjointConformances<T>' to protocol 'P2'; there cannot be more than one conformance, even with different conditional bounds}}
// FIXME: these cases should be equivalent (and both with the same output as the
// first), but the second one choses T as the representative of the
// equivalence class containing both T and U in the extension's generic
// signature, meaning the stored conditional requirement is T: P1, which isn't
// true in the original type's generic signature.
struct RedundancyOrderDependenceGood<T: P1, U> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceGood
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceGood
// CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceGood<T, U> protocol=P2
// CHECK-NEXT: same_type: T U)
extension RedundancyOrderDependenceGood: P2 where U: P1, T == U {}
struct RedundancyOrderDependenceBad<T, U: P1> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceBad
// CHECK-LABEL: ExtensionDecl line={{.*}} base=RedundancyOrderDependenceBad
// CHECK-NEXT: (normal_conformance type=RedundancyOrderDependenceBad<T, U> protocol=P2
// CHECK-NEXT: conforms_to: T P1
// CHECK-NEXT: same_type: T U)
extension RedundancyOrderDependenceBad: P2 where T: P1, T == U {}
// Checking of conditional requirements for existential conversions.
func existential_good<T: P1>(_: T.Type) {
_ = Free<T>() as P2
}
func existential_bad<T>(_: T.Type) {
_ = Free<T>() as P2 // expected-error{{protocol 'P2' requires that 'T' conform to 'P1'}}
}
// rdar://problem/35837054
protocol P7 { }
protocol P8 {
associatedtype A
}
struct X0 { }
struct X1 { }
extension X1: P8 {
typealias A = X0
}
struct X2<T> { }
extension X2: P7 where T: P8, T.A: P7 { } // expected-note {{requirement from conditional conformance of 'X2<X1>' to 'P7'}}
func takesF7<T: P7>(_: T) { }
func passesConditionallyNotF7(x21: X2<X1>) {
takesF7(x21) // expected-error{{global function 'takesF7' requires that 'X1.A' (aka 'X0') conform to 'P7'}}
}
public struct SR6990<T, U> {}
extension SR6990: Sequence where T == Int {
public typealias Element = Float
public typealias Iterator = IndexingIterator<[Float]>
public func makeIterator() -> Iterator { fatalError() }
}
// SR-8324
protocol ElementProtocol {
associatedtype BaseElement: BaseElementProtocol = Self
}
protocol BaseElementProtocol: ElementProtocol where BaseElement == Self {}
protocol ArrayProtocol {
associatedtype Element: ElementProtocol
}
protocol NestedArrayProtocol: ArrayProtocol where Element: ArrayProtocol, Element.Element.BaseElement == Element.BaseElement {
associatedtype BaseElement = Element.BaseElement
}
extension Array: ArrayProtocol where Element: ElementProtocol {}
extension Array: NestedArrayProtocol where Element: ElementProtocol, Element: ArrayProtocol, Element.Element.BaseElement == Element.BaseElement {
// with the typealias uncommented you do not get a crash.
// typealias BaseElement = Element.BaseElement
}
// SR-8337
struct Foo<Bar> {}
protocol P {
associatedtype A
var foo: Foo<A> { get }
}
extension Foo: P where Bar: P {
var foo: Foo { return self }
}
// rdar://problem/47871590
extension BinaryInteger {
var foo: Self {
return self <= 1
? 1
: (2...self).reduce(1, *)
// expected-error@-1 {{referencing instance method 'reduce' on 'ClosedRange' requires that 'Self.Stride' conform to 'SignedInteger'}}
}
}
// SR-10992
protocol SR_10992_P {}
struct SR_10992_S<T> {}
extension SR_10992_S: SR_10992_P where T: SR_10992_P {} // expected-note {{requirement from conditional conformance of 'SR_10992_S<String>' to 'SR_10992_P'}}
func sr_10992_foo(_ fn: (SR_10992_S<String>) -> Void) {}
func sr_10992_bar(_ fn: (SR_10992_P) -> Void) {
sr_10992_foo(fn) // expected-error {{global function 'sr_10992_foo' requires that 'String' conform to 'SR_10992_P'}}
}
| apache-2.0 | 226e391699404c998b8e54edabdfc27a | 41.083527 | 179 | 0.707465 | 3.505605 | false | false | false | false |
glessard/swift-atomics | Xcode-Old/SwiftAtomicsTests/AtomicsPerformanceTests.swift | 1 | 2208 | //
// AtomicsPerformanceTests.swift
// AtomicsTests
//
// Copyright © 2015-2017 Guillaume Lessard. All rights reserved.
// This file is distributed under the BSD 3-clause license. See LICENSE for details.
//
import XCTest
import Atomics
public class AtomicsPerformanceTests: XCTestCase
{
let testLoopCount = 1_000_000
public func testPerformanceStore()
{
let c = testLoopCount
var m = AtomicInt()
measure {
m.store(0)
for i in 0..<c { m.store(i, order: .relaxed) }
}
}
public func testPerformanceSynchronizedStore()
{
let c = testLoopCount
var m = AtomicInt()
measure {
m.store(0)
for i in 0..<c { m.store(i, order: .sequential) }
}
}
public func testPerformanceRead()
{
let c = testLoopCount
var m = AtomicInt()
measure {
m.store(0)
for _ in 0..<c { _ = m.load(order: .relaxed) }
}
}
public func testPerformanceSynchronizedRead()
{
let c = testLoopCount
var m = AtomicInt()
measure {
m.store(0)
for _ in 0..<c { _ = m.load(order: .sequential) }
}
}
public func testPerformanceSwiftCASSuccess()
{
let c = Int32(testLoopCount)
var m = AtomicInt32()
measure {
m.store(0)
for i in (m.value)..<c { m.CAS(current: i, future: i&+1) }
}
}
public func testPerformanceOSAtomicCASSuccess()
{
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let c = Int32(testLoopCount)
var m = Int32()
measure {
m = 0
for i in m..<c { OSAtomicCompareAndSwap32(i, i&+1, &m) }
}
#else
print("test not supported on Linux")
#endif
}
public func testPerformanceSwiftCASFailure()
{
let c = Int32(testLoopCount)
var m = AtomicInt32()
measure {
m.store(0)
for i in (m.value)..<c { m.CAS(current: i, future: 0) }
}
}
public func testPerformanceOSAtomicCASFailure()
{
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let c = Int32(testLoopCount)
var m = Int32(0)
measure {
m = 0
for i in m..<c { OSAtomicCompareAndSwap32(i, 0, &m) }
}
#else
print("test not supported on Linux")
#endif
}
}
| bsd-3-clause | 5f9d5b4e3b89f22b8ce6991b92878e7c | 20.427184 | 85 | 0.584957 | 3.565428 | false | true | false | false |
Headmast/openfights | MoneyHelper/Library/BaseClasses/Network/ServerPart/ServerResponse.swift | 1 | 2826 | //
// ServerResponse.swift
// MoneyHelper
//
// Created by Kirill Klebanov on 16/09/2017.
// Copyright © 2017 Surf. All rights reserved.
//
import Foundation
import Alamofire
public class ServerError: LocalizedError {
private struct Keys {
public static let id = "id"
public static let message = "message"
}
private(set) var id: String
private(set) var message: String?
public init(id: String, message: String?) {
self.id = id
self.message = message
}
public convenience init?(with json: NSDictionary) {
guard let guardedId = json[Keys.id] as? String else {
return nil
}
self.init(id: guardedId, message: json[Keys.message] as? String)
}
public var errorDescription: String? {
return self.message
}
}
class ServerResponse: NSObject {
var httpResponse: HTTPURLResponse?
let statusCode: Int
var notModified: Bool
var connectionFailed: Bool
var result: ResponseResult<Any>
init(dataResponse: DefaultDataResponse?, dataResult: ResponseResult<Data?>) {
self.httpResponse = dataResponse?.response
self.statusCode = self.httpResponse?.statusCode ?? 0
self.notModified = self.statusCode == 304
self.connectionFailed = false
self.result = {
guard let data = dataResult.value else {
if let err = dataResult.error {
return .failure(err)
} else {
return .failure(BaseServerError.undefind)
}
}
do {
let object = try JSONSerialization.jsonObject(with: data ?? Data(), options: .allowFragments)
return .success(object, dataResult.isCached)
} catch {
return .failure(BaseServerError.internalServerError)
}
}()
// Ошибка в бизнес-логики приложения
if let dictionary = result.value as? NSDictionary {
if let errorDict = dictionary["error"] as? NSDictionary {
if let error = ServerError(with: errorDict) {
self.result = .failure(error)
} else {
self.result = .failure(BaseServerError.undefind)
}
return
}
}
if let dict = result.value as? NSDictionary {
if let body = dict["result"] {
self.result = .success(body, dataResult.isCached)
}
}
}
/// For creatin Cached responses
internal override init() {
self.statusCode = 200
self.notModified = true
self.connectionFailed = false
self.result = .failure(BaseCacheError.cantFindInCache)
super.init()
}
}
| apache-2.0 | 03fb6b901e6ebe022859fbebb7c61ae3 | 27.824742 | 109 | 0.575823 | 4.771331 | false | false | false | false |
kostya/benchmarks | matmul/matmul.swift | 1 | 2358 | // Written by Kajal Sinha; distributed under the MIT license
import Glibc
func matgen(_ n: Int, _ seed: Double) -> [[Double]] {
var a = Array(repeating: Array<Double>(repeating: 0, count: n), count: n)
let divideBy = Double(n)
let tmp = seed / divideBy / divideBy
for i in 0..<n {
for j in 0..<n {
a[i][j] = tmp * Double(i - j) * Double(i + j)
}
}
return a
}
func matmul(_ a : [[Double]], b : [[Double]]) ->[[Double]] {
let m = a.count
let n = a[0].count
let p = b[0].count
var x = Array(repeating: Array<Double>(repeating: 0, count: p), count: m)
var c = Array(repeating: Array<Double>(repeating: 0, count: n), count: p)
// Transpose
for i in 0..<n {
for j in 0..<p {
c[j][i] = b[i][j];
}
}
for i in 0..<m {
for j in 0..<p {
var s = 0.0
for k in 0..<n{
s += a[i][k] * c[j][k];
}
x[i][j] = s;
}
}
return x
}
func notify(_ msg: String) {
let sock = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
var serv_addr = (
sa_family_t(AF_INET),
in_port_t(htons(9001)),
in_addr(s_addr: 0),
(0,0,0,0,0,0,0,0))
inet_pton(AF_INET, "127.0.0.1", &serv_addr.2)
let len = MemoryLayout.stride(ofValue: serv_addr)
let rc = withUnsafePointer(to: &serv_addr) { ptr -> Int32 in
return ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) {
bptr in return connect(sock, bptr, socklen_t(len))
}
}
if rc == 0 {
msg.withCString { (cstr: UnsafePointer<Int8>) -> Void in
send(sock, cstr, Int(strlen(cstr)), 0)
close(sock)
}
}
}
func calc(_ n: Int) -> Double {
let size = n / 2 * 2
let a = matgen(size, 1.0)
let b = matgen(size, 2.0)
let x = matmul(a, b: b)
return x[size / 2][size / 2]
}
@main
struct Matmul {
static func main() {
let n = CommandLine.argc > 1 ? Int(CommandLine.arguments[1])! : 100
let left = calc(101)
let right = -18.67
if abs(left - right) > 0.1 {
fputs("\(left) != \(right)\n", stderr)
exit(EXIT_FAILURE)
}
notify("Swift\t\(getpid())")
let results = calc(n)
notify("stop")
print(results)
}
}
| mit | ccb7a49f03fec7f3a15f6821aae56c17 | 24.912088 | 77 | 0.49788 | 3.119048 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Step Providers/Descriptors/RSTBChoiceStepDescriptor.swift | 1 | 784 | //
// RSTBChoiceStepDescriptor.swift
// Pods
//
// Created by James Kizer on 1/9/17.
//
//
import Gloss
open class RSTBChoiceStepDescriptor<ChoiceItem: RSTBChoiceItemDescriptor>: RSTBQuestionStepDescriptor {
public let items: [ChoiceItem]
public let valueSuffix: String?
public let shuffleItems: Bool
public let maximumNumberOfItems: Int?
public required init?(json: JSON) {
guard let items: [ChoiceItem] = "items" <~~ json else {
return nil
}
self.items = items
self.valueSuffix = "valueSuffix" <~~ json
self.shuffleItems = "shuffleItems" <~~ json ?? false
self.maximumNumberOfItems = "maximumNumberOfItems" <~~ json
super.init(json: json)
}
}
| apache-2.0 | b09f9a3d53212038e88b33af73b3ca28 | 23.5 | 103 | 0.619898 | 4.404494 | false | false | false | false |
diesmal/thisorthat | ThisOrThat/Code/Services/TOTAPI/TOTAPIRouter.swift | 1 | 3182 | //
// TOTAPIRouter.swift
// ThisOrThat
//
// Created by Ilya Nikolaenko on 08/01/2017.
// Copyright © 2017 Ilya Nikolaenko. All rights reserved.
//
import Alamofire
enum TOTAPIRouter: URLRequestConvertible {
case authorization(parameters: Parameters)
case getQuestions(count: Int)
case sendAnswers(answers: Parameters)
case showQuestions(ids: [QuestionIdentificator])
case showUserQuestions
case sendUserQuestions(questions: Parameters)
case getComments(questionId: Int)
case sendComments(comments: Parameters)
static let baseURLString = TOTServer.path
static var OAuthToken: String?
static var OAuthUsername: String?
var method: HTTPMethod {
switch self {
case .authorization:
return .post
case .getQuestions:
return .get
case .sendAnswers:
return .post
case .showQuestions:
return .get
case .showUserQuestions:
return .get
case .sendUserQuestions:
return .post
case .getComments:
return .get
case .sendComments:
return .post
}
}
var path: String {
switch self {
case .authorization:
return "/users/add"
case .getQuestions(let count):
return "/items/get/\(count)"
case .sendAnswers:
return "/views/add"
case .showQuestions(let ids):
return "/items/show/" + ids.flatMap({ String(describing: $0) }).joined(separator: ",")
case .showUserQuestions:
return "/items/self"
case .sendUserQuestions:
return "/items/add"
case .getComments(let questionId):
return "/comments/show/\(questionId)"
case .sendComments:
return "/comments/add"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try TOTAPIRouter.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
if let username = TOTAPIRouter.OAuthUsername,
let token = TOTAPIRouter.OAuthToken {
let basicAuthCredentials = "\(username):\(token)"
let authData = Data(basicAuthCredentials.utf8).base64EncodedString()
urlRequest.setValue("Basic \(authData)", forHTTPHeaderField: "Authorization")
}
switch self {
case .authorization(let parameters):
urlRequest = try Alamofire.JSONEncoding.default.encode(urlRequest, with: parameters)
case .sendAnswers(let answers):
urlRequest = try Alamofire.JSONEncoding.default.encode(urlRequest, with: answers)
case .sendUserQuestions(let questions):
urlRequest = try Alamofire.JSONEncoding.default.encode(urlRequest, with: questions)
case .sendComments(let comments):
urlRequest = try Alamofire.JSONEncoding.default.encode(urlRequest, with: comments)
default:
break
}
return urlRequest
}
}
| apache-2.0 | 3d18544c343ebf63f0ff478ab92180f1 | 30.81 | 98 | 0.613015 | 5.057234 | false | false | false | false |
ixx1232/swiftStudy | swiftStudy/swiftStudyTests/03-for.playground/Contents.swift | 1 | 2710 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// OC 中的写法仍然可以使用, 不过有两个细节
// 1.没有括号
// 2. 没有语法提示
for var i = 0; i < 10; i++ {
print(i)
}
// Swift 中的标准写法
for i in 1..<10 {
print(i)
}
// 从 0 到 10, 一共 11
for i in 0...10{
print(i)
}
// 如果循环的时候, 对索引数字不需要, 可以使用"_" 忽略
for _ in 0...10 {
print("haha")
}
/**
swift中,不需要在每一个case后面增加break,执行完case对应的代码后默认会自动退出switch语句
swift中,每一个case后面必须有可以执行的语句
*/
let grade = "B"
switch grade {
case "A":
print("优秀等级")
case "B":
print("良好等级")
case "C":
print("中等等级")
default:
print("未知等级")
}
// swift中,每一个case后面可以填写多个匹配条件,条件之间用逗号,隔开
let score = 95
switch score/10 {
case 10, 9:
print("优秀")
case 8,7,6:
print("及格")
default:
print("不及格")
}
//swift中,case后面可以填写一个范围作为匹配条件,
//switch包保证处理所有可能的情况,不然编译器直接报错
// 因此,这里的default一定要加,不然就出现了一些处理不到的情况
let score1 = 95
switch score1 {
case 90...100:
print("优秀")
case 60...89:
print("及格")
default:
print("不及格")
}
// 在case匹配的同时,可以将switch中的值绑定给一个特定的常量或者变量,以便在case后面的语句中使用
let point = (10,0)
switch point {
case (let x, 0):
print("这个点在x轴上,x值是\(x)")
case (0, let y):
print("这个点在y轴上,y值是\(y)")
case let (x, y):
print("这个点的x值是\(x),y值是\(y)")
}
// switch语句可以使用where来增加判断的条件
var point1 = (10, -10)
switch point1 {
case let (x, y) where x == y :
print("这个点在绿线上")
case let (x, y) where x == -y :
print("这个点在紫线上")
default :
print("这个点不在这两条线上")
}
// fallthrough的作用
// 执行完当前case后,会接着执行fallthrough后面的case或者default语句
let num = 20
var str1 = "\(num)是个"
switch num {
case 0...50 :
str1 += "0~50之间的"
fallthrough
default:
str1 += "整数"
}
print(str1)
// 标签: 使用标签的其中1个作用:可以用于明确指定要退出哪个循环
// 做 2 组俯卧撑,没组 3 个, 做完一组就休息一会
group :
for _ in 1...2 {
for item in 1...3 {
print("做 1 个俯卧撑")
if item == 2 {
break group
}
}
print("休息一会")
} | mit | f83d8998ad31debb2b23a95ee5ecdbf1 | 14.908333 | 56 | 0.596436 | 2.430573 | false | false | false | false |
iusn/BJNumberPlateSwift | BJNumberPlateSwift/BJNumberPlateSwift.swift | 1 | 11870 | //
// BJNumberPlateSwift.swift
// BJNumberPlateSwift
//
// Created by Sun on 15/10/2016.
// Copyright © 2016 Sun. All rights reserved.
//
import UIKit
enum BJKeyboardButtonStyle{
case BJKeyboardButtonStyleProvince
case BJKeyboardButtonStyleLetter
case BJKeyboardButtonStyleDelegate
case BJKeyboardButtonStyleChange
}
class BJKeyboardButton: UIButton {
var style:BJKeyboardButtonStyle?
class func keyboardButtonWithStyle(buttonStyle:BJKeyboardButtonStyle) -> (BJKeyboardButton){
let button = BJKeyboardButton(type:UIButtonType.custom)
button.style = buttonStyle
return button
}
}
var currentFirstResponder:UIResponder?
extension UIResponder{
func BJFindFirstResponder(sender:Any){
currentFirstResponder = self
}
class func BJCurrentFirstResponder() -> (UIResponder){
currentFirstResponder = nil
UIApplication.shared.sendAction(#selector(BJFindFirstResponder(sender:)), to: nil, from: nil, for: nil)
return currentFirstResponder!
}
}
public class BJNumberPlate: UIInputView,UIInputViewAudioFeedback {
enum BJKeyboardStyle {
case BJKeyboardStyleProvince
case BJKeyboardStyleLetter
}
private let pArray = ["京","沪","津","渝","冀","晋","辽",
"吉","黑","苏","浙","皖","闽","赣",
"鲁","豫","鄂","湘","粤","琼","川",
"贵","云","陕","甘","青","蒙","桂",
"宁","新","藏","台","港","澳"]
private let lArray = ["1", "2", "3", "4", "5", "6", "7", "8",
"9", "0", "Q", "W", "E", "R", "T", "Y",
"U", "I", "O", "P", "A", "S", "D", "F",
"G", "H", "J", "K", "L", "Z", "X", "C",
"V", "B", "N", "M"]
private var isProvinceKeyBoard = true
private let buttonImage = UIImage(named:"key")
private var changeBtn:BJKeyboardButton?
private var deleteBtn:BJKeyboardButton?
private var buttonFont:UIFont?
private var width:CGFloat?
private var height:CGFloat?
private var provinceArr:Array<BJKeyboardButton>
private var letterArr:Array<BJKeyboardButton>
private var toolBarView:UIView?
private var donebutton:UIButton?
private let toolBarViewHeight:CGFloat = 35.0
private let kKeyHorizontalSpace:CGFloat = 2.0
private let kKeyVerticalSpace:CGFloat = 5.0
private var keyInput:UIKeyInput?
public init(){
self.provinceArr = [BJKeyboardButton]()
self.letterArr = [BJKeyboardButton]()
super.init(frame:CGRect.zero, inputViewStyle: UIInputViewStyle.keyboard)
buttonFont = UIFont.systemFont(ofSize: 18)
changeBtn = BJKeyboardButton(type:UIButtonType.custom)
changeBtn?.setTitle("ABC", for: .normal)
changeBtn?.style = .BJKeyboardButtonStyleChange
changeBtn = self.setButtonStyle(button: changeBtn!)
self.addSubview(changeBtn!)
deleteBtn = BJKeyboardButton(type:UIButtonType.custom)
deleteBtn?.setImage(UIImage(named:"[email protected]"), for: .normal)
deleteBtn?.style = .BJKeyboardButtonStyleDelegate
deleteBtn = self.setButtonStyle(button: deleteBtn!)
self.addSubview(deleteBtn!)
var tempArray = [BJKeyboardButton]()
for str in pArray {
var btn = BJKeyboardButton.keyboardButtonWithStyle(buttonStyle:.BJKeyboardButtonStyleProvince)
btn = self.setButtonStyle(button: btn)
btn.setTitle(str, for: .normal)
self.addSubview(btn)
tempArray.append(btn)
}
provinceArr = tempArray
tempArray = [BJKeyboardButton]()
for str in lArray {
var btn = BJKeyboardButton.keyboardButtonWithStyle(buttonStyle:.BJKeyboardButtonStyleLetter)
btn = self.setButtonStyle(button: btn)
btn.setTitle(str, for: .normal)
self.addSubview(btn)
tempArray.append(btn)
}
letterArr = tempArray
toolBarView = UIView()
toolBarView?.backgroundColor = self.RGBColor(R: 246.0, G: 246.0, B: 246.0)
self.addSubview(toolBarView!)
donebutton = UIButton(type:.custom)
donebutton?.setTitle("完成", for: .normal)
donebutton?.setTitleColor(UIColor.darkGray, for: .normal)
donebutton?.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
donebutton?.backgroundColor = UIColor.clear
donebutton?.addTarget(self, action: #selector(doneButtonAction(button:)), for: .touchUpInside)
toolBarView?.addSubview(donebutton!)
self.sizeToFit()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func layoutSubviews() {
super.layoutSubviews()
let bounds = self.bounds
self.width = bounds.size.width
self.height = bounds.size.height
toolBarView?.frame = CGRect(x:0,y:0,width:self.width!,height:toolBarViewHeight)
donebutton?.frame = CGRect(x:width! - 40 - 10,y:(toolBarViewHeight - 20)/2,width:40,height:20)
if isProvinceKeyBoard{
self.creatKeyBoardWithType(buttonType: .BJKeyboardStyleProvince, hidenOrNot: false)
}else{
self.creatKeyBoardWithType(buttonType: .BJKeyboardStyleLetter, hidenOrNot: false)
}
}
override public func sizeThatFits(_ size: CGSize) -> CGSize {
var tempSize = CGSize()
tempSize.width = UIScreen.main.bounds.width
tempSize.height = UIScreen.main.bounds.height <= 480 ?
UIScreen.main.bounds.height*0.4 :
UIScreen.main.bounds.height*0.35
tempSize.height = tempSize.height + toolBarViewHeight
return tempSize
}
private func creatKeyBoardWithType(buttonType type:BJKeyboardStyle , hidenOrNot hiden:Bool){
var array = [BJKeyboardButton]() //Array<BJKeyboardButton>
var buttonCount = 0
var tempW = 0.00
switch type {
case .BJKeyboardStyleProvince:
array = provinceArr
buttonCount = 28
tempW = 0.0
case .BJKeyboardStyleLetter:
array = letterArr
buttonCount = 29
tempW = 0.5
}
height = height! - toolBarViewHeight
let KeyWidth = (width!/10.0 - kKeyHorizontalSpace*2.0)
let KeyHeight = (height!/4.0 - kKeyVerticalSpace*2.0)
for index in 0...(array.count-1){
let btn = array[index]
btn.isHidden = hiden
var k = index
var j = index/10
if index >= 10 && index < buttonCount {
k = index % 10
}else if index >= buttonCount {
k = index - buttonCount
j = 3
}
if index < 20{
btn.frame = CGRect(x:kKeyHorizontalSpace + CGFloat(k)*(width!/10),
y:toolBarViewHeight+kKeyVerticalSpace + CGFloat(j)*(height! / 4),
width:KeyWidth,
height:KeyHeight)
}else if index < buttonCount{
btn.frame = CGRect(x:kKeyHorizontalSpace + (CGFloat(k+1)-CGFloat(tempW)) * (width!/10.0),
y:toolBarViewHeight+kKeyVerticalSpace + CGFloat(j)*(height!/4),
width:KeyWidth,
height:KeyHeight)
}else{
btn.frame = CGRect(x:kKeyHorizontalSpace + (CGFloat(k+2)-CGFloat(tempW))*(width!/10),
y:toolBarViewHeight+kKeyVerticalSpace + CGFloat(j)*(height!/4),
width:KeyWidth,
height:KeyHeight)
}
}
deleteBtn?.frame = CGRect(x:width! - KeyWidth*1.5 - kKeyHorizontalSpace,
y:height! - KeyHeight - kKeyVerticalSpace+toolBarViewHeight,
width:KeyWidth*1.5,
height:KeyHeight)
changeBtn?.frame = CGRect(x:kKeyHorizontalSpace,
y:height! - KeyHeight - kKeyVerticalSpace+toolBarViewHeight,
width:KeyWidth * 1.5,
height:KeyHeight)
}
private func setButtonStyle(button:BJKeyboardButton) -> (BJKeyboardButton){
button.isExclusiveTouch = true
button.backgroundColor = UIColor.clear
button.setBackgroundImage(buttonImage, for: .normal)
button.setTitleColor(UIColor.darkGray, for: .normal)
button.titleLabel?.font = buttonFont
button.addTarget(self,
action: #selector(buttonInput(button:)),
for: .touchUpInside)
button.addTarget(self,
action: #selector(buttonPlayClick(button:)),
for: .touchDown)
return button
}
func buttonInput(button:BJKeyboardButton){
keyInput = findKeyInput()
if keyInput == nil{
return
}
if button.style == .BJKeyboardButtonStyleProvince ||
button.style == .BJKeyboardButtonStyleLetter{
keyInput?.insertText((button.titleLabel?.text)!)
}else if button.style == .BJKeyboardButtonStyleDelegate{
keyInput?.deleteBackward()
}else if button.style == .BJKeyboardButtonStyleChange{
isProvinceKeyBoard = !isProvinceKeyBoard
for case let btn as BJKeyboardButton in self.subviews{
if isProvinceKeyBoard{
if btn.style == .BJKeyboardButtonStyleLetter{
self.creatKeyBoardWithType(buttonType: .BJKeyboardStyleLetter, hidenOrNot: true)
}else if btn.style == .BJKeyboardButtonStyleProvince{
self.creatKeyBoardWithType(buttonType: .BJKeyboardStyleProvince, hidenOrNot: false)
}
}else{
if btn.style == .BJKeyboardButtonStyleProvince{
self.creatKeyBoardWithType(buttonType: .BJKeyboardStyleProvince, hidenOrNot: true)
}else if btn.style == .BJKeyboardButtonStyleLetter{
self.creatKeyBoardWithType(buttonType: .BJKeyboardStyleLetter, hidenOrNot: false)
}
}
}
if isProvinceKeyBoard{
changeBtn?.setTitle("ABC", for: .normal)
}else{
changeBtn?.setTitle("省份", for: .normal)
}
}
}
func findKeyInput() ->(UIKeyInput?){
keyInput = UIResponder.BJCurrentFirstResponder() as? UIKeyInput
if (keyInput?.conforms(to:UITextInput.self))!{
return keyInput
}else{
return nil
}
}
func buttonPlayClick(button:BJKeyboardButton){
UIDevice.current.playInputClick()
}
public var enableInputClicksWhenVisible: Bool {
return true
}
func doneButtonAction(button:UIButton){
if UIResponder.BJCurrentFirstResponder().isFirstResponder{
UIResponder.BJCurrentFirstResponder().resignFirstResponder()
}else{
print("BJNumberPlate>>>>Not Find First responder")
}
}
private func RGBColor(R r:CGFloat,G g:CGFloat,B b:CGFloat) ->(UIColor){
let color = UIColor(red:r/255.0,green:g/255.0,blue:b/255.0,alpha:1.0)
return color
}
}
| mit | 703c30729008e80e5a0810b57c39371e | 38.573826 | 111 | 0.575172 | 5.022572 | false | false | false | false |
CrowdShelf/ios | CrowdShelf/CrowdShelf/ViewControllers/BookInformationViewController.swift | 1 | 1540 | //
// CSBookInformationViewController.swift
// CrowdShelf
//
// Created by Øyvind Grimnes on 23/09/15.
// Copyright © 2015 Øyvind Grimnes. All rights reserved.
//
import UIKit
class BookInformationViewController: BaseViewController {
@IBOutlet weak var authorsLabel: UILabel?
@IBOutlet weak var publisherLabel: UILabel?
@IBOutlet weak var isbnLabel: UILabel?
@IBOutlet weak var pageCountLabel: UILabel?
@IBOutlet weak var thumbnailImage: UIImageView?
@IBOutlet weak var summaryTextArea: UITextView?
@IBOutlet weak var backgroundImage: UIImageView?
var bookInformation: BookInformation? {
didSet {
self.updateView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.thumbnailImage?.layer.borderWidth = 1
self.thumbnailImage?.layer.borderColor = UIColor.lightGrayColor().CGColor
self.updateView()
}
func updateView() {
self.title = self.bookInformation?.title
self.authorsLabel?.text = self.bookInformation?.authors.joinWithSeparator(", ")
self.publisherLabel?.text = self.bookInformation?.publisher
self.isbnLabel?.text = self.bookInformation?.isbn
self.pageCountLabel?.text = "\(self.bookInformation?.numberOfPages ?? 0)"
self.thumbnailImage?.image = self.bookInformation?.thumbnail
self.backgroundImage?.image = self.bookInformation?.thumbnail
self.summaryTextArea?.text = self.bookInformation?.summary
}
} | mit | fe498288b5074b1be2c865e35749c88c | 31.723404 | 87 | 0.683149 | 5.072607 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Easy/Easy_102_Binary_Tree_Level_Order_Traversal.swift | 1 | 1582 | /*
https://leetcode.com/problems/binary-tree-level-order-traversal/
#102 Binary Tree Level Order Traversal
Level: easy
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Inspired by [@d40a](https://discuss.leetcode.com/topic/2399/it-is-my-ac-solution)
*/
import Foundation
class Easy_102_Binary_Tree_Level_Order_Traversal {
class Node {
var left: Node?
var right: Node?
var value: Int
init(value v: Int, left l: Node?, right r: Node?) {
self.value = v
self.left = l
self.right = r
}
}
// t = O(N), best s = O(logN), worst s = O(N)
class func levelOrder(_ root: Node?) -> [[Int]] {
guard let unwrappedRoot = root else {
return []
}
var ret: [[Int]] = []
var queue: [(Node, Int)] = [(unwrappedRoot, 0)]
while let pair: (node: Node, index: Int) = queue.first {
if ret.count <= pair.index {
ret.append([Int]())
}
ret[pair.index].append(pair.node.value)
if let l = pair.node.left {
queue.append((l, pair.index + 1))
}
if let r = pair.node.right {
queue.append((r, pair.index + 1))
}
_ = queue.removeFirst()
}
return ret
}
}
| mit | 59e1a49ff1bfbcd7bb4a0e35299f864e | 24.111111 | 117 | 0.518331 | 3.53125 | false | false | false | false |
elpassion/el-space-ios | ELSpace/Screens/Hub/Activity/ProjectSearch/ProjectSearchViewModel.swift | 1 | 2017 | import RxSwift
import RxCocoa
protocol ProjectSearchViewModelProtocol {
var selectedProjectId: Int? { get }
var projects: Driver<[ProjectDTO]> { get }
var searchText: AnyObserver<String> { get }
var selectProject: AnyObserver<ProjectDTO> { get }
var didSelectProject: Driver<ProjectDTO> { get }
}
class ProjectSearchViewModel: ProjectSearchViewModelProtocol {
init(projectId: Int?,
projectSearchController: ProjectSearchControlling) {
self.selectedProjectId = projectId
self.projectSearchController = projectSearchController
fetchData()
}
let selectedProjectId: Int?
var projects: Driver<[ProjectDTO]> {
return projectsRelay.asDriver(onErrorDriveWith: .empty())
}
var searchText: AnyObserver<String> {
return AnyObserver(onNext: { [weak self] in self?.searchTextString = $0 })
}
var selectProject: AnyObserver<ProjectDTO> {
return selectedProjectSubject.asObserver()
}
var didSelectProject: Driver<ProjectDTO> {
return selectedProjectSubject.asDriver(onErrorDriveWith: .never())
}
// MARK: Privates
private let disposeBag = DisposeBag()
private let projectSearchController: ProjectSearchControlling
private let projectsRelay = PublishRelay<[ProjectDTO]>()
private let selectedProjectSubject = PublishSubject<ProjectDTO>()
private var allProjects: [ProjectDTO] = [] {
didSet { projectsRelay.accept(allProjects) }
}
private var searchTextString: String? {
didSet {
if let searchTextString = searchTextString {
searchTextString != "" ? projectsRelay.accept(allProjects.filter { $0.name.lowercased() .contains(searchTextString.lowercased()) }) : projectsRelay.accept(allProjects)
}
}
}
private func fetchData() {
projectSearchController.projects
.subscribe(onNext: { [weak self] in self?.allProjects = $0 })
.disposed(by: disposeBag)
}
}
| gpl-3.0 | b39d2e092a192e918a50486ccbdc1183 | 30.515625 | 183 | 0.68121 | 5.106329 | false | false | false | false |
ahoppen/swift | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-clang_node-1distinct_use.swift | 19 | 1662 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays(mock-sdk-directory: %S/../Inputs)
// REQUIRES: VENDOR=apple || OS=linux-gnu
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs -I %t) -prespecialize-generic-metadata -target %module-target-future -primary-file %s -emit-ir | %FileCheck %s -DINT=i%target-ptrsize
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// REQUIRES: objc_interop
import Foundation
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
struct Value<T> {
let value: T
init(_ value: T) {
self.value = value
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[TYPE:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s4main5ValueVySo12NSDictionaryCGMD") #{{[0-9]+}}
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[TYPE]])
// CHECK: }
func doit() {
consume(Value(NSDictionary()))
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 21af40af30fa6fdfde3879860d7f4052 | 37.651163 | 257 | 0.646209 | 3.159696 | false | false | false | false |
arvedviehweger/swift | benchmark/single-source/DictionaryRemove.swift | 3 | 2199 | //===--- DictionaryRemove.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Dictionary element removal benchmark
// rdar://problem/19804127
import TestsUtils
@inline(never)
public func run_DictionaryRemove(_ N: Int) {
let size = 100
var dict = [Int: Int](minimumCapacity: size)
// Fill dictionary
for i in 1...size {
dict[i] = i
}
CheckResults(dict.count == size,
"Incorrect dict count: \(dict.count) != \(size).")
var tmpDict = dict
for _ in 1...1000*N {
tmpDict = dict
// Empty dictionary
for i in 1...size {
tmpDict.removeValue(forKey: i)
}
if !tmpDict.isEmpty {
break
}
}
CheckResults(tmpDict.isEmpty,
"tmpDict should be empty: \(tmpDict.count) != 0.")
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionaryRemoveOfObjects(_ N: Int) {
let size = 100
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)
// Fill dictionary
for i in 1...size {
dict[Box(i)] = Box(i)
}
CheckResults(dict.count == size,
"Incorrect dict count: \(dict.count) != \(size).")
var tmpDict = dict
for _ in 1...1000*N {
tmpDict = dict
// Empty dictionary
for i in 1...size {
tmpDict.removeValue(forKey: Box(i))
}
if !tmpDict.isEmpty {
break
}
}
CheckResults(tmpDict.isEmpty,
"tmpDict should be empty: \(tmpDict.count) != 0.")
}
| apache-2.0 | 914fc9d5cf98b5d34fe936529d88a866 | 24.275862 | 80 | 0.544793 | 4.212644 | false | false | false | false |
alimysoyang/CommunicationDebugger | CommunicationDebugger/AYHMessageCell.swift | 1 | 3704 | //
// AYHMessageCell.swift
// CommunicationDebugger
//
// Created by alimysoyang on 15/11/26.
// Copyright © 2015年 alimysoyang. All rights reserved.
//
import Foundation
/**
* 自定义消息Cell组件,包括时间,消息,头像
*/
class AYHMessageCell: UITableViewCell
{
// MARK: - properties
var index:Int?;
var message:AYHMessage? {
didSet {
if let _ = self.message
{
if (self.message!.isEdit)
{
self.selectionStyle = UITableViewCellSelectionStyle.Default;
}
else
{
self.selectionStyle = UITableViewCellSelectionStyle.None;
}
self.messageTimeView?.message = self.message;
self.messageIconView?.message = self.message;
self.messageContentView?.message = self.message;
}
}
}
private var messageTimeView:AYHMessageTimeView?;
private var messageIconView:AYHMessageIconView?;
private var messageContentView:AYHMessageContentView?;
// MARK: - life cycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.backgroundColor = UIColor.clearColor();
self.initViews();
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
deinit
{
}
override func canBecomeFirstResponder() -> Bool {
return true;
}
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if (action == Selector("deleteMenuItemClicked") || action == Selector("copyMenuItemClicked"))
{
return true;
}
return false;
}
// MARK: - public methods
// MARK: - event response
internal func deleteMenuItemClicked()
{
AYHDBHelper.sharedInstance.deleteMessage(AYHCMParams.sharedInstance.socketType, msgID: self.message?.msgID, index: self.index);
}
internal func copyMenuItemClicked()
{
let pasteboard:UIPasteboard = UIPasteboard.generalPasteboard();
pasteboard.string = self.message?.msgContent;
}
internal func handlerTapPressGestureRecognizer(sender:UITapGestureRecognizer)
{
self.becomeFirstResponder();
let deleteMenuItem:UIMenuItem = UIMenuItem(title: NSLocalizedString("Delete", comment: ""), action: Selector("deleteMenuItemClicked"));
let copyMenuItem:UIMenuItem = UIMenuItem(title: NSLocalizedString("Copy", comment: ""), action: Selector("copyMenuItemClicked"));
let menuController:UIMenuController = UIMenuController.sharedMenuController();
menuController.menuItems = [deleteMenuItem, copyMenuItem];
menuController.setTargetRect(self.messageContentView!.frame, inView: self);
menuController.setMenuVisible(true, animated: true);
}
// MARK: - delegate
// MARK: - private methods
private func initViews()
{
self.messageTimeView = AYHMessageTimeView(frame: CGRectZero);
self.messageIconView = AYHMessageIconView(frame: CGRectZero);
self.messageContentView = AYHMessageContentView(frame: CGRectZero);
self.addSubview(self.messageTimeView!);
self.addSubview(self.messageIconView!);
self.addSubview(self.messageContentView!);
let tapGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handlerTapPressGestureRecognizer:"));
self.messageContentView?.addGestureRecognizer(tapGestureRecognizer);
}
} | mit | 55a7c37516866f46de8340b9db307ffb | 33.261682 | 150 | 0.651842 | 5.2886 | false | false | false | false |
huonw/swift | test/SILGen/property_abstraction.swift | 1 | 6172 |
// RUN: %target-swift-emit-silgen -module-name property_abstraction -enable-sil-ownership %s | %FileCheck %s
struct Int {
mutating func foo() {}
}
struct Foo<T, U> {
var f: (T) -> U
var g: T
}
// CHECK-LABEL: sil hidden @$S20property_abstraction4getF{{[_0-9a-zA-Z]*}}Foo{{.*}}F : $@convention(thin) (@guaranteed Foo<Int, Int>) -> @owned @callee_guaranteed (Int) -> Int {
// CHECK: bb0([[X_ORIG:%.*]] : @guaranteed $Foo<Int, Int>):
// CHECK: [[F_ORIG:%.*]] = struct_extract [[X_ORIG]] : $Foo<Int, Int>, #Foo.f
// CHECK: [[F_ORIG_COPY:%.*]] = copy_value [[F_ORIG]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]([[F_ORIG_COPY]])
// CHECK: return [[F_SUBST]]
// CHECK: } // end sil function '$S20property_abstraction4getF{{[_0-9a-zA-Z]*}}F'
func getF(_ x: Foo<Int, Int>) -> (Int) -> Int {
return x.f
}
// CHECK-LABEL: sil hidden @$S20property_abstraction4setF{{[_0-9a-zA-Z]*}}F
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_ORIG:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]({{%.*}})
// CHECK: [[F_ADDR:%.*]] = struct_element_addr {{%.*}} : $*Foo<Int, Int>, #Foo.f
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
func setF(_ x: inout Foo<Int, Int>, f: @escaping (Int) -> Int) {
x.f = f
}
func inOutFunc(_ f: inout ((Int) -> Int)) { }
// CHECK-LABEL: sil hidden @$S20property_abstraction6inOutF{{[_0-9a-zA-Z]*}}F :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Foo<Int, Int>):
// CHECK: [[XBOX:%.*]] = alloc_box ${ var Foo<Int, Int> }, var, name "x"
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] : ${ var Foo<Int, Int> }, 0
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[XBOX_PB]] : $*Foo<Int, Int>
// CHECK: [[F_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*Foo<Int, Int>, #Foo.f
// CHECK: [[F_SUBST_MAT:%.*]] = alloc_stack
// CHECK: [[F_ORIG:%.*]] = load [copy] [[F_ADDR]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_SUBST_IN:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]([[F_ORIG]])
// CHECK: store [[F_SUBST_IN]] to [init] [[F_SUBST_MAT]]
// CHECK: [[INOUTFUNC:%.*]] = function_ref @$S20property_abstraction9inOutFunc{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[INOUTFUNC]]([[F_SUBST_MAT]])
// CHECK: [[F_SUBST_OUT:%.*]] = load [take] [[F_SUBST_MAT]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F_ORIG:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_FN]]([[F_SUBST_OUT]])
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
// CHECK: destroy_value [[XBOX]]
// CHECK: } // end sil function '$S20property_abstraction6inOutF{{[_0-9a-zA-Z]*}}F'
func inOutF(_ x: Foo<Int, Int>) {
var x = x
inOutFunc(&x.f)
}
// Don't produce a writeback for generic lvalues when there's no real
// abstraction difference. <rdar://problem/16530674>
// CHECK-LABEL: sil hidden @$S20property_abstraction23noAbstractionDifference{{[_0-9a-zA-Z]*}}F
func noAbstractionDifference(_ x: Foo<Int, Int>) {
var x = x
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}}, #Foo.g
// CHECK: apply {{%.*}}([[ADDR]])
x.g.foo()
}
protocol P {}
struct AddressOnlyLet<T> {
let f: (T) -> T
let makeAddressOnly: P
}
// CHECK-LABEL: sil hidden @$S20property_abstraction34getAddressOnlyReabstractedProperty{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in_guaranteed AddressOnlyLet<Int>) -> @owned @callee_guaranteed (Int) -> Int
// CHECK: bb0([[ARG:%.*]] : @trivial $*AddressOnlyLet<Int>):
// CHECK: [[CLOSURE_ADDR:%.*]] = struct_element_addr {{%.*}} : $*AddressOnlyLet<Int>, #AddressOnlyLet.f
// CHECK: [[CLOSURE_ORIG:%.*]] = load [copy] [[CLOSURE_ADDR]]
// CHECK: [[REABSTRACT:%.*]] = function_ref
// CHECK: [[CLOSURE_SUBST:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[CLOSURE_ORIG]])
// CHECK-NOT: destroy_addr [[ARG]]
// CHECK: return [[CLOSURE_SUBST]]
// CHECK: } // end sil function '$S20property_abstraction34getAddressOnlyReabstractedProperty{{[_0-9a-zA-Z]*}}F'
func getAddressOnlyReabstractedProperty(_ x: AddressOnlyLet<Int>) -> (Int) -> Int {
return x.f
}
enum Bar<T, U> {
case F((T) -> U)
}
func getF(_ x: Bar<Int, Int>) -> (Int) -> Int {
switch x {
case .F(var f):
return f
}
}
func makeF(_ f: @escaping (Int) -> Int) -> Bar<Int, Int> {
return Bar.F(f)
}
struct ArrayLike<T> {
subscript(x: ()) -> T { get {} set {} }
}
typealias Test20341012 = (title: (), action: () -> ())
struct T20341012 {
private var options: ArrayLike<Test20341012> { get {} set {} }
// CHECK-LABEL: sil hidden @$S20property_abstraction9T20341012V1t{{[_0-9a-zA-Z]*}}F
// CHECK: [[TMP1:%.*]] = alloc_stack $(title: (), action: @callee_guaranteed (@in_guaranteed ()) -> @out ())
// CHECK: apply {{.*}}<(title: (), action: () -> ())>([[TMP1]],
mutating func t() {
_ = self.options[].title
}
}
class MyClass {}
// When simply assigning to a property, reabstract the r-value and assign
// to the base instead of materializing and then assigning.
protocol Factory {
associatedtype Product
var builder : () -> Product { get set }
}
func setBuilder<F: Factory>(_ factory: inout F) where F.Product == MyClass {
factory.builder = { return MyClass() }
}
// CHECK: sil hidden @$S20property_abstraction10setBuilder{{[_0-9a-zA-Z]*}}F : $@convention(thin) <F where F : Factory, F.Product == MyClass> (@inout F) -> ()
// CHECK: bb0(%0 : @trivial $*F):
// CHECK: [[F0:%.*]] = function_ref @$S20property_abstraction10setBuilder{{[_0-9a-zA-Z]*}} : $@convention(thin) () -> @owned MyClass
// CHECK: [[F1:%.*]] = thin_to_thick_function [[F0]]
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @$S{{.*}}TR :
// CHECK: [[F2:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[F1]])
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*F
// CHECK: [[SETTER:%.*]] = witness_method $F, #Factory.builder!setter.1
// CHECK: apply [[SETTER]]<F>([[F2]], [[WRITE]])
| apache-2.0 | 7125e2f207d0a4e20bbf985bbb1bcb8b | 41.861111 | 206 | 0.583603 | 3.136179 | false | false | false | false |
danielcwj16/ConnectedAlarmApp | Pods/SwiftAddressBook/Pod/Classes/SwiftAddressBookDataStructures.swift | 2 | 5447 | //
// SwiftAddressBookDataStructures.swift
// Pods
//
// Created by Socialbit - Tassilo Karge on 09.03.15.
//
//
import Foundation
import AddressBook
@available(iOS, deprecated: 9.0)
//MARK: multivalue entry for multivalue properties
public struct MultivalueEntry<T> {
public var value : T
public var label : String?
public let id : Int
public init(value: T, label: String?, id: Int) {
self.value = value
self.label = label
self.id = id
}
}
//MARK: swift structs for convenience
public enum SwiftAddressBookOrdering {
case lastName, firstName
init(ordering : ABPersonSortOrdering) {
switch Int(ordering) {
case kABPersonSortByLastName :
self = .lastName
case kABPersonSortByFirstName :
self = .firstName
default :
self = .firstName
}
}
public var abPersonSortOrderingValue : UInt32 {
get {
switch self {
case .lastName :
return UInt32(kABPersonSortByLastName)
case .firstName :
return UInt32(kABPersonSortByFirstName)
}
}
}
}
public enum SwiftAddressBookCompositeNameFormat {
case firstNameFirst, lastNameFirst
init(format : ABPersonCompositeNameFormat) {
switch Int(format) {
case kABPersonCompositeNameFormatFirstNameFirst :
self = .firstNameFirst
case kABPersonCompositeNameFormatLastNameFirst :
self = .lastNameFirst
default :
self = .firstNameFirst
}
}
}
public enum SwiftAddressBookRecordType {
case source, group, person
init(abRecordType : ABRecordType) {
switch Int(abRecordType) {
case kABSourceType :
self = .source
case kABGroupType :
self = .group
default :
self = .person
}
}
}
public enum SwiftAddressBookSourceType {
case local, exchange, exchangeGAL, mobileMe, ldap, cardDAV, cardDAVSearch
init(abSourceType : ABSourceType) {
switch Int(abSourceType) {
case kABSourceTypeLocal :
self = .local
case kABSourceTypeExchange :
self = .exchange
case kABSourceTypeExchangeGAL :
self = .exchangeGAL
case kABSourceTypeMobileMe :
self = .mobileMe
case kABSourceTypeLDAP :
self = .ldap
case kABSourceTypeCardDAV :
self = .cardDAV
case kABSourceTypeCardDAVSearch :
self = .cardDAVSearch
default :
self = .local
}
}
}
public enum SwiftAddressBookPersonImageFormat {
case thumbnail
case originalSize
public var abPersonImageFormat : ABPersonImageFormat {
switch self {
case .thumbnail :
return kABPersonImageFormatThumbnail
case .originalSize :
return kABPersonImageFormatOriginalSize
}
}
}
public enum SwiftAddressBookSocialProfileProperty {
case url, service, username, userIdentifier
init(property : String) {
switch property {
case String(kABPersonSocialProfileURLKey) :
self = .url
case String(kABPersonSocialProfileServiceKey) :
self = .service
case String(kABPersonSocialProfileUsernameKey) :
self = .username
case String(kABPersonSocialProfileUserIdentifierKey) :
self = .userIdentifier
default :
self = .url
}
}
public var abSocialProfileProperty : String {
switch self {
case .url :
return String(kABPersonSocialProfileURLKey)
case .service :
return String(kABPersonSocialProfileServiceKey)
case .username :
return String(kABPersonSocialProfileUsernameKey)
case .userIdentifier :
return String(kABPersonSocialProfileUserIdentifierKey)
}
}
}
public enum SwiftAddressBookInstantMessagingProperty {
case service, username
init(property : String) {
switch property {
case String(kABPersonInstantMessageServiceKey) :
self = .service
case String(kABPersonInstantMessageUsernameKey) :
self = .username
default :
self = .service
}
}
public var abInstantMessageProperty : String {
switch self {
case .service :
return String(kABPersonInstantMessageServiceKey)
case .username :
return String(kABPersonInstantMessageUsernameKey)
}
}
}
public enum SwiftAddressBookPersonType {
case person, organization
init(type : CFNumber?) {
let typeNumber = type as NSNumber?
if typeNumber?.compare(kABPersonKindPerson).rawValue == 0 {
self = .person
}
else if typeNumber?.compare(kABPersonKindOrganization).rawValue == 0 {
self = .organization
}
else {
self = .person
}
}
public var abPersonType : CFNumber {
get {
switch self {
case .person :
return kABPersonKindPerson
case .organization :
return kABPersonKindOrganization
}
}
}
}
public enum SwiftAddressBookAddressProperty {
case street, city, state, zip, country, countryCode
init(property : String) {
switch property {
case String(kABPersonAddressStreetKey):
self = .street
case String(kABPersonAddressCityKey):
self = .city
case String(kABPersonAddressStateKey):
self = .state
case String(kABPersonAddressZIPKey):
self = .zip
case String(kABPersonAddressCountryKey):
self = .country
case String(kABPersonAddressCountryCodeKey):
self = .countryCode
default:
self = .street
}
}
public var abAddressProperty : String {
get {
switch self {
case .street :
return String(kABPersonAddressStreetKey)
case .city :
return String(kABPersonAddressCityKey)
case .state :
return String(kABPersonAddressStateKey)
case .zip :
return String(kABPersonAddressZIPKey)
case .country :
return String(kABPersonAddressCountryKey)
case .countryCode :
return String(kABPersonAddressCountryCodeKey)
}
}
}
}
| mit | 60d8a2339c3f343b5149be2f45d43f33 | 20.360784 | 74 | 0.720029 | 3.899069 | false | false | false | false |
eliasbloemendaal/KITEGURU | KITEGURU/KITEGURU/SignIn.swift | 1 | 1348 | //
// SignIn.swift
// KITEGURU
//
// Created by Elias Houttuijn Bloemendaal on 14-01-16.
// Copyright © 2016 Elias Houttuijn Bloemendaal. All rights reserved.
//
import Foundation
import UIKit
typealias userHandler = (user: PFUser?, error: NSError?)
// https://github.com/kevincaughman/Resume-App/tree/master/Models
//
class SignIn {
var logIn: Bool = false
// Een check of the fields niet leeg zijn
static func hasEmptyFields(userName: String, password: String) -> Bool {
if userName.isEmpty || password.isEmpty {
return true
}
return false
}
// Gebruik de username om in te loggen
static func loginUserAsync(userName: String, password: String, completion:(success:Bool) -> Void)
{
let logIn = false
PFUser.logInWithUsernameInBackground(userName, password: password)
{ (user: PFUser?, error: NSError?) -> Void in
if error == nil {
completion(success: true)
let login = true
print(login)
}
else {
completion(success: false)
let login = false
print(login)
}
}
print(logIn)
}
}
| mit | 2fb26e2f71b45ddbd910bdc44457493a | 24.903846 | 101 | 0.536748 | 4.628866 | false | false | false | false |
DerekYuYi/Ant | MyPlayground.playground/Pages/Subscripts.xcplaygroundpage/Contents.swift | 1 | 2138 | //: [Previous](@previous)
import Foundation
var str = "Hello, Subscripts"
//: https://docs.swift.org/swift-book/LanguageGuide/Methods.html
//: [Next](@next)
//: - Summary
/**
- 让开发者可以通过 `[]` 的形式去查询某个类型实例的值
- 类, 结构体 和 枚举都可以使用下标, 常用于集合(collection), list(表), sequence(序列)
- 设置或者解析值功能来代替: 某些需要单独的方法来设置或者解析值的功能
定义关键字: subscript
***/
// read-write for computed properties
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
// read-only computed properties
subscript(index: Int) -> Int {
// return an appropriate subscript value here
}
/*
n倍乘法表
*/
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int { // read-only computed properties
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 6)
print("six times three is \(threeTimesTable[6])")
//: - Subscript Options
///: subscript overloading(下标运算符重载): 多个下标运算符的定义
/*
通过下标来取二维矩阵中的每个值
*/
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >=0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range.")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range.")
grid[(row * columns) + column] = newValue
}
}
}
// create a matrix (2*2)
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
| mit | 4a911d036729c3fe07298da678c84230 | 21.666667 | 81 | 0.605567 | 3.519409 | false | false | false | false |
sheepy1/SelectionOfZhihu | SelectionOfZhihu/HTTPManager.swift | 1 | 1697 | //
// HTTPManager.swift
// SelectionOfZhihu
//
// Created by 杨洋 on 15/12/23.
// Copyright © 2015年 Sheepy. All rights reserved.
//
import Foundation
//enum HTTPError: ErrorType {
// case InvalidURL
// case NoParameter
//}
enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
}
typealias CompletionHandler = (data: NSData?) -> ()
func getDataFromUrl(urlString: String, method: HTTPMethod, parameter: [String: AnyObject]?, completionHandler: CompletionHandler) -> NSURLSessionDataTask? {
guard let url = NSURL(string: urlString) else {
print("URL error: \(urlString)")
return nil
}
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method.rawValue
switch method {
case .POST, .PUT:
if let param = parameter {
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(param, options: NSJSONWritingOptions.init(rawValue: 0))
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
}
request.addValue("application/json", forHTTPHeaderField: "Accept")
default:
break
}
let task = session.dataTaskWithRequest(request) {data, response, error in
//NSSession会默认开启一个后台队列,所以UI操作要调度回主队列进行。
dispatch_async(dispatch_get_main_queue()) {
if let e = error {
print(e)
return
}
completionHandler(data: data)
}
}
//启动
task.resume()
return task
}
| mit | 596481c70537e0b9aff842fa2cd9b1ab | 25.354839 | 156 | 0.622399 | 4.334218 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/TableViewController/Tasks/ToDoTableViewController.swift | 1 | 1712 | //
// ToDoTableViewController.swift
// Habitica
//
// Created by Elliot Schrock on 6/7/18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import UIKit
class ToDoTableViewController: TaskTableViewController {
override func viewDidLoad() {
readableName = L10n.Tasks.todo
typeName = "todo"
dataSource = TodoTableViewDataSource(predicate: getPredicate())
super.viewDidLoad()
dataSource?.emptyDataSource = SingleItemTableViewDataSource<EmptyTableViewCell>(cellIdentifier: "emptyCell", styleFunction: EmptyTableViewCell.todoStyle)
self.tutorialIdentifier = "todos"
configureTitle(L10n.Tasks.todos)
}
override func getDefinitonForTutorial(_ tutorialIdentifier: String) -> [AnyHashable: Any]? {
if tutorialIdentifier == "todos" {
let localizedStringArray = [L10n.Tutorials.todos1, L10n.Tutorials.todos2]
return ["textList": localizedStringArray]
}
return super.getDefinitonForTutorial(tutorialIdentifier)
}
override func getCellNibName() -> String {
return "ToDoTableViewCell"
}
func clearCompletedTasks(tapRecognizer: UITapGestureRecognizer) {
dataSource?.clearCompletedTodos()
}
override func refresh() {
dataSource?.retrieveData(completed: { [weak self] in
self?.refreshControl?.endRefreshing()
if self?.filterType == 2 {
self?.dataSource?.fetchCompletedTodos()
}
})
}
override func didChangeFilter() {
super.didChangeFilter()
if filterType == 2 {
dataSource?.fetchCompletedTodos()
}
}
}
| gpl-3.0 | 9f1973190f6aa7f206ccdd4f484f8aa3 | 30.109091 | 161 | 0.645237 | 4.930836 | false | false | false | false |
0x4a616e/ArtlessEdit | ArtlessEdit/EditorFileSettings.swift | 1 | 1291 | //
// EditorFileSettings.swift
// ArtlessEdit
//
// Created by Jan Gassen on 28/12/14.
// Copyright (c) 2014 Jan Gassen. All rights reserved.
//
import Foundation
class EditorFileSettings {
private var mode: String? = nil;
private let defaultSettings: EditorDefaultSettings
private let aceView: ACEView
private let document: NSDocument
init(aceView: ACEView, document: NSDocument, defaultSettings: EditorDefaultSettings) {
self.defaultSettings = defaultSettings
self.aceView = aceView
self.document = document
mode = defaultSettings.mode
updateView()
}
func setMode(mode: String?) {
self.mode = mode
updateView()
defaultSettings.setMode(mode)
}
func setLineEndings(mode: String) {
aceView.setNewLineMode(mode.lowercaseString)
document.updateChangeCount(NSDocumentChangeType.ChangeDone)
}
func getLineEndings() -> String {
return aceView.getNewLineMode();
}
func setEncoding(encoding: String) {
}
private func updateView() {
if mode != nil {
aceView.setMode(mode!)
}
}
func getMode() -> String {
return mode ?? "text"
}
} | bsd-3-clause | dcf0e27bad3aa189d45588682a13ccce | 21.275862 | 90 | 0.61038 | 4.529825 | false | false | false | false |
hughbe/swift | validation-test/Reflection/reflect_Character.swift | 2 | 3036 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Character
// RUN: %target-run %target-swift-reflection-test %t/reflect_Character 2>&1 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
// FIXME: https://bugs.swift.org/browse/SR-2808
// XFAIL: resilient_stdlib
// See https://bugs.swift.org/browse/SR-5066, rdar://32511557
// XFAIL: *
import SwiftReflectionTest
class TestClass {
var t: Character
init(t: Character) {
self.t = t
}
}
var obj = TestClass(t: "A")
reflect(object: obj)
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Character.TestClass)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=t offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_representation offset=0
// CHECK-64-NEXT: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=large offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646
// CHECK-64-NEXT: (field name=_storage offset=0
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=2147483646
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-64-NEXT: (field name=small offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647)))))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Character.TestClass)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=24 alignment=8 stride=24 num_extra_inhabitants=0
// CHECK-32: (field name=t offset=16
// CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=_representation offset=0
// CHECK-32: (multi_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-32: (field name=large offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32: (field name=_storage offset=0
// CHECK-32: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32: (field name=some offset=0
// CHECK-32: (reference kind=strong refcounting=native))))))
// CHECK-32: (field name=small offset=0
// CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=2147483647)))))))
doneReflecting()
// CHECK-64: Done.
// CHECK-32: Done.
| apache-2.0 | 91ddd971b5ae19e650f3a1d106d7e991 | 42.371429 | 128 | 0.65942 | 3.339934 | false | true | false | false |
chenchangqing/CQTextField | Pod/Classes/CountDown/SwiftCountdownButton.swift | 1 | 2653 | //
// SwiftCountdownButton.swift
// SwiftCountdownButtonExample
//
// Created by Gesen on 15/6/4.
// Copyright (c) 2015年 Gesen. All rights reserved.
//
import UIKit
public class SwiftCountdownButton: UIButton {
// MARK: Properties
public var maxSecond = 60
public var countdown = false {
didSet {
if oldValue != countdown {
countdown ? startCountdown() : stopCountdown()
}
}
}
private var second = 0
private var timer: Timer?
private var timeLabel: UILabel!
private var normalText: String!
private var normalTextColor: UIColor!
private var disabledText: String!
private var disabledTextColor: UIColor!
// MARK: Life Cycle
override public func awakeFromNib() {
super.awakeFromNib()
setupLabel()
}
deinit {
countdown = false
}
// MARK: Setups
private func setupLabel() {
normalText = title(for: UIControlState())!
disabledText = title(for: .disabled)!
normalTextColor = titleColor(for: UIControlState())!
disabledTextColor = titleColor(for: .disabled)!
setTitle("", for: UIControlState())
setTitle("", for: .disabled)
timeLabel = UILabel(frame: bounds)
timeLabel.textAlignment = .center
timeLabel.font = titleLabel?.font
timeLabel.textColor = normalTextColor
timeLabel.text = normalText
addSubview(timeLabel)
}
// MARK: Private
private func startCountdown() {
second = maxSecond
updateDisabled()
if timer != nil {
timer!.invalidate()
timer = nil
}
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(SwiftCountdownButton.updateCountdown), userInfo: nil, repeats: true)
}
private func stopCountdown() {
timer?.invalidate()
timer = nil
updateNormal()
}
private func updateNormal() {
isEnabled = true
timeLabel.textColor = normalTextColor
timeLabel.text = normalText
}
private func updateDisabled() {
isEnabled = false
timeLabel.textColor = disabledTextColor
timeLabel.text = disabledText.replacingOccurrences(of: "second", with: "\(second)", options: String.CompareOptions.literal, range: nil)
}
@objc private func updateCountdown() {
second = second - 1;
if second <= 0 {
countdown = false
} else {
updateDisabled()
}
}
}
| mit | 39b1bfcb27790efa2d9c8ddd457fc9f0 | 24.490385 | 158 | 0.586571 | 5.167641 | false | false | false | false |
WildenChen/LionEvents | LionEventsExample/LionEventsExample/Model.swift | 1 | 1596 | //
// Model.swift
// SwiftSimpleProject
//
// Created by wilden on 2015/6/2.
// Copyright (c) 2015年 Lion Infomation Technology Co.,Ltd. Wilden. All rights reserved.
//
import Foundation
import LionEvents
class Model:EventDispatcher {
static let ADD:String = "model_add"
static let DEC:String = "model_dec"
override init() {
}
fileprivate var mIndex:Int = 0
var index:Int{
set(value){
if value > mIndex {
mIndex = value
let _event:Event = Event(aType: Model.ADD, aBubbles: false)
//var _dic:[String:Int] = [String:Int]()
//_dic["index"] = mIndex
let _vo = ModelVO(aName: "hihi",aID: "\(mIndex)")
_event.information = _vo
dispatchEvent(_event)
print("Model.index:\(Model.ADD)")
}else if value < mIndex {
mIndex = value
let _event:Event = Event(aType: Model.DEC, aBubbles: false)
//var _dic:[String:Int] = [String:Int]()
//_dic["index"] = mIndex
let _vo = ModelVO(aName: "ddd",aID: "\(mIndex)")
_event.information = _vo
dispatchEvent(_event)
print("Model.index:\(Model.DEC)")
}
}
get{
return mIndex
}
}
deinit{
print("Model.deinit")
}
}
class ModelVO {
var name:String
var id:String
init(aName:String,aID:String){
self.name = aName
self.id = aID
}
}
| bsd-3-clause | 3711fa93fcc6455b2475995f6268dffe | 25.566667 | 88 | 0.498118 | 4.066327 | false | false | false | false |
rnystrom/WatchKit-by-Tutorials | SousChef/RW Recipes Watch App/RecipesInterfaceController.swift | 1 | 1000 | //
// RecipesController.swift
// SousChef
//
// Created by Ryan Nystrom on 11/26/14.
// Copyright (c) 2014 Ray Wenderlich. All rights reserved.
//
import WatchKit
import SousChefKit
class RecipesInterfaceController: WKInterfaceController {
let recipeStore = RecipeStore()
@IBOutlet weak var table: WKInterfaceTable!
override init(context: AnyObject?) {
super.init(context: context)
table.setNumberOfRows(recipeStore.recipes.count, withRowType: "RecipeRowType")
for var i = 0; i < table.numberOfRows; i++ {
let controller = table.rowControllerAtIndex(i) as RecipeRowController
let recipe = recipeStore.recipes[i]
controller.textLabel.setText(recipe.name)
controller.ingredientsLabel.setText("\(recipe.ingredients.count) ingredients")
}
}
override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) {
let recipe = recipeStore.recipes[rowIndex]
pushControllerWithName("RecipeDetail", context: recipe)
}
}
| mit | 574f12cc3b110abc1b850f6db33a486e | 26.777778 | 84 | 0.731 | 4.347826 | false | false | false | false |
DenHeadless/DTModelStorage | Sources/DTModelStorage/BaseStorage.swift | 1 | 5858 | //
// BaseStorage.swift
// DTModelStorage
//
// Created by Denys Telezhkin on 06.07.15.
// Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/// Suggested supplementary kind for UITableView header
public let DTTableViewElementSectionHeader = "DTTableViewElementSectionHeader"
/// Suggested supplementary kind for UITableView footer
public let DTTableViewElementSectionFooter = "DTTableViewElementSectionFooter"
/// `BaseSupplementaryStorage` is a base class, that implements common functionality for `SupplementaryStorage` protocol and serves as a base class for `MemoryStorage`, `CoreDataStorage`, `SingleSectionStorage`, `RealmStorage`.
open class BaseSupplementaryStorage: NSObject, SupplementaryStorage {
/// Returns a header model for specified section index or nil.
open var headerModelProvider: ((Int) -> Any?)?
/// Returns a footer model for specified section index or nil
open var footerModelProvider: ((Int) -> Any?)?
private lazy var _supplementaryModelProvider: ((String, IndexPath) -> Any?)? = { [weak self] kind, indexPath in
if let headerModel = self?.headerModelProvider, self?.supplementaryHeaderKind == kind {
return headerModel(indexPath.section)
}
if let footerModel = self?.footerModelProvider, self?.supplementaryFooterKind == kind {
return footerModel(indexPath.section)
}
return nil
}
/// Returns supplementary model for specified section indexPath and supplementary kind, or nil. Setter for this property is overridden to allow calling `headerModelProvider` and `footerModelProvider` closures.
open var supplementaryModelProvider: ((String, IndexPath) -> Any?)? {
get {
return _supplementaryModelProvider
}
set {
_supplementaryModelProvider = { [weak self] kind, indexPath in
if let headerModel = self?.headerModelProvider, self?.supplementaryHeaderKind == kind {
return headerModel(indexPath.section)
}
if let footerModel = self?.footerModelProvider, self?.supplementaryFooterKind == kind {
return footerModel(indexPath.section)
}
return newValue?(kind, indexPath)
}
}
}
/// Supplementary kind for header in current storage
open var supplementaryHeaderKind: String?
/// Supplementary kind for footer in current storage
open var supplementaryFooterKind: String?
}
@MainActor
/// `StorageUpdating` protocol is used to transfer data storage updates.
public protocol StorageUpdating : AnyObject
{
/// Transfers data storage updates.
///
/// Object, that implements this method, may react to received update by updating UI for current storage.
func storageDidPerformUpdate(_ update: StorageUpdate)
/// Method is called when UI needs to be fully updated for data storage changes.
func storageNeedsReloading()
}
/// Base class for storage classes
open class BaseUpdateDeliveringStorage: BaseSupplementaryStorage
{
/// Current update
open var currentUpdate: StorageUpdate?
/// Batch updates are in progress. If true, update will not be finished.
open var batchUpdatesInProgress = false
/// Delegate for storage updates
open weak var delegate: StorageUpdating?
/// Performs update `block` in storage. After update is finished, delegate will be notified.
/// Parameter block: Block to execute
/// - Note: This method allows to execute several updates in a single batch. It is similar to UICollectionView method `performBatchUpdates:`.
/// - Warning: Performing mutually exclusive updates inside block can cause application crash.
open func performUpdates( _ block: () -> Void) {
batchUpdatesInProgress = true
startUpdate()
block()
batchUpdatesInProgress = false
finishUpdate()
}
/// Starts update in storage.
///
/// This creates StorageUpdate instance and stores it into `currentUpdate` property.
open func startUpdate(){
if self.currentUpdate == nil {
self.currentUpdate = StorageUpdate()
}
}
/// Finishes update.
///
/// Method verifies, that update is not empty, and sends updates to the delegate. After this method finishes, `currentUpdate` property is nilled out.
open func finishUpdate()
{
guard batchUpdatesInProgress == false else { return }
defer { currentUpdate = nil }
if let update = currentUpdate {
if update.isEmpty {
return
}
delegate?.storageDidPerformUpdate(update)
}
}
}
| mit | 5987dc9fe339cf032028d314f8fd5bd3 | 41.449275 | 227 | 0.69563 | 5.193262 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios | Pod/Classes/Common/Model/Constants.swift | 1 | 1107 | //
// Constants.swift
// SuperAwesome
//
// Created by Gunhan Sancar on 09/09/2020.
//
struct Constants {
static let defaultClickThresholdInSecs = 5
static let defaultTestMode = false
static let defaultParentalGate = false
static let defaultBumperPage = false
static let defaultCloseAtEnd = true
static let defaultCloseWarning = false
static let defaultMuteOnStart = false
static let defaultCloseButton: CloseButtonState = .hidden
static let defaultCloseButtonInterstitial: CloseButtonState = .visibleWithDelay
static let defaultSmallClick = false
static let defaultOrientation = Orientation.any
static let defaultEnvironment = Environment.production
static let defaultMoatLimitingState = true
static let defaultStartDelay = AdRequest.StartDelay.preRoll
static let backgroundGray = UIColor(red: 224.0 / 255.0, green: 224.0 / 255.0,
blue: 224.0 / 255.0, alpha: 1)
static let defaultSafeAdUrl = "https://ads.superawesome.tv/v2/safead"
static let defaultBaseUrl = "https://ads.superawesome.tv"
}
| lgpl-3.0 | fb5c93c53e03a61c6e59cba56aa02125 | 37.172414 | 83 | 0.720867 | 4.410359 | false | false | false | false |
codestergit/swift | test/IRGen/lazy_globals.swift | 3 | 2222 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-as-library -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8
// CHECK: @_T012lazy_globals1xSiv = hidden global %TSi zeroinitializer, align 8
// CHECK: @_T012lazy_globals1ySiv = hidden global %TSi zeroinitializer, align 8
// CHECK: @_T012lazy_globals1zSiv = hidden global %TSi zeroinitializer, align 8
// CHECK: define internal swiftcc void @globalinit_[[T]]_func0() {{.*}} {
// CHECK: entry:
// CHECK: store i64 1, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1xSiv, i32 0, i32 0), align 8
// CHECK: store i64 2, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1ySiv, i32 0, i32 0), align 8
// CHECK: store i64 3, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1zSiv, i32 0, i32 0), align 8
// CHECK: ret void
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1xSifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1xSiv to i8*)
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1ySifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1ySiv to i8*)
// CHECK: }
// CHECK: define hidden swiftcc i8* @_T012lazy_globals1zSifau() {{.*}} {
// CHECK: entry:
// CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*))
// CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1zSiv to i8*)
// CHECK: }
var (x, y, z) = (1, 2, 3)
// CHECK: define hidden swiftcc i64 @_T012lazy_globals4getXSiyF() {{.*}} {
// CHECK: entry:
// CHECK: %0 = call swiftcc i8* @_T012lazy_globals1xSifau()
// CHECK: %1 = bitcast i8* %0 to %TSi*
// CHECK: %._value = getelementptr inbounds %TSi, %TSi* %1, i32 0, i32 0
// CHECK: %2 = load i64, i64* %._value, align 8
// CHECK: ret i64 %2
// CHECK: }
func getX() -> Int { return x }
| apache-2.0 | aa35f535e459dce4d3caa54653a53a68 | 47.304348 | 132 | 0.647165 | 2.927536 | false | false | false | false |
inon29/INOMessageTextBox | Pod/Classes/INOMessageTextView.swift | 1 | 2431 | import UIKit
public class INOMessageTextView: INOPlaceholderTextView {
private let kDefaultFontSize: CGFloat = 12.0
private let kDefaultMaxLines: UInt = 10
// MARK: - init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
// MARK: - internal
/**
初期化時のtextViewの高さを取得
- returns: TextView Height
*/
internal func initHeight() -> CGFloat {
guard let font = self.font else {
return 0
}
return font.lineHeight + self.textContainerInset.top + self.textContainerInset.bottom
}
/**
現在のTextViewの高さを取得
- returns: TextViewHeight
*/
internal func currentHeight() -> CGFloat {
if numberOfLines() > kDefaultMaxLines { // 最大行数を超える場合
var lineHeight: CGFloat = 0
if let font = self.font {
lineHeight = font.lineHeight
}
return (lineHeight * CGFloat(kDefaultMaxLines)) + self.textContainerInset.top + self.textContainerInset.bottom
} else {
return self.sizeThatFits(self.frame.size).height
}
}
/**
現在の行数を取得
- returns: 行数
*/
internal func numberOfLines() -> UInt {
var contentSize: CGSize = self.contentSize
var contentHeight: CGFloat = contentSize.height
contentHeight -= self.textContainerInset.top + self.textContainerInset.bottom
var lines: UInt = UInt(fabs(contentHeight / (self.font?.lineHeight)!))
if lines == 1 && contentSize.height > self.bounds.size.height {
contentSize.height = self.bounds.size.height;
self.contentSize = contentSize;
}
if (lines == 0) {
lines = 1;
}
return lines
}
// MARK: - private
/**
共通初期化処理
*/
private func commonInit() {
self.layer.borderWidth = 1
self.layer.borderColor = UIColor.grayColor().CGColor
self.layer.cornerRadius = 3
self.font = UIFont.systemFontOfSize(kDefaultFontSize)
self.showsHorizontalScrollIndicator = false
}
}
| mit | 65bdcfc8564a3d7a3ccf66d10b084c27 | 28.2125 | 122 | 0.597347 | 4.878914 | false | false | false | false |
iParqDevelopers/cordova-plugin-flex-camera | src/ios/HappieCamera.swift | 1 | 2234 | import Foundation
import UIKit
@objc(HappieCamera) class HappieCamera : CDVPlugin, cameraDelegate {
//let cameraRoll: HappieCameraRoll = HappieCameraRoll();
//let cameraView = HappieCameraViewController(nibName:"HappieCameraView", bundle:nil);
var callBackId: String = "";
var rollCallBackId: String = "";
func openCamera(_ command: CDVInvokedUrlCommand) {
//cameraRoll.delegate = self;
let params: AnyObject = command.arguments[0] as AnyObject!
let qual: Int = params["quality"] as! Int
HappieCameraJSON.setQuality(newQual: qual);
let cameraVC: HappieCameraViewController = HappieCameraViewController(nibName:"HappieCameraView", bundle:nil);
cameraVC.delegate = self;
cameraVC.modalTransitionStyle = UIModalTransitionStyle.coverVertical;
cameraVC.modalPresentationStyle = UIModalPresentationStyle.fullScreen;
callBackId = command.callbackId;
self.viewController?.present(cameraVC, animated: true, completion:nil)
}
func getCameraRoll(_ command: CDVInvokedUrlCommand){
rollCallBackId = command.callbackId;
//cameraRoll.getCameraRoll()
}
func cameraFinished(_ controller: HappieCameraViewController, JSON: String){
controller.dismiss(animated: true, completion: nil);
var pluginResult: CDVPluginResult;
if(JSON.characters.count > 0){
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: JSON)
}else{
pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "no media captured")
}
commandDelegate!.send(pluginResult, callbackId:callBackId)
}
func cameraRollFinished(_ JSON: String){
var pluginResult: CDVPluginResult;
if(JSON.characters.count > 0){
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: JSON)
pluginResult.setKeepCallbackAs(true)
}else{
pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "could not find camera roll")
pluginResult.setKeepCallbackAs(false)
}
commandDelegate!.send(pluginResult, callbackId:rollCallBackId)
}
}
| mit | e36a2d89981ceda307df765c3d4ba2bb | 41.961538 | 118 | 0.695613 | 5.207459 | false | false | false | false |
rb-de0/Fluxer | FluxerTests/Dispatcher/DispatcherTests.swift | 1 | 5643 | //
// DispatcherTests.swift
// Fluxer
//
// Created by rb_de0 on 2017/03/21.
// Copyright © 2017年 rb_de0. All rights reserved.
//
import XCTest
@testable import Fluxer
class DispatcherTests: XCTestCase {
class TestStore: Store {
var value = 0
required init(with dispatcher: Dispatcher) {}
}
class TestAction: Action {}
class Test2Action: Action {}
class TestAsyncAction: AsyncAction {
let expect: XCTestExpectation
init(_ expect: XCTestExpectation) {
self.expect = expect
}
func exec(callback: @escaping Dispatcher.AsyncActionCallback) {
callback(TestAction())
expect.fulfill()
}
}
func testHandlerCallOrder() {
let dispatcher = Dispatcher()
var orderList = [Int]()
_ = dispatcher.register { _ in
orderList.append(0)
}
_ = dispatcher.register { _ in
orderList.append(1)
}
dispatcher.dispatch(TestAction())
XCTAssertEqual(orderList, [0, 1])
}
func testWaitFor() {
let dispatcher = Dispatcher()
var orderList = [Int]()
var waitTokens = [String]()
_ = dispatcher.register { action in
dispatcher.waitFor(waitTokens, action: action)
orderList.append(0)
}
let token = dispatcher.register { _ in
orderList.append(1)
}
waitTokens.append(token)
_ = dispatcher.register { _ in
orderList.append(2)
}
dispatcher.dispatch(TestAction())
XCTAssertEqual(orderList, [1, 0, 2])
}
func testStoreSubscribe() {
let dispatcher = Dispatcher()
let store = TestStore(with: dispatcher)
_ = dispatcher.register { action in
store.value = 10
}
dispatcher.dispatch(TestAction())
XCTAssertEqual(store.value, 10)
}
func testActionHandler() {
let dispatcher = Dispatcher()
let store = TestStore(with: dispatcher)
_ = dispatcher.register { action in
switch action {
case _ as TestAction:
store.value = 10
case _ as Test2Action:
store.value = -1
default:
break
}
}
dispatcher.dispatch(TestAction())
XCTAssertEqual(store.value, 10)
dispatcher.dispatch(Test2Action())
XCTAssertEqual(store.value, -1)
}
func testAsyncActionCreator() {
let expectation = self.expectation(description: #function)
let dispatcher = Dispatcher()
let store = TestStore(with: dispatcher)
_ = dispatcher.register { _ in
store.value = 10
}
dispatcher.dispatch { callback in
callback(TestAction())
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
XCTAssertEqual(store.value, 10)
}
func testAsyncStoreUpdate() {
let expectation = self.expectation(description: #function)
let dispatcher = Dispatcher()
let store = TestStore(with: dispatcher)
_ = dispatcher.register { action in
switch action {
case _ as TestAction:
store.value = 10
case _ as Test2Action:
store.value = -1
default:
break
}
}
dispatcher.dispatch { callback in
XCTAssertEqual(store.value, 0)
DispatchQueue.global().async {
sleep(2)
XCTAssertEqual(store.value, -1)
callback(TestAction())
expectation.fulfill()
}
}
dispatcher.dispatch(Test2Action())
waitForExpectations(timeout: 10, handler: nil)
XCTAssertEqual(store.value, 10)
}
func testAsyncAction() {
let expectation = self.expectation(description: #function)
let dispatcher = Dispatcher()
let store = TestStore(with: dispatcher)
_ = dispatcher.register { _ in
store.value = 10
}
dispatcher.dispatch(TestAsyncAction(expectation))
waitForExpectations(timeout: 10, handler: nil)
XCTAssertEqual(store.value, 10)
}
func testUnregister() {
let dispatcher = Dispatcher()
let store = TestStore(with: dispatcher)
let token = dispatcher.register { action in
switch action {
case _ as TestAction:
store.value = 10
case _ as Test2Action:
store.value = -1
default:
break
}
}
dispatcher.dispatch(TestAction())
XCTAssertEqual(store.value, 10)
dispatcher.unregister(registrationToken: token)
dispatcher.dispatch(Test2Action())
XCTAssertEqual(store.value, 10)
}
}
| mit | f272ea17737d2a0500c502c343bd3ef8 | 23.102564 | 71 | 0.486879 | 5.685484 | false | true | false | false |
warren-gavin/OBehave | OBehave/Classes/ViewController/Transition/Inset/BlurredBackground/OBBlurredBackgroundPresentationController.swift | 1 | 827 | //
// OBBlurredBackgroundPresentationController.swift
// OBehave
//
// Created by Warren Gavin on 13/01/16.
// Copyright © 2016 Apokrupto. All rights reserved.
//
import UIKit
/// Custom presentation controller that displays a view over a blurred background
internal class OBBlurredBackgroundPresentationController: OBInsetPresentationController {
var blurStyle: UIBlurEffect.Style = .light
override func backgroundViewForPresentation() -> UIView? {
guard let containerView = containerView else {
return nil
}
let blurringView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle))
blurringView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
blurringView.frame = containerView.bounds
return blurringView
}
}
| mit | a789148f96ab93a745e7de3fb4e816e1 | 29.592593 | 89 | 0.705811 | 5.194969 | false | false | false | false |
quran/quran-ios | Sources/QuranAudioKit/Downloads/AudioFileListRetrieval.swift | 1 | 4112 | //
// ReciterAudioFileListRetrieval.swift
// Quran
//
// Created by Mohamed Afifi on 4/17/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import Foundation
import QuranKit
protocol ReciterAudioFile {
var remote: URL { get }
var local: String { get }
}
extension ReciterAudioFile {
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.remote == rhs.remote
}
}
struct ReciterDatabaseAudioFile: ReciterAudioFile, Hashable {
let remote: URL
let local: String
}
struct ReciterSuraAudioFile: ReciterAudioFile, Hashable {
let remote: URL
let local: String
let sura: Sura
}
protocol ReciterAudioFileListRetrieval {
func get(for reciter: Reciter, from start: AyahNumber, to end: AyahNumber) -> [ReciterAudioFile]
}
struct GaplessReciterAudioFileListRetrieval: ReciterAudioFileListRetrieval {
let baseURL: URL
private let path = "data/databases/audio/"
var audioDatabaseURL: URL { baseURL.appendingPathComponent(path) }
func get(for reciter: Reciter, from start: AyahNumber, to end: AyahNumber) -> [ReciterAudioFile] {
guard case AudioType.gapless(let databaseFileName) = reciter.audioType else {
fatalError("Unsupported reciter type gapped. Only gapless reciters can be downloaded here.")
}
let databaseRemoteURL = audioDatabaseURL.appendingPathComponent(databaseFileName)
.appendingPathExtension(Files.databaseRemoteFileExtension)
let databaseLocalURL = reciter.path.stringByAppendingPath(databaseFileName).stringByAppendingExtension(Files.databaseRemoteFileExtension)
let dbFile = ReciterDatabaseAudioFile(remote: databaseRemoteURL, local: databaseLocalURL)
// loop over the files
var files = Set<ReciterSuraAudioFile>()
for sura in start.sura.array(to: end.sura) {
let fileName = sura.suraNumber.as3DigitString()
let remoteURL = reciter.audioURL.appendingPathComponent(fileName).appendingPathExtension(Files.audioExtension)
let localURL = reciter.path.stringByAppendingPath(fileName).stringByAppendingExtension(Files.audioExtension)
files.insert(ReciterSuraAudioFile(remote: remoteURL, local: localURL, sura: sura))
}
return Array(files) + [dbFile]
}
}
struct GappedReciterAudioFileListRetrieval: ReciterAudioFileListRetrieval {
let quran: Quran
func get(for reciter: Reciter, from start: AyahNumber, to end: AyahNumber) -> [ReciterAudioFile] {
guard case AudioType.gapped = reciter.audioType else {
fatalError("Unsupported reciter type gapless. Only gapless reciters can be downloaded here.")
}
var files = Set<ReciterSuraAudioFile>()
// add besm Allah for all gapped audio
files.insert(createRequestInfo(reciter: reciter, sura: quran.firstSura, ayah: 1))
for ayah in start.array(to: end) {
files.insert(createRequestInfo(reciter: reciter, sura: ayah.sura, ayah: ayah.ayah))
}
return Array(files)
}
private func createRequestInfo(reciter: Reciter, sura: Sura, ayah: Int) -> ReciterSuraAudioFile {
let fileName = sura.suraNumber.as3DigitString() + ayah.as3DigitString()
let remoteURL = reciter.audioURL.appendingPathComponent(fileName).appendingPathExtension(Files.audioExtension)
let localURL = reciter.path.stringByAppendingPath(fileName).stringByAppendingExtension(Files.audioExtension)
return ReciterSuraAudioFile(remote: remoteURL, local: localURL, sura: sura)
}
}
| apache-2.0 | 22265e4ba603f8e6f5baca79283a5f35 | 37.792453 | 145 | 0.72106 | 4.683371 | false | false | false | false |
PumpMagic/ostrich | gameboy/gameboy/Source/Memories/RAM.swift | 1 | 1920 | //
// RAM.swift
// ostrichframework
//
// Created by Ryan Conway on 4/4/16.
// Copyright © 2016 Ryan Conway. All rights reserved.
//
import Foundation
/// A random-access memory.
open class RAM: Memory, HandlesWrites {
var data: Array<UInt8>
/// An offset: specifies what memory location the first byte of the supplied data occupies
open let firstAddress: Address
open var lastAddress: Address {
return UInt16(UInt32(self.firstAddress) + UInt32(self.data.count) - 1)
}
open var addressRange: CountableClosedRange<Address> {
return self.firstAddress ... self.lastAddress
}
var addressRangeString: String {
return "[\(self.firstAddress.hexString), \(self.lastAddress.hexString)]"
}
public init(size: UInt16, fillByte: UInt8, firstAddress: Address) {
self.data = Array<UInt8>(repeating: fillByte, count: Int(size))
self.firstAddress = firstAddress
}
public convenience init(size: UInt16) {
self.init(size: size, fillByte: 0x00, firstAddress: 0x0000)
}
open func read(_ addr: Address) -> UInt8 {
if addr < self.firstAddress ||
Int(addr) > Int(self.firstAddress) + Int(self.data.count)
{
print("FATAL: attempt to access address \(addr.hexString) but our range is \(self.addressRangeString)")
exit(1)
}
return self.data[Int(addr - self.firstAddress)]
}
open func write(_ val: UInt8, to addr: Address) {
self.data[Int(addr - self.firstAddress)] = val
}
open func nonzeroes() -> String {
var nonzeroes: String = ""
for (index, datum) in self.data.enumerated() {
if datum != 0x00 {
nonzeroes += "\((firstAddress + UInt16(index)).hexString): \(datum.hexString) "
}
}
return nonzeroes
}
}
| mit | bec23d29301a060ef6241020ad954a13 | 28.984375 | 115 | 0.601876 | 4.118026 | false | false | false | false |
ddki/my_study_project | language/swift/SimpleTunnelCustomizedNetworkingUsingtheNetworkExtensionFramework/SimpleTunnel/OnDemandRuleListController.swift | 1 | 2893 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains the OnDemandRuleListController class, which is responsible for controlling a list of Connect On Demand rules.
*/
import UIKit
import NetworkExtension
/// A view controller for a view displaying a list of Connect On Demand rules.
class OnDemandRuleListController: ListViewController {
// MARK: Properties
/// The VPN configuration containing the Connect On Demand rules.
var targetManager: NEVPNManager = NEVPNManager.shared()
/// The text to display in the list's "add new item" row.
override var listAddButtonText: String {
return "Add On Demand Rule..."
}
/// The number of Connect On Demand rules.
override var listCount: Int {
return targetManager.onDemandRules?.count ?? 0
}
/// Returns UITableViewCellAccessoryType.DetailButton
override var listAccessoryType: UITableViewCellAccessoryType {
return .detailButton
}
/// Returns UITableViewCellAccessoryType.DetailButton
override var listEditingAccessoryType: UITableViewCellAccessoryType {
return .detailButton
}
// MARK: UIViewController
/// Handle the event when the view is loaded into memory.
override func viewDidLoad() {
isAddEnabled = true
isAlwaysEditing = true
super.viewDidLoad()
}
// MARK: Interface
/// Handle unwind segues to this view controller.
@IBAction func handleUnwind(_ sender: UIStoryboardSegue) {
}
// MARK: ListViewController
/// Set up the destination view controller of a segue away from this view controller.
override func listSetupSegue(_ segue: UIStoryboardSegue, forItemAtIndex index: Int) {
guard let identifier = segue.identifier,
let ruleAddEditController = segue.destination as? OnDemandRuleAddEditController
else { return }
switch identifier {
case "edit-on-demand-rule":
// The user tapped on the editing accessory of a rule in the list.
guard let rule = targetManager.onDemandRules?[index] else { break }
ruleAddEditController.setTargetRule(rule, title: "On Demand Rule") { newRule in
self.targetManager.onDemandRules?[index] = newRule
}
case "add-on-demand-rule":
// The user tapped on the "add a new rule" row.
ruleAddEditController.setTargetRule(nil, title: "Add On Demand Rule") { newRule in
if self.targetManager.onDemandRules == nil {
self.targetManager.onDemandRules = [NEOnDemandRule]()
}
self.targetManager.onDemandRules?.append(newRule)
}
default:
break
}
}
/// Return a description of the rule at the given index in the list.
override func listTextForItemAtIndex(_ index: Int) -> String {
return targetManager.onDemandRules?[index].action.description ?? ""
}
/// Remove a rule from the list.
override func listRemoveItemAtIndex(_ index: Int) {
targetManager.onDemandRules?.remove(at: index)
}
}
| mit | 1c39bdd4746b0fd1b099edc78c480323 | 29.755319 | 129 | 0.743687 | 4.153736 | false | false | false | false |
jvesala/teknappi | teknappi/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift | 14 | 2803 | //
// RxTableViewReactiveArrayDataSource.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/26/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
// objc monkey business
class _RxTableViewReactiveArrayDataSource: NSObject, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func _tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _tableView(tableView, numberOfRowsInSection: section)
}
func _tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return rxAbstractMethod()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return _tableView(tableView, cellForRowAtIndexPath: indexPath)
}
}
class RxTableViewReactiveArrayDataSourceSequenceWrapper<S: SequenceType> : RxTableViewReactiveArrayDataSource<S.Generator.Element>
, RxTableViewDataSourceType {
typealias Element = S
override init(cellFactory: CellFactory) {
super.init(cellFactory: cellFactory)
}
func tableView(tableView: UITableView, observedEvent: Event<S>) {
switch observedEvent {
case .Next(let value):
super.tableView(tableView, observedElements: Array(value))
case .Error(let error):
bindingErrorToInterface(error)
case .Completed:
break
}
}
}
// Please take a look at `DelegateProxyType.swift`
class RxTableViewReactiveArrayDataSource<Element> : _RxTableViewReactiveArrayDataSource {
typealias CellFactory = (UITableView, Int, Element) -> UITableViewCell
var itemModels: [Element]? = nil
func modelAtIndex(index: Int) -> Element? {
return itemModels?[index]
}
let cellFactory: CellFactory
init(cellFactory: CellFactory) {
self.cellFactory = cellFactory
}
override func _tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemModels?.count ?? 0
}
override func _tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return cellFactory(tableView, indexPath.item, itemModels![indexPath.row])
}
// reactive
func tableView(tableView: UITableView, observedElements: [Element]) {
self.itemModels = observedElements
tableView.reloadData()
}
} | gpl-3.0 | 37008acf4149814abe03e62c00c0ae08 | 29.813187 | 130 | 0.674634 | 5.628514 | false | false | false | false |
PavelGnatyuk/SimplePurchase | SimplePurchase/SimplePurchaseTests/AppPriceConverter_Tests.swift | 1 | 2313 | //
// AppPriceConverter_Tests.swift
// FairyTales
//
// Created by Pavel Gnatyuk on 29/04/2017.
//
//
import XCTest
class AppPriceConverter_Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSimple0_99_US() {
let locale = Locale(identifier: "en_US")
let number = NSDecimalNumber(string: "0.99", locale: locale)
let price = AppPriceConverter().convert(number, locale: locale)
XCTAssertEqual(price, "$0.99", "0.99$ not converted correctly")
}
func testSimple3_90_NIS() {
let etalon = "3.90 ₪"
let locale = Locale(identifier: "he_IL")
let number = NSDecimalNumber(string: "3.90", locale: locale)
let price = AppPriceConverter().convert(number, locale: locale)
XCTAssertEqual(price, etalon, "\(etalon) not converted correctly")
}
func testSimple129_RU() {
let etalon = "129,00 ₽"
let locale = Locale(identifier: "ru_RU")
let number = NSDecimalNumber(string: "129.00", locale: locale)
let price = AppPriceConverter().convert(number, locale: locale)
XCTAssertEqual(price, etalon, "\(etalon) not converted correctly")
}
func testFewLocales() {
let localeUS = Locale(identifier: "en_US")
let converter = AppPriceConverter()
let data = ["en_US": "$0.99", "ru_RU": "0,99 ₽", "he_IL": "0.99 ₪", "en_GB": "£0.99"]
data.forEach { (name, etalon) in
let locale = Locale(identifier: name)
let amount = NSDecimalNumber(string: "0.99", locale: localeUS)
let price = converter.convert(amount, locale: locale)
XCTAssertEqual(price, etalon, "Wrong converting of \(etalon)")
}
}
func testZeroPrice() {
let converter = AppPriceConverter()
let price = converter.convert(NSDecimalNumber.zero, locale: Locale(identifier: "en_US"))
XCTAssertEqual(price, "", "Zero price converted not as it is requested")
}
}
| apache-2.0 | 913b2286c0370f4f2c0a3fd4be2a93cf | 35.507937 | 111 | 0.616087 | 4.070796 | false | true | false | false |
kedu/FULL_COPY | xingLangWeiBo/xingLangWeiBo/Classes/Model/useAccount.swift | 1 | 2765 | //
// useAccount.swift
// xingLangWeiBo
//
// Created by Apple on 16/10/10.
// Copyright © 2016年 lkb-求工作qq:1218773641. All rights reserved.
//
import UIKit
//保存用户信息
class useAccount: NSObject,NSCoding {
//token值
var access_token :String?
var expires_in:NSTimeInterval=0 {
didSet {
expires_date = NSDate(timeIntervalSinceNow: expires_in)
}
}
//过期时间
var expires_date:NSDate?
var uid:String?
var avatar_large:String?
var name:String?
init(dict:[String : AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description : String {
let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
return dictionaryWithValuesForKeys(keys).description
}
//归档
func saveAccount(){
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
NSKeyedArchiver.archiveRootObject(self, toFile: path)
print(path)
}
//解归档
class func loadAccount() ->useAccount?{
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? useAccount {
//判断用户的token是否过期
if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
return account}
}
return nil
}
//解归档
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeDoubleForKey("expires_in")
uid = aDecoder.decodeObjectForKey("uid") as? String
avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
name = aDecoder.decodeObjectForKey("name") as? String
expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
}
//归档
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeDouble(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(avatar_large, forKey: "avatar_large")
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(expires_date, forKey: "expires_date")
}
}
| mit | 37fe8b9443f0873bcb15e5ec9198210e | 31.481928 | 165 | 0.639837 | 4.672444 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Heap & Priority Queue/347_Top K Frequent Elements.swift | 1 | 1250 | // 347_Top K Frequent Elements
// https://leetcode.com/problems/top-k-frequent-elements/
//
// Created by Honghao Zhang on 10/29/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a non-empty array of integers, return the k most frequent elements.
//
//Example 1:
//
//Input: nums = [1,1,1,2,2,3], k = 2
//Output: [1,2]
//Example 2:
//
//Input: nums = [1], k = 1
//Output: [1]
//Note:
//
//You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
//Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
//
// 取出出现次数最多的K个元素
import Foundation
class Num347 {
// MARK: - 统计num count然后用max heap取出
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var numCount: [Int: Int] = [:]
for n in nums {
numCount[n] = numCount[n, default: 0] + 1
}
let numCountTuples = numCount.map {
($0.key, $0.value)
}
// 按照num count来最最大heap
var heap = Heap(array: numCountTuples, sort: {
$0.1 > $1.1
})
// 取出k个元素
var answer: [Int] = []
for _ in 0..<k {
if let top = heap.remove() {
answer.append(top.0)
}
}
return answer
}
}
| mit | 786ead98443e9c13663c28983d66c1fc | 21.788462 | 95 | 0.594093 | 2.992424 | false | false | false | false |
n41l/OMChartView | OMChartView/Classes/OMChartView.swift | 1 | 1217 |
//
// OMChartView.swift
// Pods
//
// Created by HuangKun on 16/6/1.
//
//
import UIKit
public class OMChartView: UIView {
public var rectInset: UIEdgeInsets = UIEdgeInsetsZero
//
// public var xView: UIView?
// public var yView: UIView?
private var chartLayers: [OMChartLayer] = []
private var interactiveView: OMChartInteractiveView?
public func appendChartLayers(layers: [OMChartLayer]) -> OMChartView {
chartLayers = layers
return self
}
public func withInteractiveView(view: OMChartInteractiveView) -> OMChartView {
interactiveView = view
interactiveView?.isInteractive = true
return self
}
public func commit() -> OMChartView {
refineLayers()
if interactiveView == nil { interactiveView = OMChartInteractiveView(frame: self.bounds) }
interactiveView?.frame = self.bounds
interactiveView?.rectInset = rectInset
interactiveView?.appendLayers(chartLayers)
self.addSubview(interactiveView!)
return self
}
private func refineLayers() {
chartLayers.map { $0.refineLayer(self.bounds, rectInset).draw() }
}
}
| mit | 5120cf4b21ac95841ab3bdaf123947b6 | 23.34 | 98 | 0.641742 | 4.735409 | false | false | false | false |
kstaring/swift | test/Constraints/patterns.swift | 4 | 5424 | // RUN: %target-parse-verify-swift
// Leaf expression patterns are matched to corresponding pieces of a switch
// subject (TODO: or ~= expression) using ~= overload resolution.
switch (1, 2.5, "three") {
case (1, _, _):
()
// Double is ExpressibleByIntegerLiteral
case (_, 2, _),
(_, 2.5, _),
(_, _, "three"):
()
// ~= overloaded for (Range<Int>, Int)
case (0..<10, _, _),
(0..<10, 2.5, "three"),
(0...9, _, _),
(0...9, 2.5, "three"):
()
}
switch (1, 2) {
case (var a, a): // expected-error {{use of unresolved identifier 'a'}}
()
}
// 'is' patterns can perform the same checks that 'is' expressions do.
protocol P { func p() }
class B : P {
init() {}
func p() {}
func b() {}
}
class D : B {
override init() { super.init() }
func d() {}
}
class E {
init() {}
func e() {}
}
struct S : P {
func p() {}
func s() {}
}
// Existential-to-concrete.
var bp : P = B()
switch bp {
case is B,
is D,
is S:
()
case is E:
()
}
switch bp {
case let b as B:
b.b()
case let d as D:
d.b()
d.d()
case let s as S:
s.s()
case let e as E:
e.e()
}
// Super-to-subclass.
var db : B = D()
switch db {
case is D:
()
case is E: // expected-warning {{always fails}}
()
}
// Raise an error if pattern productions are used in expressions.
var b = var a // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// TODO: Bad recovery in these cases. Although patterns are never valid
// expr-unary productions, it would be good to parse them anyway for recovery.
//var e = 2 + var y
//var e = var y + 2
// 'E.Case' can be used in a dynamic type context as an equivalent to
// '.Case as E'.
protocol HairType {}
enum MacbookHair: HairType {
case HairSupply(S)
}
enum iPadHair<T>: HairType {
case HairForceOne
}
enum Watch {
case Sport, Watch, Edition
}
let hair: HairType = MacbookHair.HairSupply(S())
switch hair {
case MacbookHair.HairSupply(let s):
s.s()
case iPadHair<S>.HairForceOne:
()
case iPadHair<E>.HairForceOne:
()
case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}}
()
case Watch.Edition: // TODO: should warn that cast can't succeed with currently known conformances
()
case .HairForceOne: // expected-error{{enum case 'HairForceOne' not found in type 'HairType'}}
()
default:
break
}
// <rdar://problem/19382878> Introduce new x? pattern
switch Optional(42) {
case let x?: break
case nil: break
}
func SR2066(x: Int?) {
// nil literals should still work when wrapped in parentheses
switch x {
case (nil): break
case _?: break
}
switch x {
case ((nil)): break
case _?: break
}
switch (x, x) {
case ((nil), _): break
case (_?, _): break
}
}
// Test x???? patterns.
switch (nil as Int???) {
case let x???: print(x, terminator: "")
case let x??: print(x as Any, terminator: "")
case let x?: print(x as Any, terminator: "")
case 4???: break
case nil??: break
case nil?: break
default: break
}
// <rdar://problem/21995744> QoI: Binary operator '~=' cannot be applied to operands of type 'String' and 'String?'
switch ("foo" as String?) {
case "what": break // expected-error{{expression pattern of type 'String' cannot match values of type 'String?'}}
default: break
}
// Test some value patterns.
let x : Int?
extension Int {
func method() -> Int { return 42 }
}
func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs
}
switch 4 as Int? {
case x?.method(): break // match value
}
switch 4 {
case x ?? 42: break // match value
default: break
}
for (var x) in 0...100 {}
for var x in 0...100 {} // rdar://20167543
for (let x) in 0...100 {} // expected-error {{'let' pattern cannot appear nested in an already immutable context}}
var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
// Crash when re-typechecking EnumElementPattern.
// FIXME: This should actually type-check -- the diagnostics are bogus. But
// at least we don't crash anymore.
protocol PP {
associatedtype E
}
struct A<T> : PP {
typealias E = T
}
extension PP {
func map<T>(_ f: (Self.E) -> T) -> T {}
}
enum EE {
case A
case B
}
func good(_ a: A<EE>) -> Int {
return a.map {
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
func bad(_ a: A<EE>) {
a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }}
let _: EE = $0
return 1
}
}
func ugly(_ a: A<EE>) {
a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }}
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
// SR-2057
enum SR2057 {
case foo
}
let sr2057: SR2057?
if case .foo = sr2057 { } // expected-error{{enum case 'foo' not found in type 'SR2057?'}}
| apache-2.0 | cb6b78ada4ce0fe36bb0bf1ff82f3967 | 20.696 | 208 | 0.620022 | 3.346083 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Nodes/Playback/Phase-Locked Vocoder/AKPhaseLockedVocoder.swift | 1 | 9730 | //
// AKPhaseLockedVocoder.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// This is a phase locked vocoder. It has the ability to play back an audio
/// file loaded into an ftable like a sampler would. Unlike a typical sampler,
/// mincer allows time and pitch to be controlled separately.
///
/// - parameter audioFileURL: Location of the audio file to use.
/// - parameter position: Position in time. When non-changing it will do a spectral freeze of a the current point in time.
/// - parameter amplitude: Amplitude.
/// - parameter pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
///
public class AKPhaseLockedVocoder: AKNode {
// MARK: - Properties
internal var internalAU: AKPhaseLockedVocoderAudioUnit?
internal var token: AUParameterObserverToken?
private var positionParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var pitchRatioParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Position in time. When non-changing it will do a spectral freeze of a the current point in time.
public var position: Double = 0 {
willSet {
if position != newValue {
if internalAU!.isSetUp() {
positionParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.position = Float(newValue)
}
}
}
}
/// Amplitude.
public var amplitude: Double = 1 {
willSet {
if amplitude != newValue {
if internalAU!.isSetUp() {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
public var pitchRatio: Double = 1 {
willSet {
if pitchRatio != newValue {
if internalAU!.isSetUp() {
pitchRatioParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.pitchRatio = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
private var audioFileURL: CFURL
// MARK: - Initialization
/// Initialize this Phase-Locked Vocoder node
///
/// - parameter audioFileURL: Location of the audio file to use.
/// - parameter position: Position in time. When non-changing it will do a spectral freeze of a the current point in time.
/// - parameter amplitude: Amplitude.
/// - parameter pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
///
public init(
audioFileURL: NSURL,
position: Double = 0,
amplitude: Double = 1,
pitchRatio: Double = 1) {
self.position = position
self.amplitude = amplitude
self.pitchRatio = pitchRatio
self.audioFileURL = audioFileURL
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x6d696e63 /*'minc'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKPhaseLockedVocoderAudioUnit.self,
asComponentDescription: description,
name: "Local AKPhaseLockedVocoder",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPhaseLockedVocoderAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
positionParameter = tree.valueForKey("position") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
pitchRatioParameter = tree.valueForKey("pitchRatio") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.positionParameter!.address {
self.position = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
} else if address == self.pitchRatioParameter!.address {
self.pitchRatio = Double(value)
}
}
}
internalAU?.position = Float(position)
internalAU?.amplitude = Float(amplitude)
internalAU?.pitchRatio = Float(pitchRatio)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
Exit: do {
var err: OSStatus = noErr
var theFileLengthInFrames: Int64 = 0
var theFileFormat: AudioStreamBasicDescription = AudioStreamBasicDescription()
var thePropertySize: UInt32 = UInt32(strideofValue(theFileFormat))
var extRef: ExtAudioFileRef = nil
var theData: UnsafeMutablePointer<CChar> = nil
var theOutputFormat: AudioStreamBasicDescription = AudioStreamBasicDescription()
err = ExtAudioFileOpenURL(self.audioFileURL, &extRef)
if err != 0 { print("ExtAudioFileOpenURL FAILED, Error = \(err)"); break Exit }
// Get the audio data format
err = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat)
if err != 0 { print("ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = \(err)"); break Exit }
if theFileFormat.mChannelsPerFrame > 2 { print("Unsupported Format, channel count is greater than stereo"); break Exit }
theOutputFormat.mSampleRate = AKSettings.sampleRate
theOutputFormat.mFormatID = kAudioFormatLinearPCM
theOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat
theOutputFormat.mBitsPerChannel = UInt32(strideof(Float)) * 8
theOutputFormat.mChannelsPerFrame = 1; // Mono
theOutputFormat.mBytesPerFrame = theOutputFormat.mChannelsPerFrame * UInt32(strideof(Float))
theOutputFormat.mFramesPerPacket = 1
theOutputFormat.mBytesPerPacket = theOutputFormat.mFramesPerPacket * theOutputFormat.mBytesPerFrame
// Set the desired client (output) data format
err = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, UInt32(strideofValue(theOutputFormat)), &theOutputFormat)
if err != 0 { print("ExtAudioFileSetProperty(kExtAudioFileProperty_ClientDataFormat) FAILED, Error = \(err)"); break Exit }
// Get the total frame count
thePropertySize = UInt32(strideofValue(theFileLengthInFrames))
err = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames)
if err != 0 { print("ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = \(err)"); break Exit }
// Read all the data into memory
let dataSize = UInt32(theFileLengthInFrames) * theOutputFormat.mBytesPerFrame
theData = UnsafeMutablePointer.alloc(Int(dataSize))
if theData != nil {
var theDataBuffer: AudioBufferList = AudioBufferList()
theDataBuffer.mNumberBuffers = 1
theDataBuffer.mBuffers.mDataByteSize = dataSize
theDataBuffer.mBuffers.mNumberChannels = theOutputFormat.mChannelsPerFrame
theDataBuffer.mBuffers.mData = UnsafeMutablePointer(theData)
// Read the data into an AudioBufferList
var ioNumberFrames: UInt32 = UInt32(theFileLengthInFrames)
err = ExtAudioFileRead(extRef, &ioNumberFrames, &theDataBuffer)
if err == noErr {
// success
let data=UnsafeMutablePointer<Float>(theDataBuffer.mBuffers.mData)
internalAU?.setupAudioFileTable(data, size: ioNumberFrames)
internalAU!.start()
} else {
// failure
theData.dealloc(Int(dataSize))
theData = nil // make sure to return NULL
print("Error = \(err)"); break Exit;
}
}
}
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
internalAU!.stop()
}
}
| mit | c7e6b2518a4e94c45a492b352f1ada2e | 41.863436 | 147 | 0.619424 | 5.833333 | false | false | false | false |
headione/criticalmaps-ios | CriticalMapsKit/Tests/SettingsFeatureTests/RideEventSettingsCoreTests.swift | 1 | 1890 | import ComposableArchitecture
import Foundation
import SettingsFeature
import SharedModels
import XCTest
class RideEventSettingsCoreTests: XCTestCase {
func test_setRideEventsEnabled() {
let store = TestStore(
initialState: RideEventSettings(
isEnabled: true,
typeSettings: .all,
eventDistance: .close
),
reducer: rideeventSettingsReducer,
environment: RideEventSettingsEnvironment()
)
store.send(.setRideEventsEnabled(false)) {
$0.isEnabled = false
}
store.send(.setRideEventsEnabled(true)) {
$0.isEnabled = true
}
}
func test_setRideEventsTypeEnabled() {
let store = TestStore(
initialState: RideEventSettings(
isEnabled: true,
typeSettings: .all,
eventDistance: .close
),
reducer: rideeventSettingsReducer,
environment: RideEventSettingsEnvironment()
)
var updatedType = RideEventSettings.RideEventTypeSetting(type: .kidicalMass, isEnabled: false)
store.send(.setRideEventTypeEnabled(updatedType)) {
var updatedSettings: [RideEventSettings.RideEventTypeSetting] = .all
let index = try XCTUnwrap(updatedSettings.firstIndex(where: { setting in
setting.type == updatedType.type
}))
updatedSettings[index] = updatedType
$0.typeSettings = updatedSettings
}
updatedType.isEnabled = true
store.send(.setRideEventTypeEnabled(updatedType)) {
$0.typeSettings = .all
}
}
func test_setRideEventsRadius() {
let store = TestStore(
initialState: RideEventSettings(
isEnabled: true,
typeSettings: .all,
eventDistance: .close
),
reducer: rideeventSettingsReducer,
environment: RideEventSettingsEnvironment()
)
store.send(.setRideEventRadius(.near)) {
$0.eventDistance = .near
}
}
}
| mit | 696d5f0a2108e878c8f36dc8de191686 | 26 | 98 | 0.667725 | 4.80916 | false | true | false | false |
NeilNie/Done- | Pods/Eureka/Source/Rows/Common/GenericMultipleSelectorRow.swift | 1 | 3876 | // GenericMultipleSelectorRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Generic options selector row that allows multiple selection.
open class GenericMultipleSelectorRow<T, Cell: CellType>: Row<Cell>, PresenterRowType, NoValueDisplayTextConformance, OptionsProviderRow
where Cell: BaseCell, Cell.Value == Set<T> {
public typealias PresentedController = MultipleSelectorViewController<GenericMultipleSelectorRow<T,Cell>>
/// Defines how the view controller will be presented, pushed, etc.
open var presentationMode: PresentationMode<PresentedController>?
/// Will be called before the presentation occurs.
open var onPresentCallback: ((FormViewController, PresentedController) -> Void)?
/// Title to be displayed for the options
open var selectorTitle: String?
open var noValueDisplayText: String?
/// Options from which the user will choose
open var optionsProvider: OptionsProvider<T>?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = { (rowValue: Set<T>?) in
return rowValue?.map({ String(describing: $0) }).sorted().joined(separator: ", ")
}
presentationMode = .show(controllerProvider: ControllerProvider.callback {
return MultipleSelectorViewController<GenericMultipleSelectorRow<T,Cell>>()
}, onDismiss: { vc in
let _ = vc.navigationController?.popViewController(animated: true)
})
}
/**
Extends `didSelect` method
*/
open override func customDidSelect() {
super.customDidSelect()
guard let presentationMode = presentationMode, !isDisabled else { return }
if let controller = presentationMode.makeController() {
controller.row = self
controller.title = selectorTitle ?? controller.title
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: self.cell.formViewController()!)
} else {
presentationMode.present(nil, row: self, presentingController: self.cell.formViewController()!)
}
}
/**
Prepares the pushed row setting its title and completion callback.
*/
open override func prepare(for segue: UIStoryboardSegue) {
super.prepare(for: segue)
guard let rowVC = segue.destination as Any as? PresentedController else { return }
rowVC.title = selectorTitle ?? rowVC.title
rowVC.onDismissCallback = presentationMode?.onDismissCallback ?? rowVC.onDismissCallback
onPresentCallback?(cell.formViewController()!, rowVC)
rowVC.row = self
}
}
| apache-2.0 | 4aaed5f6c46ee962cab0ce6a2b6e9a93 | 44.6 | 136 | 0.71001 | 5.1749 | false | false | false | false |
cnbin/QRCodeReader.swift | QRCodeReader/QRCodeViewController.swift | 1 | 10393 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import AVFoundation
/// Convenient controller to display a view to scan/read 1D or 2D bar codes like the QRCodes. It is based on the `AVFoundation` framework from Apple. It aims to replace ZXing or ZBar for iOS 7 and over.
public final class QRCodeReaderViewController: UIViewController {
private var cameraView = ReaderOverlayView()
private var cancelButton = UIButton()
private var codeReader: QRCodeReader?
private var switchCameraButton: SwitchCameraButton?
private var startScanningAtLoad = true
// MARK: - Managing the Callback Responders
/// The receiver's delegate that will be called when a result is found.
public weak var delegate: QRCodeReaderViewControllerDelegate?
/// The completion blocak that will be called when a result is found.
public var completionBlock: ((String?) -> ())?
deinit {
codeReader?.stopScanning()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Creating the View Controller
/**
Initializes a view controller to read QRCodes from a displayed video preview and a cancel button to be go back.
- parameter cancelButtonTitle: The title to use for the cancel button.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
:see: init(cancelButtonTitle:, metadataObjectTypes:)
*/
convenience public init(cancelButtonTitle: String, startScanningAtLoad: Bool = true) {
self.init(cancelButtonTitle: cancelButtonTitle, metadataObjectTypes: [AVMetadataObjectTypeQRCode], startScanningAtLoad: startScanningAtLoad)
}
/**
Initializes a reader view controller with a list of metadata object types.
- parameter metadataObjectTypes: An array of strings identifying the types of metadata objects to process.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
:see: init(cancelButtonTitle:, metadataObjectTypes:)
*/
convenience public init(metadataObjectTypes: [String], startScanningAtLoad: Bool = true) {
self.init(cancelButtonTitle: "Cancel", metadataObjectTypes: metadataObjectTypes, startScanningAtLoad: startScanningAtLoad)
}
/**
Initializes a view controller to read wanted metadata object types from a displayed video preview and a cancel button to be go back.
- parameter cancelButtonTitle: The title to use for the cancel button.
- parameter metadataObjectTypes: An array of strings identifying the types of metadata objects to process.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
:see: init(cancelButtonTitle:, coderReader:)
*/
convenience public init(cancelButtonTitle: String, metadataObjectTypes: [String], startScanningAtLoad: Bool = true) {
let reader = QRCodeReader(metadataObjectTypes: metadataObjectTypes)
self.init(cancelButtonTitle: cancelButtonTitle, coderReader: reader, startScanningAtLoad: startScanningAtLoad)
}
/**
Initializes a view controller using a cancel button title and a code reader.
- parameter cancelButtonTitle: The title to use for the cancel button.
- parameter coderReader: The code reader object used to scan the bar code.
- parameter startScanningAtLoad: Flag to know whether the view controller start scanning the codes when the view will appear.
*/
required public init(cancelButtonTitle: String, coderReader reader: QRCodeReader, startScanningAtLoad startScan: Bool = true) {
super.init(nibName: nil, bundle: nil) // Workaround for init in iOS SDK 8.3
startScanningAtLoad = startScan
codeReader = reader
view.backgroundColor = UIColor.blackColor()
codeReader?.completionBlock = { [unowned self] (resultAsString) in
if let _completionBlock = self.completionBlock {
_completionBlock(resultAsString)
}
if let _delegate = self.delegate {
if let _resultAsString = resultAsString {
_delegate.reader(self, didScanResult: _resultAsString)
}
}
}
setupUIComponentsWithCancelButtonTitle(cancelButtonTitle)
setupAutoLayoutConstraints()
cameraView.layer.insertSublayer(codeReader!.previewLayer, atIndex: 0)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationDidChanged:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Responding to View Events
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if startScanningAtLoad {
startScanning()
}
}
override public func viewWillDisappear(animated: Bool) {
stopScanning()
super.viewWillDisappear(animated)
}
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
codeReader?.previewLayer.frame = view.bounds
}
// MARK: - Managing the Orientation
func orientationDidChanged(notification: NSNotification) {
cameraView.setNeedsDisplay()
if codeReader?.previewLayer.connection != nil {
let orientation = UIApplication.sharedApplication().statusBarOrientation
codeReader?.previewLayer.connection.videoOrientation = QRCodeReader.videoOrientationFromInterfaceOrientation(orientation)
}
}
// MARK: - Initializing the AV Components
private func setupUIComponentsWithCancelButtonTitle(cancelButtonTitle: String) {
cameraView.clipsToBounds = true
cameraView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(cameraView)
if let _codeReader = codeReader {
_codeReader.previewLayer.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)
if _codeReader.previewLayer.connection.supportsVideoOrientation {
let orientation = UIApplication.sharedApplication().statusBarOrientation
_codeReader.previewLayer.connection.videoOrientation = QRCodeReader.videoOrientationFromInterfaceOrientation(orientation)
}
if _codeReader.hasFrontDevice() {
let newSwitchCameraButton = SwitchCameraButton()
newSwitchCameraButton.translatesAutoresizingMaskIntoConstraints = false
newSwitchCameraButton.addTarget(self, action: "switchCameraAction:", forControlEvents: .TouchUpInside)
view.addSubview(newSwitchCameraButton)
switchCameraButton = newSwitchCameraButton
}
}
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
cancelButton.setTitleColor(UIColor.grayColor(), forState: .Highlighted)
cancelButton.addTarget(self, action: "cancelAction:", forControlEvents: .TouchUpInside)
view.addSubview(cancelButton)
}
private func setupAutoLayoutConstraints() {
let views: [String: AnyObject] = ["cameraView": cameraView, "cancelButton": cancelButton]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[cameraView][cancelButton(40)]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[cameraView]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[cancelButton]-|", options: [], metrics: nil, views: views))
if let _switchCameraButton = switchCameraButton {
let switchViews: [String: AnyObject] = ["switchCameraButton": _switchCameraButton]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[switchCameraButton(50)]", options: [], metrics: nil, views: switchViews))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[switchCameraButton(70)]|", options: [], metrics: nil, views: switchViews))
}
}
// MARK: - Controlling the Reader
/// Starts scanning the codes.
public func startScanning() {
codeReader?.startScanning()
}
/// Stops scanning the codes.
public func stopScanning() {
codeReader?.stopScanning()
}
// MARK: - Catching Button Events
func cancelAction(button: UIButton) {
codeReader?.stopScanning()
if let _completionBlock = completionBlock {
_completionBlock(nil)
}
delegate?.readerDidCancel(self)
}
func switchCameraAction(button: SwitchCameraButton) {
codeReader?.switchDeviceInput()
}
}
/**
This protocol defines delegate methods for objects that implements the `QRCodeReaderDelegate`. The methods of the protocol allow the delegate to be notified when the reader did scan result and or when the user wants to stop to read some QRCodes.
*/
public protocol QRCodeReaderViewControllerDelegate: class {
/**
Tells the delegate that the reader did scan a code.
- parameter reader: A code reader object informing the delegate about the scan result.
- parameter result: The result of the scan
*/
func reader(reader: QRCodeReaderViewController, didScanResult result: String)
/**
Tells the delegate that the user wants to stop scanning codes.
- parameter reader: A code reader object informing the delegate about the cancellation.
*/
func readerDidCancel(reader: QRCodeReaderViewController)
} | mit | 842355526cbd79bac1e5bee8bf0faacd | 38.976923 | 245 | 0.757818 | 5.318833 | false | false | false | false |
64characters/Telephone | UseCasesTestDoubles/SystemDefaultSoundIO+Equatable.swift | 1 | 1404 | //
// DefaultSettingsSoundIOSoundIOItem+Equatable.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
import DomainTestDoubles
import UseCases
extension SystemDefaultingSoundIO: Equatable {
public static func == (lhs: SystemDefaultingSoundIO, rhs: SystemDefaultingSoundIO) -> Bool {
return lhs.input == rhs.input && lhs.output == rhs.output && lhs.ringtoneOutput == rhs.ringtoneOutput
}
}
extension SystemDefaultingSoundIO.Item: Equatable {
public static func ==(lhs: SystemDefaultingSoundIO.Item, rhs: SystemDefaultingSoundIO.Item) -> Bool {
switch (lhs, rhs) {
case (.systemDefault, .systemDefault):
return true
case let (.device(l), .device(r)):
return l == r
case (.systemDefault, _),
(.device, _):
return false
}
}
}
| gpl-3.0 | c15c40021300ecf13e48fde38a78f223 | 34.05 | 109 | 0.684736 | 4.551948 | false | false | false | false |
KYawn/myiOS | WeiXin/WeiXin/BuddyListViewController.swift | 1 | 3477 | //
// BuddyListViewController.swift
// WeiXin
//
// Created by K.Yawn Xoan on 3/31/15.
// Copyright (c) 2015 KevinHsiun. All rights reserved.
//
import UIKit
class BuddyListViewController: UITableViewController {
//好友数组,作为表格的数据源
var bList = [WXMessage]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO 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 NO 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.
}
*/
@IBAction func unwindToBList(segue: UIStoryboardSegue) {
}
}
| apache-2.0 | fa0864de1917079cd37359df149e9800 | 32.852941 | 157 | 0.679699 | 5.463608 | false | false | false | false |
longdnguyen/Tipzi | Tipzi/ViewController.swift | 1 | 5376 |
// ViewController.swift
// Tipzi
//
// Created by Long Nguyen on 8/20/15.
// Copyright (c) 2015 Long Nguyen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var numberOfDiner:Double = 0.0
//supporting declare
var emptyString: String = ""
//Button
@IBOutlet weak var onePersonButton: UIButton!
@IBOutlet weak var twoPeopleButton: UIButton!
@IBOutlet weak var threePeopleButton: UIButton!
@IBOutlet weak var fourPeopleButton: UIButton!
//Label and Field
@IBOutlet weak var billAmountField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipPercentageLabel: UILabel!
@IBOutlet weak var eachLabel: UILabel!
@IBOutlet weak var dollarLabel: UILabel!
@IBOutlet weak var tipPercentageSlider: UISlider!
//View
@IBOutlet weak var tipziView: UIImageView!
@IBOutlet weak var billAmountView: UIView!
@IBOutlet weak var calculationView: UIView!
@IBOutlet weak var totalView: UIView!
@IBOutlet weak var tipView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
tipPercentageSlider.value = 0.1
tipPercentageLabel.text = "10%"
self.eachLabel.hidden = true
billAmountField.becomeFirstResponder()
animationView()
numberOfDiner = 1.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Manage the number of people
@IBAction func dinerNumberCalculation(sender: AnyObject) {
switch (sender.tag) {
case 1:
numberOfDiner = 1
self.refreshIcon()
onePersonButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
self.eachLabel.hidden = true
updateTotalBill()
case 2:
numberOfDiner = 2
self.refreshIcon()
onePersonButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
twoPeopleButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
self.eachLabel.hidden = false
updateTotalBill()
case 3:
numberOfDiner = 3
self.refreshIcon()
twoPeopleButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
threePeopleButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
self.eachLabel.hidden = false
updateTotalBill()
case 4:
numberOfDiner = 4
self.refreshIcon()
twoPeopleButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
threePeopleButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
fourPeopleButton.setImage(UIImage(named:"human_filled.png"), forState:UIControlState.Normal)
self.eachLabel.hidden = false
updateTotalBill()
default:
break
}
animationView()
}
func refreshIcon() {
twoPeopleButton.setImage(UIImage(named:"human_not_filled.png"), forState:UIControlState.Normal)
threePeopleButton.setImage(UIImage(named:"human_not_filled.png"), forState:UIControlState.Normal)
fourPeopleButton.setImage(UIImage(named:"human_not_filled.png"), forState:UIControlState.Normal)
}
func updateTotalBill() {
var tipPercentage = tipPercentageSlider.value
var tipRate = tipPercentage / 100
var updatedBillAmount = NSString(string: billAmountField.text).doubleValue
var updatedTip:Double = Double (updatedBillAmount) * Double(tipRate)
var updatedTotal = updatedTip + updatedBillAmount
var updatedTotalSplit: Double = Double(updatedTotal) / numberOfDiner
tipLabel.text = "+\(updatedTip)"
totalLabel.text = "\(updatedTotalSplit)"
tipLabel.text = String(format: "$%.2f",updatedTip)
totalLabel.text = String(format: "$%.2f",updatedTotalSplit)
}
@IBAction func sliderCalculation(sender: AnyObject) {
var tipPercentageValue = Int(tipPercentageSlider.value)
//get the value on the slider
tipPercentageLabel.text = "\(tipPercentageValue)%"
//put the value of the slider control on the label
animationView()
updateTotalBill()
}
@IBAction func onEditingChanged(sender: AnyObject) {
var billAmount = NSString(string: billAmountField.text).doubleValue
var tip = billAmount * 0.1
var total = billAmount + tip
tipLabel.text = "+\(tip)"
totalLabel.text = "\(total)"
animationView()
updateTotalBill()
}
func animationView() {
//hiding the controlview and the bill, tip ammount
if billAmountField.text == emptyString {
UIView.animateWithDuration(0.5, animations: {
self.dollarLabel.hidden = false
self.totalView.alpha = 0
self.calculationView.alpha = 0
self.tipView.alpha = 0
self.billAmountView.frame = CGRectMake(0, 150, 320, 63)
})
}
else {
UIView.animateWithDuration(0.5, animations: {
self.totalView.alpha = 1
self.calculationView.alpha = 1
self.billAmountField.alpha = 1
self.tipView.alpha = 1
self.dollarLabel.hidden = true
self.billAmountView.frame = CGRectMake(0, 58, 320, 63)
})
}
}
}
| mit | 0ec378ab104a6eddff9495f4d3aaa3cb | 28.701657 | 101 | 0.696243 | 4.410172 | false | false | false | false |
leo-lp/LPIM | LPIM+UIKit/Common/LPKCellLayoutConfig.swift | 1 | 3881 | //
// LPKCellLayoutConfig.swift
// LPIM
//
// Created by lipeng on 2017/6/23.
// Copyright © 2017年 lipeng. All rights reserved.
//
import UIKit
import NIMSDK
class LPKCellLayoutConfig: NSObject, LPKCellLayoutConfigDelegate {
/// - Returns: 返回message的内容大小
// func contentSize(_ model: LPKMessageModel, cellWidth width: CGFloat) -> CGSize {
// id<NIMSessionContentConfig>config = [[NIMSessionContentConfigFactory sharedFacotry] configBy:model.message];
// return [config contentSize:cellWidth message:model.message];
// }
/// 需要构造的cellContent类名
// func cellContent(_ model: LPKMessageModel) -> String {
// id<NIMSessionContentConfig>config = [[NIMSessionContentConfigFactory sharedFacotry] configBy:model.message];
// NSString *cellContent = [config cellContent:model.message];
// return cellContent.length ? cellContent : @"NIMSessionUnknowContentView";
// }
/// 左对齐的气泡,cell气泡距离整个cell的内间距
// func cellInsets(_ model: LPKMessageModel) -> UIEdgeInsets {
// if ([[self cellContent:model] isEqualToString:@"NIMSessionNotificationContentView"]) {
// return UIEdgeInsetsZero;
// }
// CGFloat cellTopToBubbleTop = 3;
// CGFloat otherNickNameHeight = 20;
// CGFloat otherBubbleOriginX = [self shouldShowAvatar:model]? 55 : 0;
// CGFloat cellBubbleButtomToCellButtom = 13;
// if ([self shouldShowNickName:model])
// {
// //要显示名字
// return UIEdgeInsetsMake(cellTopToBubbleTop + otherNickNameHeight ,otherBubbleOriginX,cellBubbleButtomToCellButtom, 0);
// }
// else
// {
// return UIEdgeInsetsMake(cellTopToBubbleTop,otherBubbleOriginX,cellBubbleButtomToCellButtom, 0);
// }
// }
/// 左对齐的气泡,cell内容距离气泡的内间距
// func contentViewInsets(_ model: LPKMessageModel) -> UIEdgeInsets {
// id<NIMSessionContentConfig>config = [[NIMSessionContentConfigFactory sharedFacotry] configBy:model.message];
// return [config contentViewInsets:model.message];
// }
/// 是否显示头像
func shouldShowAvatar(_ model: LPKMessageModel) -> Bool {
let config = LPKUIConfig.shared.bubbleConfig(model.message)
return config?.showAvatar ?? true
}
/// 左对齐的气泡,头像到左边的距离
func avatarMargin(_ model: LPKMessageModel) -> CGFloat {
return 8.0
}
/// 是否显示姓名
func shouldShowNickName(_ model: LPKMessageModel) -> Bool {
guard let message = model.message else { return true }
if message.messageType == .notification {
if let obj = message.messageObject as? NIMNotificationObject {
if obj.notificationType == .team {
return false
}
}
}
if message.messageType == .tip {
return false
}
var flag = false
if let session = message.session {
flag = session.sessionType == .team
}
return !message.isOutgoingMsg && flag
}
/// 左对齐的气泡,昵称到左边的距离
func nickNameMargin(_ model: LPKMessageModel) -> CGFloat {
return shouldShowAvatar(model) ? 57.0 : 10.0
}
/// 消息显示在左边
func shouldShowLeft(_ model: LPKMessageModel) -> Bool {
if let msg = model.message {
return !msg.isOutgoingMsg
}
return false
}
/// 需要添加到Cell上的自定义视图
func customViews(_ model: LPKMessageModel) -> [UIView] {
return []
}
}
| mit | 6b3c3898e86a1f4d20e9a8bf53a2185e | 32.796296 | 136 | 0.601096 | 4.608586 | false | true | false | false |
m1ksoftware/SlideMenuControllerSwift | SlideMenuControllerSwift/AppDelegate.swift | 1 | 7761 | //
// AppDelegate.swift
// test11
//
// Created by Yuji Hato on 4/20/15.
// Copyright (c) 2015 Yuji Hato. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
fileprivate func createMenuView() {
// create viewController code...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
let leftViewController = storyboard.instantiateViewController(withIdentifier: "LeftViewController") as! LeftViewController
let rightViewController = storyboard.instantiateViewController(withIdentifier: "RightViewController") as! RightViewController
let nvc: UINavigationController = UINavigationController(rootViewController: mainViewController)
UINavigationBar.appearance().tintColor = UIColor(hex: "689F38")
leftViewController.mainViewController = nvc
let slideMenuController = ExSlideMenuController(mainViewController:nvc, leftMenuViewController: leftViewController, rightMenuViewController: rightViewController)
slideMenuController.automaticallyAdjustsScrollViewInsets = true
slideMenuController.delegate = mainViewController
self.window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0)
self.window?.rootViewController = slideMenuController
self.window?.makeKeyAndVisible()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.createMenuView()
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: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "dekatotoro.test11" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .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 = Bundle.main.url(forResource: "test11", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: 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)
let url = self.applicationDocumentsDirectory.appendingPathComponent("test11.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error
error = 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 \(error), \(error!.userInfo)")
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()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.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()
}
}
}
}
}
| mit | 5294164f357b167b61a0d07b9c0d8c5d | 52.524138 | 290 | 0.693081 | 5.974596 | false | false | false | false |
suragch/aePronunciation-iOS | aePronunciation/Ipa.swift | 1 | 4406 | import Swift
struct Ipa {
static let NUMBER_OF_VOWELS = 21
static let NUMBER_OF_VOWELS_FOR_DOUBLES = 19 // not ə, ɚ
static let NUMBER_OF_CONSONANTS = 26
static let NUMBER_OF_CONSONANTS_FOR_DOUBLES = 24 // not ʔ. ɾ
static func splitDoubleSound(str: String) -> (String, String) {
//let firstChar = s.prefix(1)
var index = str.index(str.startIndex, offsetBy: 1)
let firstChar = str.prefix(upTo: index)
if isConsonant(ipa: firstChar) {
return (String(firstChar), String(str[index...]))
}
index = str.index(str.endIndex, offsetBy: -1)
let lastChar = str.suffix(1)
return (String(lastChar), String(str[..<index]))
}
static func isConsonant<T>(ipa: T) -> Bool where T: StringProtocol {
return "ptkʧfθsʃbdgʤvðzʒmnŋlwjhrʔɾ".contains(ipa)
}
static func isVowel<T>(ipa: T) -> Bool where T: StringProtocol {
return !isConsonant(ipa: ipa)
}
static func isSpecial<T>(ipa: T) -> Bool where T: StringProtocol {
return "ʔɾəɚ".contains(ipa)
}
static func hasTwoPronunciations<T>(ipa: T) -> Bool where T: StringProtocol {
return "fvθðmnl".contains(ipa)
}
static func getAllVowels() -> [String] {
return [
Ipa.i,
Ipa.i_short,
Ipa.e_short,
Ipa.ae,
Ipa.a,
Ipa.c_backwards,
Ipa.u_short,
Ipa.u,
Ipa.v_upsidedown,
Ipa.schwa,
Ipa.ei,
Ipa.ai,
Ipa.au,
Ipa.oi,
Ipa.ou,
Ipa.er_stressed,
Ipa.er_unstressed,
Ipa.ar,
Ipa.er,
Ipa.ir,
Ipa.or
]
}
static func getAllConsonants() -> [String] {
return [
Ipa.p,
Ipa.t,
Ipa.k,
Ipa.ch,
Ipa.f,
Ipa.th_voiceless,
Ipa.s,
Ipa.sh,
Ipa.b,
Ipa.d,
Ipa.g,
Ipa.dzh,
Ipa.v,
Ipa.th_voiced,
Ipa.z,
Ipa.zh,
Ipa.m,
Ipa.n,
Ipa.ng,
Ipa.l,
Ipa.w,
Ipa.j,
Ipa.h,
Ipa.r,
Ipa.glottal_stop,
Ipa.flap_t
]
}
static let p = "p"
static let t = "t"
static let k = "k"
static let ch = "ʧ"
static let f = "f"
static let th_voiceless = "θ"
static let s = "s"
static let sh = "ʃ"
static let b = "b"
static let d = "d"
static let g = "g"
static let dzh = "ʤ"
static let v = "v"
static let th_voiced = "ð"
static let z = "z"
static let zh = "ʒ"
static let m = "m"
static let n = "n"
static let ng = "ŋ"
static let l = "l"
static let w = "w"
static let j = "j"
static let h = "h"
static let r = "r"
static let i = "i"
static let i_short = "ɪ"
static let e_short = "ɛ"
static let ae = "æ"
static let a = "ɑ"
static let c_backwards = "ɔ"
static let u_short = "ʊ"
static let u = "u"
static let v_upsidedown = "ʌ"
static let schwa = "ə"
static let ei = "eɪ"
static let ai = "aɪ"
static let au = "aʊ"
static let oi = "ɔɪ"
static let ou = "oʊ"
static let flap_t = "ɾ"
static let er_stressed = "ɝ"
static let er_unstressed = "ɚ"
static let ar = "ɑr"
static let er = "ɛr"
static let ir = "ɪr"
static let or = "ɔr"
static let glottal_stop = "ʔ"
static let left_bracket = "["
static let right_bracket = "]"
static let slash = "/"
static let undertie = "‿"
//static let space = "\u0020"
static let primary_stress = "ˈ"
static let secondary_stress = "ˌ"
static let long_vowel = "ː"
//static let return = "\n"
static let alt_e_short = "e"
static let alt_c_backwards = "ɒ"
static let alt_ou = "əʊ"
static let alt_er_stressed = "ɜː"
static let alt_er_unstressed = "ə"
static let alt_ar = "ɑː"
static let alt_er = "eə"
static let alt_ir = "ɪə"
static let alt_or = "ɔː"
static let alt_l = "ɫ"
static let alt_w = "ʍ"
static let alt_h = "ʰ"
static let alt_r = "ɹ"
}
| unlicense | fa0a6d1903a4e289d719479a6d60232d | 25.120482 | 81 | 0.49631 | 3.243082 | false | false | false | false |
q231950/appwatch | AppWatchLogic/AppWatchLogic/TimeWarehouses/TimeWarehouse.swift | 1 | 839 | //
// TimeWarehouse.swift
// AppWatch
//
// Created by Martin Kim Dung-Pham on 16.08.15.
// Copyright © 2015 Martin Kim Dung-Pham. All rights reserved.
//
import Foundation
extension NSDate {
func endedWithinRange(from: NSDate, to: NSDate) -> Bool {
return (self.compare(to) == NSComparisonResult.OrderedAscending && self.compare(from) == NSComparisonResult.OrderedDescending) || self.compare(to) == NSComparisonResult.OrderedSame
}
func beganWithinRange(from: NSDate, to: NSDate) -> Bool {
return (self.compare(to) == NSComparisonResult.OrderedDescending && self.compare(from) == NSComparisonResult.OrderedAscending ) || self.compare(from) == NSComparisonResult.OrderedSame
}
}
protocol TimeWarehouse {
func timeBoxes(from: NSDate, to: NSDate, completion: ([TimeBox]?, NSError?) -> Void)
} | mit | ff1f18de4f5be431b3c802f7cc0a7a2c | 35.478261 | 191 | 0.708831 | 4.087805 | false | false | false | false |
LiuXingCode/LXScollContentViewSwift | LXScrollContentView/ViewController.swift | 1 | 2544 | //
// ViewController.swift
// LXScrollContentView
//
// Created by 刘行 on 2017/4/28.
// Copyright © 2017年 刘行. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate lazy var contentView : LXScrollContentView = {
let contentView = LXScrollContentView(frame: CGRect(x: 0, y: 40, width: self.view.bounds.width, height: self.view.bounds.height - 40))
contentView.delegate = self
return contentView
}()
fileprivate lazy var segmentBar : LXSegmentBar = {
let style = LXSegmentBarStyle()
style.backgroundColor = UIColor(r: 245, g: 245, b: 245)
let segmentBar = LXSegmentBar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 40), style: style)
segmentBar.delegate = self
return segmentBar
}()
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
setupUI()
reloadData()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
segmentBar.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 35)
contentView.frame = CGRect(x: 0, y: 35, width: view.bounds.width, height: view.bounds.height - 35)
}
}
extension ViewController {
fileprivate func setupUI() {
view.addSubview(segmentBar)
view.addSubview(contentView)
}
fileprivate func reloadData() {
segmentBar.titles = ["科技", "教育", "NBA", "每日开心", "精选文章", "订阅号", "房地产", "财经", "纪录片", "视频"]
var childVcs = [LXCategoryViewController]()
for title in segmentBar.titles {
let childVc = LXCategoryViewController()
childVc.categoryStr = title
childVc.view.backgroundColor = UIColor.randomColor()
childVcs.append(childVc)
}
contentView.reloadViewWithChildVcs(childVcs, parentVc: self)
}
}
extension ViewController : LXSegmentBarDelegate {
func segmentBar(_ segmentBar: LXSegmentBar, selectedIndex: Int) {
contentView.pageIndex = selectedIndex
}
}
extension ViewController : LXScrollContentViewDelegate {
func contentViewDidEndDecelerating(_ contentView: LXScrollContentView, startIndex: Int, endIndex: Int) {
segmentBar.selectedIndex = endIndex
}
func contentViewDidScroll(_ contentView: LXScrollContentView, fromIndex: Int, toIndex: Int, progress: CGFloat) {
}
}
| mit | 454339209ec283e6c218cc77da3e7363 | 31.246753 | 142 | 0.653242 | 4.490054 | false | false | false | false |
shimesaba9/SwiftDefaults | Example/SwiftDefaults/MyDefaults.swift | 1 | 433 | //
// MyDefaults.swift
// SwiftDefaults
//
// Created by 杉本裕樹 on 2016/01/12.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
import SwiftDefaults
class MyDefaults: SwiftDefaults {
@objc dynamic var value: String? = "10"
@objc dynamic var value2: String = "10"
@objc dynamic var value3: Int = 1
@objc dynamic var value4: Person? = nil
@objc dynamic var value5: Date? = nil
}
| mit | f22bdbdd5418ee4cfda1619b6a92bcce | 21.210526 | 53 | 0.672986 | 3.246154 | false | false | false | false |
v2panda/DaysofSwift | swift2.3/My-AnimateTableView/My-AnimateTableView/SecondTableViewController.swift | 1 | 3249 | //
// SecondTableViewController.swift
// My-AnimateTableView
//
// Created by Panda on 16/2/26.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
class SecondTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning 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 | 7b103e0b1669fefb67a8284da5db078f | 33.168421 | 157 | 0.688232 | 5.567753 | false | false | false | false |
JadenGeller/Linky | Sources/LinkedList.swift | 1 | 2402 | //
// LinkedList.swift
// Linky
//
// Created by Jaden Geller on 12/30/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
public struct LinkedList<Element>: ArrayLiteralConvertible {
private var head: Node<Element>?
public init(arrayLiteral elements: Element...) {
if let first = elements.first {
var node = Node(first)
head = node
for x in elements[1..<elements.endIndex] {
let next = Node(x)
node.nextBacking.backing = next
node = next
}
}
else {
head = nil
}
}
}
extension LinkedList: MutableCollectionType {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
var count = 0
var node = head
while let unwrappedNode = node {
node = unwrappedNode.next
count++
}
return count - 1
}
public subscript(index: Int) -> Element {
get {
for (i,v) in enumerate() {
if i == index { return v }
}
fatalError("fatal error: Linked list index out of range")
}
set {
if head != nil {
head?.setAncestorValue(distance: index, value: newValue)
}
else {
fatalError("fatal error: Linked list index out of range")
}
}
}
}
extension LinkedList: SequenceType {
public func generate() -> LinkedListGenerator<Element> {
return LinkedListGenerator(node: head)
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
var str = "["
for (i, x) in enumerate() {
str += "\(x)"
if i != self.endIndex { str += ", " }
}
str += "]"
return str
}
}
public struct LinkedListGenerator<Element>: GeneratorType {
private var node: Node<Element>?
public mutating func next() -> Element? {
guard let current = node else { return nil }
node = current.next
return current.value
}
}
public func ==<Element: Equatable>(lhs: LinkedList<Element>, rhs: LinkedList<Element>) -> Bool {
switch (lhs.head, rhs.head) {
case (nil, nil): return true
case let (l?, r?): return l == r
default: return false
}
}
| mit | 6f90b4d911f650378505b55eb35b0344 | 24.273684 | 96 | 0.530196 | 4.555977 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift | 11 | 1978 | //
// Scan.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ScanSink<ElementType, O: ObserverType> : Sink<O>, ObserverType {
typealias Accumulate = O.E
typealias Parent = Scan<ElementType, Accumulate>
typealias E = ElementType
fileprivate let _parent: Parent
fileprivate var _accumulate: Accumulate
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_accumulate = parent._seed
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<ElementType>) {
switch event {
case .next(let element):
do {
_accumulate = try _parent._accumulator(_accumulate, element)
forwardOn(.next(_accumulate))
}
catch let error {
forwardOn(.error(error))
dispose()
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
forwardOn(.completed)
dispose()
}
}
}
class Scan<Element, Accumulate>: Producer<Accumulate> {
typealias Accumulator = (Accumulate, Element) throws -> Accumulate
fileprivate let _source: Observable<Element>
fileprivate let _seed: Accumulate
fileprivate let _accumulator: Accumulator
init(source: Observable<Element>, seed: Accumulate, accumulator: @escaping Accumulator) {
_source = source
_seed = seed
_accumulator = accumulator
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Accumulate {
let sink = ScanSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 0ff26a5bd5b47a89c25d834557bacd66 | 29.415385 | 148 | 0.607992 | 4.763855 | false | false | false | false |
cegiela/DragAndDropPod | DragAndDrop/Classes/DDCollectionView.swift | 1 | 13259 | //
// DDCollectionView.swift
// Pods
//
// Created by Mat Cegiela on 5/13/17.
//
//
import UIKit
public class DDCollectionView: UICollectionView {
public var dragAndDropDelegate: DDItemDelegate?
public let dragAndDropGestureRecogniser = UILongPressGestureRecognizer()
public var nativeDragAndDropItem: DDItem?
// public var autoScrollsWhileDragging = true
public var autoScrollZone = UIEdgeInsets(top: 50.0, left: 50.0, bottom: 50.0, right: 50.0)
public var autoScrollDragSpeedCutoff = CGFloat(500.0)//UIEdgeInsets(top: 500.0, left: 500.0, bottom: 500.0, right: 500.0)
public var autoScrollSpeedLimit = UIEdgeInsets(top: 100.0, left: 100.0, bottom: 100.0, right: 100.0)
//In points per second
public var autoScrollBoundsStretchLimit = UIEdgeInsets(top: 50.0, left: 50.0, bottom: 50.0, right: 50.0)
private var lastKnownTouchLocation: CGPoint?
private var autoScrollSpeed = CGPoint()
private var lockHorizontalAutoScroll = false
private var lockVerticalAutoScroll = false
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
configureAfterInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureAfterInit()
}
func configureAfterInit() {
dragAndDropGestureRecogniser.addTarget(self, action: #selector(DDView.gestureUpdate(_:)))
dragAndDropGestureRecogniser.minimumPressDuration = 0.3
self.addGestureRecognizer(dragAndDropGestureRecogniser)
}
func gestureUpdate(_ gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
let location = gesture.location(in: self)
beginPossibleDragAndDrop(location)
}
nativeDragAndDropItem?.updateWithGesture(gesture)
if gesture.state == .ended {
nativeDragAndDropItem = nil
}
}
func beginPossibleDragAndDrop(_ location: CGPoint) {
guard
let ddDelegate = dragAndDropDelegate,
let indexPath = indexPathForItem(at: location),
let attributes = collectionViewLayout.layoutAttributesForItem(at: indexPath),
let cell = cellForItem(at: indexPath),
let transitView = cell.snapshotView(afterScreenUpdates: false)
else {
return
}
let superview = DDView.rootSuperviewFor(self)
let frame = self.convert(attributes.frame, to: superview)
transitView.frame = frame
let item = DDItem(transitView: transitView, sharedSuperview: superview, delegate: ddDelegate)
if ddDelegate.ddItemCanDrag(item, originView: self) {
nativeDragAndDropItem = item
}
}
public func autoScrollForDragItem(_ item: DDItem) {
if item.isCompleted {
resetToBounds()
return
}
let localCoordinateTouch = item.sharedSuperview.convert(item.touchLocation, to: self)
if lastKnownTouchLocation == nil {
//Assume this is a new drag and drop action
//If touch began outside of the non-autoScroll zone (center region),
//lock autoScroll untill after the user drags into the center region
let width = frame.size.width - contentInset.right
if (localCoordinateTouch.x < autoScrollZone.left ||
localCoordinateTouch.x > width - autoScrollZone.right)
{
lockHorizontalAutoScroll = true
}
let height = frame.size.height - contentInset.bottom
if (localCoordinateTouch.y < autoScrollZone.top ||
localCoordinateTouch.y > height - autoScrollZone.bottom)
{
lockVerticalAutoScroll = true
}
}
if localCoordinateTouch != lastKnownTouchLocation {
lastKnownTouchLocation = localCoordinateTouch
recalculateAutoScrollSpeedAndDirectionForDragItem(item)
}
updateContentOffsetForDragItem(item)
}
private func recalculateAutoScrollSpeedAndDirectionForDragItem(_ item: DDItem) {
guard let touchLocation = lastKnownTouchLocation else { return }
autoScrollSpeed = CGPoint.zero
let leftThreshold = autoScrollZone.left + contentInset.left
let rightThreshold = frame.size.width - autoScrollZone.right - contentInset.right
let topThreshold = autoScrollZone.top + contentInset.top
let bottomThreshold = frame.size.height - autoScrollZone.bottom - contentInset.bottom
//Check if touch is located in any autoScroll zones,
//if it is, calculate scroll speed based on how close it is to the edge of view
//Left or
if (touchLocation.x < leftThreshold) {
if (touchLocation.x > leftThreshold - autoScrollZone.left) {
//Factor scroll speed by proximity to outer edge
let distance_X = leftThreshold - touchLocation.x
let factor = distance_X / autoScrollZone.left
autoScrollSpeed.x = -throttleSpeed(autoScrollSpeedLimit.left, factor: factor)
//Prevent scrolling beyond the bounds stretch limit
if (-contentOffset.x - contentInset.left) >= autoScrollBoundsStretchLimit.left {
autoScrollSpeed.x = 0.0
}
}
}
//Right
else if (touchLocation.x > rightThreshold) {
if (touchLocation.x < rightThreshold + autoScrollZone.right) {
//Factor scroll speed by proximity to outer edge
let distance_X = touchLocation.x - rightThreshold
let factor = distance_X / autoScrollZone.right
autoScrollSpeed.x = throttleSpeed(autoScrollSpeedLimit.right, factor: factor)
//Prevent scrolling beyond the bounds stretch limit
if (contentOffset.x + bounds.size.width) - contentSize.width + contentInset.right >=
autoScrollBoundsStretchLimit.right {
autoScrollSpeed.x = 0.0
}
}
}
else {
//Touch is now in the non-autoScroll zone (center region), unlock any future autoScroll
lockHorizontalAutoScroll = false
}
//Top or
if (touchLocation.y < topThreshold) {
if (touchLocation.y > topThreshold - autoScrollZone.top) {
//Factor scroll speed by proximity to outer edge
let distance_Y = topThreshold - touchLocation.y
let factor = distance_Y / autoScrollZone.top
autoScrollSpeed.y = -throttleSpeed(autoScrollSpeedLimit.top, factor: factor)
//Prevent scrolling beyond the bounds stretch limit
if (-contentOffset.y - contentInset.top) >= autoScrollBoundsStretchLimit.top {
autoScrollSpeed.y = 0.0
}
}
}
//Bottom
else if (touchLocation.y > bottomThreshold) {
if (touchLocation.y < bottomThreshold + autoScrollZone.bottom) {
//Factor scroll speed by proximity to outer edge
let distance_Y = touchLocation.y - bottomThreshold
let factor = distance_Y / autoScrollZone.bottom
autoScrollSpeed.y = throttleSpeed(autoScrollSpeedLimit.bottom, factor: factor)
//Prevent scrolling beyond the bounds stretch limit
if (contentOffset.y + bounds.size.height) - contentSize.height + contentInset.bottom >=
autoScrollBoundsStretchLimit.bottom {
autoScrollSpeed.y = 0.0
}
}
}
else {
//Touch is now in the non-autoScroll zone (center region), unlock any future autoScroll
lockVerticalAutoScroll = false
}
// print(currentAutoScrollSpeed)
}
private func updateContentOffsetForDragItem(_ item: DDItem) {
///Scroll self according to autoScroll speed
// guard let touchLocation = lastKnownTouchLocation else { return }
//////!!!!!///////
// Include checks for scroll locks, which was done elswhere before
// Include checks for velocity
//NOTE: When the touch velocity is high,
//we can assume the user is dragging out of this collection view.
//We can forgo AutoScroll to make a smother experience.
//Cancel AutoScroll if touch is travelling at high speed.
if item.touchVelocity > autoScrollDragSpeedCutoff { return }
/*
CGPoint currentContentOffset = self.collectionView.contentOffset;
CGSize contentSize = self.collectionView.contentSize;
CGRect bounds = self.collectionView.bounds;
UIEdgeInsets insets = self.collectionView.contentInset;
contentSize.height += insets.top + insets.bottom;
contentSize.width += insets.left + insets.right;
//Determine if we're out of bounds
CGFloat overscroll_X = 0.f;
CGFloat overscroll_Y = 0.f;
if (currentContentOffset.x + insets.left < 0 && _dragScrollSpeed.x < 0)
{
overscroll_X = -currentContentOffset.x - insets.left;
}
else if (currentContentOffset.x + bounds.size.width - insets.right > contentSize.width && _dragScrollSpeed.x > 0)
{
overscroll_X = (currentContentOffset.x + bounds.size.width) - contentSize.width + insets.right;
}
if (currentContentOffset.y + insets.top < 0 && _dragScrollSpeed.y < 0)
{
overscroll_Y = -currentContentOffset.y - insets.top;
}
else if (currentContentOffset.y + bounds.size.height > contentSize.height && _dragScrollSpeed.y > 0)
{
overscroll_Y = (currentContentOffset.y + bounds.size.height) - contentSize.height;
}
//Factor speed by distance out of bounds, slowing to a halt as it gets to maxOverscroll
CGFloat factoredSpeed_X = _dragScrollSpeed.x * factorByOverscroll(overscroll_X, maxOverscroll.x);
CGFloat factoredSpeed_Y = _dragScrollSpeed.y * factorByOverscroll(overscroll_Y, maxOverscroll.y);
//Calculate distance to scroll
CGPoint distanceToScroll = CGPointMake(factoredSpeed_X, factoredSpeed_Y);
CGPoint newOffset = pointAplusB(currentContentOffset, distanceToScroll);
//Scroll calculated distance
self.collectionView.contentOffset = newOffset;
*/
//TODO: Speed should probably be calculated based on framerate of CADisplayLink
if item.frameRate == 0.0 { return }
let scrollSpeedX = lockHorizontalAutoScroll ? 0.0 : autoScrollSpeed.x
let scrollSpeedY = lockVerticalAutoScroll ? 0.0 : autoScrollSpeed.y
let delta = CGPoint(x: scrollSpeedX / item.frameRate, y: scrollSpeedY / item.frameRate)
let newOffset = CGPoint(x: contentOffset.x + delta.x, y: contentOffset.y + delta.y)
contentOffset = newOffset
// if delta != CGPoint.zero {
// print("\(delta.x)" + " " + "\(delta.y)")
// }
}
private func resetToBounds() {
/*
CGRect bounds = self.collectionView.bounds;
CGPoint offset = self.collectionView.contentOffset;
UIEdgeInsets insets = self.collectionView.contentInset;
CGSize contentSize = self.collectionView.contentSize;
CGFloat rightEdge = offset.x + bounds.size.width;
CGFloat bottomEdge = offset.y + bounds.size.height + insets.bottom;
contentSize.height += insets.top + insets.bottom;
contentSize.width += insets.left + insets.right;
BOOL overscrolled = NO;
if (offset.x < 0)
{
overscrolled = YES;
offset.x = 0 - insets.left;
}
else if (rightEdge > contentSize.width)
{
overscrolled = YES;
offset.x = contentSize.width - bounds.size.width;
}
if (offset.y < 0)
{
overscrolled = YES;
offset.y = 0 - insets.top;
}
else if (bottomEdge > contentSize.height)
{
overscrolled = YES;
offset.y = contentSize.height - bounds.size.height;
}
if (overscrolled)
{
[self.collectionView setContentOffset:offset animated:YES];
}
*/
}
}
extension DDCollectionView {
func throttleSpeed(_ maxSpeed: CGFloat, factor: CGFloat) -> CGFloat {
return min(maxSpeed, maxSpeed * factor);
}
}
| mit | 40db7270d9bc4097ff69c2cf8041f896 | 38.112094 | 125 | 0.599894 | 5.28247 | false | false | false | false |
exoplatform/exo-ios | eXo/Sources/defines.swift | 1 | 2609 | //
// defines.swift
// eXoHybrid
//
// Created by Nguyen Manh Toan on 10/7/15.
// This is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of
// the License, or (at your option) any later version.
//
// This software 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this software; if not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301 USA, or see the FSF site: http://www.fsf.org.
import Foundation
import UIKit
struct ShortcutType {
static let connectRecentServer:String = "ios.exo.connect-recent-server"
static let addNewServer:String = "ios.exo.add-new-server"
}
struct Config {
// eXo Apple Store link
static let eXoAppleStoreUrl:String = "https://apps.apple.com/us/app/exo/id410476273"
static let communityURL:String = "https://community.exoplatform.com"
static let minimumPlatformVersionSupported:Float = 4.3
static let maximumShortcutAllow:Int = 4
static let timeout:TimeInterval = 60.0 // in seconds
static let onboardingDidShow: String = "onboardingDidShow"
// based on hex code #FFCB08
static let eXoYellowColor: UIColor = UIColor(red: 255.0/255, green: 203.0/255.0, blue: 8.0/255.0, alpha: 1.0)
// based on hex code #2F5E92
static let eXoBlueColor: UIColor = UIColor(red: 68/255, green: 93/255, blue: 147/255, alpha: 1.0)
static let kTableCellHeight: CGFloat = 80.0
static let kTableHeaderHeight: CGFloat = 50.0
// eXo Jitsi Server Path
static let eXoJitsiWebServer = "/jitsi"
static let eXoJitsiJWTPath = "/jitsi/api/v1/token/"
static let avatarURL = "/portal/rest/v1/social/users/*_*/avatar"
}
struct ShareExtension {
static let NSUserDefaultSuite:String = "group.com.exoplatform.mob.eXoPlatformiPHone"
static let AllUserNameKey:String = "exo_share_all_usernames"
}
enum Cookies: String {
case username = "last_login_username"
case domain = "last_login_domain"
case session = "JSESSIONID"
case sessionSso = "JSESSIONIDSSO"
case rememberMe = "rememberme"
}
struct ConnectionError {
static let URLError = 400
static let ServerVersionNotSupport = 403
static let ServerVersionNotFound = 404
}
| lgpl-3.0 | c25b45dde42d6a37c625db346b42994c | 37.367647 | 113 | 0.723266 | 3.727143 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Views/Chat/New Chat/Cells/UnreadMarkerCell.swift | 1 | 1201 | //
// UnreadMarkerCell.swift
// Rocket.Chat
//
// Created by Rafael Streit on 25/10/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
import RocketChatViewController
final class UnreadMarkerCell: UICollectionViewCell, ChatCell, SizingCell {
static let identifier = String(describing: UnreadMarkerCell.self)
static let sizingCell: UICollectionViewCell & ChatCell = {
guard let cell = UnreadMarkerCell.instantiateFromNib() else {
return UnreadMarkerCell()
}
return cell
}()
@IBOutlet weak var label: UILabel! {
didSet {
label.font = label.font.bold()
label.text = localized("chat.unread_separator")
}
}
@IBOutlet weak var separatorLeft: UIView!
@IBOutlet weak var separatorRight: UIView!
var messageWidth: CGFloat = 0
var viewModel: AnyChatItem?
func configure(completeRendering: Bool) {}
}
// MARK: Theming
extension UnreadMarkerCell {
override func applyTheme() {
super.applyTheme()
label.textColor = .attention
separatorLeft.backgroundColor = .attention
separatorRight.backgroundColor = .attention
}
}
| mit | 1845e5bd71fbc8b514b0c0b37b9a5577 | 22.529412 | 74 | 0.6675 | 4.819277 | false | false | false | false |
heitorgcosta/Quiver | Quiver/Validating/ValidationError.swift | 1 | 1752 | //
// ValidatorError.swift
// Quiver
//
// Created by Heitor Costa on 19/09/17.
// Copyright © 2017 Heitor Costa. All rights reserved.
//
/**
`ValidationError` encapsulates all errors occurred during the validation proccess. The `read-only` property `items` contains all error items that was generated, each one describing the errors. Those items are what should be used to get the messages and etc.
*/
public struct ValidationError {
typealias ValidationErrorItemMap = [AnyKeyPath: [ValidationErrorItem]]
/// The array containing all error items occurred during validation.
public private(set) var items: [ValidationErrorItem] = []
/// A map containing all error items occurred during validation separated by keypaths.
private var mappedByField: ValidationErrorItemMap = [:]
/// The first item contained in the errors. Nil if there's no items.
public var firstItem: ValidationErrorItem? {
return items.first
}
public init(items: [ValidationErrorItem]) {
self.items = items
mapItemsByField()
}
private mutating func mapItemsByField() {
mappedByField = items.reduce(ValidationErrorItemMap(), { (dict, item) -> ValidationErrorItemMap in
var dict = dict
if dict[item.keyPath] == nil {
dict[item.keyPath] = []
}
dict[item.keyPath]?.append(item)
return dict
})
}
/**
Gets all error items occurred during validation for a specififed keypath.
*/
public subscript(keyPath: AnyKeyPath) -> [ValidationErrorItem] {
get {
return mappedByField[keyPath] ?? []
}
}
}
| mit | 119887624d23ebeeb5491e8e210cdff6 | 31.425926 | 258 | 0.630497 | 4.932394 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Core/Util/AssetManager+Image.swift | 1 | 2003 | //
// AssetManager+Image.swift
// HXPHPicker
//
// Created by Slience on 2021/1/8.
//
import UIKit
import Photos
public typealias ImageResultHandler = (UIImage?, [AnyHashable: Any]?) -> Void
public extension AssetManager {
/// 请求获取缩略图
/// - Parameters:
/// - asset: 资源对象
/// - targetWidth: 获取的图片大小
/// - completion: 完成
/// - Returns: 请求ID
@discardableResult
static func requestThumbnailImage(
for asset: PHAsset,
targetWidth: CGFloat,
completion: ImageResultHandler?
) -> PHImageRequestID {
let options = PHImageRequestOptions()
options.resizeMode = .fast
var isSimplify = false
#if HXPICKER_ENABLE_PICKER
isSimplify = PhotoManager.shared.thumbnailLoadMode == .simplify
#endif
return requestImage(
for: asset,
targetSize: isSimplify ? .init(
width: targetWidth,
height: targetWidth
) : PhotoTools.transformTargetWidthToSize(
targetWidth: targetWidth,
asset: asset
),
options: options
) { (image, info) in
DispatchQueue.main.async {
completion?(image, info)
}
}
}
/// 请求image
/// - Parameters:
/// - asset: 资源对象
/// - targetSize: 指定大小
/// - options: 可选项
/// - resultHandler: 回调
/// - Returns: 请求ID
@discardableResult
static func requestImage(
for asset: PHAsset,
targetSize: CGSize,
options: PHImageRequestOptions,
resultHandler: @escaping ImageResultHandler
) -> PHImageRequestID {
return PHImageManager.default().requestImage(
for: asset,
targetSize: targetSize,
contentMode: .aspectFill,
options: options,
resultHandler: resultHandler
)
}
}
| mit | 5617da1b716e0acb8f5d124c3fd8c95f | 25.736111 | 77 | 0.561039 | 5.013021 | false | false | false | false |
theprangnetwork/PSColorScheme | PSBorderedTextField.swift | 1 | 4914 | //
// PSBorderedTextField.swift
// ephemera
//
// Created by Pranjal Satija on 8/28/15.
// Copyright © 2015 Pranjal Satija. All rights reserved.
//
import UIKit
class EBorderedTextField: UITextField, AlternateColorSchemeForPSBorderedTextField {
var originalBackgroundColor: UIColor?
@IBInspectable var alternateBackgroundColor: UIColor?
var originalTextColor: UIColor?
@IBInspectable var alternateTextColor: UIColor?
@IBInspectable var placeholderColor: UIColor?
var originalPlaceholderColor: UIColor?
@IBInspectable var alternatePlaceholderColor: UIColor?
@IBInspectable var borderColor: UIColor?
var originalBorderColor: UIColor?
@IBInspectable var alternateBorderColor: UIColor?
var colorSchemeManager: ColorSchemeManager {
get {
return universalManager
}
set {
if newValue.currentColorScheme == .Alternate {
self.backgroundColor = self.alternateBackgroundColor
self.textColor = self.alternateTextColor
self.borderColor = self.alternateBorderColor
self.placeholderColor = self.alternatePlaceholderColor
}
}
}
var border: CALayer?
///this override sets the `originalBackgroundColor` property, and adds an NSNotificationCenter observer to listen for transitions
override func awakeFromNib() {
setUp()
}
///this function sets all the properties that PSColorScheme needs to operate, and must be called manually if instantiating this view programmatically.
func setUp() {
self.originalBackgroundColor = self.backgroundColor
self.originalTextColor = self.textColor
self.originalPlaceholderColor = self.placeholderColor
self.originalBorderColor = self.borderColor
border = CALayer()
border?.borderColor = borderColor?.CGColor
border?.frame = CGRectMake(0, self.frame.size.height - 1, self.frame.size.width, self.frame.size.height)
border?.borderWidth = 1
self.layer.addSublayer(border!)
self.layer.masksToBounds = true
if let placeholder = self.placeholder, color = self.originalPlaceholderColor {
self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName : color])
}
notificationCenter.addObserver(self, selector: "transition", name: colorSchemeNotificationName, object: nil)
}
///this function determines which color scheme the view is in, and calls the appropriate animation method to update
func transition() {
if self.colorSchemeManager.currentColorScheme == .Main {
switchToAlternate()
}
else {
switchToMain()
}
}
///this function is a helper for `transition()`
func switchToMain() {
UIView.animateWithDuration(colorSchemeTransitionDuration) {
self.backgroundColor = self.originalBackgroundColor
self.textColor = self.originalTextColor
self.border?.backgroundColor = self.originalBorderColor?.CGColor
if let placeholder = self.placeholder, color = self.originalPlaceholderColor {
self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName : color])
}
}
}
///this function is a helper for `transition()`
func switchToAlternate() {
UIView.animateWithDuration(colorSchemeTransitionDuration) {
self.backgroundColor = self.alternateBackgroundColor
self.textColor = self.alternateTextColor
self.border?.backgroundColor = self.alternateBorderColor?.CGColor
if let placeholder = self.placeholder, color = self.alternatePlaceholderColor {
self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName : color])
}
}
}
///this function sets the placeholder and clears the field, as `setPlaceholder` is already taken
func newPlaceholder(string: String) {
if self.colorSchemeManager.currentColorScheme == .Main {
if let color = self.originalPlaceholderColor {
self.attributedPlaceholder = NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName : color])
}
}
else {
if let color = self.alternatePlaceholderColor {
self.attributedPlaceholder = NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName : color])
}
}
self.text = ""
}
deinit {
notificationCenter.removeObserver(self)
}
} | apache-2.0 | 45e13a9e4dcfc80ce040c241563cef58 | 37.692913 | 154 | 0.6609 | 5.862768 | false | false | false | false |
khizkhiz/swift | stdlib/public/core/Reflection.swift | 1 | 16909 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Customizes the result of `_reflect(x)`, where `x` is a conforming
/// type.
public protocol _Reflectable {
// The runtime has inappropriate knowledge of this protocol and how its
// witness tables are laid out. Changing this protocol requires a
// corresponding change to Reflection.cpp.
/// Returns a mirror that reflects `self`.
@warn_unused_result
func _getMirror() -> _Mirror
}
/// A unique identifier for a class instance or metatype.
///
/// In Swift, only class instances and metatypes have unique identities. There
/// is no notion of identity for structs, enums, functions, or tuples.
public struct ObjectIdentifier : Hashable, Comparable {
internal let _value: Builtin.RawPointer
// FIXME: Better hashing algorithm
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return Int(Builtin.ptrtoint_Word(_value))
}
/// Construct an instance that uniquely identifies the class instance `x`.
public init(_ x: AnyObject) {
self._value = Builtin.bridgeToRawPointer(x)
}
/// Construct an instance that uniquely identifies the metatype `x`.
public init(_ x: Any.Type) {
self._value = unsafeBitCast(x, to: Builtin.RawPointer.self)
}
}
@warn_unused_result
public func <(lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool {
return UInt(lhs) < UInt(rhs)
}
@warn_unused_result
public func ==(x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value))
}
extension UInt {
/// Create a `UInt` that captures the full value of `objectID`.
public init(_ objectID: ObjectIdentifier) {
self.init(Builtin.ptrtoint_Word(objectID._value))
}
}
extension Int {
/// Create an `Int` that captures the full value of `objectID`.
public init(_ objectID: ObjectIdentifier) {
self.init(bitPattern: UInt(objectID))
}
}
/// How children of this value should be presented in the IDE.
public enum _MirrorDisposition {
/// As a struct.
case `struct`
/// As a class.
case `class`
/// As an enum.
case `enum`
/// As a tuple.
case tuple
/// As a miscellaneous aggregate with a fixed set of children.
case aggregate
/// As a container that is accessed by index.
case indexContainer
/// As a container that is accessed by key.
case keyContainer
/// As a container that represents membership of its values.
case membershipContainer
/// As a miscellaneous container with a variable number of children.
case container
/// An Optional which can have either zero or one children.
case optional
/// An Objective-C object imported in Swift.
case objCObject
}
/// The type returned by `_reflect(x)`; supplies an API for runtime
/// reflection on `x`.
public protocol _Mirror {
/// The instance being reflected.
var value: Any { get }
/// Identical to `value.dynamicType`.
var valueType: Any.Type { get }
/// A unique identifier for `value` if it is a class instance; `nil`
/// otherwise.
var objectIdentifier: ObjectIdentifier? { get }
/// The count of `value`'s logical children.
var count: Int { get }
/// Get a name and mirror for the `i`th logical child.
subscript(i: Int) -> (String, _Mirror) { get }
/// A string description of `value`.
var summary: String { get }
/// A rich representation of `value` for an IDE, or `nil` if none is supplied.
var quickLookObject: PlaygroundQuickLook? { get }
/// How `value` should be presented in an IDE.
var disposition: _MirrorDisposition { get }
}
/// An entry point that can be called from C++ code to get the summary string
/// for an arbitrary object. The memory pointed to by "out" is initialized with
/// the summary string.
@warn_unused_result
@_silgen_name("swift_getSummary")
public // COMPILER_INTRINSIC
func _getSummary<T>(out: UnsafeMutablePointer<String>, x: T) {
out.initialize(with: String(reflecting: x))
}
/// Produce a mirror for any value. If the value's type conforms to
/// `_Reflectable`, invoke its `_getMirror()` method; otherwise, fall back
/// to an implementation in the runtime that structurally reflects values
/// of any type.
@warn_unused_result
@_silgen_name("swift_reflectAny")
public func _reflect<T>(x: T) -> _Mirror
/// Dump an object's contents using its mirror to the specified output stream.
public func dump<T, TargetStream : OutputStream>(
value: T,
to target: inout TargetStream,
name: String? = nil,
indent: Int = 0,
maxDepth: Int = .max,
maxItems: Int = .max
) -> T {
var maxItemCounter = maxItems
var visitedItems = [ObjectIdentifier : Int]()
target._lock()
defer { target._unlock() }
_dump_unlocked(
value,
to: &target,
name: name,
indent: indent,
maxDepth: maxDepth,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
return value
}
/// Dump an object's contents using its mirror to standard output.
public func dump<T>(
value: T,
name: String? = nil,
indent: Int = 0,
maxDepth: Int = .max,
maxItems: Int = .max
) -> T {
var stdoutStream = _Stdout()
return dump(
value,
to: &stdoutStream,
name: name,
indent: indent,
maxDepth: maxDepth,
maxItems: maxItems)
}
/// Dump an object's contents. User code should use dump().
internal func _dump_unlocked<TargetStream : OutputStream>(
value: Any,
to target: inout TargetStream,
name: String?,
indent: Int,
maxDepth: Int,
maxItemCounter: inout Int,
visitedItems: inout [ObjectIdentifier : Int]
) {
guard maxItemCounter > 0 else { return }
maxItemCounter -= 1
for _ in 0..<indent { target.write(" ") }
let mirror = Mirror(reflecting: value)
let count = mirror.children.count
let bullet = count == 0 ? "-"
: maxDepth <= 0 ? "▹" : "▿"
target.write(bullet)
target.write(" ")
if let nam = name {
target.write(nam)
target.write(": ")
}
// This takes the place of the old mirror API's 'summary' property
_dumpPrint_unlocked(value, mirror, &target)
let id: ObjectIdentifier?
if let classInstance = value as? AnyObject where value.dynamicType is AnyObject.Type {
// Object is a class (but not an ObjC-bridged struct)
id = ObjectIdentifier(classInstance)
} else if let metatypeInstance = value as? Any.Type {
// Object is a metatype
id = ObjectIdentifier(metatypeInstance)
} else {
id = nil
}
if let theId = id {
if let previous = visitedItems[theId] {
target.write(" #")
_print_unlocked(previous, &target)
target.write("\n")
return
}
let identifier = visitedItems.count
visitedItems[theId] = identifier
target.write(" #")
_print_unlocked(identifier, &target)
}
target.write("\n")
guard maxDepth > 0 else { return }
if let superclassMirror = mirror.superclassMirror {
_dumpSuperclass_unlocked(
mirror: superclassMirror,
to: &target,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
var currentIndex = mirror.children.startIndex
for i in 0..<count {
if maxItemCounter <= 0 {
for _ in 0..<(indent+4) {
_print_unlocked(" ", &target)
}
let remainder = count - i
target.write("(")
_print_unlocked(remainder, &target)
if i > 0 { target.write(" more") }
if remainder == 1 {
target.write(" child)\n")
} else {
target.write(" children)\n")
}
return
}
let (name, child) = mirror.children[currentIndex]
currentIndex = currentIndex.successor()
_dump_unlocked(
child,
to: &target,
name: name,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
}
/// Dump information about an object's superclass, given a mirror reflecting
/// that superclass.
internal func _dumpSuperclass_unlocked<TargetStream : OutputStream>(
mirror mirror: Mirror,
to target: inout TargetStream,
indent: Int,
maxDepth: Int,
maxItemCounter: inout Int,
visitedItems: inout [ObjectIdentifier : Int]
) {
guard maxItemCounter > 0 else { return }
maxItemCounter -= 1
for _ in 0..<indent { target.write(" ") }
let count = mirror.children.count
let bullet = count == 0 ? "-"
: maxDepth <= 0 ? "▹" : "▿"
target.write(bullet)
target.write(" super: ")
_debugPrint_unlocked(mirror.subjectType, &target)
target.write("\n")
guard maxDepth > 0 else { return }
if let superclassMirror = mirror.superclassMirror {
_dumpSuperclass_unlocked(
mirror: superclassMirror,
to: &target,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
var currentIndex = mirror.children.startIndex
for i in 0..<count {
if maxItemCounter <= 0 {
for _ in 0..<(indent+4) {
target.write(" ")
}
let remainder = count - i
target.write("(")
_print_unlocked(remainder, &target)
if i > 0 { target.write(" more") }
if remainder == 1 {
target.write(" child)\n")
} else {
target.write(" children)\n")
}
return
}
let (name, child) = mirror.children[currentIndex]
currentIndex = currentIndex.successor()
_dump_unlocked(
child,
to: &target,
name: name,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
}
// -- Implementation details for the runtime's _Mirror implementation
@_silgen_name("swift_MagicMirrorData_summary")
func _swift_MagicMirrorData_summaryImpl(
metadata: Any.Type, _ result: UnsafeMutablePointer<String>
)
public struct _MagicMirrorData {
let owner: Builtin.NativeObject
let ptr: Builtin.RawPointer
let metadata: Any.Type
var value: Any {
@_silgen_name("swift_MagicMirrorData_value")get
}
var valueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_valueType")get
}
public var objcValue: Any {
@_silgen_name("swift_MagicMirrorData_objcValue")get
}
public var objcValueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_objcValueType")get
}
var summary: String {
let (_, result) = _withUninitializedString {
_swift_MagicMirrorData_summaryImpl(self.metadata, $0)
}
return result
}
public func _loadValue<T>() -> T {
return Builtin.load(ptr) as T
}
}
struct _OpaqueMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int { return 0 }
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String { return data.summary }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .aggregate }
}
internal struct _TupleMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_TupleMirror_count")get
}
subscript(i: Int) -> (String, _Mirror) {
return _subscript_get(i)
}
@_silgen_name("swift_TupleMirror_subscript")
func _subscript_get<T>(i: Int) -> (T, _Mirror)
var summary: String { return "(\(count) elements)" }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .tuple }
}
struct _StructMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_StructMirror_count")get
}
subscript(i: Int) -> (String, _Mirror) {
return _subscript_get(i)
}
@_silgen_name("swift_StructMirror_subscript")
func _subscript_get<T>(i: Int) -> (T, _Mirror)
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`struct` }
}
struct _EnumMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_EnumMirror_count")get
}
var caseName: UnsafePointer<CChar> {
@_silgen_name("swift_EnumMirror_caseName")get
}
subscript(i: Int) -> (String, _Mirror) {
return _subscript_get(i)
}
@_silgen_name("swift_EnumMirror_subscript")
func _subscript_get<T>(i: Int) -> (T, _Mirror)
var summary: String {
let maybeCaseName = String(validatingUTF8: self.caseName)
let typeName = _typeName(valueType)
if let caseName = maybeCaseName {
return typeName + "." + caseName
}
return typeName
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`enum` }
}
@warn_unused_result
@_silgen_name("swift_ClassMirror_count")
func _getClassCount(_: _MagicMirrorData) -> Int
// Like the other swift_*Mirror_subscript functions declared here and
// elsewhere, this is implemented in the runtime. The Swift CC would
// normally require the String to be returned directly and the _Mirror
// indirectly. However, Clang isn't currently capable of doing that
// reliably because the size of String exceeds the normal direct-return
// ABI rules on most platforms. Therefore, we make this function generic,
// which has the disadvantage of passing the String type metadata as an
// extra argument, but does force the string to be returned indirectly.
@warn_unused_result
@_silgen_name("swift_ClassMirror_subscript")
func _getClassChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_ClassMirror_quickLookObject")
public func _getClassPlaygroundQuickLook(
data: _MagicMirrorData
) -> PlaygroundQuickLook?
#endif
struct _ClassMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? {
#if _runtime(_ObjC)
return _getClassPlaygroundQuickLook(data)
#else
return nil
#endif
}
var disposition: _MirrorDisposition { return .`class` }
}
struct _ClassSuperMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
// Suppress the value identifier for super mirrors.
var objectIdentifier: ObjectIdentifier? {
return nil
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(data.metadata)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`class` }
}
struct _MetatypeMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return 0
}
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String {
return _typeName(data._loadValue() as Any.Type)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
// Special disposition for types?
var disposition: _MirrorDisposition { return .aggregate }
}
extension ObjectIdentifier {
@available(*, unavailable, message="use the 'UInt(_:)' initializer")
public var uintValue: UInt {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 | 9bebe738428cf6ce426c2a68c216301d | 27.841297 | 88 | 0.670789 | 4.111165 | false | false | false | false |
cbh2000/flickrtest | FlickrTest/ImageViewController.swift | 1 | 3377 | //
// ImageViewController.swift
// FlickrTest
//
// Created by Christopher Bryan Henderson on 9/20/16.
// Copyright © 2016 Christopher Bryan Henderson. All rights reserved.
//
import UIKit
/**
* Here, I decided to create the view controller programmatically, without the use of Storyboard.
*
* Sadly, there is no pinch to zoom, but you can rotate the phone into landscape.
*/
class ImageViewController: UIViewController {
let imageView = UIImageView()
let closeButton = UIButton()
let spinner = UIActivityIndicatorView()
convenience init(imageURL: URL) {
self.init(nibName: nil, bundle: nil)
setImage(with: imageURL)
}
func setImage(with url: URL) {
imageView.sd_setImage(with: url) { (image: UIImage?, _, _, _) in
self.spinner.stopAnimating()
self.spinner.isHidden = true
}
}
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// TODO: This doesn't work on the iOS 10 simulator, but it looks ok nonetheless.
view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
// Makes it fade in instead of sliding in.
modalTransitionStyle = .crossDissolve
modalPresentationStyle = .overCurrentContext
spinner.activityIndicatorViewStyle = .white
spinner.startAnimating()
spinner.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(spinner)
spinner.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
spinner.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// Configure the image view.
imageView.backgroundColor = .clear
imageView.contentMode = .scaleAspectFit
// Required for programmatically created views or else auto-generated constrants will conflict with ours.
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
// Alternatively, you can create the NSLayoutConstraints directly, or just set the frames in view(Did|Will)LayoutSubviews.
imageView.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor).isActive = true
imageView.heightAnchor.constraint(lessThanOrEqualTo: view.heightAnchor).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
// Configure the button.
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.setImage(UIImage(named: "close"), for: [])
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
view.addSubview(closeButton)
// Layout close button
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15).isActive = true
closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 15).isActive = true
closeButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
}
func closeTapped() {
dismiss(animated: true, completion: nil)
}
}
| mit | 2509b6b273d752bbaf006785d40243d6 | 39.674699 | 130 | 0.689277 | 5.35873 | false | false | false | false |
Ribeiro/SwiftEventBus | SwiftEventBus/SwiftEventBus.swift | 1 | 5847 | import Foundation
public class SwiftEventBus {
struct Static {
static let instance = SwiftEventBus()
static let queue = dispatch_queue_create("com.cesarferreira.SwiftEventBus", DISPATCH_QUEUE_SERIAL)
}
struct NamedObserver {
let observer: NSObjectProtocol
let name: String
}
var cache = [UInt:[NamedObserver]]()
////////////////////////////////////
// Publish
////////////////////////////////////
public class func post(name: String) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: nil)
}
public class func post(name: String, sender: AnyObject?) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: sender)
}
public class func post(name: String, sender: NSObject?) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: sender)
}
public class func post(name: String, userInfo: [NSObject : AnyObject]?) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: nil, userInfo: userInfo)
}
public class func post(name: String, sender: AnyObject?, userInfo: [NSObject : AnyObject]?) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: sender, userInfo: userInfo)
}
public class func postToMainThread(name: String) {
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: nil)
}
}
public class func postToMainThread(name: String, sender: AnyObject?) {
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: sender)
}
}
public class func postToMainThread(name: String, sender: NSObject?) {
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: sender)
}
}
public class func postToMainThread(name: String, userInfo: [NSObject : AnyObject]?) {
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: nil, userInfo: userInfo)
}
}
public class func postToMainThread(name: String, sender: AnyObject?, userInfo: [NSObject : AnyObject]?) {
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(name, object: sender, userInfo: userInfo)
}
}
////////////////////////////////////
// Subscribe
////////////////////////////////////
public class func on(target: AnyObject, name: String, sender: AnyObject?, queue: NSOperationQueue?, handler: ((NSNotification!) -> Void)) -> NSObjectProtocol {
let id = ObjectIdentifier(target).uintValue
let observer = NSNotificationCenter.defaultCenter().addObserverForName(name, object: sender, queue: queue, usingBlock: handler)
let namedObserver = NamedObserver(observer: observer, name: name)
dispatch_sync(Static.queue) {
if let namedObservers = Static.instance.cache[id] {
Static.instance.cache[id] = namedObservers + [namedObserver]
} else {
Static.instance.cache[id] = [namedObserver]
}
}
return observer
}
public class func onMainThread(target: AnyObject, name: String, handler: ((NSNotification!) -> Void)) -> NSObjectProtocol {
return SwiftEventBus.on(target, name: name, sender: nil, queue: NSOperationQueue.mainQueue(), handler: handler)
}
public class func onMainThread(target: AnyObject, name: String, sender: AnyObject?, handler: ((NSNotification!) -> Void)) -> NSObjectProtocol {
return SwiftEventBus.on(target, name: name, sender: sender, queue: NSOperationQueue.mainQueue(), handler: handler)
}
public class func onBackgroundThread(target: AnyObject, name: String, handler: ((NSNotification!) -> Void)) -> NSObjectProtocol {
return SwiftEventBus.on(target, name: name, sender: nil, queue: NSOperationQueue(), handler: handler)
}
public class func onBackgroundThread(target: AnyObject, name: String, sender: AnyObject?, handler: ((NSNotification!) -> Void)) -> NSObjectProtocol {
return SwiftEventBus.on(target, name: name, sender: sender, queue: NSOperationQueue(), handler: handler)
}
////////////////////////////////////
// Unregister
////////////////////////////////////
public class func unregister(target: AnyObject) {
let id = ObjectIdentifier(target).uintValue
let center = NSNotificationCenter.defaultCenter()
dispatch_sync(Static.queue) {
if let namedObservers = Static.instance.cache.removeValueForKey(id) {
for namedObserver in namedObservers {
center.removeObserver(namedObserver.observer)
}
}
}
}
public class func unregister(target: AnyObject, name: String) {
let id = ObjectIdentifier(target).uintValue
let center = NSNotificationCenter.defaultCenter()
dispatch_sync(Static.queue) {
if let namedObservers = Static.instance.cache[id] {
Static.instance.cache[id] = namedObservers.filter({ (namedObserver: NamedObserver) -> Bool in
if namedObserver.name == name {
center.removeObserver(namedObserver.observer)
return false
} else {
return true
}
})
}
}
}
}
| mit | efa8da1e5678677d4d8424f96cf564d2 | 39.324138 | 163 | 0.610912 | 5.454291 | false | false | false | false |
x331275955/- | xiong-练习微博(视频)/xiong-练习微博(视频)/OtherView/VisitorView.swift | 1 | 9003 | //
// visitorView.swift
// xiong-练习微博(视频)
//
// Created by 王晨阳 on 15/9/12.
// Copyright © 2015年 IOS. All rights reserved.
//
import UIKit
/// 设置代理
protocol VisitorViewDelegate: NSObjectProtocol {
/// 将要登录
func visitorViewWillLogin()
/// 将要注册
func visitorViewWillRegister()
}
class VisitorView: UIView {
/// 定义代理
weak var delegate: VisitorViewDelegate?
// 注册按钮的点击事件
func clickRegisterButton(){
delegate?.visitorViewWillRegister()
}
// 登录按钮的点击事件
func clickLoginButton(){
delegate?.visitorViewWillLogin()
}
/// 设置视图信息
/// - parameter isHome : 是否是主页
/// - parameter imageName: 中央显示的图片
/// - parameter message : 要显示的信息
func setupViewInfo(isHome: Bool, imageName: String, message: String){
textLabel.text = message
iconImageView.image = UIImage(named: imageName)
houseImageView.hidden = !isHome
isHome ? startAnimation() : sendSubviewToBack(backImageView)
}
/// 设置首页动画
private func startAnimation(){
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = 2 * M_PI
anim.repeatCount = MAXFLOAT
anim.duration = 10.0
// 保证动画不会被切换的时候丢失
anim.removedOnCompletion = false
iconImageView.layer.addAnimation(anim, forKey: nil)
}
// 纯代码开发的时候会进入到这个方法
override init(frame: CGRect) {
super.init(frame: frame)
// 调用方法设置UI
setupUI()
}
// XIB 和 SB 的时候会进入这个方法
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// 调用方法 设置UI
setupUI()
}
// 设置访客视图的UI界面
private func setupUI(){
// 1.添加子控件
addSubview(iconImageView)
addSubview(backImageView)
addSubview(houseImageView)
addSubview(textLabel)
addSubview(registerButton)
addSubview(loginButton)
// 设置背景颜色
backgroundColor = UIColor(white: 237.0 / 255.0, alpha: 1)
// 2.设置子控件的约束
// 圆圈背景的约束
iconImageView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: -40))
// 设置遮罩的约束
backImageView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: backImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconImageView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: backImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconImageView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
// 设置小房子的约束
houseImageView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: houseImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconImageView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: houseImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconImageView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
// 设置文字Label的约束
textLabel.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: textLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconImageView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: textLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconImageView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: textLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 224))
// 设置注册按钮的约束
registerButton.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: textLabel, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: textLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 100))
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 35))
// 设置登录按钮的约束
loginButton.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: textLabel, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: textLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 100))
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 35))
}
// MARK: - 懒加载各种控件
// 背景圆圈
lazy var iconImageView:UIImageView = {
let icon = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
return icon
}()
// 半透明遮罩
lazy var backImageView:UIImageView = {
let backImage = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
return backImage
}()
// 小房子
lazy var houseImageView:UIImageView = {
let houseView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
return houseView
}()
// 文字Label
lazy var textLabel:UILabel = {
let textLabel = UILabel()
textLabel.text = "关注一些人,回这里看看有什么惊喜关注一些人,回这里看看有什么惊喜!"
textLabel.font = UIFont.systemFontOfSize(14)
textLabel.textColor = UIColor.darkGrayColor()
textLabel.textAlignment = NSTextAlignment.Center
textLabel.numberOfLines = 0
return textLabel
}()
// 注册按钮
lazy var registerButton :UIButton = {
let register = UIButton()
register.setTitle("注册", forState: UIControlState.Normal)
register.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
register.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
register.addTarget(self, action: "clickRegisterButton", forControlEvents: UIControlEvents.TouchUpInside)
return register
}()
// 登录按钮
lazy var loginButton :UIButton = {
let login = UIButton()
login.setTitle("登录", forState: UIControlState.Normal)
login.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
login.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
login.addTarget(self, action: "clickLoginButton", forControlEvents: UIControlEvents.TouchUpInside)
return login
}()
}
| mit | e9b839d61af55c0775b33d0548e822a7 | 46.573034 | 227 | 0.707723 | 5.172877 | false | false | false | false |
nicolasgomollon/LPRTableView | LPRTableView.swift | 1 | 20338 | //
// LPRTableView.swift
// LPRTableView
//
// Objective-C code Copyright (c) 2013 Ben Vogelzang. All rights reserved.
// Swift adaptation Copyright (c) 2014 Nicolas Gomollon. All rights reserved.
//
import QuartzCore
import UIKit
/// The delegate of a `LPRTableView` object can adopt the `LPRTableViewDelegate` protocol.
/// Optional methods of the protocol allow the delegate to modify a cell visually before dragging occurs, or to be notified when a cell is about to be dragged or about to be dropped.
@objc
public protocol LPRTableViewDelegate: NSObjectProtocol {
/// Asks the delegate whether a given row can be moved to another location in the table view based on the gesture location.
///
/// The default is `true`.
@objc optional func tableView(_ tableView: UITableView, shouldMoveRowAtIndexPath indexPath: IndexPath, forDraggingGesture gesture: UILongPressGestureRecognizer) -> Bool
/// Provides the delegate a chance to modify the cell visually before dragging occurs.
///
/// Defaults to using the cell as-is if not implemented.
@objc optional func tableView(_ tableView: UITableView, draggingCell cell: UITableViewCell, at indexPath: IndexPath) -> UITableViewCell
/// Called within an animation block when the dragging view is about to show.
@objc optional func tableView(_ tableView: UITableView, showDraggingView view: UIView, at indexPath: IndexPath)
/// Called within an animation block when the dragging view is about to hide.
@objc optional func tableView(_ tableView: UITableView, hideDraggingView view: UIView, at indexPath: IndexPath)
/// Called when the dragging gesture's vertical location changes.
@objc optional func tableView(_ tableView: UITableView, draggingGestureChanged gesture: UILongPressGestureRecognizer)
}
open class LPRTableView: UITableView {
/// The object that acts as the delegate of the receiving table view.
weak open var longPressReorderDelegate: LPRTableViewDelegate?
fileprivate var longPressGestureRecognizer: UILongPressGestureRecognizer!
fileprivate var initialIndexPath: IndexPath?
fileprivate var currentLocationIndexPath: IndexPath?
fileprivate var draggingView: UIView?
fileprivate var scrollRate: Double = 0.0
fileprivate var scrollDisplayLink: CADisplayLink?
fileprivate var feedbackGenerator: AnyObject?
fileprivate var previousGestureVerticalPosition: CGFloat?
/// A Bool property that indicates whether long press to reorder is enabled.
open var longPressReorderEnabled: Bool {
get {
return longPressGestureRecognizer.isEnabled
}
set {
longPressGestureRecognizer.isEnabled = newValue
}
}
/// The minimum period a finger must press on a cell for the reordering to begin.
///
/// The time interval is in seconds. The default duration is `0.5` seconds.
open var minimumPressDuration: TimeInterval {
get {
return longPressGestureRecognizer.minimumPressDuration
}
set {
longPressGestureRecognizer.minimumPressDuration = newValue
}
}
public convenience init() {
self.init(frame: .zero)
}
public override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(LPRTableView._longPress(_:)))
longPressGestureRecognizer.delegate = self
addGestureRecognizer(longPressGestureRecognizer)
}
}
extension LPRTableView: UIGestureRecognizerDelegate {
open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == longPressGestureRecognizer else { return true }
let location: CGPoint = gestureRecognizer.location(in: self)
let indexPath: IndexPath? = indexPathForRow(at: location)
let rows: Int = (0..<numberOfSections).reduce(0, { $0 + numberOfRows(inSection: $1) })
// Long press gesture should not begin if it was not on a valid row or our table is empty
// or the `dataSource.tableView(_:canMoveRowAt:)` doesn't allow moving the row.
return (rows > 0)
&& (indexPath != nil)
&& canMoveRowAt(indexPath: indexPath!)
&& shouldMoveRowAt(indexPath: indexPath!, forDraggingGesture: longPressGestureRecognizer)
}
}
extension LPRTableView {
fileprivate func canMoveRowAt(indexPath: IndexPath) -> Bool {
return dataSource?.tableView?(self, canMoveRowAt: indexPath) ?? true
}
fileprivate func shouldMoveRowAt(indexPath: IndexPath, forDraggingGesture gesture: UILongPressGestureRecognizer) -> Bool {
return longPressReorderDelegate?.tableView?(self, shouldMoveRowAtIndexPath: indexPath, forDraggingGesture: longPressGestureRecognizer) ?? true
}
@objc internal func _longPress(_ gesture: UILongPressGestureRecognizer) {
let location: CGPoint = gesture.location(in: self)
let indexPath: IndexPath? = indexPathForRow(at: location)
switch gesture.state {
case .began: // Started
hapticFeedbackSetup()
hapticFeedbackSelectionChanged()
previousGestureVerticalPosition = location.y
guard let indexPath: IndexPath = indexPath,
var cell: UITableViewCell = cellForRow(at: indexPath) else { break }
endEditing(true)
cell.setSelected(false, animated: false)
cell.setHighlighted(false, animated: false)
// Create the view that will be dragged around the screen.
if draggingView == nil {
if let draggingCell: UITableViewCell = longPressReorderDelegate?.tableView?(self, draggingCell: cell, at: indexPath) {
cell = draggingCell
}
// Take a snapshot of the pressed table view cell.
draggingView = cell.snapshotView(afterScreenUpdates: false)
if let draggingView: UIView = draggingView {
addSubview(draggingView)
let rect: CGRect = rectForRow(at: indexPath)
draggingView.frame = draggingView.bounds.offsetBy(dx: rect.origin.x, dy: rect.origin.y)
UIView.beginAnimations("LongPressReorder-ShowDraggingView", context: nil)
longPressReorderDelegate?.tableView?(self, showDraggingView: draggingView, at: indexPath)
UIView.commitAnimations()
// Add drop shadow to image and lower opacity.
draggingView.layer.masksToBounds = false
draggingView.layer.shadowColor = UIColor.black.cgColor
draggingView.layer.shadowOffset = .zero
draggingView.layer.shadowRadius = 4.0
draggingView.layer.shadowOpacity = 0.7
draggingView.layer.opacity = 0.85
// Zoom image towards user.
UIView.beginAnimations("LongPressReorder-Zoom", context: nil)
draggingView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
draggingView.center = CGPoint(x: center.x, y: newYCenter(for: draggingView, with: location))
UIView.commitAnimations()
}
}
cell.isHidden = true
currentLocationIndexPath = indexPath
initialIndexPath = indexPath
// Enable scrolling for cell.
scrollDisplayLink = CADisplayLink(target: self, selector: #selector(LPRTableView._scrollTableWithCell(_:)))
scrollDisplayLink?.add(to: .main, forMode: .default)
case .changed: // Dragging
if let draggingView: UIView = draggingView {
// Update position of the drag view
draggingView.center = CGPoint(x: center.x, y: newYCenter(for: draggingView, with: location))
if let previousGestureVerticalPosition: CGFloat = self.previousGestureVerticalPosition {
if location.y != previousGestureVerticalPosition {
longPressReorderDelegate?.tableView?(self, draggingGestureChanged: gesture)
self.previousGestureVerticalPosition = location.y
}
} else {
longPressReorderDelegate?.tableView?(self, draggingGestureChanged: gesture)
self.previousGestureVerticalPosition = location.y
}
}
let inset: UIEdgeInsets
if #available(iOS 11.0, *) {
inset = adjustedContentInset
} else {
inset = contentInset
}
var rect: CGRect = bounds
// Adjust rect for content inset, as we will use it below for calculating scroll zones.
rect.size.height -= inset.top
// Tell us if we should scroll, and in which direction.
let scrollZoneHeight: CGFloat = rect.size.height / 6.0
let bottomScrollBeginning: CGFloat = contentOffset.y + inset.top + rect.size.height - scrollZoneHeight
let topScrollBeginning: CGFloat = contentOffset.y + inset.top + scrollZoneHeight
if location.y >= bottomScrollBeginning {
// We're in the bottom zone.
scrollRate = Double(location.y - bottomScrollBeginning) / Double(scrollZoneHeight)
} else if location.y <= topScrollBeginning {
// We're in the top zone.
scrollRate = Double(location.y - topScrollBeginning) / Double(scrollZoneHeight)
} else {
scrollRate = 0.0
}
case .ended where currentLocationIndexPath != nil, // Dropped
.cancelled,
.failed:
// Remove previously cached Gesture location
self.previousGestureVerticalPosition = nil
// Remove scrolling CADisplayLink.
scrollDisplayLink?.invalidate()
scrollDisplayLink = nil
scrollRate = 0.0
//
// For use only with Xcode UI Testing:
// Set launch argument `"-LPRTableViewUITestingScreenshots", "1"` to disable dropping a cell,
// to facilitate taking a screenshot with a hovering cell.
//
guard !UserDefaults.standard.bool(forKey: "LPRTableViewUITestingScreenshots") else { break }
// Animate the drag view to the newly hovered cell.
UIView.animate(withDuration: 0.3, animations: {
guard let draggingView: UIView = self.draggingView,
let currentLocationIndexPath: IndexPath = self.currentLocationIndexPath else { return }
UIView.beginAnimations("LongPressReorder-HideDraggingView", context: nil)
self.longPressReorderDelegate?.tableView?(self, hideDraggingView: draggingView, at: currentLocationIndexPath)
UIView.commitAnimations()
let rect: CGRect = self.rectForRow(at: currentLocationIndexPath)
draggingView.transform = .identity
draggingView.frame = draggingView.bounds.offsetBy(dx: rect.origin.x, dy: rect.origin.y)
}, completion: { (finished: Bool) in
self.draggingView?.removeFromSuperview()
// Reload the rows that were affected just to be safe.
var visibleRows: [IndexPath] = self.indexPathsForVisibleRows ?? []
if let indexPath: IndexPath = indexPath,
!visibleRows.contains(indexPath) {
visibleRows.append(indexPath)
}
if let currentLocationIndexPath: IndexPath = self.currentLocationIndexPath,
!visibleRows.contains(currentLocationIndexPath) {
visibleRows.append(currentLocationIndexPath)
}
if !visibleRows.isEmpty {
self.reloadRows(at: visibleRows, with: .none)
}
self.currentLocationIndexPath = nil
self.draggingView = nil
self.hapticFeedbackSelectionChanged()
self.hapticFeedbackFinalize()
})
default:
break
}
}
fileprivate func updateCurrentLocation(_ gesture: UILongPressGestureRecognizer) {
let location: CGPoint = gesture.location(in: self)
guard var indexPath: IndexPath = indexPathForRow(at: location) else { return }
if let iIndexPath: IndexPath = initialIndexPath,
let ip: IndexPath = delegate?.tableView?(self, targetIndexPathForMoveFromRowAt: iIndexPath, toProposedIndexPath: indexPath) {
indexPath = ip
}
guard let clIndexPath: IndexPath = currentLocationIndexPath else { return }
let oldHeight: CGFloat = rectForRow(at: clIndexPath).size.height
let newHeight: CGFloat = rectForRow(at: indexPath).size.height
switch gesture.state {
case .changed:
if let cell: UITableViewCell = cellForRow(at: clIndexPath) {
cell.setSelected(false, animated: false)
cell.setHighlighted(false, animated: false)
cell.isHidden = true
}
default:
break
}
guard indexPath != clIndexPath,
gesture.location(in: cellForRow(at: indexPath)).y > (newHeight - oldHeight),
canMoveRowAt(indexPath: indexPath) else { return }
beginUpdates()
moveRow(at: clIndexPath, to: indexPath)
dataSource?.tableView?(self, moveRowAt: clIndexPath, to: indexPath)
currentLocationIndexPath = indexPath
endUpdates()
hapticFeedbackSelectionChanged()
}
@objc internal func _scrollTableWithCell(_ sender: CADisplayLink) {
guard let gesture: UILongPressGestureRecognizer = longPressGestureRecognizer else { return }
let location: CGPoint = gesture.location(in: self)
guard !(location.y.isNaN || location.x.isNaN) else { return } // Explicitly check for out-of-bound touch.
let yOffset: Double = Double(contentOffset.y) + scrollRate * 10.0
var newOffset: CGPoint = CGPoint(x: contentOffset.x, y: CGFloat(yOffset))
let inset: UIEdgeInsets
if #available(iOS 11.0, *) {
inset = adjustedContentInset
} else {
inset = contentInset
}
if newOffset.y < -inset.top {
newOffset.y = -inset.top
} else if (contentSize.height + inset.bottom) < frame.size.height {
newOffset = contentOffset
} else if newOffset.y > ((contentSize.height + inset.bottom) - frame.size.height) {
newOffset.y = (contentSize.height + inset.bottom) - frame.size.height
}
contentOffset = newOffset
if let draggingView: UIView = draggingView {
draggingView.center = CGPoint(x: center.x, y: newYCenter(for: draggingView, with: location))
}
updateCurrentLocation(gesture)
}
fileprivate func newYCenter(for draggingView: UIView, with location: CGPoint) -> CGFloat {
let cellCenter: CGFloat = draggingView.frame.height / 2
let bottomBound: CGFloat = contentSize.height - cellCenter
if location.y < cellCenter {
return cellCenter
} else if location.y > bottomBound {
return bottomBound
}
return location.y
}
}
extension LPRTableView {
fileprivate func hapticFeedbackSetup() {
guard #available(iOS 10.0, *) else { return }
let feedbackGenerator = UISelectionFeedbackGenerator()
feedbackGenerator.prepare()
self.feedbackGenerator = feedbackGenerator
}
fileprivate func hapticFeedbackSelectionChanged() {
guard #available(iOS 10.0, *),
let feedbackGenerator = self.feedbackGenerator as? UISelectionFeedbackGenerator else { return }
feedbackGenerator.selectionChanged()
feedbackGenerator.prepare()
}
fileprivate func hapticFeedbackFinalize() {
guard #available(iOS 10.0, *) else { return }
self.feedbackGenerator = nil
}
}
open class LPRTableViewController: UITableViewController, LPRTableViewDelegate {
/// Returns the long press to reorder table view managed by the controller object.
open var lprTableView: LPRTableView { return tableView as! LPRTableView }
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
public override init(style: UITableView.Style) {
super.init(style: style)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
tableView = LPRTableView()
tableView.dataSource = self
tableView.delegate = self
registerClasses()
lprTableView.longPressReorderDelegate = self
}
/// Override this method to register custom UITableViewCell subclass(es). DO NOT call `super` within this method.
open func registerClasses() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
/// Asks the delegate whether a given row can be moved to another location in the table view based on the gesture location.
///
/// The default is `true`. The default implementation of this method is empty—no need to call `super`.
open func tableView(_ tableView: UITableView, shouldMoveRowAtIndexPath indexPath: IndexPath, forDraggingGesture gesture: UILongPressGestureRecognizer) -> Bool {
return true
}
/// Provides the delegate a chance to modify the cell visually before dragging occurs.
///
/// Defaults to using the cell as-is if not implemented. The default implementation of this method is empty—no need to call `super`.
open func tableView(_ tableView: UITableView, draggingCell cell: UITableViewCell, at indexPath: IndexPath) -> UITableViewCell {
// Empty implementation, just to simplify overriding (and to show up in code completion).
return cell
}
/// Called within an animation block when the dragging view is about to show.
///
/// The default implementation of this method is empty—no need to call `super`.
open func tableView(_ tableView: UITableView, showDraggingView view: UIView, at indexPath: IndexPath) {
// Empty implementation, just to simplify overriding (and to show up in code completion).
}
/// Called within an animation block when the dragging view is about to hide.
///
/// The default implementation of this method is empty—no need to call `super`.
open func tableView(_ tableView: UITableView, hideDraggingView view: UIView, at indexPath: IndexPath) {
// Empty implementation, just to simplify overriding (and to show up in code completion).
}
/// Called when the dragging gesture's vertical location changes.
///
/// The default implementation of this method is empty—no need to call `super`.
open func tableView(_ tableView: UITableView, draggingGestureChanged gesture: UILongPressGestureRecognizer) {
// Empty implementation, just to simplify overriding (and to show up in code completion).
}
}
| mit | bbfc10a92bc822d2cf27a50e44e363ef | 43.384279 | 182 | 0.63351 | 5.732657 | false | false | false | false |
lvogelzang/Blocky | Blocky/Levels/Level74.swift | 1 | 877 | //
// Level74.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level74: Level {
let levelNumber = 74
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| mit | 8c9b748b92a3931a489f8c3e376dc487 | 24.794118 | 89 | 0.573546 | 2.649547 | false | false | false | false |
eugeneego/utilities-ios | Sources/Common/Arithmetic.swift | 1 | 1558 | //
// Arithmetic
// Legacy
//
// Copyright (c) 2015 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
import CoreGraphics
public protocol Arithmetic {
static func + (left: Self, right: Self) -> Self
static func - (left: Self, right: Self) -> Self
static func * (left: Self, right: Self) -> Self
static func / (left: Self, right: Self) -> Self
static func += (left: inout Self, right: Self)
static func -= (left: inout Self, right: Self)
static func *= (left: inout Self, right: Self)
static func /= (left: inout Self, right: Self)
}
public protocol BitArithmetic {
static func & (left: Self, right: Self) -> Self
static func | (left: Self, right: Self) -> Self
static func ^ (left: Self, right: Self) -> Self
prefix static func ~ (left: Self) -> Self
static func &= (left: inout Self, right: Self)
static func |= (left: inout Self, right: Self)
static func ^= (left: inout Self, right: Self)
}
extension Int: BitArithmetic, Arithmetic {}
extension Int8: BitArithmetic, Arithmetic {}
extension Int16: BitArithmetic, Arithmetic {}
extension Int32: BitArithmetic, Arithmetic {}
extension Int64: BitArithmetic, Arithmetic {}
extension UInt: BitArithmetic, Arithmetic {}
extension UInt8: BitArithmetic, Arithmetic {}
extension UInt16: BitArithmetic, Arithmetic {}
extension UInt32: BitArithmetic, Arithmetic {}
extension UInt64: BitArithmetic, Arithmetic {}
extension CGFloat: Arithmetic {}
extension Float: Arithmetic {}
extension Double: Arithmetic {}
| mit | 07e377a559cf8db781cab6469599851a | 31.458333 | 72 | 0.693196 | 4.02584 | false | false | false | false |
chinlam91/edx-app-ios | Source/CourseSectionTableViewCell.swift | 2 | 1735 | //
// CourseSectionTableViewCell.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 04/06/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
protocol CourseSectionTableViewCellDelegate : class {
func sectionCellChoseDownload(cell : CourseSectionTableViewCell, block : CourseBlock)
}
class CourseSectionTableViewCell: UITableViewCell {
static let identifier = "CourseSectionTableViewCellIdentifier"
let content = CourseOutlineItemView(trailingImageIcon: Icon.ContentDownload)
weak var delegate : CourseSectionTableViewCellDelegate?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(content)
content.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(contentView)
}
content.addActionForTrailingIconTap {[weak self] _ in
if let owner = self, block = owner.block {
owner.delegate?.sectionCellChoseDownload(owner, block: block)
}
}
}
var block : CourseBlock? = nil {
didSet {
content.setTitleText(block?.name)
content.isGraded = block?.graded
let count = block?.blockCounts[CourseBlock.Category.Video.rawValue] ?? 0
let visibleCount : Int? = count > 0 ? count : nil
content.useTrailingCount(visibleCount)
content.setTrailingIconHidden(visibleCount == nil)
content.setDetailText(block?.format ?? "")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 661915ae94c26efc2040ccb7c9f06a3f | 30.545455 | 89 | 0.65072 | 4.928977 | false | false | false | false |
kickstarter/ios-oss | Library/Paginate.swift | 1 | 5242 | import Prelude
import ReactiveExtensions
import ReactiveSwift
/**
Returns signals that can be used to coordinate the process of paginating through values. This function is
specific to the type of pagination in which a page's results contains a cursor that can be used to request
the next page of values.
This function is generic over the following types:
* `Value`: The type of value that is being paginated, i.e. a single row, not the array of rows. The
value must be equatable.
* `Envelope`: The type of response we get from fetching a new page of values.
* `ErrorEnvelope`: The type of error we might get from fetching a new page of values.
* `Cursor`: The type of value that can be extracted from `Envelope` to request the next page of
values.
* `RequestParams`: The type that allows us to make a request for values without a cursor.
- parameter requestFirstPageWith: A signal that emits request params when a first page request should be
made.
- parameter requestNextPageWhen: A signal that emits whenever next page of values should be fetched.
- parameter clearOnNewRequest: A boolean that determines if results should be cleared when a new request
is made, i.e. an empty array will immediately be emitted.
- parameter skipRepeats: A boolean that determines if results can be repeated.
- parameter valuesFromEnvelope: A function to get an array of values from the results envelope.
- parameter cursorFromEnvelope: A function to get the cursor for the next page from a results envelope.
- parameter requestFromParams: A function to get a request for values from a params value.
- parameter requestFromCursor: A function to get a request for values from a cursor value.
- parameter concater: An optional function that concats a page of values to the current array of
values. By default this simply concatenates the arrays, but you might want
to do something more specific, such as concatenating only distinct values.
- returns: A tuple of signals, (paginatedValues, isLoading, pageCount, errors). The `paginatedValues` signal will
emit a full set of values when a new page has loaded. The `isLoading` signal will emit `true`
while a page of values is loading, and then `false` when it has terminated (either by completion
or error). The `pageCount` signal emits the number of the page that loaded, starting at 1. Finally,
`errors` emits the `ErrorEnvelope` when a page request fails.
*/
public func paginate<Cursor, Value: Equatable, Envelope, ErrorEnvelope, RequestParams>(
requestFirstPageWith requestFirstPage: Signal<RequestParams, Never>,
requestNextPageWhen requestNextPage: Signal<(), Never>,
clearOnNewRequest: Bool,
skipRepeats: Bool = true,
valuesFromEnvelope: @escaping ((Envelope) -> [Value]),
cursorFromEnvelope: @escaping ((Envelope) -> Cursor),
requestFromParams: @escaping ((RequestParams) -> SignalProducer<Envelope, ErrorEnvelope>),
requestFromCursor: @escaping ((Cursor) -> SignalProducer<Envelope, ErrorEnvelope>),
concater: @escaping (([Value], [Value]) -> [Value]) = (+)
)
->
(
paginatedValues: Signal<[Value], Never>,
isLoading: Signal<Bool, Never>,
pageCount: Signal<Int, Never>,
errors: Signal<ErrorEnvelope, Never>
) {
let cursor = MutableProperty<Cursor?>(nil)
let isLoading = MutableProperty<Bool>(false)
let errors = MutableProperty<ErrorEnvelope?>(nil)
// Emits the last cursor when nextPage emits
let cursorOnNextPage = cursor.producer.skipNil().sample(on: requestNextPage)
let paginatedValues = requestFirstPage
.switchMap { requestParams in
cursorOnNextPage.map(Either.right)
.prefix(value: .left(requestParams))
.switchMap { paramsOrCursor in
paramsOrCursor.ifLeft(requestFromParams, ifRight: requestFromCursor)
.subdueError()
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.liftSubduedError()
.on(
starting: { [weak isLoading] in
isLoading?.value = true
},
failed: { [weak errors] error in
errors?.value = error
},
terminated: { [weak isLoading] in
isLoading?.value = false
},
value: { [weak cursor] env in
cursor?.value = cursorFromEnvelope(env)
}
)
.map(valuesFromEnvelope)
.demoteErrors()
}
.takeUntil { $0.isEmpty }
.mergeWith(clearOnNewRequest ? .init(value: []) : .empty)
.scan([], concater)
}
.skip(first: clearOnNewRequest ? 1 : 0)
let pageCount = Signal.merge(paginatedValues, requestFirstPage.mapConst([]))
.scan(0) { accum, values in values.isEmpty ? 0 : accum + 1 }
.filter { $0 > 0 }
return (
skipRepeats ? paginatedValues.skipRepeats(==) : paginatedValues,
isLoading.signal,
pageCount,
errors.signal.skipNil()
)
}
| apache-2.0 | c1b6e6fc257b91cb935286ebc5eb19c6 | 47.091743 | 114 | 0.666539 | 4.774135 | false | false | false | false |
narner/AudioKit | Examples/iOS/SongProcessor/SongProcessor/View Controllers/VariableDelayViewController.swift | 1 | 1162 | //
// VariableDelayViewController.swift
// SongProcessor
//
// Created by Aurelius Prochazka on 6/22/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import AudioKit
import AudioKitUI
import UIKit
class VariableDelayViewController: UIViewController {
@IBOutlet private weak var timeSlider: AKSlider!
@IBOutlet private weak var feedbackSlider: AKSlider!
@IBOutlet private weak var mixSlider: AKSlider!
let songProcessor = SongProcessor.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
timeSlider.value = songProcessor.variableDelay.time
feedbackSlider.value = songProcessor.variableDelay.feedback
mixSlider.value = songProcessor.delayMixer.balance
timeSlider.callback = updateTime
feedbackSlider.callback = updateFeedback
mixSlider.callback = updateMix
}
func updateTime(value: Double) {
songProcessor.variableDelay.time = value
}
func updateFeedback(value: Double) {
songProcessor.variableDelay.feedback = value
}
func updateMix(value: Double) {
songProcessor.delayMixer.balance = value
}
}
| mit | 434eeeac2a2164d7a93b6cce670e157f | 23.702128 | 67 | 0.71404 | 4.919492 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Logging/Enums/CardType.swift | 1 | 985 | /*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 19/02/16.
*/
import Foundation
// swiftlint:disable type_name
enum CardType: Int, EnumCollection {
case invalid = 0,
game = 1,
player = 2,
hero = 3,
minion = 4,
spell = 5,
enchantment = 6,
weapon = 7,
item = 8,
token = 9,
hero_power = 10
init?(rawString: String) {
let string = rawString.lowercased()
for _enum in CardType.cases() where "\(_enum)" == string {
self = _enum
return
}
if let value = Int(rawString), let _enum = CardType(rawValue: value) {
self = _enum
return
}
self = .invalid
}
func rawString() -> String {
return "\(self)".replace("_", with: " ")
}
}
| mit | b03b000bd0c51bf0ffb8ecf0e520dd28 | 21.386364 | 78 | 0.55736 | 3.94 | false | false | false | false |
wireapp/wire-ios-data-model | Tests/Source/Model/Messages/GenericMessageTests+LegalHoldStatus.swift | 1 | 3675 | //
// Wire
// Copyright (C) 2016 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 WireTesting
@testable import WireDataModel
class GenericMessageTests_LegalHoldStatus: BaseZMClientMessageTests {
func testThatItUpdatesLegalHoldStatusFlagForTextMessage() {
// given
var genericMessage = GenericMessage(content: Text(content: "foo"), nonce: UUID.create())
// when
XCTAssertEqual(genericMessage.text.legalHoldStatus, .unknown)
genericMessage.setLegalHoldStatus(.disabled)
// then
XCTAssertEqual(genericMessage.text.legalHoldStatus, .disabled)
}
func testThatItUpdatesLegalHoldStatusFlagForReaction() {
// given
var genericMessage = GenericMessage(content: WireProtos.Reaction.createReaction(emoji: "🤠", messageID: UUID.create()))
// when
XCTAssertEqual(genericMessage.reaction.legalHoldStatus, .unknown)
genericMessage.setLegalHoldStatus(.enabled)
// then
XCTAssertEqual(genericMessage.reaction.legalHoldStatus, .enabled)
}
func testThatItUpdatesLegalHoldStatusFlagForKnock() {
// given
var genericMessage = GenericMessage(content: WireProtos.Knock.with { $0.hotKnock = true }, nonce: UUID.create())
// when
XCTAssertEqual(genericMessage.knock.legalHoldStatus, .unknown)
genericMessage.setLegalHoldStatus(.disabled)
// then
XCTAssertEqual(genericMessage.knock.legalHoldStatus, .disabled)
}
func testThatItUpdatesLegalHoldStatusFlagForLocation() {
// given
let location = WireProtos.Location.with {
$0.latitude = 0.0
$0.longitude = 0.0
}
var genericMessage = GenericMessage(content: location, nonce: UUID.create())
// when
XCTAssertEqual(genericMessage.location.legalHoldStatus, .unknown)
genericMessage.setLegalHoldStatus(.enabled)
// then
XCTAssertEqual(genericMessage.location.legalHoldStatus, .enabled)
}
func testThatItUpdatesLegalHoldStatusFlagForAsset() {
// given
var genericMessage = GenericMessage(content: WireProtos.Asset(imageSize: CGSize(width: 42, height: 12), mimeType: "image/jpeg", size: 123), nonce: UUID.create())
// when
XCTAssertEqual(genericMessage.asset.legalHoldStatus, .unknown)
genericMessage.setLegalHoldStatus(.disabled)
// then
XCTAssertEqual(genericMessage.asset.legalHoldStatus, .disabled)
}
func testThatItUpdatesLegalHoldStatusFlagForEphemeral() {
// given
let asset = WireProtos.Asset(imageSize: CGSize(width: 42, height: 12), mimeType: "image/jpeg", size: 123)
var genericMessage = GenericMessage(content: asset, nonce: UUID.create(), expiresAfter: .tenSeconds)
// when
XCTAssertEqual(genericMessage.ephemeral.legalHoldStatus, .unknown)
genericMessage.setLegalHoldStatus(.enabled)
// then
XCTAssertEqual(genericMessage.ephemeral.legalHoldStatus, .enabled)
}
}
| gpl-3.0 | 57be5a4573a75158d772e55798e77a4c | 33.317757 | 169 | 0.698802 | 5.238231 | false | true | false | false |
FreddyZeng/Charts | Source/Charts/Data/Implementations/Standard/BarChartDataSet.swift | 1 | 4998 | //
// BarChartDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet
{
private func initialize()
{
self.highlightColor = NSUIColor.black
self.calcStackSize(entries: values as! [BarChartDataEntry])
self.calcEntryCountIncludingStacks(entries: values as! [BarChartDataEntry])
}
public required init()
{
super.init()
initialize()
}
public override init(values: [ChartDataEntry]?, label: String?)
{
super.init(values: values, label: label)
initialize()
}
// MARK: - Data functions and accessors
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(entries: [BarChartDataEntry])
{
_entryCountStacks = 0
for i in 0 ..< entries.count
{
if let vals = entries[i].yValues
{
_entryCountStacks += vals.count
}
else
{
_entryCountStacks += 1
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(entries: [BarChartDataEntry])
{
for i in 0 ..< entries.count
{
if let vals = entries[i].yValues
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
open override func calcMinMax(entry e: ChartDataEntry)
{
guard let e = e as? BarChartDataEntry
else { return }
if !e.y.isNaN
{
if e.yValues == nil
{
if e.y < _yMin
{
_yMin = e.y
}
if e.y > _yMax
{
_yMax = e.y
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
calcMinMaxX(entry: e)
}
}
/// - returns: The maximum number of bars that can be stacked upon another in this DataSet.
open var stackSize: Int
{
return _stackSize
}
/// - returns: `true` if this DataSet is stacked (stacksize > 1) or not.
open var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// - returns: The overall entry count, including counting each stack-value individually
@objc open var entryCountStacks: Int
{
return _entryCountStacks
}
/// array of labels used to describe the different values of the stacked bars
open var stackLabels: [String] = ["Stack"]
/// 柱状图圆角类型
public var barCornerType:IBarChartType = .square
// MARK: - Styling functions and accessors
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// 柱状图背景是否圆角
public var barShadowType: IBarChartShadowType = .square
/// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn.
open var barBorderWidth : CGFloat = 0.0
/// the color drawing borders around the bars.
open var barBorderColor = NSUIColor.black
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
open var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BarChartDataSet
copy._stackSize = _stackSize
copy._entryCountStacks = _entryCountStacks
copy.stackLabels = stackLabels
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
| apache-2.0 | 5da47798245b1a5ca0295e19052a42a0 | 28.040936 | 148 | 0.566251 | 5.07771 | false | false | false | false |
CherishSmile/ZYBase | ZYBaseDemo/SetVC.swift | 1 | 3065 | //
// ViewController1.swift
// BaseDemo
//
// Created by Mzywx on 2016/12/21.
// Copyright © 2016年 Mzywx. All rights reserved.
//
import ZYBase
class SetVC: BaseDemoVC ,UITableViewDataSource,UITableViewDelegate{
fileprivate var setTab:UITableView!
fileprivate var setArr:Array<String> = []
override func viewDidLoad() {
super.viewDidLoad()
setArr = ["清理缓存"]
setTab = creatTabView(self, .plain, { (make) in
make.left.right.top.equalToSuperview()
make.bottom.equalTo(-TOOLBAR_HEIGHT)
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return setArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCellID")
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: "UITableViewCellID")
}
cell?.textLabel?.text = setArr[indexPath.row]
cell?.detailTextLabel?.text = byteSizeConversion(Bsize: calculateCacheSize())
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
ZYFileManager.clearTmpDirectory()
ZYFileManager.clearCachesDirectory()
if ZYFileManager.isExists(atPath: ZYFileManager.libraryDir()+"/Cookies") {
ZYFileManager.removeDirectory(atPath: ZYFileManager.libraryDir()+"/Cookies")
}
if ZYFileManager.isExists(atPath: ZYFileManager.libraryDir()+"/WebKit") {
ZYFileManager.removeDirectory(atPath: ZYFileManager.libraryDir()+"/WebKit")
}
setTab.reloadData()
}
}
func calculateCacheSize() -> Float {
let tmpSize = ZYFileManager.sizeOfDirectory(atPath: ZYFileManager.tmpDir()).floatValue
let libSize = ZYFileManager.sizeOfDirectory(atPath: ZYFileManager.libraryDir()).floatValue
let preSize = ZYFileManager.sizeOfDirectory(atPath: ZYFileManager.preferencesDir()).floatValue
return tmpSize + libSize - preSize
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setTab.reloadData()
}
/*
// 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 | 60772cb25f0dd9ed97c0a5e5daab0a66 | 33.704545 | 106 | 0.651932 | 5.098497 | false | false | false | false |
belatrix/iOSAllStars | AllStarsV2/AllStarsV2/BE/AchievementBE.swift | 1 | 1195 | //
// AchievementBE.swift
// AllStarsV2
//
// Created by Kenyi Rodriguez Vergara on 8/08/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
class AchievementBE: NSObject {
var achievement_pk : Int = 0
var achievement_date = Date()
var achievement_to_user = UserBE()
var achievement_assigned_by = UserBE()
var achievement_badge = BadgeBE()
class func parse(_ objDic : [String : Any]) -> AchievementBE{
let objBE = AchievementBE()
objBE.achievement_pk = CDMWebResponse.getInt(objDic["pk"])
objBE.achievement_assigned_by = UserBE.parse(CDMWebResponse.getDictionary(objDic["assigned_by"]))
objBE.achievement_to_user = UserBE.parse(CDMWebResponse.getDictionary(objDic["to_user"]))
objBE.achievement_badge = BadgeBE.parse(CDMWebResponse.getDictionary(objDic["badge"]))
if let date = CDMDateManager.convertirTexto(CDMWebResponse.getString(objDic["date"]), enDateConFormato: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"){
objBE.achievement_date = date
}
return objBE
}
}
| apache-2.0 | 78d58b08e820f9bc85b9913030b45fc3 | 33.114286 | 144 | 0.627303 | 3.927632 | false | false | false | false |
jpchmura/JPCDataSourceController | Source/ErrorView.swift | 1 | 2253 | //
// ErrorView.swift
// JPCDataSourceController
//
// Created by Jon Chmura on 4/15/15.
// Copyright (c) 2015 Jon Chmura. All rights reserved.
//
import UIKit
public class StandardErrorView: UIView {
public lazy var imageView: UIImageView = UIImageView()
public lazy var messageView: UILabel = UILabel()
public lazy var resolveButton: UIButton = UIButton(type: .System)
private var _constraints = [NSLayoutConstraint]()
public override func updateConstraints() {
removeConstraints(_constraints)
_constraints.removeAll()
let views = ["message" : messageView, "image" : imageView]
messageView.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false
_constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=8)-[message]-(>=8)-|", options: [], metrics: nil, views: views)
_constraints += NSLayoutConstraint.constraintsWithVisualFormat("V:[image]-[message]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: views)
_constraints.append(NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
_constraints.append(NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
addConstraints(_constraints)
super.updateConstraints()
}
private func commonInit() {
imageView.contentMode = .ScaleAspectFit
messageView.numberOfLines = 0
messageView.textAlignment = .Center
self.addSubview(imageView)
self.addSubview(messageView)
self.backgroundColor = UIColor.clearColor()
setNeedsUpdateConstraints()
}
public convenience init() {
self.init(frame: CGRectZero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
}
| mit | 9963d82f6d801125ebc112b94b4429ab | 31.652174 | 169 | 0.650688 | 5.377088 | false | false | false | false |
KieranHarper/KJHUIKit | Sources/PageControl.swift | 1 | 2327 | //
// PageControl.swift
// KJHUIKit
//
// Created by Kieran Harper on 1/7/17.
// Copyright © 2017 Kieran Harper. All rights reserved.
//
import UIKit
@objc public protocol PageControlDelegate: class {
/// The page change event, triggered when tracking detects that scrolling has brought the new page more than 50% of the way into the scroll view.
@objc func didChange(fromPage oldPage: Int, toPage newPage: Int)
}
/// Simple UIPageControl subclass that encapsulates common logic about tracking page changes and hiding itself when there's no reason for it to be shown.
@objc open class PageControl: UIPageControl {
/// Object to be notified when the current page changes.
@objc open weak var delegate: PageControlDelegate?
/// The scroll view whose page is being tracked.
@objc open var scrollViewToTrack: UIScrollView?
/// Whether or not the page control should make itself hidden when there's only one page (or zero).
@objc open var hidesWhenNotNeeded = true {
didSet {
showHideSelfIfNeeded()
}
}
/// Adjust for the scroll view's current number of pages. Will affect the hidden state as needed.
@objc open func updateNumberOfPages() {
guard let scrollView = scrollViewToTrack else {
self.numberOfPages = 0
return
}
// Calculate the number of pages
self.numberOfPages = Int(ceil(scrollView.contentSize.width / scrollView.bounds.size.width))
showHideSelfIfNeeded()
}
/// Detect page changes based on the current scroll position of the scroll view.
@objc open func trackCurrentPage() {
// Track page movement purely to update the page dots if applicable
guard let scrollView = scrollViewToTrack else { return }
let offsetPercentage = max(0, scrollView.contentOffset.x) / scrollView.contentSize.width
let newPage = Int(round(offsetPercentage * CGFloat(numberOfPages)))
if newPage != self.currentPage {
let oldPage = self.currentPage
self.currentPage = newPage
delegate?.didChange(fromPage: oldPage, toPage: newPage)
}
}
private func showHideSelfIfNeeded() {
self.isHidden = hidesWhenNotNeeded && self.numberOfPages <= 1
}
}
| mit | e1d0d88e59a3ae00b401cb82f8d294f7 | 35.920635 | 153 | 0.674549 | 4.805785 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Do.swift | 108 | 3867 | //
// Do.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> ())? = nil, onSubscribed: (() -> ())? = nil, onDispose: (() -> ())? = nil)
-> Observable<E> {
return Do(source: self.asObservable(), eventHandler: { e in
switch e {
case .next(let element):
try onNext?(element)
case .error(let e):
try onError?(e)
case .completed:
try onCompleted?()
}
}, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose)
}
}
final fileprivate class DoSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias EventHandler = (Event<Element>) throws -> Void
private let _eventHandler: EventHandler
init(eventHandler: @escaping EventHandler, observer: O, cancel: Cancelable) {
_eventHandler = eventHandler
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
do {
try _eventHandler(event)
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
catch let error {
forwardOn(.error(error))
dispose()
}
}
}
final fileprivate class Do<Element> : Producer<Element> {
typealias EventHandler = (Event<Element>) throws -> Void
fileprivate let _source: Observable<Element>
fileprivate let _eventHandler: EventHandler
fileprivate let _onSubscribe: (() -> ())?
fileprivate let _onSubscribed: (() -> ())?
fileprivate let _onDispose: (() -> ())?
init(source: Observable<Element>, eventHandler: @escaping EventHandler, onSubscribe: (() -> ())?, onSubscribed: (() -> ())?, onDispose: (() -> ())?) {
_source = source
_eventHandler = eventHandler
_onSubscribe = onSubscribe
_onSubscribed = onSubscribed
_onDispose = onDispose
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
_onSubscribe?()
let sink = DoSink(eventHandler: _eventHandler, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
_onSubscribed?()
let onDispose = _onDispose
let allSubscriptions = Disposables.create {
subscription.dispose()
onDispose?()
}
return (sink: sink, subscription: allSubscriptions)
}
}
| mit | a84d38055c9017fd3ae522c59194986a | 40.569892 | 241 | 0.62597 | 5.060209 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Sequence.swift | 24 | 3378 | //
// Sequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 11/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension Observable {
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: elements, scheduler: scheduler)
}
}
extension Observable {
/**
Converts an array to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: array, scheduler: scheduler)
}
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<S: Sequence>(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> where S.Iterator.Element == E {
return ObservableSequence(elements: sequence, scheduler: scheduler)
}
}
final fileprivate class ObservableSequenceSink<S: Sequence, O: ObserverType> : Sink<O> where S.Iterator.Element == O.E {
typealias Parent = ObservableSequence<S>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRecursive((_parent._elements.makeIterator(), _parent._elements)) { (iterator, recurse) in
var mutableIterator = iterator
if let next = mutableIterator.0.next() {
self.forwardOn(.next(next))
recurse(mutableIterator)
}
else {
self.forwardOn(.completed)
self.dispose()
}
}
}
}
final fileprivate class ObservableSequence<S: Sequence> : Producer<S.Iterator.Element> {
fileprivate let _elements: S
fileprivate let _scheduler: ImmediateSchedulerType
init(elements: S, scheduler: ImmediateSchedulerType) {
_elements = elements
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | 496172d385020c556b8963daa41010b2 | 36.94382 | 173 | 0.68019 | 4.790071 | false | false | false | false |
dgollub/pokealmanac | PokeAlmanac/Transformer.swift | 1 | 3294 | //
// Transformer.swift
// PokeAlmanac
//
// Created by 倉重ゴルプ ダニエル on 2016/04/19.
// Copyright © 2016年 Daniel Kurashige-Gollub. All rights reserved.
//
import Foundation
import JSONJoy
// TODO(dkg): Does this have to be a class? Could those functions be static functions on the class? Or
// even standalone functions?
//
// TODO(dkg): The methods have a lot of code in common - maybe refactor?
//
public class Transformer {
public func jsonToPokemonModel(json: String?) -> Pokemon? {
var pokemon: Pokemon? = nil
if let json = json {
autoreleasepool({
let data: NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
do {
pokemon = try Pokemon(JSONDecoder(data))
} catch {
logWarn("Could not convert JSON to Pokemon. \(error)")
pokemon = nil
}
})
}
return pokemon
}
public func jsonToNamedAPIResourceList(json: String?) -> NamedAPIResourceList? {
var resourceList: NamedAPIResourceList? = nil
if let json = json {
autoreleasepool({
let data: NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
do {
resourceList = try NamedAPIResourceList(JSONDecoder(data))
} catch {
logWarn("Could not convert JSON to NamedAPIResourceList. \(error)")
resourceList = nil
}
})
}
return resourceList
}
public func jsonToPokemonSpecies(json: String?) -> PokemonSpecies? {
var pokemonSpecies: PokemonSpecies? = nil
if let json = json {
autoreleasepool({
let data: NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
do {
pokemonSpecies = try PokemonSpecies(JSONDecoder(data))
} catch {
logWarn("Could not convert JSON to PokemonSpecies. \(error)")
pokemonSpecies = nil
}
})
}
return pokemonSpecies
}
public func jsonToMove(json: String?) -> Move? {
var move: Move? = nil
if let json = json {
autoreleasepool({
let data: NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
do {
move = try Move(JSONDecoder(data))
} catch {
logWarn("Could not convert JSON to Move. \(error)")
move = nil
}
})
}
return move
}
public func jsonToPokemonForm(json: String?) -> PokemonForm? {
var form: PokemonForm? = nil
if let json = json {
autoreleasepool({
let data: NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
do {
form = try PokemonForm(JSONDecoder(data))
} catch {
logWarn("Could not convert JSON to PokemonForm. \(error)")
form = nil
}
})
}
return form
}
} | mit | 29f0c2dacd84b14d9815207267a3bb25 | 29.296296 | 102 | 0.508713 | 5.336052 | false | false | false | false |
hhyyg/Miso.Gistan | Gistan/Controller/FollowingsGistsTableTableViewController.swift | 1 | 4535 | //
// FollowingsGistsTableTableViewController.swift
// Gistan
//
// Created by Hiroka Yago on 2017/10/01.
// Copyright © 2017 miso. All rights reserved.
//
import UIKit
import SafariServices
import Nuke
class FollowingsGistsTableTableViewController: UITableViewController {
private var followingUsers: [User] = []
private var gistItems: [GistItem] = []
private var isFirstAppeared = false
override func viewDidLoad() {
super.viewDidLoad()
navigationController!.navigationBar.prefersLargeTitles = true
let nib = UINib(nibName: "GistItemCell", bundle: nil)
self.tableView?.register(nib, forCellReuseIdentifier: "ItemCell")
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(refresh(sender:)), for: .valueChanged)
//セルの高さを自動調整にする
self.tableView.estimatedRowHeight = 30
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !isFirstAppeared {
isFirstAppeared = true
self.refreshControl!.beginRefreshing()
refreshData()
}
}
private func refreshData() {
if let userName = KeychainService.get(forKey: .userName) {
load(userName: userName) {
self.tableView.reloadData()
self.refreshControl!.endRefreshing()
}
}
}
@objc func refresh(sender: UIRefreshControl) {
self.gistItems = []
self.followingUsers = []
refreshData()
}
// UserのFollowsのGistを読み込む
func load(userName: String,
loadComplete: @escaping () -> Void) {
let client = GitHubClient()
let request = GitHubAPI.GetUsersFollowing(userName: userName)
client.send(request: request) { result in
switch result {
case let .success(response):
self.followingUsers = response
self.loadFollowingUsersGists(client: client, loadComplete: loadComplete)
case .failure(let error):
logger.error(error)
DispatchQueue.main.async {
loadComplete()
}
}
}
}
// FollowsのGistsを読み込む
func loadFollowingUsersGists(client: GitHubClient,
loadComplete: @escaping () -> Void) {
if followingUsers.count == 0 {
loadComplete()
return
}
var loadedUserCount = 0
for user in followingUsers {
let request = GitHubAPI.GetUsersGists(userName: user.login)
client.send(request: request) { result in
switch result {
case let .success(response):
self.gistItems.append(contentsOf: response)
loadedUserCount += 1
if loadedUserCount == self.followingUsers.count {
DispatchQueue.main.async {
self.gistItems.sort(by: { $0.createdAt > $1.createdAt })
loadComplete()
}
}
case .failure(let error):
logger.error(error)
DispatchQueue.main.async {
loadComplete()
}
}
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return gistItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard gistItems.count > indexPath.row else {
return UITableViewCell()
}
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! GistItemTableViewCell
let gistItem = gistItems[indexPath.row]
cell.setItem(item: gistItem, forMe: false)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let gistItem = gistItems[indexPath.row]
let safariViewController = SFSafariViewController(url: URL(string: gistItem.htmlUrl)!)
self.showDetailViewController(safariViewController, sender: nil)
}
}
| mit | 31a6a796ab87532fab2303b4e16f5933 | 31.014286 | 118 | 0.589469 | 5.291617 | false | false | false | false |
longsirhero/DinDinShop | DinDinShopDemo/DinDinShopDemo/海外/Views/WCOverseasCountrisCell.swift | 1 | 1744 | //
// WCOverseasCountrisCell.swift
// DinDinShopDemo
//
// Created by longsirHERO on 2017/8/21.
// Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved.
//
import UIKit
class WCOverseasCountrisCell: UICollectionViewCell {
let imageV:UIImageView = UIImageView()
let titleLab:UILabel = UILabel()
var model:WCOverseasCountry = WCOverseasCountry() {
didSet {
imageV.kf.setImage(with: URL(string: model.picPath!))
titleLab.text = model.picTitle
}
}
var category:WCHomeCategoryModel = WCHomeCategoryModel() {
didSet {
imageV.kf.setImage(with: URL(string: category.picPath!))
titleLab.text = category.typeName
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIColor.white
titleLab.textAlignment = NSTextAlignment.center
titleLab.font = k14Font
imageV.contentMode = .scaleAspectFill
self.contentView.addSubview(imageV)
self.contentView.addSubview(titleLab)
imageV.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(5)
make.centerX.equalToSuperview()
make.size.equalTo(CGSize.init(width: 45, height: 45))
}
titleLab.snp.makeConstraints { (make) in
make.top.equalTo(imageV.snp.bottom)
make.left.right.equalToSuperview()
make.height.equalTo(20)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 39d2d7ccb2a87014f5a342b2c53ba2ef | 26.634921 | 86 | 0.597932 | 4.487113 | false | false | false | false |
blinksh/blink | Blink/Commands/ssh/SSHConfigProvider.swift | 1 | 6796 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import SSH
import Combine
import BlinkConfig
fileprivate let HostKeyChangedWarningMessage = "@@WARNING! REMOTE IDENTIFICATION HAS CHANGED. New Public key hash: %@. Accepting the following prompt will add a new entry for this host. Do you trust the host key? [Y/n]: "
fileprivate let HostKeyChangedUnknownRequestMessage = "Public key hash: %@. The server is unknown. Do you trust the host key? [Y/n]: "
fileprivate let HostKeyChangedNotFoundRequestMessage = "Public key hash: %@. The server is unknown. Do you trust the host key? [Y/n]: "
// Having access from CLI
// Having access from UI. Some parameters must already exist, others need to be tweaked.
// Pass it a host and get everything necessary to connect, but some functions still need to be setup.
class SSHClientConfigProvider {
let device: TermDevice
let logger = PassthroughSubject<String, Never>()
var logCancel: AnyCancellable? = nil
let config: BKConfig
fileprivate init(using device: TermDevice) throws {
self.device = device
self.config = try BKConfig()
logCancel = logger.sink { [weak self] in self?.printLn($0, err: true) }
}
// Return HostName, SSHClientConfig for the server
static func config(host: BKSSHHost, using device: TermDevice) throws -> SSHClientConfig {
let prov = try SSHClientConfigProvider(using: device)
let agent = prov.agent(for: host)
let availableAuthMethods: [AuthMethod] = [AuthAgent(agent)] + prov.passwordAuthMethods(for: host)
return
host.sshClientConfig(authMethods: availableAuthMethods,
verifyHostCallback: (host.strictHostKeyChecking ?? true) ? prov.cliVerifyHostCallback : nil,
agent: agent,
logger: prov.logger)
}
}
extension SSHClientConfigProvider {
// NOTE Unused as we moved to a pure agent. Leaving here in case it is useful in the future.
fileprivate func keyAuthMethods(for host: BKSSHHost) -> [AuthMethod] {
var authMethods: [AuthMethod] = []
// Explicit identity
if let identities = host.identityFile {
identities.forEach { identity in
if let (identityKey, name) = config.privateKey(forIdentifier: identity) {
authMethods.append(AuthPublicKey(privateKey: identityKey, keyName: name))
}
}
} else {
// All default keys
for (defaultKey, name) in config.defaultKeys() {
authMethods.append(AuthPublicKey(privateKey: defaultKey, keyName: name))
}
}
return authMethods
}
fileprivate func passwordAuthMethods(for host: BKSSHHost) -> [AuthMethod] {
var authMethods: [AuthMethod] = []
// Host password
if let password = host.password, !password.isEmpty {
authMethods.append(AuthPassword(with: password))
}
authMethods.append(AuthKeyboardInteractive(requestAnswers: self.authPrompt, wrongRetriesAllowed: 2))
// Password-Interactive
authMethods.append(AuthPasswordInteractive(requestAnswers: self.authPrompt,
wrongRetriesAllowed: 2))
return authMethods
}
fileprivate func authPrompt(_ prompt: Prompt) -> AnyPublisher<[String], Error> {
return prompt.userPrompts.publisher.tryMap { question -> String in
guard let input = self.device.readline(question.prompt, secure: true) else {
throw CommandError(message: "Couldn't read input")
}
return input
}.collect()
.eraseToAnyPublisher()
}
fileprivate func agent(for host: BKSSHHost) -> SSHAgent {
let agent = SSHAgent()
let consts: [SSHAgentConstraint] = [SSHConstraintTrustedConnectionOnly()]
if let signers = config.signer(forHost: host) {
signers.forEach { (signer, name) in
// NOTE We could also keep the reference and just read the key at the proper time.
// TODO Errors. Either pass or log here, or if we create a different
// type of key, then let the Agent fail.
_ = agent.loadKey(signer, aka: name, constraints: consts)
}
} else {
for (signer, name) in config.defaultSigners() {
_ = agent.loadKey(signer, aka: name, constraints: consts)
}
}
// Link to Default Agent
agent.linkTo(agent: SSHAgentPool.defaultAgent)
return agent
}
}
extension SSHClientConfigProvider {
func cliVerifyHostCallback(_ prompt: SSH.VerifyHost) -> AnyPublisher<InteractiveResponse, Error> {
var response: SSH.InteractiveResponse = .negative
let messageToShow: String
switch prompt {
case .changed(serverFingerprint: let serverFingerprint):
messageToShow = String(format: HostKeyChangedWarningMessage, serverFingerprint)
case .unknown(serverFingerprint: let serverFingerprint):
messageToShow = String(format: HostKeyChangedUnknownRequestMessage, serverFingerprint)
case .notFound(serverFingerprint: let serverFingerprint):
messageToShow = String(format: HostKeyChangedNotFoundRequestMessage, serverFingerprint)
}
let readAnswer = self.device.readline(messageToShow, secure: false)
if let answer = readAnswer?.lowercased() {
if answer.starts(with: "y") || answer.isEmpty {
response = .affirmative
}
} else {
printLn("Cannot read input.", err: true)
}
return .just(response)
}
fileprivate func printLn(_ string: String, err: Bool = false) {
let line = string.appending("\r\n")
let s = err ? device.stream.err : device.stream.out
fwrite(line, line.lengthOfBytes(using: .utf8), 1, s)
}
}
| gpl-3.0 | 8d9856075ef5e760541a923853ff5369 | 36.340659 | 221 | 0.679959 | 4.500662 | false | true | false | false |
gpolitis/jitsi-meet | ios/sdk/src/callkit/JMCallKitEmitter.swift | 1 | 3748 | /*
* Copyright @ 2018-present Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import AVKit
import CallKit
import Foundation
internal final class JMCallKitEmitter: NSObject, CXProviderDelegate {
private let listeners = NSMutableArray()
private var pendingMuteActions = Set<UUID>()
internal override init() {}
// MARK: - Add/remove listeners
func addListener(_ listener: JMCallKitListener) {
if (!listeners.contains(listener)) {
listeners.add(listener)
}
}
func removeListener(_ listener: JMCallKitListener) {
listeners.remove(listener)
}
// MARK: - Add mute action
func addMuteAction(_ actionUUID: UUID) {
pendingMuteActions.insert(actionUUID)
}
// MARK: - CXProviderDelegate
func providerDidReset(_ provider: CXProvider) {
listeners.forEach {
let listener = $0 as! JMCallKitListener
listener.providerDidReset?()
}
pendingMuteActions.removeAll()
}
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
listeners.forEach {
let listener = $0 as! JMCallKitListener
listener.performAnswerCall?(UUID: action.callUUID)
}
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
listeners.forEach {
let listener = $0 as! JMCallKitListener
listener.performEndCall?(UUID: action.callUUID)
}
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
let uuid = pendingMuteActions.remove(action.uuid)
// Avoid mute actions ping-pong: if the mute action was caused by
// the JS side (we requested a transaction) don't call the delegate
// method. If it was called by the provider itself (when the user presses
// the mute button in the CallKit view) then call the delegate method.
//
// NOTE: don't try to be clever and remove this. Been there, done that.
// Won't work.
if (uuid == nil) {
listeners.forEach {
let listener = $0 as! JMCallKitListener
listener.performSetMutedCall?(UUID: action.callUUID, isMuted: action.isMuted)
}
}
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXStartCallAction) {
listeners.forEach {
let listener = $0 as! JMCallKitListener
listener.performStartCall?(UUID: action.callUUID, isVideo: action.isVideo)
}
action.fulfill()
}
func provider(_ provider: CXProvider,
didActivate audioSession: AVAudioSession) {
listeners.forEach {
let listener = $0 as! JMCallKitListener
listener.providerDidActivateAudioSession?(session: audioSession)
}
}
func provider(_ provider: CXProvider,
didDeactivate audioSession: AVAudioSession) {
listeners.forEach {
let listener = $0 as! JMCallKitListener
listener.providerDidDeactivateAudioSession?(session: audioSession)
}
}
}
| apache-2.0 | 6c6cf2cf030661ce640738757947a8a8 | 30.762712 | 93 | 0.644077 | 4.89295 | false | false | false | false |
huonw/swift | validation-test/Sema/type_checker_perf/fast/rdar17077404.swift | 13 | 497 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1
// REQUIRES: tools-release,no_asserts
func memoize<A: Hashable, R>(
f: @escaping ((A) -> R, A) -> R
) -> ((A) -> R) {
var memo = Dictionary<A,R>()
var recur: ((A) -> R)!
recur = { (a: A) -> R in
if let r = memo[a] { return r }
let r = f(recur, a)
memo[a] = r
return r
}
return recur
}
let fibonacci = memoize {
(fibonacci, n) in
n < 2 ? n as Int : fibonacci(n - 1) + fibonacci(n - 2)
}
| apache-2.0 | 1efda887b906e8c521f11ca412bfcc92 | 20.608696 | 74 | 0.557344 | 2.776536 | false | false | false | false |
allevato/swift-protobuf | Sources/SwiftProtobuf/JSONEncoder.swift | 1 | 13518 | // Sources/SwiftProtobuf/JSONEncoder.swift - JSON Encoding support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// JSON serialization engine.
///
// -----------------------------------------------------------------------------
import Foundation
private let asciiZero = UInt8(ascii: "0")
private let asciiOne = UInt8(ascii: "1")
private let asciiTwo = UInt8(ascii: "2")
private let asciiThree = UInt8(ascii: "3")
private let asciiFour = UInt8(ascii: "4")
private let asciiFive = UInt8(ascii: "5")
private let asciiSix = UInt8(ascii: "6")
private let asciiSeven = UInt8(ascii: "7")
private let asciiEight = UInt8(ascii: "8")
private let asciiNine = UInt8(ascii: "9")
private let asciiMinus = UInt8(ascii: "-")
private let asciiPlus = UInt8(ascii: "+")
private let asciiEquals = UInt8(ascii: "=")
private let asciiColon = UInt8(ascii: ":")
private let asciiComma = UInt8(ascii: ",")
private let asciiDoubleQuote = UInt8(ascii: "\"")
private let asciiBackslash = UInt8(ascii: "\\")
private let asciiForwardSlash = UInt8(ascii: "/")
private let asciiOpenSquareBracket = UInt8(ascii: "[")
private let asciiCloseSquareBracket = UInt8(ascii: "]")
private let asciiOpenCurlyBracket = UInt8(ascii: "{")
private let asciiCloseCurlyBracket = UInt8(ascii: "}")
private let asciiUpperA = UInt8(ascii: "A")
private let asciiUpperB = UInt8(ascii: "B")
private let asciiUpperC = UInt8(ascii: "C")
private let asciiUpperD = UInt8(ascii: "D")
private let asciiUpperE = UInt8(ascii: "E")
private let asciiUpperF = UInt8(ascii: "F")
private let asciiUpperZ = UInt8(ascii: "Z")
private let asciiLowerA = UInt8(ascii: "a")
private let asciiLowerZ = UInt8(ascii: "z")
private let base64Digits: [UInt8] = {
var digits = [UInt8]()
digits.append(contentsOf: asciiUpperA...asciiUpperZ)
digits.append(contentsOf: asciiLowerA...asciiLowerZ)
digits.append(contentsOf: asciiZero...asciiNine)
digits.append(asciiPlus)
digits.append(asciiForwardSlash)
return digits
}()
private let hexDigits: [UInt8] = {
var digits = [UInt8]()
digits.append(contentsOf: asciiZero...asciiNine)
digits.append(contentsOf: asciiUpperA...asciiUpperF)
return digits
}()
internal struct JSONEncoder {
private var data = [UInt8]()
private var separator: UInt8?
private let doubleFormatter = DoubleFormatter()
internal init() {}
internal var dataResult: Data { return Data(bytes: data) }
internal var stringResult: String {
get {
return String(bytes: data, encoding: String.Encoding.utf8)!
}
}
/// Append a `StaticString` to the JSON text. Because
/// `StaticString` is already UTF8 internally, this is faster
/// than appending a regular `String`.
internal mutating func append(staticText: StaticString) {
let buff = UnsafeBufferPointer(start: staticText.utf8Start, count: staticText.utf8CodeUnitCount)
data.append(contentsOf: buff)
}
/// Append a `_NameMap.Name` to the JSON text surrounded by quotes.
/// As with StaticString above, a `_NameMap.Name` provides pre-converted
/// UTF8 bytes, so this is much faster than appending a regular
/// `String`.
internal mutating func appendQuoted(name: _NameMap.Name) {
data.append(asciiDoubleQuote)
data.append(contentsOf: name.utf8Buffer)
data.append(asciiDoubleQuote)
}
/// Append a `String` to the JSON text.
internal mutating func append(text: String) {
data.append(contentsOf: text.utf8)
}
/// Append a raw utf8 in a `Data` to the JSON text.
internal mutating func append(utf8Data: Data) {
data.append(contentsOf: utf8Data)
}
/// Begin a new field whose name is given as a `_NameMap.Name`
internal mutating func startField(name: _NameMap.Name) {
if let s = separator {
data.append(s)
}
appendQuoted(name: name)
data.append(asciiColon)
separator = asciiComma
}
/// Begin a new field whose name is given as a `String`.
internal mutating func startField(name: String) {
if let s = separator {
data.append(s)
}
data.append(asciiDoubleQuote)
// Can avoid overhead of putStringValue, since
// the JSON field names are always clean ASCII.
data.append(contentsOf: name.utf8)
append(staticText: "\":")
separator = asciiComma
}
/// Append an open square bracket `[` to the JSON.
internal mutating func startArray() {
data.append(asciiOpenSquareBracket)
separator = nil
}
/// Append a close square bracket `]` to the JSON.
internal mutating func endArray() {
data.append(asciiCloseSquareBracket)
separator = asciiComma
}
/// Append a comma `,` to the JSON.
internal mutating func comma() {
data.append(asciiComma)
}
/// Append an open curly brace `{` to the JSON.
internal mutating func startObject() {
if let s = separator {
data.append(s)
}
data.append(asciiOpenCurlyBracket)
separator = nil
}
/// Append a close curly brace `}` to the JSON.
internal mutating func endObject() {
data.append(asciiCloseCurlyBracket)
separator = asciiComma
}
/// Write a JSON `null` token to the output.
internal mutating func putNullValue() {
append(staticText: "null")
}
/// Append a float value to the output.
/// This handles Nan and infinite values by
/// writing well-known string values.
internal mutating func putFloatValue(value: Float) {
if value.isNaN {
append(staticText: "\"NaN\"")
} else if !value.isFinite {
if value < 0 {
append(staticText: "\"-Infinity\"")
} else {
append(staticText: "\"Infinity\"")
}
} else {
if let v = Int64(exactly: Double(value)) {
appendInt(value: v)
} else {
let formatted = doubleFormatter.floatToUtf8(value)
data.append(contentsOf: formatted)
}
}
}
/// Append a double value to the output.
/// This handles Nan and infinite values by
/// writing well-known string values.
internal mutating func putDoubleValue(value: Double) {
if value.isNaN {
append(staticText: "\"NaN\"")
} else if !value.isFinite {
if value < 0 {
append(staticText: "\"-Infinity\"")
} else {
append(staticText: "\"Infinity\"")
}
} else {
if let v = Int64(exactly: value) {
appendInt(value: v)
} else {
let formatted = doubleFormatter.doubleToUtf8(value)
data.append(contentsOf: formatted)
}
}
}
/// Append a UInt64 to the output (without quoting).
private mutating func appendUInt(value: UInt64) {
if value >= 10 {
appendUInt(value: value / 10)
}
data.append(asciiZero + UInt8(value % 10))
}
/// Append an Int64 to the output (without quoting).
private mutating func appendInt(value: Int64) {
if value < 0 {
data.append(asciiMinus)
// This is the twos-complement negation of value,
// computed in a way that won't overflow a 64-bit
// signed integer.
appendUInt(value: 1 + ~UInt64(bitPattern: value))
} else {
appendUInt(value: UInt64(bitPattern: value))
}
}
/// Write an Enum as an int.
internal mutating func putEnumInt(value: Int) {
appendInt(value: Int64(value))
}
/// Write an `Int64` using protobuf JSON quoting conventions.
internal mutating func putInt64(value: Int64) {
data.append(asciiDoubleQuote)
appendInt(value: value)
data.append(asciiDoubleQuote)
}
/// Write an `Int32` with quoting suitable for
/// using the value as a map key.
internal mutating func putQuotedInt32(value: Int32) {
data.append(asciiDoubleQuote)
appendInt(value: Int64(value))
data.append(asciiDoubleQuote)
}
/// Write an `Int32` in the default format.
internal mutating func putInt32(value: Int32) {
appendInt(value: Int64(value))
}
/// Write a `UInt64` using protobuf JSON quoting conventions.
internal mutating func putUInt64(value: UInt64) {
data.append(asciiDoubleQuote)
appendUInt(value: value)
data.append(asciiDoubleQuote)
}
/// Write a `UInt32` with quoting suitable for
/// using the value as a map key.
internal mutating func putQuotedUInt32(value: UInt32) {
data.append(asciiDoubleQuote)
appendUInt(value: UInt64(value))
data.append(asciiDoubleQuote)
}
/// Write a `UInt32` in the default format.
internal mutating func putUInt32(value: UInt32) {
appendUInt(value: UInt64(value))
}
/// Write a `Bool` with quoting suitable for
/// using the value as a map key.
internal mutating func putQuotedBoolValue(value: Bool) {
data.append(asciiDoubleQuote)
putBoolValue(value: value)
data.append(asciiDoubleQuote)
}
/// Write a `Bool` in the default format.
internal mutating func putBoolValue(value: Bool) {
if value {
append(staticText: "true")
} else {
append(staticText: "false")
}
}
/// Append a string value escaping special characters as needed.
internal mutating func putStringValue(value: String) {
data.append(asciiDoubleQuote)
for c in value.unicodeScalars {
switch c.value {
// Special two-byte escapes
case 8: append(staticText: "\\b")
case 9: append(staticText: "\\t")
case 10: append(staticText: "\\n")
case 12: append(staticText: "\\f")
case 13: append(staticText: "\\r")
case 34: append(staticText: "\\\"")
case 92: append(staticText: "\\\\")
case 0...31, 127...159: // Hex form for C0 control chars
append(staticText: "\\u00")
data.append(hexDigits[Int(c.value / 16)])
data.append(hexDigits[Int(c.value & 15)])
case 23...126:
data.append(UInt8(extendingOrTruncating: c.value))
case 0x80...0x7ff:
data.append(0xc0 + UInt8(extendingOrTruncating: c.value >> 6))
data.append(0x80 + UInt8(extendingOrTruncating: c.value & 0x3f))
case 0x800...0xffff:
data.append(0xe0 + UInt8(extendingOrTruncating: c.value >> 12))
data.append(0x80 + UInt8(extendingOrTruncating: (c.value >> 6) & 0x3f))
data.append(0x80 + UInt8(extendingOrTruncating: c.value & 0x3f))
default:
data.append(0xf0 + UInt8(extendingOrTruncating: c.value >> 18))
data.append(0x80 + UInt8(extendingOrTruncating: (c.value >> 12) & 0x3f))
data.append(0x80 + UInt8(extendingOrTruncating: (c.value >> 6) & 0x3f))
data.append(0x80 + UInt8(extendingOrTruncating: c.value & 0x3f))
}
}
data.append(asciiDoubleQuote)
}
/// Append a bytes value using protobuf JSON Base-64 encoding.
internal mutating func putBytesValue(value: Data) {
data.append(asciiDoubleQuote)
if value.count > 0 {
value.withUnsafeBytes { (p: UnsafePointer<UInt8>) in
var t: Int = 0
var bytesInGroup: Int = 0
for i in 0..<value.count {
if bytesInGroup == 3 {
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(base64Digits[(t >> 6) & 63])
data.append(base64Digits[t & 63])
t = 0
bytesInGroup = 0
}
t = (t << 8) + Int(p[i])
bytesInGroup += 1
}
switch bytesInGroup {
case 3:
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(base64Digits[(t >> 6) & 63])
data.append(base64Digits[t & 63])
case 2:
t <<= 8
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(base64Digits[(t >> 6) & 63])
data.append(asciiEquals)
case 1:
t <<= 16
data.append(base64Digits[(t >> 18) & 63])
data.append(base64Digits[(t >> 12) & 63])
data.append(asciiEquals)
data.append(asciiEquals)
default:
break
}
}
}
data.append(asciiDoubleQuote)
}
}
| apache-2.0 | 67a8dc38e54f1762aa00d5b1ff1d4546 | 34.856764 | 104 | 0.579746 | 4.398959 | false | false | false | false |
Centine/panorama9-reader | Panorama9 Reader/SetupViewController.swift | 1 | 2564 | //
// SetupViewController.swift
// Panorama9 Reader
//
// Created by Jan Wiberg on 18/03/15.
// Copyright (c) 2015 panorama9. All rights reserved.
//
import UIKit
class SetupViewController : UIViewController, UITextFieldDelegate {
@IBOutlet weak var apiKeyField: UITextField!
@IBOutlet weak var connectResponseLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
let lastConnect:NSInteger = defaults.integerForKey("p9LastConnect")
if lastConnect > 0 {
connectResponseLabel.text = "Previously Connected"
}
if let storedApiKey = defaults.stringForKey("p9ApiKey") {
apiKeyField.text = storedApiKey
}
}
@IBAction func ConnectTapped(sender: AnyObject) {
connectResponseLabel.text = "Testing..."
let api = RestAPI()
if !api.isAuthable(apiKeyField.text) {
connectResponseLabel.text = "Key must be 64 hex digits"
return
}
api.setAuthKey(apiKeyField.text)
api.getDictionary("identity", completion: dataReceiveComplete, failure: dataReceiveError)
}
func dataReceiveComplete(data: NSDictionary?) {
connectResponseLabel.text = "Received..."
var msg: String
if let type:String = data?.objectForKey("type") as? String {
if type == "customer" {
let name = data?.objectForKey("name") as? String ?? ""
msg = "Welcome \(name)"
var date = NSDate()
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(apiKeyField.text, forKey: "p9ApiKey")
defaults.setInteger(NSInteger(date.timeIntervalSince1970), forKey: "p9LastConnect")
} else {
msg = "Only works for customers"
}
} else {
msg = "Unexpected data"
}
connectResponseLabel.text = msg
}
func dataReceiveError(message: String?) {
let alert = UIAlertController(title: "Network error", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true;
}
}
| mit | 47df2ba0bcb04a09f9eb57af83b3c733 | 33.186667 | 125 | 0.617395 | 5.087302 | false | false | false | false |
nbhasin2/NBNavigationController | NBNavigationController/TopDownTransition.swift | 2 | 2480 | //
// TopDownTransition.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Nishant Bhasin. <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
public class TopDownTransition: BaseTransition, UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return transitionDuration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to),
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
else {
transitionContext.completeTransition(true)
return
}
toView.frame = container.frame
toView.frame.origin.y = -toView.frame.maxY
container.addSubview(toView)
UIView.animate(
withDuration: transitionDuration,
animations: {
fromViewController.view.frame.origin.y = container.frame.maxY
toView.frame = container.frame
},
completion: { _ in
transitionContext.completeTransition(true)
}
)
}
}
| mit | 01862bc44a55d6c11c6f9a99936bd940 | 39.655738 | 120 | 0.702419 | 5.321888 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/SwifterSwift/Source/Extensions/IntExtensions.swift | 4 | 6834 | //
// IntExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/6/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension Int {
/// SwifterSwift: Absolute value of integer.
public var abs: Int {
return Swift.abs(self)
}
/// SwifterSwift: String with number and current locale currency.
public var asLocaleCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
return formatter.string(from: self as NSNumber)!
}
/// SwifterSwift: Radian value of degree input.
public var degreesToRadians: Double {
return Double.pi * Double(self) / 180.0
}
/// SwifterSwift: Array of digits of integer value.
public var digits: [Int] {
var digits: [Int] = []
for char in String(self).characters {
if let int = Int(String(char)) {
digits.append(int)
}
}
return digits
}
/// SwifterSwift: Number of digits of integer value.
public var digitsCount: Int {
return String(self).characters.count
}
/// SwifterSwift: Check if integer is even.
public var isEven: Bool {
return (self % 2) == 0
}
/// SwifterSwift: Check if integer is odd.
public var isOdd: Bool {
return (self % 2) != 0
}
/// SwifterSwift: Check if integer is positive.
public var isPositive: Bool {
return self > 0
}
/// SwifterSwift: Check if integer is negative.
public var isNegative: Bool {
return self < 0
}
/// SwifterSwift: Double.
public var double: Double {
return Double(self)
}
/// SwifterSwift: Float.
public var float: Float {
return Float(self)
}
/// SwifterSwift: CGFloat.
public var cgFloat: CGFloat {
return CGFloat(self)
}
/// SwifterSwift: String.
public var string: String {
return String(self)
}
/// SwifterSwift: Degree value of radian input
public var radiansToDegrees: Double {
return Double(self) * 180 / Double.pi
}
/// SwifterSwift: Roman numeral string from integer (if applicable).
public var romanNumeral: String? {
// https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7
guard self > 0 else { // there is no roman numerals for 0 or negative numbers
return nil
}
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanValue = ""
var startingValue = self
for (index, romanChar) in romanValues.enumerated() {
let arabicValue = arabicValues[index]
let div = startingValue / arabicValue
if (div > 0) {
for _ in 0..<div {
romanValue += romanChar
}
startingValue -= arabicValue * div
}
}
return romanValue
}
/// SwifterSwift: String of format (XXh XXm) from seconds Int.
public var timeString: String {
guard self > 0 else {
return "0 sec"
}
if self < 60 {
return "\(self) sec"
}
if self < 3600 {
return "\(self / 60) min"
}
let hours = self / 3600
let mins = (self % 3600) / 60
if hours != 0 && mins == 0 {
return "\(hours)h"
}
return "\(hours)h \(mins)m"
}
/// SwifterSwift: String formatted for values over ±1000 (example: 1k, -2k, 100k, 1kk, -5kk..)
public var kFormatted: String {
var sign: String {
return self >= 0 ? "" : "-"
}
let abs = self.abs
if abs == 0 {
return "0k"
} else if abs >= 0 && abs < 1000 {
return "0k"
} else if abs >= 1000 && abs < 1000000 {
return String(format: "\(sign)%ik", abs / 1000)
}
return String(format: "\(sign)%ikk", abs / 100000)
}
}
// MARK: - Methods
public extension Int {
/// SwifterSwift: Greatest common divisor of integer value and n.
///
/// - Parameter n: integer value to find gcd with.
/// - Returns: greatest common divisor of self and n.
public func gcd(of n: Int) -> Int {
return n == 0 ? self : n.gcd(of: self % n)
}
/// SwifterSwift: Least common multiple of integer and n.
///
/// - Parameter n: integer value to find lcm with.
/// - Returns: least common multiple of self and n.
public func lcm(of n: Int) -> Int {
return (self * n).abs / gcd(of: n)
}
/// SwifterSwift: Random integer between two integer values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
/// - Returns: random double between two double values.
public static func random(between min: Int, and max: Int) -> Int {
return random(inRange: min...max)
}
/// SwifterSwift: Random integer in a closed interval range.
///
/// - Parameter range: closed interval range.
/// - Returns: random double in the given closed range.
public static func random(inRange range: ClosedRange<Int>) -> Int {
let delta = UInt32(range.upperBound - range.lowerBound + 1)
return range.lowerBound + Int(arc4random_uniform(delta))
}
}
// MARK: - Initializers
public extension Int {
/// SwifterSwift: Created a random integer between two integer values.
///
/// - Parameters:
/// - min: minimum number to start random from.
/// - max: maximum number random number end before.
public init(randomBetween min: Int, and max: Int) {
self = Int.random(between: min, and: max)
}
/// SwifterSwift: Create a random integer in a closed interval range.
///
/// - Parameter range: closed interval range.
public init(randomInRange range: ClosedRange<Int>) {
self = Int.random(inRange: range)
}
}
// MARK: - Operators
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ** : PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
/// - lhs: base integer.
/// - rhs: exponent integer.
/// - Returns: exponentiation result (example: 2 ** 3 = 8).
public func ** (lhs: Int, rhs: Int) -> Double {
// http://nshipster.com/swift-operators/
return pow(Double(lhs), Double(rhs))
}
prefix operator √
/// SwifterSwift: Square root of integer.
///
/// - Parameter int: integer value to find square root for
/// - Returns: square root of given integer.
public prefix func √ (int: Int) -> Double {
// http://nshipster.com/swift-operators/
return sqrt(Double(int))
}
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
/// - lhs: integer number.
/// - rhs: integer number.
/// - Returns: tuple of plus-minus operation (example: 2 ± 3 -> (5, -1)).
public func ± (lhs: Int, rhs: Int) -> (Int, Int) {
// http://nshipster.com/swift-operators/
return (lhs + rhs, lhs - rhs)
}
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: integer number
/// - Returns: tuple of plus-minus operation (example: ± 2 -> (2, -2)).
public prefix func ± (int: Int) -> (Int, Int) {
// http://nshipster.com/swift-operators/
return 0 ± int
}
| mit | 671334e23328c343bcb6ee7b606d1338 | 24.262963 | 95 | 0.651078 | 3.338718 | false | false | false | false |
ishkawa/APIKit | Sources/APIKit/Serializations/URLEncodedSerialization.swift | 1 | 3670 | import Foundation
private func escape(_ string: String) -> String {
// Reserved characters defined by RFC 3986
// Reference: https://www.ietf.org/rfc/rfc3986.txt
let generalDelimiters = ":#[]@"
let subDelimiters = "!$&'()*+,;="
let reservedCharacters = generalDelimiters + subDelimiters
var allowedCharacterSet = CharacterSet()
allowedCharacterSet.formUnion(.urlQueryAllowed)
allowedCharacterSet.remove(charactersIn: reservedCharacters)
// Crashes due to internal bug in iOS 7 ~ iOS 8.2.
// References:
// - https://github.com/Alamofire/Alamofire/issues/206
// - https://github.com/AFNetworking/AFNetworking/issues/3028
// return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
let batchSize = 50
var index = string.startIndex
var escaped = ""
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = String(string[range])
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring
index = endIndex
}
return escaped
}
private func unescape(_ string: String) -> String {
return CFURLCreateStringByReplacingPercentEscapes(nil, string as CFString, nil) as String
}
/// `URLEncodedSerialization` parses `Data` and `String` as urlencoded,
/// and returns dictionary that represents the data or the string.
public final class URLEncodedSerialization {
public enum Error: Swift.Error {
case cannotGetStringFromData(Data, String.Encoding)
case cannotGetDataFromString(String, String.Encoding)
case cannotCastObjectToDictionary(Any)
case invalidFormatString(String)
}
/// Returns `[String: String]` that represents urlencoded `Data`.
/// - Throws: URLEncodedSerialization.Error
public static func object(from data: Data, encoding: String.Encoding) throws -> [String: String] {
guard let string = String(data: data, encoding: encoding) else {
throw Error.cannotGetStringFromData(data, encoding)
}
var dictionary = [String: String]()
for pair in string.components(separatedBy: "&") {
let contents = pair.components(separatedBy: "=")
guard contents.count == 2 else {
throw Error.invalidFormatString(string)
}
dictionary[contents[0]] = unescape(contents[1])
}
return dictionary
}
/// Returns urlencoded `Data` from the object.
/// - Throws: URLEncodedSerialization.Error
public static func data(from object: Any, encoding: String.Encoding) throws -> Data {
guard let dictionary = object as? [String: Any] else {
throw Error.cannotCastObjectToDictionary(object)
}
let string = self.string(from: dictionary)
guard let data = string.data(using: encoding, allowLossyConversion: false) else {
throw Error.cannotGetDataFromString(string, encoding)
}
return data
}
/// Returns urlencoded `String` from the dictionary.
public static func string(from dictionary: [String: Any]) -> String {
let pairs = dictionary.map { key, value -> String in
if value is NSNull {
return "\(escape(key))"
}
let valueAsString = (value as? String) ?? "\(value)"
return "\(escape(key))=\(escape(valueAsString))"
}
return pairs.joined(separator: "&")
}
}
| mit | 20b161f7a4d00d6a44a7a953d35f0a47 | 34.621359 | 110 | 0.658763 | 4.951417 | false | false | false | false |
ashfurrow/FunctionalReactiveAwesome | Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/ReplaySubject.swift | 2 | 7041 | //
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ReplaySubjectImplementation<Element> : SubjectType<Element, Element>, Disposable {
typealias Observer = ObserverOf<Element>
typealias BagType = Bag<Observer>
typealias DisposeKey = BagType.KeyType
var hasObservers: Bool {
get {
return abstractMethod()
}
}
func unsubscribe(key: DisposeKey) {
return abstractMethod()
}
func dispose() {
}
}
class ReplaySubscription<Element> : Disposable {
typealias Observer = ObserverOf<Element>
typealias BagType = Bag<Observer>
typealias DisposeKey = BagType.KeyType
typealias Subject = ReplaySubjectImplementation<Element>
typealias State = (
subject: Subject?,
disposeKey: DisposeKey?
)
var lock = Lock()
var state: State
init(subject: Subject, disposeKey: DisposeKey) {
self.state = (
subject: subject,
disposeKey: disposeKey
)
}
func dispose() {
let oldState = lock.calculateLocked { () -> State in
var state = self.state
self.state = (
subject: nil,
disposeKey: nil
)
return state
}
if let subject = oldState.subject, disposeKey = oldState.disposeKey {
subject.unsubscribe(disposeKey)
}
}
}
class ReplayBufferBase<Element> : ReplaySubjectImplementation<Element> {
typealias Observer = ObserverOf<Element>
typealias BagType = Bag<Observer>
typealias DisposeKey = BagType.KeyType
typealias State = (
disposed: Bool,
stoppedEvent: Event<Element>?,
observers: BagType
)
var lock = Lock()
var state: State = (
disposed: false,
stoppedEvent: nil,
observers: Bag()
)
override init() {
}
func trim() {
return abstractMethod()
}
func addValueToBuffer(value: Element) {
return abstractMethod()
}
func replayBuffer(observer: Observer) {
return abstractMethod()
}
override var hasObservers: Bool {
get {
return state.observers.count > 0
}
}
override func on(event: Event<Element>) {
let observers: [Observer] = lock.calculateLocked {
if self.state.disposed {
return []
}
if self.state.stoppedEvent != nil {
return []
}
switch event {
case .Next(let boxedValue):
let value = boxedValue.value
addValueToBuffer(value)
trim()
return self.state.observers.all
case .Error: fallthrough
case .Completed:
state.stoppedEvent = event
trim()
var bag = self.state.observers
var observers = bag.all
bag.removeAll()
return observers
}
}
dispatch(event, observers)
}
override func subscribe<O : ObserverType where O.Element == Element>(observer: O) -> Disposable {
return lock.calculateLocked {
if self.state.disposed {
sendError(observer, DisposedError)
return DefaultDisposable()
}
let observerOf = ObserverOf(observer)
replayBuffer(observerOf)
if let stoppedEvent = self.state.stoppedEvent {
observer.on(stoppedEvent)
return DefaultDisposable()
}
else {
let key = self.state.observers.put(observerOf)
return ReplaySubscription(subject: self, disposeKey: key)
}
}
}
override func unsubscribe(key: DisposeKey) {
lock.performLocked {
if self.state.disposed {
return
}
_ = self.state.observers.removeKey(key)
}
}
func lockedDispose() {
state.disposed = true
state.observers.removeAll()
}
override func dispose() {
super.dispose()
lock.performLocked {
self.lockedDispose()
}
}
}
class ReplayOne<Element> : ReplayBufferBase<Element> {
var value: Element?
init(firstElement: Element) {
self.value = firstElement
super.init()
}
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(value: Element) {
self.value = value
}
override func replayBuffer(observer: Observer) {
if let value = self.value {
sendNext(observer, value)
}
}
override func lockedDispose() {
super.lockedDispose()
value = nil
}
}
class ReplayManyBase<Element> : ReplayBufferBase<Element> {
var queue: Queue<Element>
init(queueSize: Int) {
queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(value: Element) {
queue.enqueue(value)
}
override func replayBuffer(observer: Observer) {
for item in queue {
sendNext(observer, item)
}
}
override func lockedDispose() {
super.lockedDispose()
while queue.count > 0 {
queue.dequeue()
}
}
}
class ReplayMany<Element> : ReplayManyBase<Element> {
let bufferSize: Int
init(bufferSize: Int) {
self.bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while queue.count > bufferSize {
queue.dequeue()
}
}
}
class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
class ReplaySubject<Element> : SubjectType<Element, Element> {
typealias Observer = ObserverOf<Element>
typealias BagType = Bag<Observer>
typealias DisposeKey = BagType.KeyType
let implementation: ReplaySubjectImplementation<Element>
init(firstElement: Element) {
implementation = ReplayOne(firstElement: firstElement)
}
init(bufferSize: Int) {
if bufferSize == 1 {
implementation = ReplayOne()
}
else {
implementation = ReplayMany(bufferSize: bufferSize)
}
}
override func subscribe<O : ObserverType where O.Element == Element>(observer: O) -> Disposable {
return implementation.subscribe(observer)
}
override func on(event: Event<Element>) {
implementation.on(event)
}
} | mit | f625ae7d3f97ef9be2e8f802b5c6d279 | 22.790541 | 101 | 0.546371 | 5.211695 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Criteria/AndSpecification.swift | 1 | 1185 | public struct AndSpecification<
First: Specification,
Second: Specification
> where First.Element == Second.Element {
private let first: First
private let second: Second
init(_ first: First, second: Second) {
self.first = first
self.second = second
}
}
// MARK: AndSpecification + Specification
extension AndSpecification: Specification {
public typealias Element = First.Element
public func isSatisfied(by element: Element) -> Bool {
first.isSatisfied(by: element) && second.isSatisfied(by: element)
}
public func contains<S>(_ specification: S.Type) -> Bool {
first.contains(specification) || second.contains(specification)
}
}
// MARK: Convenience Creation
@inline(__always)
public func && <
S1: Specification,
S2: Specification
> (_ s1: S1, _ s2: S2) -> AndSpecification<S1, S2> where S1.Element == S2.Element {
s1.and(s2)
}
extension Specification {
public func and<Other: Specification>(
_ other: Other
) -> AndSpecification<Self, Other> where Other.Element == Element {
AndSpecification(self, second: other)
}
}
| mit | 952f920b466f9a9b5e5f2c84289509b6 | 22.7 | 83 | 0.64135 | 4.143357 | false | false | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/06068-swift-typebase-getcanonicaltype.swift | 11 | 309 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol P {
func b<T where T>() { e
class B<T.B == "\(e : B
func b<T.B == g: d = c<T>(v: A"\() { }
protocol A : NSObject {
typealias e : e
| mit | afa4a5c78d8a34ace2ff7eb5ed483183 | 29.9 | 87 | 0.660194 | 3.21875 | false | true | false | false |
dangnguyenhuu/JSQMessagesSwift | Sources/Models/JSQMessagesAvatarImage.swift | 1 | 1988 | //
// JSQMessagesAvatarImage.swift
// JSQMessagesViewController
//
// Created by Sylvain FAY-CHATELARD on 20/08/2015.
// Copyright (c) 2015 Dviance. All rights reserved.
//
import Foundation
import UIKit
open class JSQMessagesAvatarImage: NSObject, JSQMessageAvatarImageDataSource, NSCopying {
open var avatarImage: UIImage?
open var avatarHighlightedImage: UIImage?
fileprivate(set) open var avatarPlaceholderImage: UIImage
public required init(avatarImage: UIImage?, highlightedImage: UIImage?, placeholderImage: UIImage) {
self.avatarImage = avatarImage
self.avatarHighlightedImage = highlightedImage
self.avatarPlaceholderImage = placeholderImage
super.init()
}
open class func avatar(image: UIImage) -> JSQMessagesAvatarImage {
return JSQMessagesAvatarImage(avatarImage: image, highlightedImage: image, placeholderImage: image)
}
open class func avatar(placeholder: UIImage) -> JSQMessagesAvatarImage {
return JSQMessagesAvatarImage(avatarImage: nil, highlightedImage: nil, placeholderImage: placeholder)
}
// MARK: - NSObject
open override var description: String {
get {
return "<\(type(of: self)): avatarImage=\(self.avatarImage), avatarHighlightedImage=\(self.avatarHighlightedImage), avatarPlaceholderImage=\(self.avatarPlaceholderImage)>"
}
}
func debugQuickLookObject() -> AnyObject? {
return UIImageView(image: self.avatarImage != nil ? self.avatarImage : self.avatarPlaceholderImage)
}
// MARK: - NSCopying
open func copy(with zone: NSZone?) -> Any {
return type(of: self).init(avatarImage: UIImage(cgImage: self.avatarImage!.cgImage!), highlightedImage: UIImage(cgImage: self.avatarHighlightedImage!.cgImage!), placeholderImage: UIImage(cgImage: self.avatarPlaceholderImage.cgImage!))
}
}
| apache-2.0 | 2ed04c5f2711471621fa47f05bb89e56 | 33.275862 | 242 | 0.687123 | 5.537604 | false | false | false | false |
andresbrun/UIDynamicsPlayground | UIDynamicPlayground.playground/Sources/UITapGestureRecognizerHelper.swift | 1 | 676 | import UIKit
public class UITapGestureRecognizerHelper: NSObject {
public typealias OnTapAction = (CGPoint) -> Void
var tapGesture: UITapGestureRecognizer!
let onTap: OnTapAction
let view: UIView
public init(view: UIView, onTap: @escaping OnTapAction) {
self.view = view
self.onTap = onTap
super.init()
tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognizer(tapGesture:)))
view.addGestureRecognizer(tapGesture)
}
@objc func tapGestureRecognizer(tapGesture: UITapGestureRecognizer) {
let location = tapGesture.location(in: view)
onTap(location)
}
}
| mit | 89b2b894b2c738c94379f3f58a886297 | 27.166667 | 111 | 0.693787 | 5.121212 | false | false | false | false |
selfzhou/Swift3 | Playground/Swift3-I.playground/Pages/Type-Casting.xcplaygroundpage/Contents.swift | 1 | 2593 | //: [Previous](@previous)
import Foundation
// 类型转换 可以判断实例的类型,也可以将实例看作是其父类或者子类的实例。
// is as :检查值的类型 或 转换它的类型,也可以检查一个类型是否实现某个协议。
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
// [MedialItem]
let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// 检查类型:is 找到属于各自类型的实例。
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
movieCount
songCount
// 向下转型
// 某类型的一个常量或变量可能在幕后实际上属于一个子类。
// 你可尝试向下转到它的子类型, as? as!
for item in library {
if let movie = item as? Movie {
print("M -\(movie.name) - \(movie.director)")
} else if let song = item as? Song {
print("S -\(song.name) - \(song.artist)")
}
}
// 转换并没有真的改变实例或它的值,根本的实例保持不变,只是简单地把它作为它被转换成的类型来使用。
// Any AnyObject 的类型转换
/**
Any: 可以表示任何类型,包括函数类型。
AnyObject: 可以表示任意类类型的`实例`。
*/
var things = [Any]()
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman"))
things.append({ (name: String) -> String in "Hello, \(name)" })
// Any 可以表示所有类型的值,包括 可选类型。
// Swift 会在你用 Any 类型来表示一个可选值的时候,给你一个警告。
// 如果你确实想使用 Any 类型来承载可选值,可以使用 as 显示转换为 Any
let optionalNumber: Int? = 3
things.append(optionalNumber as Any) // 去掉 as Any 有警告。
| mit | 82e4a0c571cbb9f79eaf34b8c360f1f1 | 19.683673 | 68 | 0.637395 | 2.924964 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Nodes/Generators/Oscillators/Square Wave/AKSquareWaveOscillator.swift | 1 | 7971 | //
// AKSquareWaveOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// This is a bandlimited square oscillator ported from the "square" function
/// from the Faust programming language.
///
/// - parameter frequency: In cycles per second, or Hz.
/// - parameter amplitude: Output amplitude
/// - parameter pulseWidth: Duty cycle width (range 0-1).
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public class AKSquareWaveOscillator: AKVoice {
// MARK: - Properties
internal var internalAU: AKSquareWaveOscillatorAudioUnit?
internal var token: AUParameterObserverToken?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var pulseWidthParameter: AUParameter?
private var detuningOffsetParameter: AUParameter?
private var detuningMultiplierParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet(newValue) {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// In cycles per second, or Hz.
public var frequency: Double = 440 {
willSet(newValue) {
if frequency != newValue {
if internalAU!.isSetUp() {
frequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.frequency = Float(newValue)
}
}
}
}
/// Output Amplitude.
public var amplitude: Double = 1 {
willSet(newValue) {
if amplitude != newValue {
if internalAU!.isSetUp() {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Frequency offset in Hz.
public var detuningOffset: Double = 0 {
willSet(newValue) {
if detuningOffset != newValue {
if internalAU!.isSetUp() {
detuningOffsetParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningOffset = Float(newValue)
}
}
}
}
/// Frequency detuning multiplier
public var detuningMultiplier: Double = 1 {
willSet(newValue) {
if detuningMultiplier != newValue {
if internalAU!.isSetUp() {
detuningMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningMultiplier = Float(newValue)
}
}
}
}
/// Duty cycle width (range 0-1).
public var pulseWidth: Double = 0.5 {
willSet(newValue) {
if pulseWidth != newValue {
pulseWidthParameter?.setValue(Float(newValue), originator: token!)
if internalAU!.isSetUp() {
pulseWidthParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.pulseWidth = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
override public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
public convenience override init() {
self.init(frequency: 440)
}
/// Initialize this oscillator node
///
/// - parameter frequency: In cycles per second, or Hz.
/// - parameter amplitude: Output amplitude
/// - parameter pulseWidth: Duty cycle width (range 0-1).
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public init(
frequency: Double,
amplitude: Double = 1.0,
pulseWidth: Double = 0.5,
detuningOffset: Double = 0,
detuningMultiplier: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
self.pulseWidth = pulseWidth
self.detuningOffset = detuningOffset
self.detuningMultiplier = detuningMultiplier
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x7371726f /*'sqro'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKSquareWaveOscillatorAudioUnit.self,
asComponentDescription: description,
name: "Local AKSquareWaveOscillator",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKSquareWaveOscillatorAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
pulseWidthParameter = tree.valueForKey("pulseWidth") as? AUParameter
detuningOffsetParameter = tree.valueForKey("detuningOffset") as? AUParameter
detuningMultiplierParameter = tree.valueForKey("detuningMultiplier") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
} else if address == self.pulseWidthParameter!.address {
self.pulseWidth = Double(value)
} else if address == self.detuningOffsetParameter!.address {
self.detuningOffset = Double(value)
} else if address == self.detuningMultiplierParameter!.address {
self.detuningMultiplier = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
internalAU?.pulseWidth = Float(pulseWidth)
internalAU?.detuningOffset = Float(detuningOffset)
internalAU?.detuningMultiplier = Float(detuningMultiplier)
}
/// Function create an identical new node for use in creating polyphonic instruments
public override func duplicate() -> AKVoice {
let copy = AKSquareWaveOscillator(frequency: self.frequency, amplitude: self.amplitude, pulseWidth: self.pulseWidth, detuningOffset: self.detuningOffset, detuningMultiplier: self.detuningMultiplier)
return copy
}
/// Function to start, play, or activate the node, all do the same thing
public override func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public override func stop() {
self.internalAU!.stop()
}
}
| apache-2.0 | 998b4052579575306dd6d8107e190a49 | 35.39726 | 206 | 0.610087 | 5.83956 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.