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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
natecook1000/swift | test/attr/attr_noescape.swift | 2 | 20025 | // RUN: %target-typecheck-verify-swift
@noescape var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}}
func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{@escaping conflicts with @noescape}}
// expected-error@-1{{@noescape is the default and has been removed}} {{29-39=}}
func doesEscape(_ fn : @escaping () -> Int) {}
func takesGenericClosure<T>(_ a : Int, _ fn : @noescape () -> T) {} // expected-error{{@noescape is the default and has been removed}} {{47-57=}}
var globalAny: Any = 0
func assignToGlobal<T>(_ t: T) {
globalAny = t
}
func takesArray(_ fns: [() -> Int]) {
doesEscape(fns[0]) // Okay - array-of-function parameters are escaping
}
func takesVariadic(_ fns: () -> Int...) {
doesEscape(fns[0]) // Okay - variadic-of-function parameters are escaping
}
func takesNoEscapeClosure(_ fn : () -> Int) {
// expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-2{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-3{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-4{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-5{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-6{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
// expected-note@-7{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }}
takesNoEscapeClosure { 4 } // ok
_ = fn() // ok
var x = fn // expected-error {{non-escaping parameter 'fn' may only be called}}
// This is ok, because the closure itself is noescape.
takesNoEscapeClosure { fn() }
// This is not ok, because it escapes the 'fn' closure.
doesEscape { fn() } // expected-error {{closure use of non-escaping parameter 'fn' may allow it to escape}}
// This is not ok, because it escapes the 'fn' closure.
func nested_function() {
_ = fn() // expected-error {{declaration closing over non-escaping parameter 'fn' may allow it to escape}}
}
takesNoEscapeClosure(fn) // ok
doesEscape(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
takesGenericClosure(4, fn) // ok
takesGenericClosure(4) { fn() } // ok.
_ = [fn] // expected-error {{converting non-escaping value to 'Element' may allow it to escape}}
_ = [doesEscape(fn)] // expected-error {{'(() -> Int) -> ()' is not convertible to '(@escaping () -> Int) -> ()'}}
_ = [1 : fn] // expected-error {{converting non-escaping value to 'Value' may allow it to escape}}
_ = [1 : doesEscape(fn)] // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
_ = "\(doesEscape(fn))" // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}}
_ = "\(takesArray([fn]))" // expected-error {{using non-escaping parameter 'fn' in a context expecting an @escaping closure}}
assignToGlobal(fn) // expected-error {{converting non-escaping value to 'T' may allow it to escape}}
}
class SomeClass {
final var x = 42
func test() {
// This should require "self."
doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
// Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't
// require "self." qualification of member references.
takesNoEscapeClosure { x }
}
@discardableResult
func foo() -> Int {
foo()
func plain() { foo() }
let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{31-31=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{18-18=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
func outer() {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{28-28=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() }
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 }
}
let outer2: () -> Void = {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
}
doesEscape {
func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{29-29=self.}}
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
return 0
}
takesNoEscapeClosure {
func inner() { foo() }
let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
func multi() -> Int { foo(); return 0 }
let mulit2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{33-33=self.}}
doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo() } // okay
doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{20-20=self.}}
takesNoEscapeClosure { foo(); return 0 } // okay
return 0
}
struct Outer {
@discardableResult
func bar() -> Int {
bar()
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{30-30=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{22-22=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
func structOuter() {
struct Inner {
@discardableResult
func bar() -> Int {
bar() // no-warning
func plain() { bar() }
let plain2 = { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{26-26=self.}}
func multi() -> Int { bar(); return 0 }
let _: () -> Int = { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{32-32=self.}}
doesEscape { bar() } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar() } // okay
doesEscape { bar(); return 0 } // expected-error {{call to method 'bar' in closure requires explicit 'self.' to make capture semantics explicit}} {{24-24=self.}}
takesNoEscapeClosure { bar(); return 0 } // okay
return 0
}
}
}
return 0
}
}
// Implicit conversions (in this case to @convention(block)) are ok.
@_silgen_name("whatever")
func takeNoEscapeAsObjCBlock(_: @noescape @convention(block) () -> Void) // expected-error{{@noescape is the default and has been removed}} {{33-43=}}
func takeNoEscapeTest2(_ fn : @noescape () -> ()) { // expected-error{{@noescape is the default and has been removed}} {{31-41=}}
takeNoEscapeAsObjCBlock(fn)
}
// Autoclosure implies noescape, but produce nice diagnostics so people know
// why noescape problems happen.
func testAutoclosure(_ a : @autoclosure () -> Int) { // expected-note{{parameter 'a' is implicitly non-escaping}}
doesEscape { a() } // expected-error {{closure use of non-escaping parameter 'a' may allow it to escape}}
}
// <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both
func redundant(_ fn : @noescape // expected-error @+1 {{@noescape is implied by @autoclosure and should not be redundantly specified}}
@autoclosure () -> Int) {
// expected-error@-2{{@noescape is the default and has been removed}} {{23-33=}}
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1, T>(_ source: O, _ transform: @escaping (O.Element) -> (), _: T) {}
func overloadedEach<P: P2, T>(_ source: P, _ transform: @escaping (P.Element) -> (), _: T) {}
struct S : P2 {
typealias Element = Int
func each(_ transform: @noescape (Int) -> ()) { // expected-error{{@noescape is the default and has been removed}} {{26-36=}}
overloadedEach(self, // expected-error {{cannot invoke 'overloadedEach' with an argument list of type '(S, (Int) -> (), Int)'}}
transform, 1)
// expected-note @-2 {{overloads for 'overloadedEach' exist with these partially matching parameter lists: (O, @escaping (O.Element) -> (), T), (P, @escaping (P.Element) -> (), T)}}
}
}
// rdar://19763676 - False positive in @noescape analysis triggered by parameter label
func r19763676Callee(_ f: @noescape (_ param: Int) -> Int) {} // expected-error{{@noescape is the default and has been removed}} {{27-37=}}
func r19763676Caller(_ g: @noescape (Int) -> Int) { // expected-error{{@noescape is the default and has been removed}} {{27-37=}}
r19763676Callee({ _ in g(1) })
}
// <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments
func calleeWithDefaultParameters(_ f: @noescape () -> (), x : Int = 1) {} // expected-error{{@noescape is the default and has been removed}} {{39-49=}}
func callerOfDefaultParams(_ g: @noescape () -> ()) { // expected-error{{@noescape is the default and has been removed}} {{33-43=}}
calleeWithDefaultParameters(g)
}
// <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape
class NoEscapeImmediatelyApplied {
func f() {
// Shouldn't require "self.", the closure is obviously @noescape.
_ = { return ivar }()
}
final var ivar = 42
}
// Reduced example from XCTest overlay, involves a TupleShuffleExpr
public func XCTAssertTrue(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
}
public func XCTAssert(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void {
XCTAssertTrue(expression, message, file: file, line: line);
}
/// SR-770 - Currying and `noescape`/`rethrows` don't work together anymore
func curriedFlatMap<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-error{{@noescape is the default and has been removed}} {{41-50=}}
return { f in
x.flatMap(f)
}
}
func curriedFlatMap2<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-error{{@noescape is the default and has been removed}} {{42-51=}}
return { (f : @noescape (A) -> [B]) in // expected-error{{@noescape is the default and has been removed}} {{17-27=}}
x.flatMap(f)
}
}
func bad(_ a : @escaping (Int)-> Int) -> Int { return 42 }
func escapeNoEscapeResult(_ x: [Int]) -> (@noescape (Int) -> Int) -> Int { // expected-error{{@noescape is the default and has been removed}} {{43-52=}}
return { f in // expected-note{{parameter 'f' is implicitly non-escaping}}
bad(f) // expected-error {{passing non-escaping parameter 'f' to function expecting an @escaping closure}}
}
}
// SR-824 - @noescape for Type Aliased Closures
//
// Old syntax -- @noescape is the default, and is redundant
typealias CompletionHandlerNE = @noescape (_ success: Bool) -> () // expected-error{{@noescape is the default and has been removed}} {{33-43=}}
// Explicit @escaping is not allowed here
typealias CompletionHandlerE = @escaping (_ success: Bool) -> () // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}}
// No @escaping -- it's implicit from context
typealias CompletionHandler = (_ success: Bool) -> ()
var escape : CompletionHandlerNE
var escapeOther : CompletionHandler
func doThing1(_ completion: (_ success: Bool) -> ()) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing2(_ completion: CompletionHandlerNE) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing3(_ completion: CompletionHandler) {
// expected-note@-1{{parameter 'completion' is implicitly non-escaping}}
// expected-error @+2 {{non-escaping value 'escape' may only be called}}
// expected-error @+1 {{non-escaping parameter 'completion' may only be called}}
escape = completion // expected-error {{declaration closing over non-escaping parameter 'escape' may allow it to escape}}
}
func doThing4(_ completion: @escaping CompletionHandler) {
escapeOther = completion
}
// <rdar://problem/19997680> @noescape doesn't work on parameters of function type
func apply<T, U>(_ f: @noescape (T) -> U, g: @noescape (@noescape (T) -> U) -> U) -> U {
// expected-error@-1{{@noescape is the default and has been removed}} {{23-33=}}
// expected-error@-2{{@noescape is the default and has been removed}} {{46-56=}}
// expected-error@-3{{@noescape is the default and has been removed}} {{57-66=}}
return g(f)
// expected-error@-1{{passing a non-escaping function parameter 'f' to a call to a non-escaping function parameter}}
}
// <rdar://problem/19997577> @noescape cannot be applied to locals, leading to duplication of code
enum r19997577Type {
case Unit
case Function(() -> r19997577Type, () -> r19997577Type)
case Sum(() -> r19997577Type, () -> r19997577Type)
func reduce<Result>(_ initial: Result, _ combine: @noescape (Result, r19997577Type) -> Result) -> Result { // expected-error{{@noescape is the default and has been removed}} {{53-63=}}
let binary: @noescape (r19997577Type, r19997577Type) -> Result = { combine(combine(combine(initial, self), $0), $1) } // expected-error{{@noescape is the default and has been removed}} {{17-27=}}
switch self {
case .Unit:
return combine(initial, self)
case let .Function(t1, t2):
return binary(t1(), t2())
case let .Sum(t1, t2):
return binary(t1(), t2())
}
}
}
// type attribute and decl attribute
func noescapeD(@noescape f: @escaping () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
func noescapeT(f: @noescape () -> Bool) {} // expected-error{{@noescape is the default and has been removed}} {{19-29=}}
func noescapeG<T>(@noescape f: () -> T) {} // expected-error{{attribute can only be applied to types, not declarations}}
func autoclosureD(@autoclosure f: () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
func autoclosureT(f: @autoclosure () -> Bool) {} // ok
func autoclosureG<T>(@autoclosure f: () -> T) {} // expected-error{{attribute can only be applied to types, not declarations}}
func noescapeD_noescapeT(@noescape f: @noescape () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
// expected-error@-1{{@noescape is the default and has been removed}} {{39-49=}}
func autoclosureD_noescapeT(@autoclosure f: @noescape () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}}
// expected-error@-1{{@noescape is the default and has been removed}} {{45-55=}}
| apache-2.0 | f288f01192c3eccba8c54af104d70aeb | 53.415761 | 199 | 0.659176 | 3.982697 | false | false | false | false |
berishaerblin/Attendance | Attendance/Professor.swift | 1 | 1479 | //
// Professor.swift
// Attendance
//
// Created by Erblin Berisha on 8/9/17.
// Copyright © 2017 Erblin Berisha. All rights reserved.
//
import UIKit
import CoreData
class Professor: NSManagedObject {
class func insertIntoProfessor(theProfessor: CreateProfessor, in context: NSManagedObjectContext) {
let professor = Professor(context: context)
professor.professorName = theProfessor.professorName
professor.professorSurname = theProfessor.professorSurname
professor.usernameProfessor = theProfessor.professorUsername
professor.passwordPofessor = theProfessor.professorPassword
professor.addToSubjects(Subjects.insertIntoSubjects(theSubject: theProfessor.professorSubject, in: context))
}
class func insertNewSubject(into theProfessor: CreateNewSubjectIntoProfessor, in context: NSManagedObjectContext) -> Professor {
// let professor = Professor(context: context)
let request: NSFetchRequest<Professor> = Professor.fetchRequest()
request.predicate = NSPredicate(format: "usernameProfessor = %@", theProfessor.professorsUsername)
do {
let matches = try context.fetch(request)
if matches.count > 0{
assert (matches.count >= 1, "Professor -- database inconsistency!")
return matches[0]
}
} catch {
print("unable to find")
}
return Professor()
}
}
| gpl-3.0 | 72f9005dea6356c063ad0e542ed33990 | 34.190476 | 132 | 0.677943 | 4.692063 | false | false | false | false |
huonw/swift | stdlib/private/StdlibUnittest/StringConvertible.swift | 2 | 5346 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that has different `CustomStringConvertible` and
/// `CustomDebugStringConvertible` representations.
///
/// This type also conforms to other protocols, to make it
/// usable in constrained contexts. It is not intended to be a
/// minimal type that only conforms to certain protocols.
///
/// This type can be used to check that code uses the correct
/// kind of string representation.
public struct CustomPrintableValue
: Equatable, Comparable, Hashable, Strideable
{
public static var timesDescriptionWasCalled = ResettableValue(0)
public static var timesDebugDescriptionWasCalled = ResettableValue(0)
public static var descriptionImpl =
ResettableValue<(_ value: Int, _ identity: Int) -> String>({
(value: Int, identity: Int) -> String in
if identity == 0 {
return "(value: \(value)).description"
} else {
return "(value: \(value), identity: \(identity)).description"
}
})
public static var debugDescriptionImpl =
ResettableValue<(_ value: Int, _ identity: Int) -> String>({
(value: Int, identity: Int) -> String in
CustomPrintableValue.timesDescriptionWasCalled.value += 1
if identity == 0 {
return "(value: \(value)).debugDescription"
} else {
return "(value: \(value), identity: \(identity)).debugDescription"
}
})
public var value: Int
public var identity: Int
public init(_ value: Int) {
self.value = value
self.identity = 0
}
public init(_ value: Int, identity: Int) {
self.value = value
self.identity = identity
}
public var hashValue: Int {
return value.hashValue
}
public typealias Stride = Int
public func distance(to other: CustomPrintableValue) -> Stride {
return other.value - self.value
}
public func advanced(by n: Stride) -> CustomPrintableValue {
return CustomPrintableValue(self.value + n, identity: self.identity)
}
}
public func == (
lhs: CustomPrintableValue,
rhs: CustomPrintableValue
) -> Bool {
return lhs.value == rhs.value
}
public func < (
lhs: CustomPrintableValue,
rhs: CustomPrintableValue
) -> Bool {
return lhs.value < rhs.value
}
extension CustomPrintableValue : CustomStringConvertible {
public var description: String {
CustomPrintableValue.timesDescriptionWasCalled.value += 1
return CustomPrintableValue.descriptionImpl.value(
value, identity)
}
}
extension CustomPrintableValue : CustomDebugStringConvertible {
public var debugDescription: String {
CustomPrintableValue.timesDebugDescriptionWasCalled.value += 1
return CustomPrintableValue.debugDescriptionImpl.value(
value, identity)
}
}
public func expectPrinted<T>(
expectedOneOf patterns: [String], _ object: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
let actual = String(describing: object)
if !patterns.contains(actual) {
expectationFailure(
"expected: any of \(String(reflecting: patterns))\n"
+ "actual: \(String(reflecting: actual))",
trace: message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
}
public func expectPrinted<T>(
_ expected: String, _ object: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectPrinted(expectedOneOf: [expected], object, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
public func expectDebugPrinted<T>(
expectedOneOf patterns: [String], _ object: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectPrinted(expectedOneOf: patterns, String(reflecting: object), message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
public func expectDebugPrinted<T>(
_ expected: String, _ object: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
expectDebugPrinted(expectedOneOf: [expected], object, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
public func expectDumped<T>(
_ expected: String, _ object: T,
_ message: @autoclosure () -> String = "",
stackTrace: SourceLocStack = SourceLocStack(),
showFrame: Bool = true,
file: String = #file, line: UInt = #line
) {
var actual = ""
dump(object, to: &actual)
expectEqual(expected, actual, message(),
stackTrace: stackTrace.pushIf(showFrame, file: file, line: line))
}
// Local Variables:
// eval: (read-only-mode 1)
// End:
| apache-2.0 | e324a81027a3a7256324f11bc07f62c1 | 29.724138 | 80 | 0.668724 | 4.293976 | false | false | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Classify/Views/StrategyColumnSubCellViewModel.swift | 1 | 934 | //
// StrategyColumnSubCellViewModel.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/21.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
class StrategyColumnSubCellDataModel: NSObject{
}
class StrategyColumnSubCellViewModel: NSObject {
var dataModel:StrategyColumnSubCellDataModel?
var photoImage:UIImage?
var titleLabelText:String?
var detialLabelText:String?
var nameLabelText:String?
init(withModel model:StrategyColumnSubCellDataModel) {
self.dataModel = model
photoImage = UIImage(named: "strategy_\(Int(arc4random() % 17) + 1).jpg")
titleLabelText = "美体日记"
detialLabelText = "更新至第1期"
let name = ["小小礼物","大大的店","好好礼物","萌萌哒,我啊❤️","我最开心","妹妹的袜子","小坏坏","不打烊的店"]
nameLabelText = name[Int(arc4random() % 8)]
}
}
| mit | 44f421f40d75368aa2958b9e6bd6413d | 25.483871 | 81 | 0.666261 | 3.35102 | false | false | false | false |
testpress/ios-app | ios-app/UI/QuizReviewViewController.swift | 1 | 5853 | //
// QuizReviewViewController.swift
// ios-app
//
// Created by Karthik on 19/05/20.
// Copyright © 2020 Testpress. All rights reserved.
//
import UIKit
import WebKit
class QuizReviewViewController: BaseWebViewController, WKWebViewDelegate, WKScriptMessageHandler {
var attemptItem: AttemptItem!
override func viewDidLoad() {
super.viewDidLoad()
webViewDelegate = self
webView.loadHTMLString(
WebViewUtils.getQuestionHeader() + WebViewUtils.getTestEngineHeader() + getHtml(),
baseURL: Bundle.main.bundleURL
)
}
override func initWebView() {
let contentController = WKUserContentController()
contentController.add(self, name: "callbackHandler")
let config = WKWebViewConfiguration()
config.userContentController = contentController
config.preferences.javaScriptEnabled = true
webView = WKWebView( frame: self.view.bounds, configuration: config)
}
func getHtml() -> String {
let question = attemptItem.question!;
var html: String = "<div style='padding-left: 5px; padding-right: 5px;'>"
html += "<div style='overflow:scroll'>"
html += "<div class='review-question-index'>\(attemptItem.index)</div>"
html += getDirectionHTML(question: question)
html += getQuestionHTML(question: question)
html += getAnswerHTML()
html += getExplanationHTML(question: question)
html += getSubjectHTML(question: question)
html += "</div>"
html = html.replacingOccurrences(of: "Â", with: "")
return html
}
func getDirectionHTML(question: AttemptQuestion) -> String {
var htmlContent = ""
if !question.direction.isNilOrEmpty {
htmlContent += "<div class='question' style='padding-bottom: 0px;'>" +
question.direction! +
"</div>";
}
return htmlContent
}
func getQuestionHTML(question: AttemptQuestion) -> String {
return "<div class='question'>" + question.questionHtml! + "</div>";
}
func getExplanationHTML(question: AttemptQuestion) -> String {
var htmlContent = ""
let explanationHtml = question.explanationHtml
if !explanationHtml.isNilOrEmpty {
htmlContent += WebViewUtils.getReviewHeadingTags(headingText: Strings.EXPLANATION)
htmlContent += "<div class='review-explanation'>" +
explanationHtml! +
"</div>";
}
return htmlContent
}
func getSubjectHTML(question: AttemptQuestion) -> String {
var htmlContent = ""
if !question.subject.isEmpty &&
!question.subject.elementsEqual("Uncategorized") {
htmlContent += WebViewUtils.getReviewHeadingTags(headingText:Strings.SUBJECT_HEADING)
htmlContent += "<div class='subject'>" +
question.subject +
"</div>";
}
return htmlContent
}
func getAnswerHTML() -> String {
var html = ""
let question = attemptItem.question!;
var correctAnswerHtml: String = ""
for (i, attemptAnswer) in question.answers.enumerated() {
if question.isSingleMcq || question.isMultipleMcq {
var optionColor: String?
if attemptItem.selectedAnswers.contains(attemptAnswer.id) {
if attemptAnswer.isCorrect {
optionColor = Colors.MATERIAL_GREEN
} else {
optionColor = Colors.MATERIAL_RED
}
}
if attemptAnswer.isCorrect {
optionColor = Colors.MATERIAL_GREEN
}
html += "\n" + WebViewUtils.getOptionWithTags(
optionText: attemptAnswer.textHtml,
index: i,
color: optionColor,
isCorrect: attemptAnswer.isCorrect
)
if attemptAnswer.isCorrect {
correctAnswerHtml += WebViewUtils.getCorrectAnswerIndexWithTags(index: i)
}
} else if question.isNumerical {
correctAnswerHtml = attemptAnswer.textHtml
} else {
if i == 0 {
html += "<table width='100%' style='margin-top:0px; margin-bottom:15px;'>"
+ WebViewUtils.getShortAnswerHeadersWithTags()
}
html += WebViewUtils.getShortAnswersWithTags(
shortAnswerText: attemptAnswer.textHtml,
marksAllocated: attemptAnswer.marks!
)
if i == question.answers.count - 1 {
html += "</table>"
}
}
}
if question.questionType == .SINGLE_CORRECT_MCQ || question.questionType == .MULTIPLE_CORRECT_MCQ || question.questionType == .NUMERICAL {
html += "<div style='display:block;'>" +
WebViewUtils.getReviewHeadingTags(headingText: Strings.CORRECT_ANSWER) +
correctAnswerHtml +
"</div>"
}
return html
}
override func getJavascript() -> String {
let instituteSettings = DBManager<InstituteSettings>().getResultsFromDB()[0]
var javascript = super.getJavascript()
javascript += WebViewUtils.addWaterMark(imageUrl: instituteSettings.appToolbarLogo)
return javascript
}
func onFinishLoadingWebView() {
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
}
| mit | 8b4192cc3f4b22198f97931a66b49cf1 | 35.798742 | 146 | 0.569817 | 5.187057 | false | false | false | false |
dymx101/Gamers | Gamers/Views/ChannelVideoController.swift | 1 | 10910 | //
// ChannelVideoController.swift
// Gamers
//
// Created by 虚空之翼 on 15/8/31.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import UIKit
import Bolts
import MJRefresh
import MBProgressHUD
import Social
import RealmSwift
class ChannelVideoController: UITableViewController {
var userData: User!
var videoListData = [Video]()
var videoPageOffset = 1 //分页偏移量,默认为上次最后一个视频ID
var videoPageCount = 20 //每页视频总数
var isNoMoreData: Bool = false //解决控件不能自己判断BUG
override func viewDidLoad() {
super.viewDidLoad()
// 刷新功能
self.tableView.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewData")
self.tableView.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadMoreData")
// 子页面PlayerView的导航栏返回按钮文字,可为空(去掉按钮文字)
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
// 删除多余的分割线
self.tableView.tableFooterView = UIView(frame: CGRectZero)
// cell分割线边距,ios8处理
if self.tableView.respondsToSelector("setSeparatorInset:") {
self.tableView.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if self.tableView.respondsToSelector("setLayoutMargins:") {
self.tableView.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 加载初始化数据
loadInitData()
self.navigationItem.title = self.userData.userName
}
// 初始化数据
func loadInitData() {
let hub = MBProgressHUD.showHUDAddedTo(self.navigationController!.view, animated: true)
hub.labelText = NSLocalizedString("Loading...", comment: "加载中...")
videoPageOffset = 1
ChannelBL.sharedSingleton.getChannelVideo(channelId: userData.userId, offset: videoPageOffset, count: videoPageCount, channels: nil).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
self!.videoListData = (task.result as? [Video])!
self!.videoPageOffset += 1
self?.tableView.reloadData()
if self!.videoListData.count < self!.videoPageCount {
self?.tableView.footer.noticeNoMoreData()
}
return nil
}).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
if task.error != nil { println(task.error) }
MBProgressHUD.hideHUDForView(self!.navigationController!.view, animated: true)
return nil
})
}
/**
刷新数据
*/
func loadNewData() {
videoPageOffset = 1
ChannelBL.sharedSingleton.getChannelVideo(channelId: userData.userId, offset: videoPageOffset, count: videoPageCount, channels: nil).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
self!.videoListData = (task.result as? [Video])!
self!.videoPageOffset += 1
self?.tableView.reloadData()
if self!.videoListData.count < self!.videoPageCount {
self?.tableView.footer.noticeNoMoreData()
} else {
self?.tableView.footer.resetNoMoreData()
}
return nil
}).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
if task.error != nil { println(task.error) }
self?.tableView.header.endRefreshing()
self!.isNoMoreData = false
return nil
})
}
/**
加载更多数据
*/
func loadMoreData() {
ChannelBL.sharedSingleton.getChannelVideo(channelId: userData.userId, offset: videoPageOffset, count: videoPageCount, channels: nil).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
var newData = (task.result as? [Video])!
// 如果没有数据显示加载完成,否则继续
if newData.isEmpty {
self?.tableView.footer.noticeNoMoreData()
self!.isNoMoreData = true
} else{
if newData.count < self!.videoPageCount {
self!.isNoMoreData = true
}
self!.videoListData += newData
self!.videoPageOffset += 1
self?.tableView.reloadData()
}
return nil
}).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
if task.error != nil { println(task.error) }
if !self!.isNoMoreData {
self?.tableView.footer.endRefreshing()
}
return nil
})
}
override func viewWillAppear(animated: Bool) {
// 播放页面返回后,重置导航条的透明属性,//todo:image_1.jpg需求更换下
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "navigation-bar1.png"),forBarMetrics: UIBarMetrics.CompactPrompt)
self.navigationController?.navigationBar.shadowImage = UIImage(named: "navigation-bar1.png")
self.navigationController?.navigationBar.translucent = false
}
// 跳转传值
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// 定义列表控制器
var playerViewController = segue.destinationViewController as! PlayerViewController
// 提取选中的游戏视频,把值传给列表页面
var indexPath = self.tableView.indexPathForSelectedRow()!
playerViewController.videoData = videoListData[indexPath.row]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 表格数据源代理协议
extension ChannelVideoController: UITableViewDataSource, UITableViewDelegate {
// 一个分区
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
// 设置表格行数
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return videoListData.count
}
// 设置行高
// override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// return 100
// }
// 设置表格行内容
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ChannelVideoCell", forIndexPath: indexPath) as! VideoListCell
cell.setVideo(self.videoListData[indexPath.row])
cell.delegate = self
return cell
}
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 30))
return footerView
}
// cell分割线的边距
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector("setSeparatorInset:") {
cell.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if cell.respondsToSelector("setLayoutMargins:") {
cell.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
}
}
// MARK: - 表格行Cell代理
extension ChannelVideoController: MyCellDelegate {
// 分享按钮
func clickCellButton(sender: UITableViewCell) {
var index: NSIndexPath = self.tableView.indexPathForCell(sender)!
var video = self.videoListData[index.row]
// 退出
var actionSheetController: UIAlertController = UIAlertController()
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "取消"), style: UIAlertActionStyle.Cancel) { (alertAction) -> Void in
//code
})
// 分享到Facebook
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Share on Facebook", comment: "分享到Facebook"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in
var slComposerSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
slComposerSheet.setInitialText(video.videoTitle)
slComposerSheet.addImage(UIImage(named: video.imageSource))
slComposerSheet.addURL(NSURL(string: "https://www.youtube.com/watch?v=\(video.videoId)"))
self.presentViewController(slComposerSheet, animated: true, completion: nil)
SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)
slComposerSheet.completionHandler = { (result: SLComposeViewControllerResult) in
if result == .Done {
var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Share Finish", comment: "分享完成"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定"))
alertView.show()
}
}
})
// 分享到Twitter
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Share on Twitter", comment: "分享到Twitter"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in
var slComposerSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
slComposerSheet.setInitialText(video.videoTitle)
slComposerSheet.addImage(UIImage(named: video.imageSource))
slComposerSheet.addURL(NSURL(string: "https://www.youtube.com/watch?v=\(video.videoId)"))
self.presentViewController(slComposerSheet, animated: true, completion: nil)
slComposerSheet.completionHandler = { (result: SLComposeViewControllerResult) in
if result == .Done {
var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Share Finish", comment: "分享完成"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定"))
alertView.show()
}
}
})
// 显示Sheet
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
}
| apache-2.0 | ac9f5e0bafd62d2f760904644cb4ed88 | 40.616 | 209 | 0.633699 | 5.11002 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Wallet/Currency.swift | 1 | 18294 | //
// Currency.swift
// breadwallet
//
// Created by Ehsan Rezaie on 2018-01-10.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
import Foundation
import WalletKit
import UIKit
import CoinGecko
protocol CurrencyWithIcon {
var code: String { get }
var colors: (UIColor, UIColor) { get }
}
typealias CurrencyUnit = WalletKit.Unit
typealias CurrencyId = Identifier<Currency>
/// Combination of the Core Currency model and its metadata properties
class Currency: CurrencyWithIcon {
public enum TokenType: String {
case native
case erc20
case unknown
}
private let core: WalletKit.Currency
let network: WalletKit.Network
/// Unique identifier from BlockchainDB
var uid: CurrencyId { assert(core.uid == metaData.uid); return metaData.uid }
/// Ticker code (e.g. BTC)
var code: String { return core.code.uppercased() }
/// Display name (e.g. Bitcoin)
var name: String { return metaData.name }
var cryptoCompareCode: String {
return metaData.alternateCode?.uppercased() ?? core.code.uppercased()
}
var coinGeckoId: String? {
return metaData.coinGeckoId
}
// Number of confirmations needed until a transaction is considered complete
// eg. For bitcoin, a txn is considered complete when it has 6 confirmations
var confirmationsUntilFinal: Int {
return Int(network.confirmationsUntilFinal)
}
var tokenType: TokenType {
guard let type = TokenType(rawValue: core.type.lowercased()) else { assertionFailure("unknown token type"); return .unknown }
return type
}
// MARK: Units
/// The smallest divisible unit (e.g. satoshi)
let baseUnit: CurrencyUnit
/// The default unit used for fiat exchange rate and amount display (e.g. bitcoin)
let defaultUnit: CurrencyUnit
/// All available units for this currency by name
private let units: [String: CurrencyUnit]
var defaultUnitName: String {
return name(forUnit: defaultUnit)
}
/// Returns the unit associated with the number of decimals if available
func unit(forDecimals decimals: Int) -> CurrencyUnit? {
return units.values.first { $0.decimals == decimals }
}
func unit(named name: String) -> CurrencyUnit? {
return units[name.lowercased()]
}
func name(forUnit unit: CurrencyUnit) -> String {
if unit.decimals == defaultUnit.decimals {
return code.uppercased()
} else {
return unit.name
}
}
func unitName(forDecimals decimals: UInt8) -> String {
return unitName(forDecimals: Int(decimals))
}
func unitName(forDecimals decimals: Int) -> String {
guard let unit = unit(forDecimals: decimals) else { return "" }
return name(forUnit: unit)
}
// MARK: Metadata
let metaData: CurrencyMetaData
/// Primary + secondary color
var colors: (UIColor, UIColor) { return metaData.colors }
/// False if a token has been delisted, true otherwise
var isSupported: Bool { return metaData.isSupported }
var tokenAddress: String? { return metaData.tokenAddress }
// MARK: URI
var urlSchemes: [String]? {
if isBitcoin {
return ["bitcoin"]
}
if isBitcoinCash {
return E.isTestnet ? ["bchtest"] : ["bitcoincash"]
}
if isEthereumCompatible {
return ["ethereum"]
}
if isXRP {
return ["xrpl", "xrp", "ripple"]
}
if isHBAR {
return ["hbar"]
}
return nil
}
func doesMatchPayId(_ details: PayIdAddress) -> Bool {
let environment = (E.isTestnet || E.isRunningTests) ? "testnet" : "mainnet"
guard details.environment.lowercased() == environment else { return false }
guard let id = payId else { return false }
return details.paymentNetwork.lowercased() == id.lowercased()
}
var payId: String? {
if isBitcoin { return "btc" }
if isEthereum { return "eth" }
if isXRP { return "xrpl" }
return nil
}
var attributeDefinition: AttributeDefinition? {
if isXRP {
return AttributeDefinition(key: "DestinationTag",
label: S.Send.destinationTagLabel,
keyboardType: .numberPad,
maxLength: 10)
}
if isHBAR {
return AttributeDefinition(key: "Memo",
label: S.Send.memoTagLabelOptional,
keyboardType: .default,
maxLength: 100)
}
return nil
}
/// Can be used if an example address is required eg. to estimate the max send limit
var placeHolderAddress: String? {
if isBitcoin {
return E.isTestnet ? "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx" : "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq"
}
if isBitcoinCash {
return E.isTestnet ? "bchtest:qqpz7r5k72e07j0syq26f0h8srvdqeqjg50wg9fp3z" : "bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"
}
if isEthereumCompatible {
return "0xA6A60123Feb7F61081b1BFe063464b3219cEdCEc"
}
if isXRP {
return "r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV"
}
if isHBAR {
return "0.0.39768"
}
return nil
}
/// Returns a transfer URI with the given address
func addressURI(_ address: String) -> String? {
//Tezos doesn't have a URI scheme
if isTezos, isValidAddress(address) { return address }
guard let scheme = urlSchemes?.first, isValidAddress(address) else { return nil }
if isERC20Token, let tokenAddress = tokenAddress {
//This is a non-standard uri format to maintain backwards compatibility with old versions of BRD
return "\(scheme):\(address)?tokenaddress=\(tokenAddress)"
} else {
return "\(scheme):\(address)"
}
}
func shouldAcceptQRCodeFrom(_ currency: Currency, request: PaymentRequest) -> Bool {
if self == currency {
return true
}
//Allows sending erc20 tokens to an Eth receive uri, but not the other way around
if self == Currencies.eth.instance
&& currency.isERC20Token
&& request.amount == nil //We shouldn't send tokens to an Eth request amount uri
{
return true
}
return false
}
var isGiftingEnabled: Bool {
if #available(iOS 13.0, *), isBitcoin {
return true
} else {
return false
}
}
var supportsStaking: Bool {
return isTezos
}
// MARK: Init
init?(core: WalletKit.Currency,
network: WalletKit.Network,
metaData: CurrencyMetaData,
units: Set<WalletKit.Unit>,
baseUnit: WalletKit.Unit,
defaultUnit: WalletKit.Unit) {
guard core.uid == metaData.uid else { return nil }
self.core = core
self.network = network
self.metaData = metaData
self.units = Array(units).reduce([String: CurrencyUnit]()) { (dict, unit) -> [String: CurrencyUnit] in
var dict = dict
dict[unit.name.lowercased()] = unit
return dict
}
self.baseUnit = baseUnit
self.defaultUnit = defaultUnit
}
}
extension Currency: Hashable {
static func == (lhs: Currency, rhs: Currency) -> Bool {
return lhs.core == rhs.core && lhs.metaData == rhs.metaData
}
func hash(into hasher: inout Hasher) {
hasher.combine(core)
hasher.combine(metaData)
}
}
// MARK: - Convenience Accessors
extension Currency {
func isValidAddress(_ address: String) -> Bool {
return Address.create(string: address, network: network) != nil
}
/// Ticker code for support pages
var supportCode: String {
if tokenType == .erc20 {
return "erc20"
} else {
return code.lowercased()
}
}
var isBitcoin: Bool { return uid == Currencies.btc.uid }
var isBitcoinCash: Bool { return uid == Currencies.bch.uid }
var isEthereum: Bool { return uid == Currencies.eth.uid }
var isERC20Token: Bool { return tokenType == .erc20 }
var isBRDToken: Bool { return uid == Currencies.brd.uid }
var isXRP: Bool { return uid == Currencies.xrp.uid }
var isHBAR: Bool { return uid == Currencies.hbar.uid }
var isBitcoinCompatible: Bool { return isBitcoin || isBitcoinCash }
var isEthereumCompatible: Bool { return isEthereum || isERC20Token }
var isTezos: Bool { return uid == Currencies.xtz.uid }
}
// MARK: - Confirmation times
extension Currency {
func feeText(forIndex index: Int) -> String {
if isEthereumCompatible {
return ethFeeText(forIndex: index)
} else if isBitcoinCompatible {
return btcFeeText(forIndex: index)
} else {
return String(format: S.Confirmation.processingTime, S.FeeSelector.ethTime)
}
}
private func ethFeeText(forIndex index: Int) -> String {
switch index {
case 0:
return String(format: S.FeeSelector.estimatedDelivery, timeString(forMinutes: 6))
case 1:
return String(format: S.FeeSelector.estimatedDelivery, timeString(forMinutes: 4))
case 2:
return String(format: S.FeeSelector.estimatedDelivery, timeString(forMinutes: 2))
default:
return ""
}
}
private func timeString(forMinutes minutes: Int) -> String {
let duration: TimeInterval = Double(minutes * 60)
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief
formatter.allowedUnits = [.minute]
formatter.zeroFormattingBehavior = [.dropLeading]
return formatter.string(from: duration) ?? ""
}
private func btcFeeText(forIndex index: Int) -> String {
switch index {
case 0:
return String(format: S.FeeSelector.estimatedDelivery, S.FeeSelector.economyTime)
case 1:
return String(format: S.FeeSelector.estimatedDelivery, S.FeeSelector.regularTime)
case 2:
return String(format: S.FeeSelector.estimatedDelivery, S.FeeSelector.priorityTime)
default:
return ""
}
}
}
// MARK: - Images
extension CurrencyWithIcon {
/// Icon image with square color background
public var imageSquareBackground: UIImage? {
if let baseURL = AssetArchive(name: imageBundleName, apiClient: Backend.apiClient)?.extractedUrl {
let path = baseURL.appendingPathComponent("white-square-bg").appendingPathComponent(code.lowercased()).appendingPathExtension("png")
if let data = try? Data(contentsOf: path) {
return UIImage(data: data)
}
}
return TokenImageSquareBackground(code: code, color: colors.0).renderedImage
}
/// Icon image with no background using template rendering mode
public var imageNoBackground: UIImage? {
if let baseURL = AssetArchive(name: imageBundleName, apiClient: Backend.apiClient)?.extractedUrl {
let path = baseURL.appendingPathComponent("white-no-bg").appendingPathComponent(code.lowercased()).appendingPathExtension("png")
if let data = try? Data(contentsOf: path) {
return UIImage(data: data)?.withRenderingMode(.alwaysTemplate)
}
}
return TokenImageNoBackground(code: code, color: colors.0).renderedImage
}
private var imageBundleName: String {
return (E.isDebug || E.isTestFlight) ? "brd-tokens-staging" : "brd-tokens"
}
}
// MARK: - Metadata Model
/// Model representing metadata for supported currencies
public struct CurrencyMetaData: CurrencyWithIcon {
let uid: CurrencyId
let code: String
let isSupported: Bool
let colors: (UIColor, UIColor)
let name: String
var tokenAddress: String?
var decimals: UInt8
var isPreferred: Bool {
return Currencies.allCases.map { $0.uid }.contains(uid)
}
/// token type string in format expected by System.asBlockChainDBModelCurrency
var type: String {
return uid.rawValue.contains("__native__") ? "NATIVE" : "ERC20"
}
var alternateCode: String?
var coinGeckoId: String?
enum CodingKeys: String, CodingKey {
case uid = "currency_id"
case code
case isSupported = "is_supported"
case colors
case tokenAddress = "contract_address"
case name
case decimals = "scale"
case alternateNames = "alternate_names"
}
}
extension CurrencyMetaData: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
//TODO:CRYPTO temp hack until testnet support to added /currencies endpoint (BAK-318)
var uid = try container.decode(String.self, forKey: .uid)
if E.isTestnet {
uid = uid.replacingOccurrences(of: "mainnet", with: "testnet")
uid = uid.replacingOccurrences(of: "0x558ec3152e2eb2174905cd19aea4e34a23de9ad6", with: "0x7108ca7c4718efa810457f228305c9c71390931a") // BRD token
uid = uid.replacingOccurrences(of: "ethereum-testnet", with: "ethereum-ropsten")
}
self.uid = CurrencyId(rawValue: uid) //try container.decode(CurrencyId.self, forKey: .uid)
code = try container.decode(String.self, forKey: .code)
let colorValues = try container.decode([String].self, forKey: .colors)
if colorValues.count == 2 {
colors = (UIColor.fromHex(colorValues[0]), UIColor.fromHex(colorValues[1]))
} else {
if E.isDebug {
throw DecodingError.dataCorruptedError(forKey: .colors, in: container, debugDescription: "Invalid/missing color values")
}
colors = (UIColor.black, UIColor.black)
}
isSupported = try container.decode(Bool.self, forKey: .isSupported)
name = try container.decode(String.self, forKey: .name)
tokenAddress = try container.decode(String.self, forKey: .tokenAddress)
decimals = try container.decode(UInt8.self, forKey: .decimals)
var didFindCoinGeckoID = false
if let alternateNames = try? container.decode([String: String].self, forKey: .alternateNames) {
if let code = alternateNames["cryptocompare"] {
alternateCode = code
}
if let id = alternateNames["coingecko"] {
didFindCoinGeckoID = true
coinGeckoId = id
}
}
// If the /currencies endpoint hasn't provided a coingeckoID,
// use the local list. Eventually /currencies should provide
// all of them
if !didFindCoinGeckoID {
if let id = CoinGeckoCodes.map[code.uppercased()] {
coinGeckoId = id
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(uid, forKey: .uid)
try container.encode(code, forKey: .code)
var colorValues = [String]()
colorValues.append(colors.0.toHex)
colorValues.append(colors.1.toHex)
try container.encode(colorValues, forKey: .colors)
try container.encode(isSupported, forKey: .isSupported)
try container.encode(name, forKey: .name)
try container.encode(tokenAddress, forKey: .tokenAddress)
try container.encode(decimals, forKey: .decimals)
var alternateNames = [String: String]()
if let alternateCode = alternateCode {
alternateNames["cryptocompare"] = alternateCode
}
if let coingeckoId = coinGeckoId {
alternateNames["coingecko"] = coingeckoId
}
if !alternateNames.isEmpty {
try container.encode(alternateNames, forKey: .alternateNames)
}
}
}
extension CurrencyMetaData: Hashable {
public static func == (lhs: CurrencyMetaData, rhs: CurrencyMetaData) -> Bool {
return lhs.uid == rhs.uid
}
public func hash(into hasher: inout Hasher) {
hasher.combine(uid)
}
}
/// Natively supported currencies. Enum maps to ticker code.
enum Currencies: String, CaseIterable {
case btc
case bch
case eth
case brd
case tusd
case xrp
case hbar
case xtz
case usdc
var code: String { return rawValue }
var uid: CurrencyId {
var uids = ""
switch self {
case .btc:
uids = "bitcoin-\(E.isTestnet ? "testnet" : "mainnet"):__native__"
case .bch:
uids = "bitcoincash-\(E.isTestnet ? "testnet" : "mainnet"):__native__"
case .eth:
uids = "ethereum-\(E.isTestnet ? "ropsten" : "mainnet"):__native__"
case .brd:
uids = "ethereum-mainnet:0x558ec3152e2eb2174905cd19aea4e34a23de9ad6"
case .tusd:
uids = "ethereum-mainnet:0x0000000000085d4780B73119b644AE5ecd22b376"
case .xrp:
uids = "ripple-\(E.isTestnet ? "testnet" : "mainnet"):__native__"
case .hbar:
uids = "hedera-mainnet:__native__"
case .xtz:
uids = "tezos-mainnet:__native__"
case .usdc:
uids = "ethereum-mainnet:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
}
return CurrencyId(rawValue: uids)
}
var state: WalletState? { return Store.state.wallets[uid] }
var wallet: Wallet? { return state?.wallet }
var instance: Currency? { return state?.currency }
}
extension WalletKit.Currency {
var uid: CurrencyId { return CurrencyId(rawValue: uids) }
}
struct AttributeDefinition {
let key: String
let label: String
let keyboardType: UIKeyboardType
let maxLength: Int
}
| mit | 8013d7d51f9974c2a0c357ceecefabb7 | 33.001859 | 157 | 0.614388 | 4.264103 | false | false | false | false |
Eonil/Monolith.Swift | UIKitExtras/Sources/StaticTable/StaticTableViewCells.swift | 3 | 1235 | //
// StaticTableViewCells.swift
// CratesIOViewer
//
// Created by Hoon H. on 11/23/14.
//
//
import Foundation
import UIKit
public class StaticTableRowWithFunctions: StaticTableRow {
public var willSelectFunction = {$0} as (StaticTableRow?)->(StaticTableRow?)
public var willDeselectFunction = {$0} as (StaticTableRow?)->(StaticTableRow?)
public var didSelectFunction = {} as ()->()
public var didDeselectFunction = {} as ()->()
public override func willSelect() -> StaticTableRow? {
return willSelectFunction(super.willSelect())
}
public override func didSelect() {
didSelectFunction()
super.didSelect()
}
public override func willDeselect() -> StaticTableRow? {
return willDeselectFunction(super.willDeselect())
}
public override func didDeselect() {
didDeselectFunction()
super.didDeselect()
}
}
public extension StaticTableSection {
public func appendRowWithFunctions(label:String) -> StaticTableRowWithFunctions {
let c1 = UITableViewCell()
c1.textLabel!.text = label
return appendRowWithFunctions(c1)
}
public func appendRowWithFunctions(cell:UITableViewCell) -> StaticTableRowWithFunctions {
let r1 = StaticTableRowWithFunctions(cell: cell)
appendRow(r1)
return r1
}
}
| mit | 61cccd86fe16916960f03da12c2d33e3 | 24.204082 | 90 | 0.7417 | 3.569364 | false | false | false | false |
orta/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchViewModel.swift | 1 | 1570 | //
// SearchViewModel.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class SearchViewModel: Disposable {
typealias Dependencies = (
API: WikipediaAPI,
imageService: ImageService,
backgroundWorkScheduler: ImmediateScheduler,
mainScheduler: DispatchQueueScheduler,
wireframe: Wireframe
)
// outputs
let rows: Observable<[SearchResultViewModel]>
var $: Dependencies
let disposeBag = DisposeBag()
// public methods
init($: Dependencies,
searchText: Observable<String>,
selectedResult: Observable<SearchResultViewModel>) {
self.$ = $
let wireframe = $.wireframe
let API = $.API
self.rows = searchText >- throttle(300, $.mainScheduler) >- distinctUntilChanged >- map { query in
$.API.getSearchResults(query)
>- startWith([]) // clears results on new search term
>- catch([])
} >- switchLatest >- map { results in
results.map {
SearchResultViewModel(
$: $,
searchResult: $0
)
}
}
selectedResult >- subscribeNext { searchResult in
$.wireframe.openURL(searchResult.searchResult.URL)
} >- disposeBag.addDisposable
}
func dispose() {
disposeBag.dispose()
}
} | mit | c7e11277e75d30517e6d9593e6d953b3 | 24.754098 | 106 | 0.564331 | 5.508772 | false | false | false | false |
jjatie/Charts | Source/Charts/Renderers/XAxisRendererRadarChart.swift | 1 | 2584 | //
// XAxisRendererRadarChart.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 CoreGraphics
import Foundation
open class XAxisRendererRadarChart: XAxisRenderer {
open weak var chart: RadarChartView?
public init(viewPortHandler: ViewPortHandler, axis: XAxis, chart: RadarChartView) {
super.init(viewPortHandler: viewPortHandler, axis: axis, transformer: nil)
self.chart = chart
}
override open func renderAxisLabels(context: CGContext) {
guard
let chart = chart,
axis.isEnabled,
axis.isDrawLabelsEnabled
else { return }
let labelFont = axis.labelFont
let labelTextColor = axis.labelTextColor
let labelRotationAngleRadians = axis.labelRotationAngle.RAD2DEG
let drawLabelAnchor = CGPoint(x: 0.5, y: 0.25)
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
for i in 0 ..< (chart.data?.maxEntryCountSet?.count ?? 0) {
let label = axis.valueFormatter?.stringForValue(Double(i), axis: axis) ?? ""
let angle = (sliceangle * CGFloat(i) + chart.rotationAngle).truncatingRemainder(dividingBy: 360.0)
let p = center.moving(distance: CGFloat(chart.yRange) * factor + axis.labelRotatedWidth / 2.0, atAngle: angle)
drawLabel(context: context,
formattedLabel: label,
x: p.x,
y: p.y - axis.labelRotatedHeight / 2.0,
attributes: [.font: labelFont, .foregroundColor: labelTextColor],
anchor: drawLabelAnchor,
angleRadians: labelRotationAngleRadians)
}
}
open func drawLabel(
context: CGContext,
formattedLabel: String,
x: CGFloat,
y: CGFloat,
attributes: [NSAttributedString.Key: Any],
anchor: CGPoint,
angleRadians: CGFloat
) {
context.drawText(formattedLabel,
at: CGPoint(x: x, y: y),
anchor: anchor,
angleRadians: angleRadians,
attributes: attributes)
}
override open func renderLimitLines(context _: CGContext) {
/// XAxis LimitLines on RadarChart not yet supported.
}
}
| apache-2.0 | bb256d1dbe7c88919638cb0c264166d0 | 32.558442 | 122 | 0.607198 | 5.116832 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/AddNewBankAccount/AddNewBankAccountInteractor.swift | 1 | 2291 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import MoneyKit
import PlatformKit
import RIBs
import RxCocoa
import RxSwift
import ToolKit
typealias AddNewBankAccountDetailsInteractionState = ValueCalculationState<PaymentAccountDescribing>
enum AddNewBankAccountAction {
case details(AddNewBankAccountDetailsInteractionState)
}
public enum AddNewBankAccountEffects {
case termsTapped(TitledLink)
case close
}
public protocol AddNewBankAccountRouting: AnyObject {
func showTermsScreen(link: TitledLink)
}
public protocol AddNewBankAccountListener: AnyObject {
func dismissAddNewBankAccount()
}
protocol AddNewBankAccountPresentable: Presentable {
func connect(action: Driver<AddNewBankAccountAction>) -> Driver<AddNewBankAccountEffects>
}
final class AddNewBankAccountInteractor: PresentableInteractor<AddNewBankAccountPresentable>,
AddNewBankAccountInteractable
{
weak var router: AddNewBankAccountRouting?
weak var listener: AddNewBankAccountListener?
private let fiatCurrency: FiatCurrency
private let paymentAccountService: PaymentAccountServiceAPI
init(
presenter: AddNewBankAccountPresentable,
fiatCurrency: FiatCurrency,
paymentAccountService: PaymentAccountServiceAPI = resolve()
) {
self.fiatCurrency = fiatCurrency
self.paymentAccountService = paymentAccountService
super.init(presenter: presenter)
}
override func didBecomeActive() {
super.didBecomeActive()
let detailsAction = paymentAccountService
.paymentAccount(for: fiatCurrency)
.asObservable()
.map { AddNewBankAccountDetailsInteractionState.value($0) }
.startWith(.calculating)
.asDriver(onErrorJustReturn: .invalid(.valueCouldNotBeCalculated))
.map(AddNewBankAccountAction.details)
presenter.connect(action: detailsAction)
.drive(onNext: handle(effect:))
.disposeOnDeactivate(interactor: self)
}
func handle(effect: AddNewBankAccountEffects) {
switch effect {
case .close:
listener?.dismissAddNewBankAccount()
case .termsTapped(let link):
router?.showTermsScreen(link: link)
}
}
}
| lgpl-3.0 | 25b1f7324f3607bd5b3bd3c12506d2b3 | 28.358974 | 100 | 0.731878 | 5.337995 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Post/PostCompactCell.swift | 1 | 6518 | import AutomatticTracks
import UIKit
import Gridicons
class PostCompactCell: UITableViewCell, ConfigurablePostView {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var badgesLabel: UILabel!
@IBOutlet weak var menuButton: UIButton!
@IBOutlet weak var featuredImageView: CachedAnimatedImageView!
@IBOutlet weak var headerStackView: UIStackView!
@IBOutlet weak var innerView: UIView!
@IBOutlet weak var contentStackView: UIStackView!
@IBOutlet weak var ghostView: UIView!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var separator: UIView!
private weak var actionSheetDelegate: PostActionSheetDelegate?
lazy var imageLoader: ImageLoader = {
return ImageLoader(imageView: featuredImageView, gifStrategy: .mediumGIFs)
}()
private var post: Post? {
didSet {
guard let post = post, post != oldValue else {
return
}
viewModel = PostCardStatusViewModel(post: post)
}
}
private var viewModel: PostCardStatusViewModel?
func configure(with post: Post) {
self.post = post
resetGhostStyles()
configureTitle()
configureDate()
configureStatus()
configureFeaturedImage()
configureProgressView()
}
@IBAction func more(_ sender: Any) {
guard let viewModel = viewModel, let button = sender as? UIButton else {
return
}
actionSheetDelegate?.showActionSheet(viewModel, from: button)
}
override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
setupReadableGuideForiPad()
setupSeparator()
setupAccessibility()
}
private func resetGhostStyles() {
toggleGhost(visible: false)
menuButton.layer.opacity = Constants.opacity
}
private func applyStyles() {
WPStyleGuide.configureTableViewCell(self)
WPStyleGuide.applyPostCardStyle(self)
WPStyleGuide.applyPostProgressViewStyle(progressView)
WPStyleGuide.configureLabel(timestampLabel, textStyle: .subheadline)
WPStyleGuide.configureLabel(badgesLabel, textStyle: .subheadline)
titleLabel.font = WPStyleGuide.notoBoldFontForTextStyle(.headline)
titleLabel.adjustsFontForContentSizeCategory = true
titleLabel.textColor = .text
timestampLabel.textColor = .textSubtle
menuButton.tintColor = .textSubtle
menuButton.setImage(.gridicon(.ellipsis), for: .normal)
featuredImageView.layer.cornerRadius = Constants.imageRadius
innerView.backgroundColor = .listForeground
backgroundColor = .listForeground
contentView.backgroundColor = .listForeground
}
private func setupSeparator() {
WPStyleGuide.applyBorderStyle(separator)
}
private func setupReadableGuideForiPad() {
guard WPDeviceIdentification.isiPad() else { return }
innerView.leadingAnchor.constraint(equalTo: readableContentGuide.leadingAnchor).isActive = true
innerView.trailingAnchor.constraint(equalTo: readableContentGuide.trailingAnchor).isActive = true
}
private func configureFeaturedImage() {
if let post = post, let url = post.featuredImageURL {
featuredImageView.isHidden = false
let host = MediaHost(with: post, failure: { error in
// We'll log the error, so we know it's there, but we won't halt execution.
WordPressAppDelegate.crashLogging?.logError(error)
})
imageLoader.loadImage(with: url, from: host, preferredSize: CGSize(width: featuredImageView.frame.width, height: featuredImageView.frame.height))
} else {
featuredImageView.isHidden = true
}
}
private func configureTitle() {
titleLabel.text = post?.titleForDisplay()
}
private func configureDate() {
guard let post = post else {
return
}
timestampLabel.text = post.latest().dateStringForDisplay()
timestampLabel.isHidden = false
}
private func configureStatus() {
guard let viewModel = viewModel else {
return
}
badgesLabel.textColor = viewModel.statusColor
badgesLabel.text = viewModel.statusAndBadges(separatedBy: Constants.separator)
if badgesLabel.text?.isEmpty ?? true {
badgesLabel.isHidden = true
} else {
badgesLabel.isHidden = false
}
}
private func configureProgressView() {
guard let viewModel = viewModel else {
return
}
let shouldHide = viewModel.shouldHideProgressView
progressView.isHidden = shouldHide
progressView.progress = viewModel.progress
if !shouldHide && viewModel.progressBlock == nil {
viewModel.progressBlock = { [weak self] progress in
self?.progressView.setProgress(progress, animated: true)
if progress >= 1.0, let post = self?.post {
self?.configure(with: post)
}
}
}
}
private func setupAccessibility() {
menuButton.accessibilityLabel =
NSLocalizedString("More", comment: "Accessibility label for the More button in Post List (compact view).")
}
private enum Constants {
static let separator = " · "
static let contentSpacing: CGFloat = 8
static let imageRadius: CGFloat = 2
static let labelsVerticalAlignment: CGFloat = -1
static let opacity: Float = 1
}
}
extension PostCompactCell: InteractivePostView {
func setInteractionDelegate(_ delegate: InteractivePostViewDelegate) {
}
func setActionSheetDelegate(_ delegate: PostActionSheetDelegate) {
actionSheetDelegate = delegate
}
}
extension PostCompactCell: GhostableView {
func ghostAnimationWillStart() {
toggleGhost(visible: true)
menuButton.layer.opacity = GhostConstants.opacity
}
private func toggleGhost(visible: Bool) {
isUserInteractionEnabled = !visible
menuButton.isGhostableDisabled = true
separator.isGhostableDisabled = true
ghostView.isHidden = !visible
ghostView.backgroundColor = .listForeground
contentStackView.isHidden = visible
}
private enum GhostConstants {
static let opacity: Float = 0.5
}
}
| gpl-2.0 | 63a64980fc4c60a523c69f76d61eda32 | 30.635922 | 157 | 0.659659 | 5.41729 | false | true | false | false |
mziyut/TodoApp | TodoApp/TodoTableViewController.swift | 1 | 4785 | //
// TodoTableViewController.swift
// TodoApp
//
// Created by Yuta Mizui on 9/30/14.
// Copyright (c) 2014 Yuta Mizui. All rights reserved.
//
import Foundation
import UIKit
enum TodoAlertViewType {
case Create, Update(Int), Remove(Int)
}
class TodoTableViewController : UIViewController {
var tableView : UITableView?
var alert : UIAlertController?
var alertType : TodoAlertViewType?
var todo = TodoDataManager.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
let header = UIImageView(frame: CGRect(x: 0, y: 0, width: 320, height: 64))
header.image = UIImage(named: "header")
header.userInteractionEnabled = true
let title = UILabel(frame: CGRect(x: 10, y: 20, width: 310, height: 44))
title.text = "TodoList"
self.view.addSubview(title)
let button = UIButton.buttonWithType(.System) as UIButton
button.frame = CGRect(x: 320 - 50, y: 20, width: 50, height: 44)
button.setTitle("Add", forState: .Normal)
button.addTarget(self, action: "showCreateView", forControlEvents: .TouchUpInside)
header.addSubview(button)
let screenWidth = UIScreen.mainScreen().bounds.size.height
self.tableView = UITableView(frame: CGRect(x: 0, y: 60, width: 320, height: screenWidth - 60))
self.tableView!.dataSource = self
self.view.addSubview(self.tableView!)
self.view.addSubview(header)
}
func showCreateView() {
self.alertType = TodoAlertViewType.Create
self.alert = UIAlertController(title: "Add Todo", message: nil, preferredStyle: .Alert)
self.alert!.addTextFieldWithConfigurationHandler({ textField in
textField.delegate = self
textField.returnKeyType = .Done
})
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
self.presentViewController(alert!, animated: true, completion: nil)
}
}
extension TodoTableViewController : UITextFieldDelegate {
func textFieldShouldEndEditing(textField: UITextField!) -> Bool {
if let type = self.alertType {
switch type {
case .Create:
let todo = TODO(title: textField.text)
if self.todo.create(todo) {
textField.text = nil
self.tableView!.reloadData()
}
case let .Update(index):
let todo = TODO(title: textField.text)
if self.todo.update(todo, at: index) {
textField.text = nil
self.tableView!.reloadData()
}
case let .Remove(index):
break
}
}
self.alert!.dismissViewControllerAnimated(false, completion: nil)
return true
}
}
extension TodoTableViewController : TodoTabelViewCellDelegate {
func updateTodo(index: Int) {
self.alertType = TodoAlertViewType.Update(index)
self.alert = UIAlertController(title: "Edit", message: nil, preferredStyle: .Alert)
self.alert!.addTextFieldWithConfigurationHandler({ textField in
textField.text = self.todo[index].title
textField.delegate = self
textField.returnKeyType = .Done
})
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
self.alert!.addAction(okAction)
self.presentViewController(self.alert!, animated: true, completion: nil)
}
func removeTodo(index: Int) {
self.alertType = TodoAlertViewType.Remove(index)
self.alert = UIAlertController(title: "Delete", message: nil, preferredStyle: .Alert)
self.alert!.addAction(UIAlertAction(title: "Delete", style: .Destructive) { action in
self.todo.remove(index)
self.tableView!.reloadData()
})
self.alert!.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(self.alert!, animated: true, completion: nil)
}
}
extension TodoTableViewController : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todo.size
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = TodoTableViewCell(style: .Default, reuseIdentifier: nil)
cell.delegate = self
cell.textLabel?.text = self.todo[indexPath.row].title
cell.tag = indexPath.row
return cell
}
} | mit | 5529cb70aa771935b18b64fc8efce105 | 32.943262 | 109 | 0.612121 | 4.843117 | false | false | false | false |
apple/swift | benchmark/single-source/UTF8Decode.swift | 10 | 9540 | //===--- UTF8Decode.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
public let benchmarks = [
BenchmarkInfo(
name: "UTF8Decode",
runFunction: run_UTF8Decode,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_contiguous",
runFunction: run_UTF8Decode_InitFromCustom_contiguous,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_contiguous_ascii",
runFunction: run_UTF8Decode_InitFromCustom_contiguous_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_contiguous_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromCustom_contiguous_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_noncontiguous",
runFunction: run_UTF8Decode_InitFromCustom_noncontiguous,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_noncontiguous_ascii",
runFunction: run_UTF8Decode_InitFromCustom_noncontiguous_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromCustom_noncontiguous_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromCustom_noncontiguous_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromData",
runFunction: run_UTF8Decode_InitFromData,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitDecoding",
runFunction: run_UTF8Decode_InitDecoding,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromBytes",
runFunction: run_UTF8Decode_InitFromBytes,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromData_ascii",
runFunction: run_UTF8Decode_InitFromData_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitDecoding_ascii",
runFunction: run_UTF8Decode_InitDecoding_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromBytes_ascii",
runFunction: run_UTF8Decode_InitFromBytes_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromData_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromData_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitDecoding_ascii_as_ascii",
runFunction: run_UTF8Decode_InitDecoding_ascii_as_ascii,
tags: [.validation, .api, .String]),
BenchmarkInfo(
name: "UTF8Decode_InitFromBytes_ascii_as_ascii",
runFunction: run_UTF8Decode_InitFromBytes_ascii_as_ascii,
tags: [.validation, .api, .String]),
]
// 1-byte sequences
// This test case is the longest as it's the most performance sensitive.
let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
let asciiBytes: [UInt8] = Array(ascii.utf8)
let asciiData: Data = Data(asciiBytes)
// 2-byte sequences
let russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа."
// 3-byte sequences
let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"
// 4-byte sequences
// Most commonly emoji, which are usually mixed with other text.
let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭."
let allStrings = [ascii, russian, japanese, emoji].map { Array($0.utf8) }
let allStringsBytes: [UInt8] = Array(allStrings.joined())
let allStringsData: Data = Data(allStringsBytes)
@inline(never)
public func run_UTF8Decode(_ n: Int) {
let strings = allStrings
func isEmpty(_ result: UnicodeDecodingResult) -> Bool {
switch result {
case .emptyInput:
return true
default:
return false
}
}
for _ in 1...200*n {
for string in strings {
var it = string.makeIterator()
var utf8 = UTF8()
while !isEmpty(utf8.decode(&it)) { }
}
}
}
@inline(never)
public func run_UTF8Decode_InitFromData(_ n: Int) {
let input = allStringsData
for _ in 0..<200*n {
blackHole(String(data: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitDecoding(_ n: Int) {
let input = allStringsBytes
for _ in 0..<200*n {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromBytes(_ n: Int) {
let input = allStringsBytes
for _ in 0..<200*n {
blackHole(String(bytes: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitFromData_ascii(_ n: Int) {
let input = asciiData
for _ in 0..<1_000*n {
blackHole(String(data: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitDecoding_ascii(_ n: Int) {
let input = asciiBytes
for _ in 0..<1_000*n {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromBytes_ascii(_ n: Int) {
let input = asciiBytes
for _ in 0..<1_000*n {
blackHole(String(bytes: input, encoding: .utf8))
}
}
@inline(never)
public func run_UTF8Decode_InitFromData_ascii_as_ascii(_ n: Int) {
let input = asciiData
for _ in 0..<1_000*n {
blackHole(String(data: input, encoding: .ascii))
}
}
@inline(never)
public func run_UTF8Decode_InitDecoding_ascii_as_ascii(_ n: Int) {
let input = asciiBytes
for _ in 0..<1_000*n {
blackHole(String(decoding: input, as: Unicode.ASCII.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromBytes_ascii_as_ascii(_ n: Int) {
let input = asciiBytes
for _ in 0..<1_000*n {
blackHole(String(bytes: input, encoding: .ascii))
}
}
struct CustomContiguousCollection: Collection {
let storage: [UInt8]
typealias Index = Int
typealias Element = UInt8
init(_ bytes: [UInt8]) { self.storage = bytes }
subscript(position: Int) -> Element { self.storage[position] }
var startIndex: Index { 0 }
var endIndex: Index { storage.count }
func index(after i: Index) -> Index { i+1 }
@inline(never)
func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R? {
try storage.withContiguousStorageIfAvailable(body)
}
}
struct CustomNoncontiguousCollection: Collection {
let storage: [UInt8]
typealias Index = Int
typealias Element = UInt8
init(_ bytes: [UInt8]) { self.storage = bytes }
subscript(position: Int) -> Element { self.storage[position] }
var startIndex: Index { 0 }
var endIndex: Index { storage.count }
func index(after i: Index) -> Index { i+1 }
@inline(never)
func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R? {
nil
}
}
let allStringsCustomContiguous = CustomContiguousCollection(allStringsBytes)
let asciiCustomContiguous = CustomContiguousCollection(Array(ascii.utf8))
let allStringsCustomNoncontiguous = CustomNoncontiguousCollection(allStringsBytes)
let asciiCustomNoncontiguous = CustomNoncontiguousCollection(Array(ascii.utf8))
@inline(never)
public func run_UTF8Decode_InitFromCustom_contiguous(_ n: Int) {
let input = allStringsCustomContiguous
for _ in 0..<200*n {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_contiguous_ascii(_ n: Int) {
let input = asciiCustomContiguous
for _ in 0..<1_000*n {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_contiguous_ascii_as_ascii(_ n: Int) {
let input = asciiCustomContiguous
for _ in 0..<1_000*n {
blackHole(String(decoding: input, as: Unicode.ASCII.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_noncontiguous(_ n: Int) {
let input = allStringsCustomNoncontiguous
for _ in 0..<200*n {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_noncontiguous_ascii(_ n: Int) {
let input = asciiCustomNoncontiguous
for _ in 0..<1_000*n {
blackHole(String(decoding: input, as: UTF8.self))
}
}
@inline(never)
public func run_UTF8Decode_InitFromCustom_noncontiguous_ascii_as_ascii(_ n: Int) {
let input = asciiCustomNoncontiguous
for _ in 0..<1_000*n {
blackHole(String(decoding: input, as: Unicode.ASCII.self))
}
}
| apache-2.0 | 9f2617e94cedc25d64540a8538be4218 | 33.186131 | 589 | 0.690936 | 3.50824 | false | false | false | false |
liuqiang03109/PlayGifImage | PlayGifImage/Classes/LoadGifImageTool.swift | 1 | 2399 | //
// LoadGifImageTool.swift
// PlayGifImage
//
// Created by DanLi on 2017/3/6.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
import ImageIO
public class LoadGifImageTool {
//
public class func loadGifImage(_ imageView: UIImageView, _ imageName: String, _ repeate: Bool = true) {
//加载gif路径
guard let path = Bundle.main.path(forResource: imageName, ofType: nil) else {
return
}
guard let data = NSData(contentsOfFile: path) else {
return
}
//从data中读取数据,并将data转成 CGImageSource对象
guard let imageSource = CGImageSourceCreateWithData(data, nil) else {
return
}
let imageCount = CGImageSourceGetCount(imageSource)
var images = [UIImage]()
var totalDuration : TimeInterval = 0
for i in 0..<imageCount {
//取出图片,放入数组中,准备播放
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else {
continue
}
let image = UIImage(cgImage: cgImage)
if i == 0 {
imageView.image = image
}
images.append(image)
//取出播放时间
guard let propertites = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? NSDictionary else {
continue
}
//得到image的属性字典
guard let gifDict = propertites[kCGImagePropertyGIFDictionary] as? NSDictionary else {
continue
}
//获取每一帧的时间
guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else {
continue
}
totalDuration += frameDuration.doubleValue
}
startAnimate(imageView, images, totalDuration, repeate)
}
private class func startAnimate(_ imageView: UIImageView, _ images: [UIImage], _ totalDuration: TimeInterval, _ repeate: Bool) {
imageView.animationImages = images
imageView.animationDuration = totalDuration
imageView.animationRepeatCount = repeate ? 0 : 1;
imageView.startAnimating()
}
}
| mit | 5ee70c2fe2e71445cb0d34eb3eb7a562 | 29.131579 | 132 | 0.562882 | 5.362998 | false | false | false | false |
dpricha89/DrApp | Source/Utls/LibConst.swift | 1 | 2111 | //
// GlobalConst.swift
// Venga
//
// Created by David Richards on 4/29/17.
// Copyright © 2017 David Richards. All rights reserved.
//
import UIKit
struct LibConst {
// messages
static let successMessage = "SUCCESS"
static let failureMessage = "FAILURE"
// hud
static let alertDelay: TimeInterval = 3.0
// colors
static let logoutLabelColor: UIColor = .black
static let buttonTextColor: UIColor = .white
static let sectionTitleColor: UIColor = .white
// sizes
static let defaultRowEstimate: CGFloat = 60.0
static let buttonWidth: CGFloat = 280.0
static let buttonHeight: CGFloat = 40.0
static let leftViewWidth: CGFloat = 180
static let contentViewScale: CGFloat = 0.90
static let accountImageWidth: CGFloat = 80.0
static let smallMenuImageSize: CGFloat = 60.0
static let cornerRadius: CGFloat = 5.0
static let borderWidth: CGFloat = 1.0
static let labelHeight: CGFloat = 20
static let logoHeight: CGFloat = 130
static let topPadding: CGFloat = 80.0
static let rowHeight: CGFloat = 60.0
static let amountHeight: CGFloat = 50.0
static let leftOffset: CGFloat = 60.0
static let rightOffset: CGFloat = -60.0
static let topOffset: CGFloat = 30.0
static let labelOffset: CGFloat = 1
static let loginOffset: CGFloat = 10.0
static let spacingOffset: CGFloat = 10.0
static let smallLeftOffset: CGFloat = 20.0
static let smallTopOffset: CGFloat = 5.0
static let smallLabelHeight: CGFloat = 15
static let smallRightOffset: CGFloat = -20.0
static let smallBottomOffset: CGFloat = -5.0
static let lockImageSize: CGFloat = 80
static let titleLeftOffset: CGFloat = 30
static let paymentImageWidth: CGFloat = 60
static let paymentImageHeight: CGFloat = 40
static let paymentTypeHeight: CGFloat = 75
static let toolbarHeight: CGFloat = 60
static let largeLabelhieght: CGFloat = 28
static let profileImageHeight: CGFloat = 140.0
static let profileImageWidth: Float = 140.0
static let defaultOffset: Float = 10.0
}
| apache-2.0 | 004fc3cc29f85a771fc8c45601d2cca9 | 30.969697 | 57 | 0.698104 | 4.341564 | false | false | false | false |
allbto/WayThere | ios/WayThere/WayThere/Classes/Controllers/Today/TodayDataStore.swift | 2 | 3082 | //
// TodayDataStore.swift
// WayThere
//
// Created by Allan BARBATO on 5/25/15.
// Copyright (c) 2015 Allan BARBATO. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public protocol TodayDataStoreDelegate
{
func foundRandomImageUrl(imageUrl: String)
func unableToFindRandomImageUrl(error : NSError?)
}
public class TodayDataStore
{
/// Vars
public var delegate: TodayDataStoreDelegate?
let FlickrApiKey = "3594a6b0ef2dd35d01334424954caf00"
let FlickrPerPage = 100
// Url
let FindImagesUrl = "https://api.flickr.com/services/rest/"
/// Funcs
public init() {}
private func _getRandomUrlFromLocalImages(#city: City) -> String?
{
if let localImages = CityPhoto.MR_findByAttribute("cityId", withValue: city.remoteId) as? [CityPhoto] where localImages.count > 0 {
var random = Int.random(min: 0, max: localImages.count - 1)
if let url = localImages[random].url {
return url
}
}
return nil
}
private func _saveLocalImagesJSON(images: JSON, forCity: City)
{
for (index, (sIndex : String, photoJson : JSON)) in enumerate(images) {
let farm = photoJson["farm"].stringValue, server = photoJson["server"].stringValue, id = photoJson["id"].stringValue, secret = photoJson["secret"].stringValue
var imageUrl = "https://farm\(farm).staticflickr.com/\(server)/\(id)_\(secret)_b.jpg"
if let cityPhoto = CityPhoto.MR_createEntity() as? CityPhoto {
cityPhoto.url = imageUrl
cityPhoto.cityId = forCity.remoteId
}
}
CoreDataHelper.saveAndWait()
}
public func retrieveRandomImageUrlFromCity(city: City)
{
// Try to get local images url
if let url = _getRandomUrlFromLocalImages(city: city) {
delegate?.foundRandomImageUrl(url)
return
}
// Not found request Flickr
Alamofire.request(.POST, FindImagesUrl, parameters: [
"method" : "flickr.photos.search",
"api_key" : FlickrApiKey,
"text" : String(city.name),
"sort" : "relevance",
"accuracy" : "11",
"safe_search" : "1",
"content_type": "1",
"format" : "json",
"nojsoncallback" : "1",
"privacy_filter" : "1",
"per_page" : FlickrPerPage
])
.responseJSON { [unowned self] (request, response, json, error) -> Void in
if (error == nil && json != nil) {
var json = JSON(json!)
self._saveLocalImagesJSON(json["photos"]["photo"], forCity: city)
self.delegate?.foundRandomImageUrl(self._getRandomUrlFromLocalImages(city: city) ?? "")
} else {
self.delegate?.unableToFindRandomImageUrl(error)
}
}
}
}
| mit | 9750c372a4d24e2c037e666f9d8e028b | 30.773196 | 170 | 0.560675 | 4.365439 | false | false | false | false |
koneman/Hearth | HotspotTableViewController.swift | 1 | 4480 | //
// HotspotTableViewController.swift
// Hearth
//
// Created by Sathvik Koneru on 5/22/16.
// Copyright © 2016 Sathvik Koneru. All rights reserved.
//
import UIKit
//this global variable represents an array of all the addresses from hotSpotDict
var hotspotArr = [String]()
class HotspotTableViewController: UITableViewController {
//default constructor
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
}
//default memory warning method
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
//this method returns the 1 section that the Hotspot Table View controller needs
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
//this method is used to create the number of rows in
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
//creates an instance of a heap structure with a dictioanry passed in
let heapList = PriorityQueue<[String:String]>()
for (_, locationInfo) in hotSpotDict {
//pushing in the freq as a priority item and the locationInformation
heapList.push(((locationInfo["freq"]! as NSString).integerValue), item:locationInfo)
}
var n = 0
print(hotSpotDict.count)
hotspotArr.removeAll()
//adding the "hot" top 20 locations to the hotspotArr of addresses
while (n < heapList.count){
var (_, loc) = heapList.pop()
let hotSpot = loc["address"]
hotspotArr.append(hotSpot!)
n += 1
}
return hotspotArr.count
}
//sets the text of the cell to the corresponding address in hotspotArr
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var hotSpotDict = [String:[String:Double]]()
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = hotspotArr[indexPath.row]
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 | d9867473fd1a1f9cde1b420e545fadc9 | 32.177778 | 158 | 0.640768 | 5.495706 | false | false | false | false |
Incipia/Goalie | Goalie/SettingsViewController.swift | 1 | 3127 | //
// SettingsViewController.swift
// Goalie
//
// Created by Gregory Klein on 12/30/15.
// Copyright © 2015 Incipia. All rights reserved.
//
import UIKit
import CoreData
protocol MenuController: class
{
var view: UIView! {get set}
var dialogContainer: UIView {get}
}
protocol SettingsViewControllerDelegate: class
{
func settingsDidClose()
}
class SettingsViewController: UIViewController, ManagedObjectContextSettable, MenuController
{
var moc: NSManagedObjectContext! {
didSet {
_taskPriorityStateSnapshotter = TaskPriorityStateSnapshotter(moc: moc)
}
}
fileprivate var _taskPriorityStateSnapshotter: TaskPriorityStateSnapshotter!
weak var delegate: SettingsViewControllerDelegate?
@IBOutlet fileprivate weak var _containerView: UIVisualEffectView!
@IBOutlet fileprivate weak var _showCompletedTasksSwitch: UISwitch!
@IBOutlet fileprivate weak var _manuallySwitchPrioritySwitch: UISwitch!
var dialogContainer: UIView {
return _containerView
}
// Mark: - Lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
_setupShadow()
// _containerView.layer.cornerRadius = 4.0
// _containerView.layer.masksToBounds = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let shadowPath = UIBezierPath(rect: _containerView.bounds)
_containerView.layer.shadowPath = shadowPath.cgPath
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
_showCompletedTasksSwitch.isOn = GoalieSettingsManager.showCompletedTasks
_manuallySwitchPrioritySwitch.isOn = GoalieSettingsManager.manuallySwitchPriority
}
override var preferredStatusBarStyle : UIStatusBarStyle
{
return .lightContent
}
// Mark: - Private
fileprivate func _setupShadow()
{
_containerView.layer.shadowColor = UIColor.black.cgColor
_containerView.layer.shadowOpacity = 0.2
_containerView.layer.shadowOffset = CGSize(width: 0, height: 4)
_containerView.layer.shadowRadius = 4
}
// Mark: - IBActions
@IBAction fileprivate func _closeButtonPressed()
{
dismiss(animated: true) { () -> Void in
GoalieSettingsManager.setShowCompletedTasks(self._showCompletedTasksSwitch.isOn)
let autoSwitchPriorityChanged = GoalieSettingsManager.setManuallySwitchPriority(self._manuallySwitchPrioritySwitch.isOn)
if autoSwitchPriorityChanged {
if GoalieSettingsManager.manuallySwitchPriority {
self._taskPriorityStateSnapshotter.snapshotCurrentState()
}
else {
self._taskPriorityStateSnapshotter.applyPreviousSnapshot()
}
}
self.delegate?.settingsDidClose()
}
}
@IBAction fileprivate func _tapRecognized(_ gestureRecognizer: UIGestureRecognizer)
{
let touchLocation = gestureRecognizer.location(in: nil)
guard !_containerView.frame.contains(touchLocation) else { return }
_closeButtonPressed()
}
}
| apache-2.0 | 22d6bb9756512548dd779d17f51dde19 | 27.944444 | 129 | 0.701216 | 5.066451 | false | false | false | false |
takeshineshiro/WeatherMap | WeatherAroundUs/Pods/Spring/Spring/DesignableTextField.swift | 24 | 3663 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([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 UIKit
@IBDesignable public class DesignableTextField: SpringTextField {
@IBInspectable public var placeholderColor: UIColor = UIColor.clearColor() {
didSet {
attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: placeholderColor])
layoutSubviews()
}
}
@IBInspectable public var sidePadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, sidePadding, sidePadding))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var leftPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, leftPadding, 0))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
}
}
@IBInspectable public var rightPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, 0, rightPadding))
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
var font = UIFont(name: self.font.fontName, size: self.font.pointSize)
var text = self.text
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
var attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| apache-2.0 | d1ba5bc4d5e70ca8eb65463b6a77249c | 36 | 143 | 0.648922 | 5.541604 | false | false | false | false |
BradLarson/GPUImage2 | framework/Source/FillMode.swift | 1 | 4309 | #if os(Linux)
import Glibc
#endif
#if canImport(OpenGL)
import OpenGL.GL3
#endif
#if canImport(OpenGLES)
import OpenGLES
#endif
#if canImport(COpenGL)
import COpenGL
#endif
public enum FillMode {
case stretch
case preserveAspectRatio
case preserveAspectRatioAndFill
func transformVertices(_ vertices:[GLfloat], fromInputSize:GLSize, toFitSize:GLSize) -> [GLfloat] {
guard (vertices.count == 8) else { fatalError("Attempted to transform a non-quad to account for fill mode.") }
let aspectRatio = GLfloat(fromInputSize.height) / GLfloat(fromInputSize.width)
let targetAspectRatio = GLfloat(toFitSize.height) / GLfloat(toFitSize.width)
let yRatio:GLfloat
let xRatio:GLfloat
switch self {
case .stretch: return vertices
case .preserveAspectRatio:
if (aspectRatio > targetAspectRatio) {
yRatio = 1.0
// xRatio = (GLfloat(toFitSize.height) / GLfloat(fromInputSize.height)) * (GLfloat(fromInputSize.width) / GLfloat(toFitSize.width))
xRatio = (GLfloat(fromInputSize.width) / GLfloat(toFitSize.width)) * (GLfloat(toFitSize.height) / GLfloat(fromInputSize.height))
} else {
xRatio = 1.0
yRatio = (GLfloat(fromInputSize.height) / GLfloat(toFitSize.height)) * (GLfloat(toFitSize.width) / GLfloat(fromInputSize.width))
}
case .preserveAspectRatioAndFill:
if (aspectRatio > targetAspectRatio) {
xRatio = 1.0
yRatio = (GLfloat(fromInputSize.height) / GLfloat(toFitSize.height)) * (GLfloat(toFitSize.width) / GLfloat(fromInputSize.width))
} else {
yRatio = 1.0
xRatio = (GLfloat(toFitSize.height) / GLfloat(fromInputSize.height)) * (GLfloat(fromInputSize.width) / GLfloat(toFitSize.width))
}
}
// Pixel-align to output dimensions
// return [vertices[0] * xRatio, vertices[1] * yRatio, vertices[2] * xRatio, vertices[3] * yRatio, vertices[4] * xRatio, vertices[5] * yRatio, vertices[6] * xRatio, vertices[7] * yRatio]
// TODO: Determine if this is misaligning things
let xConversionRatio:GLfloat = xRatio * GLfloat(toFitSize.width) / 2.0
let xConversionDivisor:GLfloat = GLfloat(toFitSize.width) / 2.0
let yConversionRatio:GLfloat = yRatio * GLfloat(toFitSize.height) / 2.0
let yConversionDivisor:GLfloat = GLfloat(toFitSize.height) / 2.0
// The Double casting here is required by Linux
let value1:GLfloat = GLfloat(round(Double(vertices[0] * xConversionRatio))) / xConversionDivisor
let value2:GLfloat = GLfloat(round(Double(vertices[1] * yConversionRatio))) / yConversionDivisor
let value3:GLfloat = GLfloat(round(Double(vertices[2] * xConversionRatio))) / xConversionDivisor
let value4:GLfloat = GLfloat(round(Double(vertices[3] * yConversionRatio))) / yConversionDivisor
let value5:GLfloat = GLfloat(round(Double(vertices[4] * xConversionRatio))) / xConversionDivisor
let value6:GLfloat = GLfloat(round(Double(vertices[5] * yConversionRatio))) / yConversionDivisor
let value7:GLfloat = GLfloat(round(Double(vertices[6] * xConversionRatio))) / xConversionDivisor
let value8:GLfloat = GLfloat(round(Double(vertices[7] * yConversionRatio))) / yConversionDivisor
return [value1, value2, value3, value4, value5, value6, value7, value8]
// This expression chokes the compiler in Xcode 8.0, Swift 3
// return [GLfloat(round(Double(vertices[0] * xConversionRatio))) / xConversionDivisor, GLfloat(round(Double(vertices[1] * yConversionRatio))) / yConversionDivisor,
// GLfloat(round(Double(vertices[2] * xConversionRatio))) / xConversionDivisor, GLfloat(round(Double(vertices[3] * yConversionRatio))) / yConversionDivisor,
// GLfloat(round(Double(vertices[4] * xConversionRatio))) / xConversionDivisor, GLfloat(round(Double(vertices[5] * yConversionRatio))) / yConversionDivisor,
// GLfloat(round(Double(vertices[6] * xConversionRatio))) / xConversionDivisor, GLfloat(round(Double(vertices[7] * yConversionRatio))) / yConversionDivisor]
}
}
| bsd-3-clause | 68c50630c2192ab72af1bfbd95e92f29 | 53.544304 | 193 | 0.667672 | 4.065094 | false | false | false | false |
johnnysay/GoodAccountsMakeGoodFriends | Good Accounts/Models/Color.swift | 1 | 838 | //
// Color.swift
// Good Accounts
//
// Created by Johnny on 13/02/2016.
// Copyright © 2016 fake. All rights reserved.
//
import UIKit
/// Custom colors.
struct Color {
static let darkBlue = UIColor(red: 31, green: 38, blue: 59)
static let purple = UIColor(red: 47, green: 29, blue: 55)
static let orange = UIColor(red: 255, green: 190, blue: 82)
static let pink = UIColor(red: 223, green: 6, blue: 123)
static let blue = UIColor(red: 82, green: 190, blue: 255)
static let turquoise = UIColor(red: 6, green: 205, blue: 223)
static let yellow = UIColor(red: 223, green: 186, blue: 6)
// Pastel colors
static let pastelOrange = UIColor(red: 255, green: 223, blue: 186)
static let pastelGreen = UIColor(red: 193, green: 252, blue: 198)
static let rain = UIColor(white: 1.0, alpha: 0.75)
}
| mit | 749eb2dde702cedbeecc7f6306be1ae0 | 31.192308 | 70 | 0.653524 | 3.206897 | false | false | false | false |
crazypoo/PTools | Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift | 2 | 2839 | //
// ChaCha20Poly1305.swift
// CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
//
// https://tools.ietf.org/html/rfc7539#section-2.8.1
/// AEAD_CHACHA20_POLY1305
public final class AEADChaCha20Poly1305: AEAD {
public static let kLen = 32 // key length
public static var ivRange = Range<Int>(12...12)
/// Authenticated encryption
public static func encrypt(_ plainText: Array<UInt8>, key: Array<UInt8>, iv: Array<UInt8>, authenticationHeader: Array<UInt8>) throws -> (cipherText: Array<UInt8>, authenticationTag: Array<UInt8>) {
let cipher = try ChaCha20(key: key, iv: iv)
var polykey = Array<UInt8>(repeating: 0, count: kLen)
var toEncrypt = polykey
polykey = try cipher.encrypt(polykey)
toEncrypt += polykey
toEncrypt += plainText
let fullCipherText = try cipher.encrypt(toEncrypt)
let cipherText = Array(fullCipherText.dropFirst(64))
let tag = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader)
return (cipherText, tag)
}
/// Authenticated decryption
public static func decrypt(_ cipherText: Array<UInt8>, key: Array<UInt8>, iv: Array<UInt8>, authenticationHeader: Array<UInt8>, authenticationTag: Array<UInt8>) throws -> (plainText: Array<UInt8>, success: Bool) {
let chacha = try ChaCha20(key: key, iv: iv)
let polykey = try chacha.encrypt(Array<UInt8>(repeating: 0, count: self.kLen))
let mac = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader)
guard mac == authenticationTag else {
return (cipherText, false)
}
var toDecrypt = Array<UInt8>(reserveCapacity: cipherText.count + 64)
toDecrypt += polykey
toDecrypt += polykey
toDecrypt += cipherText
let fullPlainText = try chacha.decrypt(toDecrypt)
let plainText = Array(fullPlainText.dropFirst(64))
return (plainText, true)
}
}
| mit | 9dda2aeb5edbcad140955438f8b2039c | 47.101695 | 217 | 0.738196 | 4.071736 | false | false | false | false |
payjp/payjp-ios | Sources/Core/PAYJPSDK.swift | 1 | 1490 | //
// PAYJPSDK.swift
// PAYJP
//
// Created by Li-Hsuan Chen on 2019/07/24.
// Copyright © 2019 PAY, Inc. All rights reserved.
//
import Foundation
#if SWIFT_PACKAGE
@_exported import PAYJP_ObjC
#endif
/// PAY.JP SDK initial settings.
public protocol PAYJPSDKType: AnyObject {
/// PAY.JP public key.
static var publicKey: String? { get set }
/// Locale.
static var locale: Locale? { get set }
/// 3DSecure URL configuration.
static var threeDSecureURLConfiguration: ThreeDSecureURLConfiguration? { get set }
}
/// see PAYJPSDKType.
@objc(PAYJPSDK) @objcMembers
public final class PAYJPSDK: NSObject, PAYJPSDKType {
private override init() {}
// MARK: - PAYJPSDKType
public static var publicKey: String? {
didSet {
guard let publicKey = publicKey else {
authToken = ""
return
}
// public key validation
PublicKeyValidator.shared.validate(publicKey: publicKey)
let data = "\(publicKey):".data(using: .utf8)!
let base64String = data.base64EncodedString()
authToken = "Basic \(base64String)"
}
}
public static var locale: Locale?
public static var threeDSecureURLConfiguration: ThreeDSecureURLConfiguration?
public static var clientInfo: ClientInfo = .default
// Update by Fastlane :bump_up_version
public static let sdkVersion: String = "1.6.2"
static var authToken: String = ""
}
| mit | afb36e27df9a10c7b3355747120a1511 | 25.589286 | 86 | 0.644056 | 4.254286 | false | true | false | false |
oisdk/ContiguousDeque | ContiguousDeque/ContiguousList.swift | 1 | 8654 | // MARK: Definition
public struct ContiguousList<Element> {
private var contents: ContiguousArray<Element>
}
extension ContiguousList : CustomDebugStringConvertible {
public var debugDescription: String {
return "[" + ", ".join(map {String(reflecting: $0)}) + "]"
}
}
// MARK: Init
extension ContiguousList : ArrayLiteralConvertible {
public init(arrayLiteral: Element...) {
contents = ContiguousArray(arrayLiteral.reverse())
}
public init(_ array: [Element]) {
contents = ContiguousArray(array.reverse())
}
public init<S: SequenceType where S.Generator.Element == Element>(_ seq: S) {
contents = ContiguousArray(seq.reverse())
}
public init() {
contents = []
}
internal init(alreadyReversed: ContiguousArray<Element>) {
contents = alreadyReversed
}
}
// MARK: Indexable
extension ContiguousList : Indexable {
public var endIndex: ContiguousListIndex {
return ContiguousListIndex(contents.startIndex.predecessor())
}
public var startIndex: ContiguousListIndex {
return ContiguousListIndex(contents.endIndex.predecessor())
}
public subscript(idx: ContiguousListIndex) -> Element {
get { return contents[idx.val] }
set { contents[idx.val] = newValue }
}
}
// MARK: SequenceType
extension ContiguousList : SequenceType {
public typealias SubSequence = ContiguousListSlice<Element>
public func dropFirst() -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.dropLast())
}
public func dropLast() -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.dropFirst())
}
public func dropFirst(n: Int) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.dropLast(n))
}
public func dropLast(n: Int) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.dropFirst(n))
}
public func generate() -> IndexingGenerator<ContiguousList> {
return IndexingGenerator(self)
}
public func prefix(maxLength: Int) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.suffix(maxLength))
}
public func suffix(maxLength: Int) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.prefix(maxLength))
}
public func split(
maxSplit: Int,
allowEmptySlices: Bool,
@noescape isSeparator: Element -> Bool
) -> [ContiguousListSlice<Element>] {
var result: [ContiguousListSlice<Element>] = []
var curent: ContiguousListSlice<Element> = []
curent.reserveCapacity(maxSplit)
for element in self {
if isSeparator(element) {
if !curent.isEmpty || allowEmptySlices {
result.append(curent)
curent.removeAll(keepCapacity: true)
}
} else {
curent.append(element)
}
}
if !curent.isEmpty || allowEmptySlices {
result.append(curent)
}
return result
}
public func underestimateCount() -> Int {
return contents.underestimateCount()
}
public func reverse() -> ContiguousArray<Element> {
return contents
}
}
// MARK: CollectionType
extension ContiguousList : CollectionType {
public var count: Int {
return contents.count
}
public var first: Element? {
return contents.last
}
public var last: Element? {
return contents.first
}
public var isEmpty: Bool {
return contents.isEmpty
}
public mutating func popFirst() -> Element? {
return contents.popLast()
}
public mutating func popLast() -> Element? {
return contents.isEmpty ? nil : contents.removeFirst()
}
public func prefixThrough(i: ContiguousListIndex) -> ContiguousListSlice<Element> {
return prefixUpTo(i.successor())
}
public func prefixUpTo(i: ContiguousListIndex) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.suffixFrom(i.val.successor()))
}
public func prefixThrough(i: Int) -> ContiguousListSlice<Element> {
return prefixUpTo(i.successor())
}
public func prefixUpTo(i: Int) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.suffix(i))
}
public mutating func removeFirst() -> Element {
return contents.removeLast()
}
public mutating func removeLast() -> Element {
return contents.removeFirst()
}
public func suffixFrom(i: ContiguousListIndex) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.prefixThrough(i.val))
}
public func suffixFrom(i: Int) -> ContiguousListSlice<Element> {
return ContiguousListSlice(alreadyReversed: contents.prefixUpTo(contents.endIndex - i))
}
public subscript(idxs: Range<ContiguousListIndex>) -> ContiguousListSlice<Element> {
get {
let start = idxs.endIndex.val.successor()
let end = idxs.startIndex.val.successor()
return ContiguousListSlice(alreadyReversed: contents[start..<end])
} set {
let start = idxs.endIndex.val.successor()
let end = idxs.startIndex.val.successor()
contents[start..<end] = newValue.contents
}
}
public subscript(idx: Int) -> Element {
get { return contents[contents.endIndex.predecessor() - idx] }
set { contents[contents.endIndex.predecessor() - idx] = newValue }
}
public subscript(idxs: Range<Int>) -> ContiguousListSlice<Element> {
get {
let str = contents.endIndex - idxs.endIndex
let end = contents.endIndex - idxs.startIndex
return ContiguousListSlice(alreadyReversed: contents[str..<end] )
} set {
let str = contents.endIndex - idxs.endIndex
let end = contents.endIndex - idxs.startIndex
contents[str..<end] = newValue.contents
}
}
}
// MARK: RangeReplaceableCollectionType
extension ContiguousList : RangeReplaceableCollectionType {
public mutating func append(with: Element) {
contents.insert(with, atIndex: contents.startIndex)
}
public mutating func prepend(with: Element) {
contents.append(with)
}
public mutating func extend<S : CollectionType where S.Generator.Element == Element>(newElements: S) {
contents.replaceRange(contents.startIndex..<contents.startIndex, with: newElements.reverse())
}
public mutating func extend<S : SequenceType where S.Generator.Element == Element>(newElements: S) {
extend(Array(newElements))
}
public mutating func prextend<S : SequenceType where S.Generator.Element == Element>(newElements: S) {
contents.extend(newElements.reverse())
}
public mutating func insert(newElement: Element, atIndex i: ContiguousListIndex) {
contents.insert(newElement, atIndex: i.val.successor())
}
public mutating func insert(newElement: Element, atIndex i: Int) {
print(debugDescription)
print(i)
contents.insert(newElement, atIndex: contents.endIndex - i)
}
public mutating func removeAll(keepCapacity keepCapacity: Bool) {
contents.removeAll(keepCapacity: keepCapacity)
}
public mutating func removeAtIndex(index: ContiguousListIndex) -> Element {
return contents.removeAtIndex(index.val)
}
public mutating func removeAtIndex(index: Int) -> Element {
return contents.removeAtIndex(contents.endIndex.predecessor() - index)
}
public mutating func removeFirst(n: Int) {
contents.removeRange((contents.endIndex - n)..<contents.endIndex)
}
public mutating func removeLast(n: Int) {
contents.removeFirst(n)
}
public mutating func removeRange(subRange: Range<ContiguousListIndex>) {
let str = subRange.endIndex.val.successor()
let end = subRange.startIndex.val.successor()
contents.removeRange(str..<end)
}
public mutating func removeRange(subRange: Range<Int>) {
let str = contents.endIndex - subRange.endIndex
let end = contents.endIndex - subRange.startIndex
contents.removeRange(str..<end)
}
public mutating func replaceRange<
C : CollectionType where C.Generator.Element == Element
>(subRange: Range<ContiguousListIndex>, with newElements: C) {
let str = subRange.endIndex.val.successor()
let end = subRange.startIndex.val.successor()
contents.replaceRange((str..<end), with: newElements.reverse())
}
public mutating func replaceRange<
C : CollectionType where C.Generator.Element == Element
>(subRange: Range<Int>, with newElements: C) {
let str = contents.endIndex - subRange.endIndex
let end = contents.endIndex - subRange.startIndex
contents.replaceRange((str..<end), with: newElements.reverse())
}
public mutating func reserveCapacity(n: Int) {
contents.reserveCapacity(n)
}
}
| mit | 40381229453aca97a42e08ab62a9a9f0 | 34.036437 | 104 | 0.710654 | 4.370707 | false | false | false | false |
Kesoyuh/Codebrew2017 | Codebrew2017/CalendarThumbnailView.swift | 1 | 7567 | //
// CalendarThumbnailView.swift
// Getit
//
// Created by Federico Malesani on 19/03/2016.
// Copyright © 2016 UniMelb. All rights reserved.
//
import Foundation
//
// CalendarThumbnailView.swift
// GPSTrackY
//
// Created by Federico Malesani on 18/02/2016.
// Copyright © 2016 UniMelb. All rights reserved.
//
import UIKit
@IBDesignable
class CalendarThumbnailView: UIView {
@IBInspectable
var topBandColor: UIColor = UIColor.red { didSet { setNeedsDisplay() } }
@IBInspectable
var bottomBandColor: UIColor = UIColor.white { didSet { setNeedsDisplay() } }
@IBInspectable
var monthTextColor: UIColor = UIColor.white { didSet { setNeedsDisplay() } }
@IBInspectable
var dayTextColor: UIColor = UIColor.black { didSet { setNeedsDisplay() } }
var topBandRatio: Double = 2/5 { didSet { setNeedsDisplay() } }
var bottomBandRatio: Double = 3/5 { didSet { setNeedsDisplay() } }
var day: NSString = "7" { didSet { setNeedsDisplay() } }
var month: NSString = "MAY" { didSet { setNeedsDisplay() } }
// var month: String?
// var day: Int?
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
//TODO: remove all magic numbers!
// Drawing code
let topBarPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height*(2/5)))
topBandColor.set()
topBarPath.fill()
topBarPath.stroke()
let bottomBarPath = UIBezierPath(rect: CGRect(x: 0, y: self.bounds.size.height*(2/5), width: self.bounds.size.width, height: self.bounds.size.height*(3/5)))
bottomBandColor.set()
bottomBarPath.fill()
bottomBarPath.stroke()
//let month: NSString = "MAY"
// set the text color to dark gray
//let fieldColor: UIColor = UIColor.darkGrayColor()
// set the font
//let monthFont = UIFont(name: "Helvetica Neue", size: 16)
let monthFont = UIFont(name: "Helvetica Neue", size: self.bounds.size.height*(25/100))
// set the paragraph style
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
// set the Obliqueness to 0.1
//let skew = 0.0
let monthTextAttributes: NSDictionary = [
//NSForegroundColorAttributeName: fieldColor,
NSParagraphStyleAttributeName: paragraphStyle,
//NSObliquenessAttributeName: skew,
NSFontAttributeName: monthFont!
]
month.draw(in: CGRect(x: 0, y: self.bounds.size.height*(9/100), width: self.bounds.size.width, height: self.bounds.size.height*(2/5)), withAttributes: (monthTextAttributes as! [String : AnyObject]))
//let day: NSString = "30"
// set the font
//let dayFont = UIFont(name: "Helvetica Neue", size: 34)
let dayFont = UIFont(name: "Helvetica Neue", size: self.bounds.size.height*(54/100))
let dayTextAttributes: NSDictionary = [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: dayFont!
]
day.draw(in: CGRect(x: 0, y: self.bounds.size.height*(2/5) - self.bounds.size.height*(8/100), width: self.bounds.size.width, height: self.bounds.size.height*(4/7)), withAttributes: (dayTextAttributes as! [String : AnyObject]))
}
// //@IBInspectalbe
// var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } }
// //@IBInspectalbe
// var scale: CGFloat = 0.90 { didSet { setNeedsDisplay() } }
//
// var faceCenter: CGPoint {
// return convertPoint(center, fromView: superview)
// }
//
// var faceRadius: CGFloat {
// return min(bounds.size.width, bounds.size.height) / 2*scale
// }
//
// weak var dataSource: CalendarThumbnailViewDataSource?
//
// func scale (gesture: UIPinchGestureRecognizer) {
// if gesture.state == .Changed {
// scale *= gesture.scale
// gesture.scale = 1
// }
// }
//
// private struct Scaling {
// static let FaceRadiusToEyeRadiusRatio: CGFloat = 10
// static let FaceRadiusToEyeOffsetRatio: CGFloat = 3
// static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5
// static let FaceRadiusToMouthWidthRatio: CGFloat = 1
// static let FaceRadiusToMouthHeightRatio: CGFloat = 3
// static let FaceRadiusToMouthOffsetRatio: CGFloat = 3
// }
//
// private enum Eye {case Left, Right}
//
// private func bezierPathForEye(whichEye: Eye) -> UIBezierPath {
// let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
// let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio
// let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio
//
// var eyeCenter = faceCenter
// eyeCenter.y -= eyeVerticalOffset
// switch whichEye {
// case .Left: eyeCenter.x -= eyeHorizontalSeparation/2
// case .Right: eyeCenter.x += eyeHorizontalSeparation/2
// }
//
// let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true)
// path.lineWidth = lineWidth
// return path
// }
//
// private func bezierPathForSmile (fractionOfSmile: Double) -> UIBezierPath {
// let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio
// let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio
// let mouthVerticalOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio
//
// let smileHeight = CGFloat(max(min(fractionOfSmile, 1), -1)) * mouthHeight
// let start = CGPoint(x: faceCenter.x - mouthWidth/2, y: faceCenter.y + mouthVerticalOffset)
// let end = CGPoint(x: start.x + mouthWidth, y: start.y)
// let cp1 = CGPoint(x: start.x + mouthWidth/3, y: start.y + smileHeight)
// let cp2 = CGPoint(x: end.x - mouthWidth/3, y: cp1.y)
//
// let path = UIBezierPath()
// path.moveToPoint(start)
// path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2)
// path.lineWidth = lineWidth
// return path
// }
//
// // Only override drawRect: if you perform custom drawing.
// // An empty implementation adversely affects performance during animation.
// override func drawRect(rect: CGRect) {
// // Drawing code
// let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true)
// facePath.lineWidth = lineWidth
// color.set()
// facePath.stroke()
//
// bezierPathForEye(.Left).stroke()
// bezierPathForEye(.Right).stroke()
//
// let smiliness = dataSource?.smilinessForFaceView(self) ?? 0.0 //if the left part is not nil then usit, otherwise use the right part
// let smilePath = bezierPathForSmile(smiliness)
// smilePath.stroke()
//
// }
}
| mit | 6c0ed35bd348c2547995f5ad158a8cb4 | 40.11413 | 234 | 0.606874 | 4.398256 | false | false | false | false |
openbuild-sheffield/jolt | Sources/RouteCMS/validate.BodyPageVariables.swift | 1 | 5693 | import OpenbuildExtensionPerfect
import OpenbuildExtensionCore
let ValidateBodyPageVariables = RequestValidationBody(
name: "variables",
required: true,
type: RequestValidationTypeArray(
closure: { (data: Any) -> RequestValidation in
var results = RequestValidation()
if let dataDictionary = data as? [String: Any] {
if dataDictionary["variable"] == nil {
results.addError(key: "variable", value: "Should be set")
}else{
if dataDictionary["variable"] as! String !=~ "^[A-Za-z0-9]{3,255}$" {
results.addError(
key:"variable",
value: "Should match ^[A-Za-z0-9]{3,255}$."
)
}
}
if dataDictionary["content"] == nil {
results.addError(key: "content", value: "Should be set")
} else {
if let contentArray = dataDictionary["content"]! as? [[String: String]] {
for (index, v) in contentArray.enumerated(){
var errors: [String:String] = [:]
if v["type"] == nil {
errors["type"] = "Should be set"
} else if v["type"]! != "markdown" && v["type"]! != "words" {
errors["type"] = "Should be 'markdown' or 'words'"
}
if v["handle"] == nil {
errors["handle"] = "Should be set"
} else if v["handle"]! !=~ "^[A-Za-z0-9_]{3,255}$" {
errors["handle"] = "Should match ^[A-Za-z0-9_]{3,255}$"
}
if errors.isEmpty == false {
results.addError(key: "content_\(index)", value: errors)
} else {
//Looks valid so check if it's in the DB
if v["type"] == "markdown" {
do {
var repositoryMarkdown = try RepositoryCMSMarkdown()
let entityMarkdown = try repositoryMarkdown.getByHandle(
handle: v["handle"]!
)
if entityMarkdown == nil {
errors["handle"] = "Not found"
}
} catch {
errors["handle"] = "Not found"
}
}
if v["type"] == "words" {
do {
var repositoryWords = try RepositoryCMSWords()
let entityWords = try repositoryWords.getByHandle(
handle: v["handle"]!
)
if entityWords == nil {
errors["handle"] = "Not found"
}
} catch {
errors["handle"] = "Not found"
}
}
if errors.isEmpty == false {
results.addError(key: "content_\(index)", value: errors)
}
}
}
}else{
results.addError(key: "format", value: "Content doesn't appear to be a valid array.")
}
}
} else {
results.addError(key: "format", value: "Item doesn't appear to be a valid object.")
}
return results
},
raml: { () -> [String] in
var raml = ["type: array"]
raml.append("minItems: 1")
raml.append("items:")
raml.append(" type: object")
raml.append(" description: Object describing the variable and it's content.")
raml.append(" properties:")
raml.append(" variable:")
raml.append(" type: string")
raml.append(" description: the variable used in the template")
raml.append(" content:")
raml.append(" type: array")
raml.append(" description: array of content type objects")
raml.append(" items:")
raml.append(" type: object")
raml.append(" properties:")
raml.append(" content_type:")
raml.append(" type: string")
raml.append(" description: the type of content, currently words or markdown")
raml.append(" pattern: ^(markdown|words)$")
raml.append(" handle:")
raml.append(" type: string")
raml.append(" description: the handle used to lookup the content")
raml.append(" pattern: ^[A-Za-z0-9_]{3,255}$")
raml.append("example:")
raml.append(" -")
return raml
}
)
) | gpl-2.0 | 95365e5fcc568a7e8a1950a8fad03dc6 | 35.037975 | 109 | 0.371333 | 5.670319 | false | false | false | false |
aoifukuoka/XMLModelizer | Demo/RSSTableViewController.swift | 1 | 2582 | //
// RSSTableViewController.swift
// XMLModelizer
//
// Created by aoponaopon on 2016/09/24.
// Copyright © 2016年 aoponapopon. All rights reserved.
//
import UIKit
import WebKit
import XMLModelizer
import SDWebImage
class RSSTableViewController: UITableViewController {
var models: [NSObject] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: "RSSTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
models = XMLModelizer.modelize(modelClass: NYTimesArticle.self,
urlString: "http://rss.nytimes.com/services/xml/rss/nyt/World.xml") as! [NYTimesArticle]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 75
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
let model: NYTimesArticle = models[indexPath.row] as! NYTimesArticle
let webViewController: UIViewController = WebViewController.instantiateWithStoryBoard()
let webView: WKWebView = WKWebView(frame: webViewController.view.bounds)
webViewController.view.addSubview(webView)
webView.load(URLRequest(url: model.linkURL()!))
self.navigationController?.pushViewController(webViewController, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RSSTableViewCell
let model: NYTimesArticle = models[indexPath.row] as! NYTimesArticle
cell.titleTextLabel.text = model.title.first
cell.categoryLabel.text = model.category.first
cell.pubDateLabel.text = model.formattedDate()
cell.thumbImageView.sd_setImage(with: model.thumbImageURL())
return cell
}
}
| mit | f053a2bccca6d889f61e355011419a57 | 35.842857 | 127 | 0.692904 | 4.978764 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Nodes/Generators/Oscillators/Oscillator/AKOscillator.swift | 1 | 7246 | //
// AKOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Reads from the table sequentially and repeatedly at given frequency. Linear
/// interpolation is applied for table look up from internal phase values.
///
/// - parameter frequency: Frequency in cycles per second
/// - parameter amplitude: Output Amplitude.
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public class AKOscillator: AKVoice {
// MARK: - Properties
internal var internalAU: AKOscillatorAudioUnit?
internal var token: AUParameterObserverToken?
private var waveform: AKTable?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: 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 {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// In cycles per second, or Hz.
public var frequency: Double = 440 {
willSet {
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 {
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 {
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 {
if detuningMultiplier != newValue {
if internalAU!.isSetUp() {
detuningMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningMultiplier = 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
override public convenience init() {
self.init(waveform: AKTable(.Sine))
}
/// Initialize this oscillator node
///
/// - parameter waveform: The waveform of oscillation
/// - parameter frequency: Frequency in cycles per second
/// - parameter amplitude: Output Amplitude.
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public init(
waveform: AKTable,
frequency: Double = 440,
amplitude: Double = 1,
detuningOffset: Double = 0,
detuningMultiplier: Double = 1) {
self.waveform = waveform
self.frequency = frequency
self.amplitude = amplitude
self.detuningOffset = detuningOffset
self.detuningMultiplier = detuningMultiplier
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x6f73636c /*'oscl'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKOscillatorAudioUnit.self,
asComponentDescription: description,
name: "Local AKOscillator",
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? AKOscillatorAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
self.internalAU?.setupWaveform(Int32(waveform.size))
for i in 0 ..< waveform.size {
self.internalAU?.setWaveformValue(waveform.values[i], atIndex: UInt32(i))
}
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") 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.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?.detuningOffset = Float(detuningOffset)
internalAU?.detuningMultiplier = Float(detuningMultiplier)
}
/// Function create an identical new node for use in creating polyphonic instruments
override public func duplicate() -> AKVoice {
let copy = AKOscillator(waveform: self.waveform!, frequency: self.frequency, amplitude: self.amplitude, detuningOffset: self.detuningOffset, detuningMultiplier: self.detuningMultiplier)
return copy
}
/// Function to start, play, or activate the node, all do the same thing
override public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
override public func stop() {
self.internalAU!.stop()
}
}
| mit | 813a16992e87f4c1c8d071f4b797b7b2 | 34.871287 | 193 | 0.61427 | 5.810746 | false | false | false | false |
russelhampton05/MenMew | App Prototypes/Menu_Server_App_Prototype_001/Menu_Server_App_Prototype_001/RegisterViewController.swift | 1 | 5903 | //
// RegisterViewController.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 9/28/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
import Firebase
class RegisterViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var reenterLabel: UILabel!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var registerLabel: UILabel!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var confirmPasswordField: UITextField!
@IBOutlet weak var confirmRegisterButton: UIButton!
@IBOutlet weak var emailField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
usernameField.delegate = self
passwordField.delegate = self
confirmPasswordField.delegate = self
confirmRegisterButton.isEnabled = false
usernameField.keyboardType = UIKeyboardType.emailAddress
passwordField.isSecureTextEntry = true
confirmPasswordField.isSecureTextEntry = true
usernameField.autocorrectionType = UITextAutocorrectionType.no
passwordField.autocorrectionType = UITextAutocorrectionType.no
confirmPasswordField.autocorrectionType = UITextAutocorrectionType.no
loadTheme()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
let nextResponder = textField.superview?.viewWithTag(nextTag)
if nextResponder != nil {
nextResponder?.becomeFirstResponder()
}
else {
textField.resignFirstResponder()
}
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
if self.usernameField.text != "" && self.passwordField.text != "" && self.confirmPasswordField.text != "" {
confirmRegisterButton.isEnabled = true
}
}
@IBAction func registerButtonPressed(_ sender: AnyObject) {
if self.usernameField.text! == "" || self.passwordField.text! == "" {
showPopup(message: "Please enter an email and password.", isRegister: false)
}
else if self.passwordField.text != self.confirmPasswordField.text {
showPopup(message: "Password entries do not match.", isRegister: false)
self.passwordField.text = ""
self.confirmPasswordField.text = ""
}
else {
FIRAuth.auth()?.createUser(withEmail: self.usernameField.text!, password: self.passwordField.text!, completion: {(user, error) in
if error == nil {
//Add Server to Firebase
self.passwordField.text = ""
self.confirmPasswordField.text = ""
self.showPopup(message: "Thank you for registering, " + self.usernameField.text! + "!", isRegister: true)
self.usernameField.text = ""
}
else {
self.showPopup(message: (error?.localizedDescription)!, isRegister: false)
}
})
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "QRScanSegue" {
//let scanVC = segue.destination as! QRViewController
}
}
func loadTheme() {
currentTheme = Theme.init(type: "Salmon")
UIView.animate(withDuration: 0.8, animations: { () -> Void in
//Background and Tint
self.view.backgroundColor = currentTheme!.primary!
self.view.tintColor = currentTheme!.highlight!
//Labels
self.registerLabel.textColor = currentTheme!.highlight!
self.emailLabel.textColor = currentTheme!.highlight!
self.passwordLabel.textColor = currentTheme!.highlight!
self.reenterLabel.textColor = currentTheme!.highlight!
//Fields
self.usernameField.textColor = currentTheme!.highlight!
self.usernameField.tintColor = currentTheme!.highlight!
self.emailField.textColor = currentTheme!.highlight!
self.emailField.tintColor = currentTheme!.highlight!
self.passwordField.textColor = currentTheme!.highlight!
self.passwordField.tintColor = currentTheme!.highlight!
self.confirmPasswordField.textColor = currentTheme!.highlight!
self.confirmPasswordField.tintColor = currentTheme!.highlight!
//Buttons
self.confirmRegisterButton.backgroundColor = currentTheme!.highlight!
self.confirmRegisterButton.setTitleColor(currentTheme!.primary!, for: .normal)
// self.cancelButton.backgroundColor = currentTheme!.highlight!
// self.cancelButton.setTitleColor(currentTheme!.primary!, for: .normal)
})
}
func showPopup(message: String, isRegister: Bool) {
let loginPopup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Popup") as! PopupViewController
if isRegister {
loginPopup.condition = "RegisterUser"
}
self.addChildViewController(loginPopup)
loginPopup.view.frame = self.view.frame
self.view.addSubview(loginPopup.view)
loginPopup.didMove(toParentViewController: self)
loginPopup.addMessage(context: message)
}
}
| mit | 2451b51805a8c646bb72a48916cc9adc | 36.592357 | 141 | 0.616232 | 5.724539 | false | false | false | false |
Yalantis/AppearanceNavigationController | AppearanceNavigationController/NavigationController/Appearance.swift | 1 | 884 |
import Foundation
import UIKit
public struct Appearance: Equatable {
public struct Bar: Equatable {
var style: UIBarStyle = .default
var backgroundColor = UIColor(red: 234 / 255, green: 46 / 255, blue: 73 / 255, alpha: 1)
var tintColor = UIColor.white
var barTintColor: UIColor?
}
var statusBarStyle: UIStatusBarStyle = .default
var navigationBar = Bar()
var toolbar = Bar()
}
public func ==(lhs: Appearance.Bar, rhs: Appearance.Bar) -> Bool {
return lhs.style == rhs.style &&
lhs.backgroundColor == rhs.backgroundColor &&
lhs.tintColor == rhs.tintColor &&
rhs.barTintColor == lhs.barTintColor
}
public func ==(lhs: Appearance, rhs: Appearance) -> Bool {
return lhs.statusBarStyle == rhs.statusBarStyle && lhs.navigationBar == rhs.navigationBar && lhs.toolbar == rhs.toolbar
}
| mit | 1bd75178bb4239f6586b27c5c52af581 | 29.482759 | 123 | 0.649321 | 4.510204 | false | false | false | false |
superk589/DereGuide | DereGuide/Toolbox/Gacha/Model/GachaOdds.swift | 3 | 3363 | //
// GachaOdds.swift
// DereGuide
//
// Created by zzk on 19/01/2018.
// Copyright © 2018 zzk. All rights reserved.
//
import Foundation
import MessagePack
enum ChargeRarityType: String, Codable {
case ssr
case sr
case r
init(rarityTypes: CGSSRarityTypes) {
switch rarityTypes {
case .ssr:
self = .ssr
case .sr:
self = .sr
default:
self = .r
}
}
}
struct CardOdds: Codable {
var cardID: Int
var chargeOdds: String
var srOdds: String
}
struct GachaOdds: Codable {
static let path = Path.cache + "/Data/Gacha"
private(set) var ssr = [CardOdds]()
private(set) var sr = [CardOdds]()
private(set) var r = [CardOdds]()
var cardIDOdds: [Int: CardOdds] {
let combined = ssr + sr + r
return combined.reduce(into: [Int: CardOdds]()) { dict, odds in
dict[odds.cardID] = odds
}
}
private(set) var chargeRate = [ChargeRarityType: String]()
private(set) var srChargeRate = [ChargeRarityType: String]()
init?(fromMsgPack pack: MessagePackValue) {
guard let rates = pack[.string("data")]?[.string("gacha_rate")] else { return nil }
chargeRate[.r] = rates[.string("charge")]?[.string("r")]?.stringValue ?? ""
chargeRate[.sr] = rates[.string("charge")]?[.string("sr")]?.stringValue ?? ""
chargeRate[.ssr] = rates[.string("charge")]?[.string("ssr")]?.stringValue ?? ""
srChargeRate[.r] = rates[.string("sr")]?[.string("r")]?.stringValue ?? ""
srChargeRate[.sr] = rates[.string("sr")]?[.string("sr")]?.stringValue ?? ""
srChargeRate[.ssr] = rates[.string("sr")]?[.string("ssr")]?.stringValue ?? ""
guard let idols = pack[.string("data")]?[.string("idol_list")] else { return nil }
let mapInnerPack: (MessagePackValue) -> CardOdds = { pack in
let id = Int(pack[.string("card_id")]?.unsignedIntegerValue ?? 0)
let chargeOdds = pack[.string("charge_odds")]?.stringValue ?? ""
let srOdds = pack[.string("sr_odds")]?.stringValue ?? ""
return CardOdds(cardID: id, chargeOdds: chargeOdds, srOdds: srOdds)
}
ssr = idols[.string("ssr")]?.arrayValue?.map(mapInnerPack) ?? []
sr = idols[.string("sr")]?.arrayValue?.map(mapInnerPack) ?? []
r = idols[.string("r")]?.arrayValue?.map(mapInnerPack) ?? []
guard (ssr + sr + r).count > 0 else { return nil }
}
init?(fromCachedDataByGachaID gachaID: Int) {
let url = URL(fileURLWithPath: GachaOdds.path + "/\(gachaID).json")
if let data = try? Data(contentsOf: url), let odds = try? JSONDecoder().decode(GachaOdds.self, from: data), odds.ssr.count > 0 {
self = odds
} else {
return nil
}
}
func save(gachaID: Int) throws {
if !FileManager.default.fileExists(atPath: GachaOdds.path) {
try FileManager.default.createDirectory(atPath: GachaOdds.path, withIntermediateDirectories: true, attributes: nil)
}
let url = URL(fileURLWithPath: GachaOdds.path + "/\(gachaID).json")
let data = try JSONEncoder().encode(self)
try data.write(to: url)
}
}
| mit | 9b8e19b4b81335dd9791d6ccca903015 | 31.019048 | 136 | 0.56395 | 3.686404 | false | false | false | false |
vmanot/swift-package-manager | Sources/Commands/UserToolchain.swift | 1 | 4261 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import POSIX
import Basic
import Build
import PackageLoading
import protocol Build.Toolchain
import Utility
#if os(macOS)
private let whichClangArgs = ["xcrun", "--find", "clang"]
#else
private let whichClangArgs = ["which", "clang"]
#endif
/// Concrete object for manifest resource provider.
private struct UserManifestResources: ManifestResourceProvider {
let swiftCompiler: AbsolutePath
let libDir: AbsolutePath
let sdkRoot: AbsolutePath?
}
public struct UserToolchain: Toolchain {
/// The manifest resource provider.
public let manifestResources: ManifestResourceProvider
/// Path of the `swiftc` compiler.
public let swiftCompiler: AbsolutePath
/// Path of the `clang` compiler.
public let clangCompiler: AbsolutePath
public let extraCCFlags: [String]
public let extraSwiftCFlags: [String]
public var extraCPPFlags: [String] {
return destination.extraCPPFlags
}
public var dynamicLibraryExtension: String {
return destination.dynamicLibraryExtension
}
/// Path of the `swift` interpreter.
public var swiftInterpreter: AbsolutePath {
return swiftCompiler.parentDirectory.appending(component: "swift")
}
/// Path to llbuild.
let llbuild: AbsolutePath
/// The compilation destination object.
let destination: Destination
public init(destination: Destination) throws {
self.destination = destination
// Get the search paths from PATH.
let envSearchPaths = getEnvSearchPaths(
pathString: getenv("PATH"), currentWorkingDirectory: currentWorkingDirectory)
func lookup(fromEnv: String) -> AbsolutePath? {
return lookupExecutablePath(
filename: getenv(fromEnv),
searchPaths: envSearchPaths)
}
// Get the binDir from destination.
let binDir = destination.binDir
// First look in env and then in bin dir.
swiftCompiler = lookup(fromEnv: "SWIFT_EXEC") ?? binDir.appending(component: "swiftc")
// Check that it's valid in the file system.
guard localFileSystem.isExecutableFile(swiftCompiler) else {
throw Error.invalidToolchain(problem: "could not find `swiftc` at expected path \(swiftCompiler.asString)")
}
// Look for llbuild in bin dir.
llbuild = binDir.appending(component: "swift-build-tool")
guard localFileSystem.exists(llbuild) else {
throw Error.invalidToolchain(problem: "could not find `llbuild` at expected path \(llbuild.asString)")
}
// Find the Clang compiler, looking first in the environment.
if let value = lookup(fromEnv: "CC") {
clangCompiler = value
} else {
// No value in env, so search for `clang`.
let foundPath = try Process.checkNonZeroExit(arguments: whichClangArgs).chomp()
guard !foundPath.isEmpty else {
throw Error.invalidToolchain(problem: "could not find `clang`")
}
clangCompiler = AbsolutePath(foundPath)
}
// Check that it's valid in the file system.
guard localFileSystem.isExecutableFile(clangCompiler) else {
throw Error.invalidToolchain(problem: "could not find `clang` at expected path \(clangCompiler.asString)")
}
self.extraSwiftCFlags = [
"-target", destination.target,
"-sdk", destination.sdk.asString
] + destination.extraSwiftCFlags
self.extraCCFlags = [
"-target", destination.target,
"--sysroot", destination.sdk.asString
] + destination.extraCCFlags
manifestResources = UserManifestResources(
swiftCompiler: swiftCompiler,
libDir: binDir.parentDirectory.appending(components: "lib", "swift", "pm"),
sdkRoot: self.destination.sdk
)
}
}
| apache-2.0 | 2922dfaf16f2ade8bf2427f04297d738 | 32.031008 | 119 | 0.665337 | 4.989461 | false | false | false | false |
nua-schroers/mvvm-frp | 42_MVVM_FRP-App_WarningDialog/MatchGame/MatchGame/ViewModel/PresentDialog.swift | 3 | 1274 | //
// CanPresentDialog.swift
// MatchGame
//
// Created by Dr. Wolfram Schroers on 5/27/16.
// Copyright © 2016 Wolfram Schroers. All rights reserved.
//
import Foundation
import ReactiveSwift
import ReactiveCocoa
/// Container describing a dialog handled by `PresentDialog`.
struct DialogContext {
/// Designated initializer.
init(title: String,
message: String,
okButtonText: String,
action: @escaping () -> Void = {},
hasCancel: Bool = false) {
self.title = title
self.message = message
self.okButtonText = okButtonText
self.action = action
self.hasCancel = hasCancel
}
/// Dialog title.
let title: String
/// Dialog message.
let message: String
/// Text of "Ok" button.
let okButtonText: String
/// Action to be taken once user taps "Ok".
let action: () -> Void
/// Whether or not the dialog has a "Cancel" button.
let hasCancel: Bool
}
/// Generic view controller functionality for presenting a dialog with a main action.
protocol PresentDialog: class {
/// Present a dialog with a title, a message, a main action and whether it should have a "Cancel" button.
var dialogSignal: Signal<DialogContext, Never> { get }
}
| mit | 76a8e136263f66936d0c7754c461342f | 24.46 | 109 | 0.651218 | 4.300676 | false | false | false | false |
mownier/photostream | Photostream/Modules/Home/Wireframe/HomeWireframe.swift | 1 | 1152 | //
// HomeWireframe.swift
// Photostream
//
// Created by Mounir Ybanez on 15/08/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
class HomeWireframe: HomeWireframeInterface {
lazy var dependencies: [HomeModuleDependency]? = [HomeModuleDependency]()
var root: RootWireframeInterface?
required init(root: RootWireframeInterface?, view: HomeViewInterface) {
self.root = root
let presenter = HomePresenter()
presenter.view = view
presenter.wireframe = self
view.presenter = presenter
}
func attachRoot(with controller: UIViewController, in window: UIWindow) {
root?.showRoot(with: controller, in: window)
}
func dependency<T>() -> T? {
guard dependencies != nil, dependencies!.count > 0 else {
return nil
}
let result = dependencies!.filter { (dependency) -> Bool in
return type(of: dependency) == T.self
}
guard result.count > 0 else {
return nil
}
return result[0] as? T
}
}
| mit | c2d7b9b2d405d635b259baa1a3982842 | 24.021739 | 77 | 0.586447 | 4.775934 | false | false | false | false |
crypton-watanabe/morurun-ios | morurun/views/PostingView/PostingViewModel.swift | 1 | 9566 | //
// PostingViewModel.swift
// morurun
//
// Created by watanabe on 2016/11/06.
// Copyright © 2016年 Crypton Future Media, INC. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import AVFoundation
import Alamofire
import RxAlamofire
class PostingViewModel : ReactiveCompatible {
private let disposeBag = DisposeBag()
let comment = Variable<String?>("")
let image = Variable<UIImage?>(nil)
let movieUrl = Variable<URL?>(nil)
let isValid = Variable<Bool>(false)
let thumbnail = Variable<UIImage?>(nil)
let errorMessage = Variable<String>("")
let location = Variable<Location?>(nil)
init() {
self.image.asObservable()
.bindTo(self.thumbnail)
.addDisposableTo(self.disposeBag)
self.movieUrl
.asObservable()
.map { url -> UIImage? in
var thumbnailImage: UIImage?
guard let movieUrl = url else { return nil }
let avAsset = AVURLAsset(url: movieUrl)
let imageGenerator = AVAssetImageGenerator(asset: avAsset)
imageGenerator.appliesPreferredTrackTransform = true
let ctTime = CMTime(seconds: 0.0, preferredTimescale: 30)
if let cgImage = try? imageGenerator.copyCGImage(at: ctTime, actualTime: nil) {
thumbnailImage = UIImage(cgImage: cgImage)
}
return thumbnailImage
}
.subscribeOn(SerialDispatchQueueScheduler(qos: .default))
.observeOn(MainScheduler.instance)
.bindNext({[unowned self] image in
assert(Thread.current.isMainThread)
self.thumbnail.value = image
})
.addDisposableTo(self.disposeBag)
Observable.combineLatest(self.comment.asObservable(),
self.image.asObservable(),
self.movieUrl.asObservable(),
resultSelector:{ ($0, $1, $2) } )
.bindNext { comment, image, url in
if image == nil && url == nil {
self.isValid.value = false
self.errorMessage.value = NSLocalizedString("写真/動画を選択して下さい", comment: "")
return
}
let trimString = (comment as NSString?)?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let charCount = trimString?.lengthOfBytes(using: String.Encoding.utf8) ?? 0
guard charCount > 0 else {
self.isValid.value = false
self.errorMessage.value = NSLocalizedString("コメントを入力して下さい", comment: "")
return
}
self.isValid.value = true
self.errorMessage.value = ""
}
.addDisposableTo(self.disposeBag)
}
}
extension Reactive where Base: PostingViewModel {
private func postImage(request: URLRequest, image: UIImage) -> Observable<Float> {
return Observable.create { observer in
guard let data = UIImageJPEGRepresentation(image, 0.7) else {
observer.onError(RegistrationDialogViewModel.Error.deserializationError)
return Disposables.create { }
}
let uploadTask = Alamofire.upload(data, with: request)
let responseDisposable = uploadTask
.rx
.responseJSON()
.subscribe(onNext: nil,
onError: {observer.onError($0)},
onCompleted: {observer.onCompleted()},
onDisposed: nil)
let progressDisposable = Observable<Int>
.interval(0.3, scheduler: MainScheduler.instance)
.bindNext { _ in
let comleted = Float(uploadTask.uploadProgress.completedUnitCount)
let total = Float(uploadTask.uploadProgress.totalUnitCount)
var progress = comleted / total / 2 + 0.5
if progress.isNaN { progress = 0 }
observer.onNext(progress) }
return Disposables.create { responseDisposable.dispose(); progressDisposable.dispose() }
}
}
private func exportMovie(sourceUrl: URL, destUrl: URL) -> Observable<Float> {
return Observable.create { observer in
guard let exportSession = AVAssetExportSession(asset: AVAsset(url: sourceUrl), presetName: AVAssetExportPresetHighestQuality) else {
observer.onError(RegistrationDialogViewModel.Error.deserializationError)
return Disposables.create { }
}
exportSession.outputFileType = AVFileTypeQuickTimeMovie
exportSession.outputURL = destUrl
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously(completionHandler: {
if let error = exportSession.error {
observer.onError(error)
}
else {
observer.onCompleted()
}
})
let disposable = Observable<Int>
.interval(0.3, scheduler: MainScheduler.instance)
.bindNext { _ in
var progress = exportSession.progress / 2
if progress.isNaN { progress = 0 }
observer.onNext(progress)
}
return Disposables.create { disposable.dispose() }
}
}
private func sendMovie(request: URLRequest, url: URL) -> Observable<Float> {
return Observable.create { observer in
let uploadTask = Alamofire.upload(url, with: request)
let responseDisposable = uploadTask
.rx
.responseJSON()
.subscribe(onNext: nil,
onError: {observer.onError($0)},
onCompleted: {observer.onCompleted()},
onDisposed: nil)
let progressDisposable = Observable<Int>
.interval(0.3, scheduler: MainScheduler.instance)
.bindNext { _ in
let completed = Float(uploadTask.uploadProgress.completedUnitCount)
let total = Float(uploadTask.uploadProgress.totalUnitCount)
var progress = completed / total / 2 + 0.5
if progress.isNaN { progress = 0 }
observer.onNext(progress) }
return Disposables.create { responseDisposable.dispose(); progressDisposable.dispose() }
}
}
private func postMovie(request: URLRequest, url: URL) -> Observable<Float> {
return Observable.create { observer in
var tmpFileUrl = URL(fileURLWithPath: NSTemporaryDirectory())
tmpFileUrl.appendPathComponent(UUID().uuidString)
let export = self.exportMovie(sourceUrl: url, destUrl: tmpFileUrl)
let send = self.sendMovie(request: request, url: tmpFileUrl)
let disposable = export.concat(send).asObservable()
.asObservable()
.subscribe(observer)
return Disposables.create {
disposable.dispose()
_ = try? FileManager().removeItem(at: tmpFileUrl)
}
}
}
func postData() -> Observable<Float> {
return Observable.create { observer in
let location = AppDelegate.shared.userLocation.currentLocation.value
var headers = [String : String]()
headers["Content-Type"] = "undefined"
headers["uid"] = AppConfig.shared.uid.value ?? ""
headers["type"] = self.base.image.value == nil ? "1" : "2"
headers["comment"] = self.base.comment.value?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
if let location = self.base.location.value {
headers["location_id"] = "\(location.location_id)"
}
else {
headers["location_id"] = ""
}
headers["latitude"] = "\(location?.coordinate.latitude ?? 0)"
headers["longitude"] = "\(location?.coordinate.longitude ?? 0)"
guard var request = try? urlRequest(.post, URLManager.shared.postData, headers: headers) else {
observer.onError(RegistrationDialogViewModel.Error.requestGenerateError)
return Disposables.create {}
}
request.timeoutInterval = Bundle.main.infoDictionary!["RequestTimeoutInterval"] as! Double
var disposable: Disposable?
if let image = self.base.image.value {
disposable = self.postImage(request: request, image: image)
.asObservable()
.subscribe(observer)
}
else if let url = self.base.movieUrl.value {
disposable = self.postMovie(request: request, url: url)
.asObservable()
.subscribe(observer)
}
return Disposables.create { disposable?.dispose() }
}
}
}
| mit | e29d675f95c8a8cdc3ea68e228efcd2e | 41.10177 | 144 | 0.549764 | 5.643535 | false | false | false | false |
maxbilbow/iOS-8-SceneKit-Globe-Test | SceneKitTest/GameViewController.swift | 2 | 3628 | //
// GameViewController.swift
// SceneKitTest
//
// Created by Jonathan Wight on 6/6/14.
// Copyright (c) 2014 schwa.io. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = GlobeScene()
// create and add a light to the scene
let lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light?.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
// let ambientLightNode = SCNNode()
// ambientLightNode.light = SCNLight()
// ambientLightNode.light.type = SCNLightTypeAmbient
// ambientLightNode.light.color = UIColor.darkGrayColor()
// scene.rootNode.addChildNode(ambientLightNode)
// retrieve the SCNView
let scnView = self.view as SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.blackColor()
// add a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
let gestureRecognizers = NSMutableArray()
gestureRecognizers.addObject(tapGesture)
if let arr = scnView.gestureRecognizers { gestureRecognizers.addObjectsFromArray(arr) }
scnView.gestureRecognizers = gestureRecognizers
}
func handleTap(gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let scnView = self.view as SCNView
// check what nodes are tapped
let p = gestureRecognize.locationInView(scnView)
let hitResults = scnView.hitTest(p, options: nil)
// check that we clicked on at least one object
if hitResults?.count > 0 {
// retrieved the first clicked object
let result: AnyObject! = hitResults?[0]
// get its material
let material = result.node!.geometry?.firstMaterial
// highlight it
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - unhighlight
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
material?.emission.contents = UIColor.blackColor()
SCNTransaction.commit()
}
material?.emission.contents = UIColor.redColor()
SCNTransaction.commit()
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| bsd-2-clause | 77cf6ec61bf48e6975175f440f1a7027 | 31.684685 | 95 | 0.605568 | 5.795527 | false | false | false | false |
alleycat-at-git/Atom | Example/Atom/View/MainCell.swift | 1 | 1181 | //
// MainCell.swift
// Atom
//
// Created by Алексей Карасев on 18/06/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
class MainCell: UITableViewCell, AtomComponent {
struct Props {
let key: Int
let title: String
let status: Bool
}
var props: Props! {
didSet {
render()
}
}
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var statusSwitch: UISwitch!
@IBOutlet weak var statusLabel: UILabel!
func render() {
guard props != nil else { return }
titleLabel.text = props.title
statusSwitch.on = props.status
statusLabel.text = props.status ? "On" : "Off"
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func switchClicked(sender: AnyObject) {
guard props != nil else { return }
Actions.instance.toggleTodo(props.key)
}
}
| mit | dc2d1e48ecab6109d6f767f5c880f1ef | 21.862745 | 63 | 0.601201 | 4.318519 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/SelfProfile/DotView.swift | 1 | 3993 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireSyncEngine
final class DotView: UIView {
fileprivate let circleView = ShapeView()
fileprivate let centerView = ShapeView()
private var userObserver: NSObjectProtocol!
private var clientsObserverTokens: [NSObjectProtocol] = []
private let user: ZMUser?
public var hasUnreadMessages: Bool = false {
didSet { self.updateIndicator() }
}
var showIndicator: Bool {
get {
return !isHidden
}
set {
isHidden = !newValue
}
}
init(user: ZMUser? = nil) {
self.user = user
super.init(frame: .zero)
isHidden = true
circleView.pathGenerator = {
return UIBezierPath(ovalIn: CGRect(origin: .zero, size: $0))
}
circleView.hostedLayer.lineWidth = 0
circleView.hostedLayer.fillColor = UIColor.white.cgColor
centerView.pathGenerator = {
return UIBezierPath(ovalIn: CGRect(origin: .zero, size: $0))
}
centerView.hostedLayer.fillColor = UIColor.accent().cgColor
addSubview(circleView)
addSubview(centerView)
createConstraints()
if let userSession = ZMUserSession.shared(),
let user = user {
userObserver = UserChangeInfo.add(observer: self, for: user, in: userSession)
}
createClientObservers()
}
private func createConstraints() {
[self, circleView, centerView].prepareForLayout()
let centerViewConstraints = centerView.fitInConstraints(view: self, inset: 1)
NSLayoutConstraint.activate([
circleView.topAnchor.constraint(equalTo: topAnchor),
circleView.bottomAnchor.constraint(equalTo: bottomAnchor),
circleView.leftAnchor.constraint(equalTo: leftAnchor),
circleView.rightAnchor.constraint(equalTo: rightAnchor)] + centerViewConstraints)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func createClientObservers() {
guard let user = user else { return }
clientsObserverTokens = user.clients.map { UserClientChangeInfo.add(observer: self, for: $0) }
}
func updateIndicator() {
showIndicator = hasUnreadMessages ||
user?.clientsRequiringUserAttention.count > 0 ||
user?.readReceiptsEnabledChangedRemotely == true
}
}
extension DotView: ZMUserObserver {
func userDidChange(_ changeInfo: UserChangeInfo) {
guard changeInfo.trustLevelChanged ||
changeInfo.clientsChanged ||
changeInfo.accentColorValueChanged ||
changeInfo.readReceiptsEnabledChanged ||
changeInfo.readReceiptsEnabledChangedRemotelyChanged else { return }
centerView.hostedLayer.fillColor = UIColor.accent().cgColor
updateIndicator()
if changeInfo.clientsChanged {
createClientObservers()
}
}
}
// MARK: - Clients observer
extension DotView: UserClientObserver {
func userClientDidChange(_ changeInfo: UserClientChangeInfo) {
guard changeInfo.needsToNotifyUserChanged else { return }
updateIndicator()
}
}
| gpl-3.0 | e6bba24abd9abecc6944ac09d3acf384 | 30.440945 | 102 | 0.660155 | 5.028967 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDKTests/MockObjects/MockActivityManager.swift | 1 | 6339 | //
// MockActivityManager.swift
// BridgeAppSDK
//
// Copyright © 2017 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
@testable import BridgeAppSDK
class MockActivityManager : NSObject, SBBActivityManagerProtocol {
fileprivate let taskQueue = DispatchQueue(label: UUID().uuidString)
// MARK: getScheduledActivities
var getScheduledActivities_Result: [SBBScheduledActivity]?
var getScheduledActivities_Error: Error?
var getScheduledActivities_called: Bool = false
var getScheduledActivities_daysAhead: Int = 0
var getScheduledActivities_daysBehind: Int = 0
var getScheduledActivities_cachingPolicy: SBBCachingPolicy = SBBCachingPolicy.noCaching
func getScheduledActivities(forDaysAhead daysAhead: Int, daysBehind: Int, cachingPolicy policy: SBBCachingPolicy, withCompletion completion: @escaping SBBActivityManagerGetCompletionBlock) -> URLSessionTask {
getScheduledActivities_called = true
getScheduledActivities_daysAhead = daysAhead
getScheduledActivities_daysBehind = daysBehind
getScheduledActivities_cachingPolicy = policy
taskQueue.async {
completion(self.getScheduledActivities_Result, self.getScheduledActivities_Error)
}
return URLSessionTask()
}
func getScheduledActivities(forDaysAhead daysAhead: Int, cachingPolicy policy: SBBCachingPolicy, withCompletion completion: @escaping SBBActivityManagerGetCompletionBlock) -> URLSessionTask {
return self.getScheduledActivities(forDaysAhead: daysAhead, daysBehind: 0, cachingPolicy: policy, withCompletion: completion)
}
func getScheduledActivities(forDaysAhead daysAhead: Int, withCompletion completion: @escaping SBBActivityManagerGetCompletionBlock) -> URLSessionTask {
return self.getScheduledActivities(forDaysAhead: daysAhead, daysBehind: 0, cachingPolicy: .noCaching, withCompletion: completion)
}
func getCachedSchedules(using predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]?, fetchLimit: UInt) throws -> [SBBScheduledActivity] {
return []
}
// MARK: Not implemented
func start(_ scheduledActivity: SBBScheduledActivity, asOf startDate: Date, withCompletion completion: SBBActivityManagerUpdateCompletionBlock? = nil) -> URLSessionTask {
return URLSessionTask()
}
func finish(_ scheduledActivity: SBBScheduledActivity, asOf finishDate: Date, withCompletion completion: SBBActivityManagerUpdateCompletionBlock? = nil) -> URLSessionTask {
return URLSessionTask()
}
func delete(_ scheduledActivity: SBBScheduledActivity, withCompletion completion: SBBActivityManagerUpdateCompletionBlock? = nil) -> URLSessionTask {
return URLSessionTask()
}
func setClientData(_ clientData: SBBJSONValue, for scheduledActivity: SBBScheduledActivity, withCompletion completion: SBBActivityManagerUpdateCompletionBlock? = nil) -> URLSessionTask {
return URLSessionTask()
}
public func updateScheduledActivities(_ scheduledActivities: [Any], withCompletion completion: SBBActivityManagerUpdateCompletionBlock? = nil) -> URLSessionTask {
return URLSessionTask()
}
// MARK: getScheduledActivitiesForGuid
var getScheduledActivitiesForRange_Result: [SBBScheduledActivity]?
var getScheduledActivitiesForRange_Error: Error?
var getScheduledActivitiesForRange_called: Bool = false
var getScheduledActivitiesForRange_scheduledFrom: Date?
var getScheduledActivitiesForRange_scheduledTo: Date?
var getScheduledActivitiesForRange_cachingPolicy: SBBCachingPolicy = SBBCachingPolicy.noCaching
public func getScheduledActivities(from scheduledFrom: Date, to scheduledTo: Date, cachingPolicy policy: SBBCachingPolicy, withCompletion completion: @escaping SBBActivityManagerGetCompletionBlock) -> URLSessionTask {
getScheduledActivitiesForRange_called = true
getScheduledActivitiesForRange_scheduledFrom = scheduledFrom
getScheduledActivitiesForRange_scheduledTo = scheduledTo
getScheduledActivitiesForRange_cachingPolicy = policy
taskQueue.async {
completion(self.getScheduledActivitiesForRange_Result, self.getScheduledActivitiesForRange_Error)
}
return URLSessionTask()
}
public func getScheduledActivities(from scheduledFrom: Date, to scheduledTo: Date, withCompletion completion: @escaping SBBActivityManagerGetCompletionBlock) -> URLSessionTask {
return getScheduledActivities(from: scheduledFrom, to: scheduledTo, cachingPolicy: .fallBackToCached, withCompletion: completion)
}
}
| bsd-3-clause | db7b04104bcbcd03cf944f39322ec212 | 47.015152 | 221 | 0.763806 | 5.246689 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-422/SafeRide/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift | 8 | 12154 | //
// SHA2.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 24/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
final class SHA2 : HashProtocol {
var size:Int { return variant.rawValue }
let variant:SHA2.Variant
let message: [UInt8]
init(_ message:[UInt8], variant: SHA2.Variant) {
self.variant = variant
self.message = message
}
enum Variant: RawRepresentable {
case sha224, sha256, sha384, sha512
typealias RawValue = Int
var rawValue: RawValue {
switch (self) {
case .sha224:
return 224
case .sha256:
return 256
case .sha384:
return 384
case .sha512:
return 512
}
}
init?(rawValue: RawValue) {
switch (rawValue) {
case 224:
self = .sha224
break;
case 256:
self = .sha256
break;
case 384:
self = .sha384
break;
case 512:
self = .sha512
break;
default:
return nil
}
}
var size:Int { return self.rawValue }
private var h:[UInt64] {
switch (self) {
case .sha224:
return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]
case .sha256:
return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
case .sha384:
return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4]
case .sha512:
return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179]
}
}
private var k:[UInt64] {
switch (self) {
case .sha224, .sha256:
return [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]
case .sha384, .sha512:
return [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538,
0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe,
0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235,
0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab,
0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725,
0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed,
0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218,
0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53,
0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373,
0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c,
0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6,
0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc,
0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817]
}
}
private func resultingArray<T>(hh:[T]) -> ArraySlice<T> {
switch (self) {
case .sha224:
return hh[0..<7]
case .sha384:
return hh[0..<6]
default:
break;
}
return ArraySlice(hh)
}
}
//FIXME: I can't do Generic func out of calculate32 and calculate64 (UInt32 vs UInt64), but if you can - please do pull request.
func calculate32() -> [UInt8] {
var tmpMessage = self.prepare(64)
// hash values
var hh = [UInt32]()
variant.h.forEach {(h) -> () in
hh.append(UInt32(h))
}
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage += (message.count * 8).bytes(64 / 8)
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 32-bit words into sixty-four 32-bit words:
var M:[UInt32] = [UInt32](count: variant.k.count, repeatedValue: 0)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex + (x * sizeofValue(M[x]))
let end = start + sizeofValue(M[x])
let le = toUInt32Array(chunk[start..<end])[0]
M[x] = le.bigEndian
break
default:
let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n
let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10)
M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
var F = hh[5]
var G = hh[6]
var H = hh[7]
// Main loop
for j in 0..<variant.k.count {
let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22)
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ UInt32(variant.k[j]) &+ M[j]
H = G
G = F
F = E
E = D &+ t1
D = C
C = B
B = A
A = t1 &+ t2
}
hh[0] = (hh[0] &+ A)
hh[1] = (hh[1] &+ B)
hh[2] = (hh[2] &+ C)
hh[3] = (hh[3] &+ D)
hh[4] = (hh[4] &+ E)
hh[5] = (hh[5] &+ F)
hh[6] = (hh[6] &+ G)
hh[7] = (hh[7] &+ H)
}
// Produce the final hash value (big-endian) as a 160 bit number:
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
variant.resultingArray(hh).forEach {
let item = $0.bigEndian
result += [UInt8(item & 0xff), UInt8((item >> 8) & 0xff), UInt8((item >> 16) & 0xff), UInt8((item >> 24) & 0xff)]
}
return result
}
func calculate64() -> [UInt8] {
var tmpMessage = self.prepare(128)
// hash values
var hh = [UInt64]()
variant.h.forEach {(h) -> () in
hh.append(h)
}
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage += (message.count * 8).bytes(64 / 8)
// Process the message in successive 1024-bit chunks:
let chunkSizeBytes = 1024 / 8 // 128
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 64-bit words into eighty 64-bit words:
var M = [UInt64](count: variant.k.count, repeatedValue: 0)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex + (x * sizeofValue(M[x]))
let end = start + sizeofValue(M[x])
let le = toUInt64Array(chunk[start..<end])[0]
M[x] = le.bigEndian
break
default:
let s0 = rotateRight(M[x-15], n: 1) ^ rotateRight(M[x-15], n: 8) ^ (M[x-15] >> 7)
let s1 = rotateRight(M[x-2], n: 19) ^ rotateRight(M[x-2], n: 61) ^ (M[x-2] >> 6)
M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1
break
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
var F = hh[5]
var G = hh[6]
var H = hh[7]
// Main loop
for j in 0..<variant.k.count {
let s0 = rotateRight(A,n: 28) ^ rotateRight(A,n: 34) ^ rotateRight(A,n: 39) //FIXME: n:
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E,n: 14) ^ rotateRight(E,n: 18) ^ rotateRight(E,n: 41)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ variant.k[j] &+ UInt64(M[j])
H = G
G = F
F = E
E = D &+ t1
D = C
C = B
B = A
A = t1 &+ t2
}
hh[0] = (hh[0] &+ A)
hh[1] = (hh[1] &+ B)
hh[2] = (hh[2] &+ C)
hh[3] = (hh[3] &+ D)
hh[4] = (hh[4] &+ E)
hh[5] = (hh[5] &+ F)
hh[6] = (hh[6] &+ G)
hh[7] = (hh[7] &+ H)
}
// Produce the final hash value (big-endian)
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
variant.resultingArray(hh).forEach {
let item = $0.bigEndian
var partialResult = [UInt8]()
partialResult.reserveCapacity(8)
for i in 0..<8 {
let shift = UInt64(8 * i)
partialResult.append(UInt8((item >> shift) & 0xff))
}
result += partialResult
}
return result
}
} | gpl-3.0 | 5baf42c38d0ffbcad19264a311e662bd | 41.472028 | 183 | 0.502305 | 3.04793 | false | false | false | false |
raulriera/HuntingCompanion | ProductHunt/PostVotesCollectionViewController.swift | 1 | 1250 | //
// PostVotesCollectionViewController.swift
// ProductHunt
//
// Created by Raúl Riera on 14/05/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
import HuntingKit
class PostVotesCollectionViewController: UICollectionViewController {
var votes:[Vote] = [Vote]() {
didSet {
collectionView?.reloadData()
}
}
// MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let insets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
collectionView?.scrollIndicatorInsets = insets
collectionView?.contentInset = insets
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return votes.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(.VoteCollectionViewCell, forIndexPath: indexPath) as! VoteCollectionViewCell
// Configure the cell
cell.vote = votes[indexPath.row]
return cell
}
}
| mit | 5f573ffeaa433ba2e625e5f6540f6701 | 26.755556 | 139 | 0.681345 | 5.406926 | false | false | false | false |
RedRoma/Lexis | Code/Lexis/SimpleShareViewController.swift | 1 | 2029 | //
// SimpleShareViewController.swift
// Lexis
//
// Created by Wellington Moreno on 9/28/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import Foundation
import LexisDatabase
import Archeota
class SimpleShareViewController: UIViewController
{
@IBOutlet weak var wordNameLabel: UILabel!
@IBOutlet weak var wordTypeLabel: UILabel!
@IBOutlet weak var definitionLabel1: UILabel!
@IBOutlet weak var definitionLabel2: UILabel!
@IBOutlet weak var definitionLabel3: UILabel!
@IBOutlet weak var definitionLabel4: UILabel!
@IBOutlet weak var definitionLabel5: UILabel!
private var definitionLabels: [UILabel]
{
return [definitionLabel1, definitionLabel2, definitionLabel3, definitionLabel4, definitionLabel5]
}
var word: LexisWord!
override func viewDidLoad()
{
guard word != nil else { return }
setupView()
}
private func setupView()
{
wordNameLabel.text = word.forms.joined(separator: ", ")
wordTypeLabel.text = word.wordTypeInfo
hideDefinitionLabels()
let definitions: [String] = word.definitions.flatMap() { $0.terms.joined(separator: ", ") }
setDefinitions(definitions)
}
private func hideDefinitionLabels()
{
definitionLabels.forEach() { $0.isHidden = true }
}
private func show(_ view: UIView)
{
view.isHidden = false
}
private func setDefinitions(_ definitions: [String])
{
let amount = definitions.count
guard amount > 0 else { return }
for (index, definition) in definitions.enumerated()
{
guard index.isValidIndexFor(array: definitionLabels) else { continue }
let text = definition.removingFirstCharacterIfWhitespace()
let label = definitionLabels[index]
show(label)
label.text = "‣ \(text)"
}
}
}
| apache-2.0 | 488a70796e23241258c2aec1b68e174d | 25.311688 | 105 | 0.617966 | 4.800948 | false | false | false | false |
the-grid/Disc | Disc/Networking/Authorization/RequestEmailLogin.swift | 1 | 1428 | import Result
import Swish
private struct GetEmailLoginRequest: Request {
typealias ResponseObject = Bool
typealias ResponseParser = StringParser
fileprivate static let authSendUrl = "api/auth/send"
let url: String
let body: [String: String]
init(clientId: String, redirectUri:String, email: String) {
url = GetEmailLoginRequest.authSendUrl
body = createRequestParameters(clientId: clientId, redirectUri: redirectUri, email: email)
}
func build() -> URLRequest {
return createRequest(.POST, url, body: body as [String : AnyObject]?) as URLRequest
}
fileprivate func parse(_ s: String) -> Result<Bool, SwishError> {
return Result(true)
}
}
public extension APIClient {
/// Get a Passport access token using a Passport auth `code`.
///
/// - parameter clientId: The unique identifier of your application.
/// - parameter redirectUri: The redirect URI for the `provider`.
/// - parameter email: The email address associated with the account.
static func requestEmailLogin(_ clientId: String, redirectUri:String, email: String, completionHandler: @escaping (Result<Bool, SwishError>) -> Void) {
let request = GetEmailLoginRequest(clientId: clientId, redirectUri: redirectUri, email: email)
let _ = staticJsonlessClient.performRequest(request, completionHandler: completionHandler)
}
}
| mit | e9c421dfe42bf1d0857cb506328febdc | 37.594595 | 155 | 0.696779 | 4.808081 | false | false | false | false |
Olinguito/YoIntervengoiOS | Yo Intervengo/Helpers/RadialMenu/JOCentralMenu.swift | 1 | 3865 | //
// JOSideBarMenu.swift
// Yo Intervengo
//
// Created by Jorge Raul Ovalle Zuleta on 1/24/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import UIKit
@objc protocol JOCentralMenuDelegate{
optional func buttoTapped(button:UIButton!,withCentralBar sideBar:JOCentralMenu)
}
class JOCentralMenu: UIView,UICollectionViewDataSource,UICollectionViewDelegate,JOSideBarMenuDelegate {
var collectionView:UICollectionView!
var data:NSMutableArray!
var delegate:JOCentralMenuDelegate?
var type:Int!
init(frame: CGRect, data: NSMutableArray?, type:Int) {
super.init(frame: frame)
self.data = data
self.type = type
let coll = UICollectionViewFlowLayout()
coll.scrollDirection = UICollectionViewScrollDirection.Vertical
coll.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
coll.itemSize = CGSize(width: 130, height: 57)
collectionView = UICollectionView(frame: frame, collectionViewLayout: coll)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.clearColor()
collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Top, animated: true)
collectionView.registerNib(UINib(nibName: "SubCategoryCell", bundle: nil), forCellWithReuseIdentifier: "SubCategoryCell")
self.addSubview(collectionView)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//COLLECTION VIEW DELEGATE
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SubCategoryCell", forIndexPath: indexPath) as! SubCategoryCell
cell.layer.shadowColor = UIColor.blackColor().CGColor
cell.layer.shadowOffset = CGSizeMake(0, 1.0)
cell.btnSubCat.addTarget(self, action: Selector("goSubCategory:"), forControlEvents: UIControlEvents.TouchUpInside)
cell.lblSubCat.text = (data.objectAtIndex(indexPath.row) as! Category).name
cell.lblSubCat.textColor = UIColor.addThemeContrast()
cell.alpha = 0
cell.type = self.type
cell.btnSubCat.tag = (data.objectAtIndex(indexPath.row) as! Category).id
return cell
}
func goSubCategory(sender:UIButton!){
self.delegate?.buttoTapped!(sender, withCentralBar: self)
}
func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
UIView.beginAnimations("rotation", context: nil)
UIView.setAnimationDuration(0.8)
cell.alpha = 0
UIView.commitAnimations()
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath){
var s = CGFloat((90.0*M_PI)/180)
var rotation = CATransform3DMakeRotation(s, 0.0, 0.7, 0.4)
cell.layer.shadowColor = UIColor.blackColor().CGColor
cell.layer.shadowOffset = CGSizeMake(0, 0.5)
UIView.beginAnimations("rotation", context: nil)
UIView.setAnimationDuration(0.4)
cell.alpha = 1
cell.layer.shadowOffset = CGSizeMake(0, 0)
UIView.commitAnimations()
}
func closeSideView(){
var pop = POPSpringAnimation(propertyNamed: kPOPViewAlpha)
pop.toValue = 0
self.pop_addAnimation(pop, forKey: "Animation")
removeFromSuperview()
}
}
| mit | 675caa1a56082ff22e33eb4ab37bed2b | 40.117021 | 154 | 0.703493 | 4.88622 | false | false | false | false |
likedan/KDIntroView | Example/IntroViewDemo/IntroViewDemo/FourthView.swift | 1 | 9167 | //
// FourthView.swift
// IntroViewDemo
//
// Created by Kedan Li on 15/7/5.
// Copyright (c) 2015年 TakeFive Interactive. All rights reserved.
//
import UIKit
import KDIntroView
class FourthView: KDIntroView {
@IBOutlet var lab1: UILabel!
@IBOutlet var lab2: UILabel!
@IBOutlet var lab3: UILabel!
@IBOutlet var year: UILabel!
var year1: UIButton!
var year2: UIButton!
var year3: UIButton!
var year4: UIButton!
@IBOutlet var slipBoard: UIView!
@IBOutlet var logo: UIButton!
@IBOutlet var slideBoard: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addYears()
}
func toInitialState(){
self.backgroundColor = UIColor.clear
_ = CGAffineTransform(a: 20, b: 0, c: 0, d: 20, tx: 0, ty: 0)
}
override func moveEverythingAccordingToIndex(_ index: CGFloat){
_ = CGAffineTransform(translationX: index, y: 0) // stay
_ = CGAffineTransform(translationX: index, y: -index / 3) //up
_ = CGAffineTransform(translationX: -index/5, y: 0) //speed1
_ = CGAffineTransform(translationX: index/4, y: 0) //speed2
_ = CGAffineTransform(a: 1 + index / 20, b: 0, c: 0, d: 1 + index / 20, tx: index, ty: 0) //enlarge
if index < 200{
let slideMotion = CGAffineTransform(translationX: -320 + index, y: 200 - index)
slideBoard.transform = slideMotion
}else if index >= 200 && index <= 220 {
slideBoard.transform = CGAffineTransform(translationX: -320 + index, y: 200 - index)
}else if index > 220 && index < 230{
slideBoard.transform = CGAffineTransform(translationX: -320 + index, y: -(230 - index) * 2)
}else if index >= 220 && index <= 320{
slideBoard.transform = CGAffineTransform(translationX: -320 + index, y: 0)
}else if index > 320{
slideBoard.transform = CGAffineTransform(translationX: -320 + index, y: (320 - index) * 2)
}
if index > frame.width * 1.7{
slipBoard.backgroundColor = UIColor.clear
}else{
slipBoard.backgroundColor = UIColor.white
}
if index < 100{
lab1.transform = CGAffineTransform(translationX: 0, y: 200)
lab2.transform = CGAffineTransform(translationX: 0, y: 200)
lab3.transform = CGAffineTransform(translationX: 0, y: 200)
}else if index >= 100 && index <= 140{
lab1.transform = CGAffineTransform(translationX: 0, y: (140 - index) * 5)
lab2.transform = CGAffineTransform(translationX: 0, y: 200)
lab3.transform = CGAffineTransform(translationX: 0, y: 200)
}else if index > 140 && index < 180{
lab1.transform = CGAffineTransform(translationX: 0, y: 0)
lab2.transform = CGAffineTransform(translationX: 0, y: (180 - index) * 5)
lab3.transform = CGAffineTransform(translationX: 0, y: 200)
}else if index >= 180 && index <= 200{
lab1.transform = CGAffineTransform(translationX: 0, y: 0)
lab2.transform = CGAffineTransform(translationX: 0, y: 0)
lab3.transform = CGAffineTransform(translationX: 0, y: (200 - index) * 10)
}else if index > 200{
lab1.transform = CGAffineTransform(translationX: 0, y: 0)
lab2.transform = CGAffineTransform(translationX: 0, y: 0)
lab3.transform = CGAffineTransform(translationX: 0, y: 0)
}
if index < 220{
year1.transform = CGAffineTransform(translationX: 0, y: 0)
year2.transform = CGAffineTransform(translationX: 0, y: 0)
year3.transform = CGAffineTransform(translationX: 0, y: 0)
year4.transform = CGAffineTransform(translationX: 0, y: 0)
}else if index >= 220 && index <= 240{
year1.transform = CGAffineTransform(translationX: -(index - 220) * 15, y: 0)
year2.transform = CGAffineTransform(translationX: 0, y: 0)
year3.transform = CGAffineTransform(translationX: 0, y: 0)
year4.transform = CGAffineTransform(translationX: 0, y: 0)
}else if index > 240 && index < 260{
year1.transform = CGAffineTransform(translationX: -300, y: 0)
year2.transform = CGAffineTransform(translationX: -(index - 240) * 15, y: 0)
year3.transform = CGAffineTransform(translationX: 0, y: 0)
year4.transform = CGAffineTransform(translationX: 0, y: 0)
}else if index >= 260 && index <= 280{
year1.transform = CGAffineTransform(translationX: -300, y: 0)
year2.transform = CGAffineTransform(translationX: -300, y: 0)
year3.transform = CGAffineTransform(translationX: -(index - 260) * 15, y: 0)
year4.transform = CGAffineTransform(translationX: 0, y: 0)
}else if index > 280 && index < 300{
year1.transform = CGAffineTransform(translationX: -300, y: 0)
year2.transform = CGAffineTransform(translationX: -300, y: 0)
year3.transform = CGAffineTransform(translationX: -300, y: 0)
year4.transform = CGAffineTransform(translationX: -(index - 280) * 15, y: 0)
}else if index >= 300 && index <= 320{
year1.transform = CGAffineTransform(translationX: -300 + (index - 300), y: 0)
year2.transform = CGAffineTransform(translationX: -300 + (index - 300), y: 0)
year3.transform = CGAffineTransform(translationX: -300 + (index - 300), y: 0)
year4.transform = CGAffineTransform(translationX: -300 + (index - 300), y: 0)
}else if index > 320{
year1.transform = CGAffineTransform(translationX: -600 + index, y: (320 - index))
year2.transform = CGAffineTransform(translationX: -600 + index, y: (320 - index))
year3.transform = CGAffineTransform(translationX: -600 + index, y: (320 - index))
year4.transform = CGAffineTransform(translationX: -600 + index, y: (320 - index))
}
if index < 320 {
year.transform = CGAffineTransform(translationX: 0, y: 0)
}else if index >= 320{
year.transform = CGAffineTransform(translationX: index - 320, y: (320 - index))
}
if index < 400{
logo.alpha = 0
}else if index >= 400{
logo.alpha = (index - 400) / 200
}
}
func addYears(){
year1 = UIButton(frame: CGRect(x: 320, y: 80, width: 260, height: 90))
let angle = CGAffineTransform(rotationAngle: 0.242);
var line = UIImageView(frame: CGRect(x: -0, y: 40, width: 290, height: 4))
line.backgroundColor = UIColor.white
line.transform = angle
year1.addSubview(line)
var label = UILabel(frame: CGRect(x: -60, y: -40, width: 304, height: 110))
label.text = "2014"
label.font = UIFont(name: "AvenirNext-Medium", size: 32)
label.textAlignment = NSTextAlignment.right
label.textColor = UIColor.white
label.transform = angle
year1.addSubview(label)
addSubview(year1)
year2 = UIButton(frame: CGRect(x: 320, y: 170, width: 260, height: 90))
line = UIImageView(frame: CGRect(x: -0, y: 40, width: 290, height: 4))
line.backgroundColor = UIColor.white
line.transform = angle
year2.addSubview(line)
label = UILabel(frame: CGRect(x: -60, y: -40, width: 304, height: 110))
label.text = "2013"
label.font = UIFont(name: "AvenirNext-Medium", size: 32)
label.textAlignment = NSTextAlignment.right
label.textColor = UIColor.white
label.transform = angle
year2.addSubview(label)
addSubview(year2)
year3 = UIButton(frame: CGRect(x: 320, y: 260, width: 260, height: 90))
line = UIImageView(frame: CGRect(x: -0, y: 40, width: 290, height: 4))
line.backgroundColor = UIColor.white
line.transform = angle
year3.addSubview(line)
label = UILabel(frame: CGRect(x: -60, y: -40, width: 304, height: 110))
label.text = "2012"
label.font = UIFont(name: "AvenirNext-Medium", size: 32)
label.textAlignment = NSTextAlignment.right
label.textColor = UIColor.white
label.transform = angle
year3.addSubview(label)
addSubview(year3)
year4 = UIButton(frame: CGRect(x: 320, y: 350, width: 260, height: 90))
line = UIImageView(frame: CGRect(x: -0, y: 40, width: 290, height: 4))
line.backgroundColor = UIColor.white
line.transform = angle
year4.addSubview(line)
label = UILabel(frame: CGRect(x: -60, y: -40, width: 304, height: 110))
label.text = "2011"
label.font = UIFont(name: "AvenirNext-Medium", size: 32)
label.textAlignment = NSTextAlignment.right
label.textColor = UIColor.white
label.transform = angle
year4.addSubview(label)
addSubview(year4)
}
}
| mit | c6c822d37f4498f48d1082a449fcbfb3 | 43.490291 | 107 | 0.59629 | 4.104344 | false | false | false | false |
sunbrice/CNAutoScrollView | LearnSwift-AutoScrollView/OCAutoScrollController.swift | 2 | 1181 | //
// OCAutoScrollController.swift
// LearnSwift-AutoScrollView
//
// Created by shscce on 15/4/24.
// Copyright (c) 2015年 shscce. All rights reserved.
//
import UIKit
class OCAutoScrollController: UIViewController,CNScrollViewDelegate {
var autoScrollViewOC: CNScrollView!
let localImages = ["0","1","2","3","4","5","6","7","8","9"]
override func viewDidLoad() {
autoScrollViewOC = CNScrollView(frame: CGRectMake(20, 60, 280, 200))
autoScrollViewOC.delegate = self
autoScrollViewOC.backgroundColor = UIColor.redColor()
view.addSubview(autoScrollViewOC)
}
@IBAction func changeAutoScroll() {
autoScrollViewOC.autoScroll = !autoScrollViewOC.autoScroll
}
//MARK:- CNAutoScrollViewDelegate<##>
func numberOfPages() -> Int {
return localImages.count
}
func imageNameOfIndex(index: Int) -> String! {
return localImages[index]
}
func didSelectedIndex(index: Int) {
println("you click autoScrollView index:\(index)")
}
func indexDidChange(index: Int) {
println("scrollView currentIndexDidChange :\(index)")
}
}
| mit | dba1594365f57885f11cc237ee99b672 | 25.2 | 76 | 0.64631 | 4.180851 | false | false | false | false |
frootloops/swift | test/SILGen/if_while_binding.swift | 1 | 16442 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -enable-sil-ownership %s | %FileCheck %s
func foo() -> String? { return "" }
func bar() -> String? { return "" }
func a(_ x: String) {}
func b(_ x: String) {}
func c(_ x: String) {}
func marker_1() {}
func marker_2() {}
func marker_3() {}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F
func if_no_else() {
// CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3fooSSSgyF
// CHECK: [[OPT_RES:%.*]] = apply [[FOO]]()
// CHECK: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], case #Optional.none!enumelt: [[NO:bb[0-9]+]]
//
// CHECK: [[NO]]:
// CHECK: br [[CONT:bb[0-9]+]]
if let x = foo() {
// CHECK: [[YES]]([[VAL:%[0-9]+]] : @owned $String):
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a
// CHECK: apply [[A]]([[VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
a(x)
}
// CHECK: [[CONT]]:
// CHECK-NEXT: tuple ()
}
// CHECK: } // end sil function '_T016if_while_binding0A8_no_else{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T016if_while_binding0A11_else_chainyyF : $@convention(thin) () -> () {
func if_else_chain() {
// CHECK: [[FOO:%.*]] = function_ref @_T016if_while_binding3foo{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: [[OPT_RES:%.*]] = apply [[FOO]]()
// CHECK-NEXT: switch_enum [[OPT_RES]] : $Optional<String>, case #Optional.some!enumelt.1: [[YESX:bb[0-9]+]], case #Optional.none!enumelt: [[NOX:bb[0-9]+]]
if let x = foo() {
// CHECK: [[NOX]]:
// CHECK: br [[FAILURE_DESTX:bb[0-9]+]]
//
// CHECK: [[YESX]]([[VAL:%[0-9]+]] : @owned $String):
// CHECK: debug_value [[VAL]] : $String, let, name "x"
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: [[A:%.*]] = function_ref @_T016if_while_binding1a
// CHECK: apply [[A]]([[VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL]] from [[VAL]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT_X:bb[0-9]+]]
a(x)
//
// CHECK: [[FAILURE_DESTX]]:
// CHECK: alloc_box ${ var String }, var, name "y"
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YESY:bb[0-9]+]], case #Optional.none!enumelt: [[ELSE1:bb[0-9]+]]
// CHECK: [[ELSE1]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: br [[ELSE:bb[0-9]+]]
} else if var y = bar() {
// CHECK: [[YESY]]([[VAL:%[0-9]+]] : @owned $String):
// CHECK: br [[CONT_Y:bb[0-9]+]]
// CHECK: [[CONT_Y]]:
// CHECK: br [[CONT_Y2:bb[0-9]+]]
b(y)
} else {
// CHECK: [[ELSE]]:
// CHECK: function_ref if_while_binding.c
c("")
// CHECK: br [[CONT_Y2]]
}
// CHECK: [[CONT_Y2]]:
// br [[CONT_X]]
// CHECK: [[CONT_X]]:
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0B5_loopyyF : $@convention(thin) () -> () {
func while_loop() {
// CHECK: br [[LOOP_ENTRY:bb[0-9]+]]
//
// CHECK: [[LOOP_ENTRY]]:
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[LOOP_BODY:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NO_TRAMPOLINE]]:
// CHECK: br [[LOOP_EXIT:bb[0-9]+]]
while let x = foo() {
// CHECK: [[LOOP_BODY]]([[X:%[0-9]+]] : @owned $String):
// CHECK: switch_enum {{.*}} : $Optional<String>, case #Optional.some!enumelt.1: [[YES:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE_2:bb[0-9]+]]
//
// CHECK: [[NO_TRAMPOLINE_2]]:
// CHECK: br [[FAILURE_DEST_2:bb[0-9]+]]
if let y = bar() {
// CHECK: [[YES]]([[Y:%[0-9]+]] : @owned $String):
a(y)
break
// CHECK: destroy_value [[Y]]
// CHECK: destroy_value [[X]]
// CHECK: br [[LOOP_EXIT]]
}
// CHECK: [[FAILURE_DEST_2]]:
// CHECK: destroy_value [[X]]
// CHECK: br [[LOOP_ENTRY]]
}
// CHECK: [[LOOP_EXIT]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// Don't leak alloc_stacks for address-only conditional bindings in 'while'.
// <rdar://problem/16202294>
// CHECK-LABEL: sil hidden @_T016if_while_binding0B13_loop_generic{{[_0-9a-zA-Z]*}}F
// CHECK: br [[COND:bb[0-9]+]]
// CHECK: [[COND]]:
// CHECK: [[X:%.*]] = alloc_stack $T, let, name "x"
// CHECK: [[OPTBUF:%[0-9]+]] = alloc_stack $Optional<T>
// CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[LOOPBODY:bb.*]], case #Optional.none!enumelt: [[OUT:bb[0-9]+]]
// CHECK: [[OUT]]:
// CHECK: dealloc_stack [[OPTBUF]]
// CHECK: dealloc_stack [[X]]
// CHECK: br [[DONE:bb[0-9]+]]
// CHECK: [[LOOPBODY]]:
// CHECK: [[ENUMVAL:%.*]] = unchecked_take_enum_data_addr
// CHECK: copy_addr [take] [[ENUMVAL]] to [initialization] [[X]]
// CHECK: destroy_addr [[X]]
// CHECK: dealloc_stack [[X]]
// CHECK: br [[COND]]
// CHECK: [[DONE]]:
// CHECK: destroy_value %0
func while_loop_generic<T>(_ source: () -> T?) {
while let x = source() {
}
}
// <rdar://problem/19382942> Improve 'if let' to avoid optional pyramid of doom
// CHECK-LABEL: sil hidden @_T016if_while_binding0B11_loop_multiyyF
func while_loop_multi() {
// CHECK: br [[LOOP_ENTRY:bb[0-9]+]]
// CHECK: [[LOOP_ENTRY]]:
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[LOOP_EXIT0:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[LOOP_BODY:bb.*]], case #Optional.none!enumelt: [[LOOP_EXIT2a:bb[0-9]+]]
// CHECK: [[LOOP_EXIT2a]]:
// CHECK: destroy_value [[A]]
// CHECK: br [[LOOP_EXIT0]]
// CHECK: [[LOOP_BODY]]([[B:%[0-9]+]] : @owned $String):
while let a = foo(), let b = bar() {
// CHECK: debug_value [[B]] : $String, let, name "b"
// CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]]
// CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]]
// CHECK: debug_value [[A_COPY]] : $String, let, name "c"
// CHECK: end_borrow [[BORROWED_A]] from [[A]]
// CHECK: destroy_value [[A_COPY]]
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[LOOP_ENTRY]]
let c = a
}
// CHECK: [[LOOP_EXIT0]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A6_multiyyF
func if_multi() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[IF_DONE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[PB:%[0-9]+]] = project_box [[B]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
// CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : @owned $String):
if let a = foo(), var b = bar() {
// CHECK: store [[BVAL]] to [init] [[PB]] : $*String
// CHECK: debug_value {{.*}} : $String, let, name "c"
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
let c = a
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A11_multi_elseyyF
func if_multi_else() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[ELSE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[PB:%[0-9]+]] = project_box [[B]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[IF_BODY:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[ELSE]]
// CHECK: [[IF_BODY]]([[BVAL:%[0-9]+]] : @owned $String):
if let a = foo(), var b = bar() {
// CHECK: store [[BVAL]] to [init] [[PB]] : $*String
// CHECK: debug_value {{.*}} : $String, let, name "c"
// CHECK: destroy_value [[B]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE:bb[0-9]+]]
let c = a
} else {
let d = 0
// CHECK: [[ELSE]]:
// CHECK: debug_value {{.*}} : $Int, let, name "d"
// CHECK: br [[IF_DONE]]
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T016if_while_binding0A12_multi_whereyyF
func if_multi_where() {
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECKBUF2:bb.*]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[ELSE:bb[0-9]+]]
// CHECK: [[CHECKBUF2]]([[A:%[0-9]+]] : @owned $String):
// CHECK: debug_value [[A]] : $String, let, name "a"
// CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var String }, var, name "b"
// CHECK: [[PB:%[0-9]+]] = project_box [[BBOX]]
// CHECK: switch_enum {{.*}}, case #Optional.some!enumelt.1: [[CHECK_WHERE:bb.*]], case #Optional.none!enumelt: [[IF_EXIT1a:bb[0-9]+]]
// CHECK: [[IF_EXIT1a]]:
// CHECK: dealloc_box {{.*}} ${ var String }
// CHECK: destroy_value [[A]]
// CHECK: br [[ELSE]]
// CHECK: [[CHECK_WHERE]]([[B:%[0-9]+]] : @owned $String):
// CHECK: function_ref Swift.Bool._getBuiltinLogicValue() -> Builtin.Int1
// CHECK: cond_br {{.*}}, [[IF_BODY:bb[0-9]+]], [[IF_EXIT3:bb[0-9]+]]
// CHECK: [[IF_EXIT3]]:
// CHECK: destroy_value [[BBOX]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE:bb[0-9]+]]
if let a = foo(), var b = bar(), a == b {
// CHECK: [[IF_BODY]]:
// CHECK: destroy_value [[BBOX]]
// CHECK: destroy_value [[A]]
// CHECK: br [[IF_DONE]]
let c = a
}
// CHECK: [[IF_DONE]]:
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
// <rdar://problem/19797158> Swift 1.2's "if" has 2 behaviors. They could be unified.
// CHECK-LABEL: sil hidden @_T016if_while_binding0A16_leading_booleanySiF
func if_leading_boolean(_ a : Int) {
// Test the boolean condition.
// CHECK: debug_value %0 : $Int, let, name "a"
// CHECK: [[EQRESULT:%[0-9]+]] = apply {{.*}}(%0, %0{{.*}}) : $@convention({{.*}}) (Int, Int{{.*}}) -> Bool
// CHECK: [[FN:%.*]] = function_ref {{.*}}
// CHECK-NEXT: [[EQRESULTI1:%[0-9]+]] = apply [[FN:%.*]]([[EQRESULT]]) : $@convention(method) (Bool) -> Builtin.Int1
// CHECK-NEXT: cond_br [[EQRESULTI1]], [[CHECKFOO:bb[0-9]+]], [[IFDONE:bb[0-9]+]]
// Call Foo and test for the optional being present.
// CHECK: [[CHECKFOO]]:
// CHECK: [[OPTRESULT:%[0-9]+]] = apply {{.*}}() : $@convention(thin) () -> @owned Optional<String>
// CHECK: switch_enum [[OPTRESULT]] : $Optional<String>, case #Optional.some!enumelt.1: [[SUCCESS:bb.*]], case #Optional.none!enumelt: [[IF_DONE:bb[0-9]+]]
// CHECK: [[SUCCESS]]([[B:%[0-9]+]] : @owned $String):
// CHECK: debug_value [[B]] : $String, let, name "b"
// CHECK: [[BORROWED_B:%.*]] = begin_borrow [[B]]
// CHECK: [[B_COPY:%.*]] = copy_value [[BORROWED_B]]
// CHECK: debug_value [[B_COPY]] : $String, let, name "c"
// CHECK: end_borrow [[BORROWED_B]] from [[B]]
// CHECK: destroy_value [[B_COPY]]
// CHECK: destroy_value [[B]]
// CHECK: br [[IFDONE]]
if a == a, let b = foo() {
let c = b
}
// CHECK: [[IFDONE]]:
// CHECK-NEXT: tuple ()
}
/// <rdar://problem/20364869> Assertion failure when using 'as' pattern in 'if let'
class BaseClass {}
class DerivedClass : BaseClass {}
// CHECK-LABEL: sil hidden @_T016if_while_binding20testAsPatternInIfLetyAA9BaseClassCSgF
func testAsPatternInIfLet(_ a : BaseClass?) {
// CHECK: bb0([[ARG:%.*]] : @owned $Optional<BaseClass>):
// CHECK: debug_value [[ARG]] : $Optional<BaseClass>, let, name "a"
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Optional<BaseClass>
// CHECK: switch_enum [[ARG_COPY]] : $Optional<BaseClass>, case #Optional.some!enumelt.1: [[OPTPRESENTBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
// CHECK: [[NILBB]]:
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: br [[EXITBB:bb[0-9]+]]
// CHECK: [[OPTPRESENTBB]]([[CLS:%.*]] : @owned $BaseClass):
// CHECK: checked_cast_br [[CLS]] : $BaseClass to $DerivedClass, [[ISDERIVEDBB:bb[0-9]+]], [[ISBASEBB:bb[0-9]+]]
// CHECK: [[ISDERIVEDBB]]([[DERIVED_CLS:%.*]] : @owned $DerivedClass):
// CHECK: [[DERIVED_CLS_SOME:%.*]] = enum $Optional<DerivedClass>, #Optional.some!enumelt.1, [[DERIVED_CLS]] : $DerivedClass
// CHECK: br [[MERGE:bb[0-9]+]]([[DERIVED_CLS_SOME]] : $Optional<DerivedClass>)
// CHECK: [[ISBASEBB]]([[BASECLASS:%.*]] : @owned $BaseClass):
// CHECK: destroy_value [[BASECLASS]] : $BaseClass
// CHECK: = enum $Optional<DerivedClass>, #Optional.none!enumelt
// CHECK: br [[MERGE]](
// CHECK: [[MERGE]]([[OPTVAL:%[0-9]+]] : @owned $Optional<DerivedClass>):
// CHECK: switch_enum [[OPTVAL]] : $Optional<DerivedClass>, case #Optional.some!enumelt.1: [[ISDERIVEDBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
// CHECK: [[ISDERIVEDBB]]([[DERIVEDVAL:%[0-9]+]] : @owned $DerivedClass):
// CHECK: debug_value [[DERIVEDVAL]] : $DerivedClass
// => SEMANTIC SIL TODO: This is benign, but scoping wise, this end borrow should be after derived val.
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[DERIVEDVAL]] : $DerivedClass
// CHECK: br [[EXITBB]]
// CHECK: [[EXITBB]]:
// CHECK: destroy_value [[ARG]] : $Optional<BaseClass>
// CHECK: tuple ()
// CHECK: return
if case let b as DerivedClass = a {
}
}
// <rdar://problem/22312114> if case crashes swift - bools not supported in let/else yet
// CHECK-LABEL: sil hidden @_T016if_while_binding12testCaseBoolySbSgF
func testCaseBool(_ value : Bool?) {
// CHECK: bb0([[ARG:%.*]] : @trivial $Optional<Bool>):
// CHECK: switch_enum [[ARG]] : $Optional<Bool>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_TRAMPOLINE:bb[0-9]+]]
//
// CHECK: [[NONE_TRAMPOLINE]]:
// CHECK: br [[CONT_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[PAYLOAD:%.*]] : @trivial $Bool):
// CHECK: [[ISTRUE:%[0-9]+]] = struct_extract [[PAYLOAD]] : $Bool, #Bool._value
// CHECK: cond_br [[ISTRUE]], [[TRUE_TRAMPOLINE_BB:bb[0-9]+]], [[CONT_BB]]
//
// CHECK: [[TRUE_TRAMPOLINE_BB:bb[0-9]+]]
// CHECK: br [[TRUE_BB:bb[0-9]+]]
//
// CHECK: [[TRUE_BB]]:
// CHECK: function_ref @_T016if_while_binding8marker_1yyF
// CHECK: br [[CONT_BB]]
if case true? = value {
marker_1()
}
// CHECK: [[CONT_BB]]:
// CHECK: switch_enum [[ARG]] : $Optional<Bool>, case #Optional.some!enumelt.1: [[SUCC_BB_2:bb[0-9]+]], case #Optional.none!enumelt: [[NO_TRAMPOLINE_2:bb[0-9]+]]
// CHECK: [[NO_TRAMPOLINE_2]]:
// CHECK: br [[EPILOG_BB:bb[0-9]+]]
// CHECK: [[SUCC_BB_2]]([[PAYLOAD2:%.*]] : @trivial $Bool):
// CHECK: [[ISTRUE:%[0-9]+]] = struct_extract [[PAYLOAD2]] : $Bool, #Bool._value
// CHECK: cond_br [[ISTRUE]], [[EPILOG_BB]], [[FALSE2_TRAMPOLINE_BB:bb[0-9]+]]
// CHECK: [[FALSE2_TRAMPOLINE_BB]]:
// CHECK: br [[FALSE2_BB:bb[0-9]+]]
//
// CHECK: [[FALSE2_BB]]:
// CHECK: function_ref @_T016if_while_binding8marker_2yyF
// CHECK: br [[EPILOG_BB]]
// CHECK: [[EPILOG_BB]]:
// CHECK: return
if case false? = value {
marker_2()
}
}
| apache-2.0 | 0a33b5f523ef59db3996bae142577bbc | 39.200489 | 169 | 0.54896 | 2.993809 | false | false | false | false |
VadimPavlov/Swifty | Sources/Swifty/Common/Reactive/Listenable.swift | 1 | 1048 | //
// Listenable.swift
// Swifty
//
// Created by Vadim Pavlov on 1/28/19.
// Copyright © 2019 Vadym Pavlov. All rights reserved.
//
import Foundation
public class Listenable<Value> {
public typealias Listener = (Value) -> Void
private var listeners: Atomic<[UUID: Listener]>
public init() {
self.listeners = Atomic([:])
}
public func listen(listener: @escaping Listener) -> Disposable {
let id = UUID()
self.listeners.mutate { listeners in
listeners[id] = listener
}
return Disposable {
self.listeners.mutate { listeners in
listeners[id] = nil
}
}
}
public func write(value: Value) {
listeners.value.forEach { (_, listener) in
listener(value)
}
}
}
final public class Disposable {
public typealias Dispose = () -> Void
private let dispose: Dispose
init(_ dispose: @escaping Dispose) {
self.dispose = dispose
}
deinit {
dispose()
}
}
| mit | 1d57016bcf38160737e43ccbc764d9a3 | 19.94 | 68 | 0.572111 | 4.3625 | false | false | false | false |
dimitris-c/Omicron | Tests/Helpers.swift | 1 | 2753 | //
// Helpers.swift
// Omicron
//
// Created by Dimitris C. on 20/06/2017.
// Copyright © 2017 Decimal. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import Omicron
struct User {
let name: String
let lastname: String
init(name: String, lastname: String) {
self.name = name
self.lastname = lastname
}
init(with json: JSON) {
self.name = json["name"].stringValue
self.lastname = json["lastname"].stringValue
}
}
class UserResponseFromHTTPBin: APIResponse<User> {
override func toData(rawData data: JSON) -> User? {
let args = data["args"]
let converted = JSON.init(parseJSON: args["user"].stringValue)
let name = converted["name"].stringValue
return User(name: name, lastname: "")
}
}
class UserReponse: APIResponse<User> {
override func toData(rawData data: JSON) -> User? {
return User(with: data)
}
}
class UsersResponse: APIResponse<[User]> {
override func toData(rawData data: JSON) -> [User]? {
return data["users"].arrayValue.map { User(with: $0) }
}
}
class GithubUserResponse: APIResponse<GithubUser> {
override func toData(rawData data: JSON) -> GithubUser {
return GithubUser(with: data)
}
}
struct GithubUser {
let id: String
let user: String
let name: String
init(with json: JSON) {
self.id = json["id"].stringValue
self.user = json["user"].stringValue
self.name = json["name"].stringValue
}
}
enum GithubService {
case user(name: String)
}
extension GithubService: Service {
var baseURL: URL { return URL(string: "https://api.github.com")! }
var path: String {
switch self {
case .user(let name): return "/users/\(name)"
}
}
var method: HTTPMethod {
return .get
}
var params: RequestParameters {
return RequestParameters.default
}
}
enum HTTPBin {
case get
case nonExistingPath
case anything(value: String)
}
extension HTTPBin: Service {
var baseURL: URL { return URL(string: "https://httpbin.org")! }
var path: String {
switch self {
case .get:
return "/get"
case .nonExistingPath:
return "/non.existing.path"
case .anything(_):
return "/anything"
}
}
var method: HTTPMethod {
return .get
}
var params: RequestParameters {
switch self {
case .anything(let value):
return RequestParameters(parameters: ["user": value], encoding: URLEncoding.default)
default:
return RequestParameters.default
}
}
}
| mit | 885a6407f417f32b16ba6059364a413d | 21.016 | 96 | 0.595203 | 4.207951 | false | false | false | false |
1aurabrown/eidolon | KioskTests/Models/SystemTimeTests.swift | 1 | 1427 | import Quick
import Nimble
// Note, stubbed json contains a date in 2422
// If this is an issue ( hello future people! ) then move it along a few centuries.
class SystemTimeTests: QuickSpec {
override func spec() {
describe("in sync") {
setupProviderForSuite(Provider.StubbingProvider())
it("returns true") {
let time = SystemTime()
time.syncSignal().subscribeNext { (_) -> Void in
expect(time.inSync()) == true
return
}
}
it("returns a date in the future") {
let time = SystemTime()
time.syncSignal().subscribeNext { (_) -> Void in
let currentYear = yearFromDate(NSDate())
let timeYear = yearFromDate(time.date())
expect(timeYear) > currentYear
expect(timeYear) == 2422
}
}
}
describe("not in sync") {
it("returns false") {
let time = SystemTime()
expect(time.inSync()) == false
}
it("returns current time") {
let time = SystemTime()
let currentYear = yearFromDate(NSDate())
let timeYear = yearFromDate(time.date())
expect(timeYear) == currentYear
}
}
}
}
| mit | 789396d0d433df79555501f575719d89 | 28.122449 | 83 | 0.480028 | 5.265683 | false | false | false | false |
Phelthas/TEST_XMLCommon | TEST_Common/One/TestTakePhotoViewController.swift | 1 | 10287 | //
// TestTakePhotoViewController.swift
// Instagram_ouj
//
// Created by luxiaoming on 16/2/19.
// Copyright © 2016年 com.ouj. All rights reserved.
//
import UIKit
import AVFoundation
private var myContext = 0
class TestTakePhotoViewController: UIViewController {
@IBOutlet weak var takePhotoView: UIView!
@IBOutlet weak var cameraChangeButton: UIButton!
@IBOutlet weak var flashButton: UIButton!
let stillImageOutput = AVCaptureStillImageOutput()
var session = AVCaptureSession()
var backCameraDevice: AVCaptureDevice?
var frontCameraDevice: AVCaptureDevice?
var isBackCamera: Bool = true
var previewLayer: AVCaptureVideoPreviewLayer!
var flashMode: AVCaptureDevice.FlashMode = AVCaptureDevice.FlashMode.auto
var authorizationStatus: AVAuthorizationStatus {
return AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
}
var currentCameraDevice: AVCaptureDevice? {
if self.isBackCamera {
return self.backCameraDevice
} else {
return self.frontCameraDevice
}
}
deinit {
self.stillImageOutput.removeObserver(self, forKeyPath: "capturingStillImage")
}
override func viewDidLoad() {
super.viewDidLoad()
setupTakePhotoView()
setupCamera()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startSession()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopSession()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer?.frame = takePhotoView.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext && keyPath == "capturingStillImage" {
if let dict = change,
let value = dict[NSKeyValueChangeKey.newKey] as? Bool, value == true {
self.stopSession()
} else {
self.startSession()
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
// MARK: - PrivateMethod
extension TestTakePhotoViewController {
fileprivate func setupTakePhotoView() {
takePhotoView.isUserInteractionEnabled = true
let changeFocusGesture = UITapGestureRecognizer(target: self, action: #selector(TestTakePhotoViewController.handleChangeFocusGesture(_:)))
takePhotoView.addGestureRecognizer(changeFocusGesture)
}
fileprivate func setupCamera() {
self.stillImageOutput.addObserver(self, forKeyPath: "capturingStillImage", options: .new, context: &myContext)
switch authorizationStatus {
case.notDetermined:
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) -> Void in
if granted {
self.configureCamera()
} else {
self.showErrorAlertView()
}
})
case.authorized:
self.configureCamera()
default:
self.showErrorAlertView()
}
}
fileprivate func configureCamera() {
session.sessionPreset = AVCaptureSession.Preset.photo
let availableCameraArray = AVCaptureDevice.devices(for: AVMediaType.video)
for tempDevice in availableCameraArray {
if tempDevice.position == .back {
backCameraDevice = tempDevice
} else if tempDevice.position == .front {
frontCameraDevice = tempDevice
}
}
previewLayer = AVCaptureVideoPreviewLayer(session: self.session)
if let tempLayer = previewLayer {
tempLayer.frame = self.takePhotoView.bounds
tempLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.takePhotoView.layer.addSublayer(tempLayer)
}
if session.canAddOutput(self.stillImageOutput) {
session.addOutput(self.stillImageOutput)
}
do {
for tempInput in session.inputs { //貌似不这么先删一遍就加不进去
session.removeInput(tempInput)
}
let cameraInput: AVCaptureDeviceInput = try AVCaptureDeviceInput(device: self.currentCameraDevice!)
if session.canAddInput(cameraInput) {
session.addInput(cameraInput)
} else {
NSLog("error")
}
if let tempDevice = self.currentCameraDevice {
try tempDevice.lockForConfiguration()
if tempDevice.hasFlash {
tempDevice.flashMode = self.flashMode
}
if tempDevice.isFocusModeSupported(.autoFocus) {
tempDevice.focusMode = .autoFocus
}
if tempDevice.isWhiteBalanceModeSupported(.autoWhiteBalance) {
tempDevice.whiteBalanceMode = .autoWhiteBalance
}
tempDevice.unlockForConfiguration()
}
} catch {
NSLog("")
}
self.startSession()
}
fileprivate func showErrorAlertView() {
let alert = UIAlertView(title: "提醒", message: "未授权应用使用相机,请前往设置内打开相机权限", delegate: nil, cancelButtonTitle: "确定")
alert.show()
}
fileprivate func startSession() { //如果有需要,可能需要另开线程来做
if authorizationStatus == .authorized {
session.startRunning()
}
}
fileprivate func stopSession() { //如果有需要,可能需要另开线程来做
if authorizationStatus == .authorized {
session.stopRunning()
}
}
}
// MARK: - Action
extension TestTakePhotoViewController {
@objc func image(_ image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
NSLog("error is \(String(describing: didFinishSavingWithError))")
}
@IBAction func handleTakePhotoButtonTapped(_ sender: UIButton) {
guard let connection = self.stillImageOutput.connection(with: AVMediaType.video) else { return }
self.stillImageOutput.captureStillImageAsynchronously(from: connection) { [unowned self] (imageDataSampleBuffer, error) -> Void in
if error == nil {
// 如果使用 session .Photo 预设,或者在设备输出设置中明确进行了设置,就能获得已经压缩为JPEG的数据
if let imageDataSampleBuffer = imageDataSampleBuffer,
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer),
let image = UIImage(data: imageData) {
// 样本缓冲区也包含元数据
// let metadata:NSDictionary = CMCopyDictionaryOfAttachments(nil, imageDataSampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))!
//注意这个image还是摄像头拍下来时的分辨率,并不是你设置的layer大小的,如果还需要剪裁,就剪裁之后在保存
UIImageWriteToSavedPhotosAlbum(image, self, #selector(TestTakePhotoViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
} else {
NSLog("error while capturing still image: \(String(describing: error))")
}
}
}
@IBAction func handleChangeCameraButtonTapped(_ sender: UIButton) {
self.isBackCamera = !self.isBackCamera
self.configureCamera()
}
@IBAction func handleFlashButtonTapped(_ sender: UIButton) {
if let currentCameraDevice = currentCameraDevice {
if currentCameraDevice.hasFlash == true {
try! currentCameraDevice.lockForConfiguration()
if currentCameraDevice.flashMode == .off {
currentCameraDevice.flashMode = .on;
} else if currentCameraDevice.flashMode == .on {
currentCameraDevice.flashMode = .auto;
} else if currentCameraDevice.flashMode == .auto {
currentCameraDevice.flashMode = .off;
}
currentCameraDevice.unlockForConfiguration()
}
}
}
@IBAction func handleBackButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true) { () -> Void in
}
}
@IBAction func handleChangeFocusGesture(_ sender: UITapGestureRecognizer) {
let pointInPreview = sender.location(in: sender.view)
if let tempLayer = self.previewLayer {
let pointInCamera = tempLayer.captureDevicePointConverted(fromLayerPoint: pointInPreview)
if let currentCameraDevice = currentCameraDevice {
try! currentCameraDevice.lockForConfiguration()
if currentCameraDevice.isFocusPointOfInterestSupported == true {
currentCameraDevice.focusPointOfInterest = pointInCamera
currentCameraDevice.focusMode = .autoFocus
}
if currentCameraDevice.isExposureModeSupported(.autoExpose) {
if currentCameraDevice.isExposurePointOfInterestSupported == true {
currentCameraDevice.exposurePointOfInterest = pointInCamera
currentCameraDevice.exposureMode = .autoExpose
}
}
currentCameraDevice.unlockForConfiguration()
}
}
}
}
| mit | dae4c8a9bca7ea27f9b42d7d2fe01106 | 34.304965 | 162 | 0.605364 | 5.751589 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/Algorithm/Raywenderlich/SelectMinimumMaximun.swift | 1 | 1407 | //
// SelectMinimumMaximun.swift
// Algorithm
//
// Created by 朱双泉 on 2018/5/23.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
//n
func minimum<T: Comparable>(_ array: [T]) -> T? {
guard var minimum = array.first else {
return nil
}
for element in array.dropFirst() {
minimum = element < minimum ? element : minimum
}
return minimum
}
func maximum<T: Comparable>(_ array: [T]) -> T? {
guard var maximum = array.first else {
return nil
}
for element in array.dropFirst() {
maximum = element > maximum ? element : maximum
}
return maximum
}
func minimumMaximum<T: Comparable>(_ array: [T]) -> (minimum: T, maximum: T)? {
guard var minimum = array.first else {
return nil
}
var maximum = minimum
let start = array.count % 2
for i in stride(from: start, to: array.count, by: 2) {
let pair = (array[i], array[i + 1])
if pair.0 > pair.1 {
if pair.0 > maximum {
maximum = pair.0
}
if pair.1 < minimum {
minimum = pair.1
}
} else {
if pair.1 > maximum {
maximum = pair.1
}
if pair.0 < minimum {
minimum = pair.0
}
}
}
return (minimum, maximum)
}
| mit | 79bd7713530480a44d97dfe05d359f63 | 21.580645 | 79 | 0.507857 | 3.977273 | false | false | false | false |
srn214/Floral | Floral/Pods/CleanJSON/CleanJSON/Classes/CleanJSONKeyedDecodingContainer.swift | 1 | 34424 | //
// CleanJSONKeyedDecodingContainer.swift
// CleanJSON
//
// Created by Pircate([email protected]) on 2018/10/10
// Copyright © 2018 Pircate. All rights reserved.
//
import Foundation
struct CleanJSONKeyedDecodingContainer<K : CodingKey>: KeyedDecodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _CleanJSONDecoder
/// A reference to the container we're reading from.
private let container: [String : Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
init(referencing decoder: _CleanJSONDecoder, wrapping container: [String : Any]) {
self.decoder = decoder
switch decoder.options.keyDecodingStrategy {
case .useDefaultKeys:
self.container = container
case .convertFromSnakeCase:
// Convert the snake case keys in the container to camel case.
// If we hit a duplicate key after conversion, then we'll use the first one we saw. Effectively an undefined behavior with JSON dictionaries.
self.container = Dictionary(container.map {
dict in (CleanJSONDecoder.KeyDecodingStrategy._convertFromSnakeCase(dict.key), dict.value)
}, uniquingKeysWith: { (first, _) in first })
case .custom(let converter):
self.container = Dictionary(container.map {
key, value in (converter(decoder.codingPath + [CleanJSONKey(stringValue: key, intValue: nil)]).stringValue, value)
}, uniquingKeysWith: { (first, _) in first })
@unknown default:
self.container = container
}
self.codingPath = decoder.codingPath
}
// MARK: - KeyedDecodingContainerProtocol Methods
public var allKeys: [Key] {
return self.container.keys.compactMap { Key(stringValue: $0) }
}
public func contains(_ key: Key) -> Bool {
return self.container[key.stringValue] != nil
}
public func decodeNil(forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
}
return entry is NSNull
}
@inline(__always)
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Bool.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Bool.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Int.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int8.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Int8.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int16.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Int16.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int32.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Int32.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int64.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Int64.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return UInt.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt8.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return UInt8.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt16.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return UInt16.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt32.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return UInt32.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt64.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return UInt64.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Float.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Float.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Double.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return Double.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let entry = self.container[key.stringValue] else {
return try decodeIfKeyNotFound(key)
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: String.self) else {
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return String.defaultValue
case .custom(let adapter):
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try adapter.adapt(decoder)
}
}
return value
}
@inline(__always)
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = container[key.stringValue] else {
switch decoder.options.keyNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
decoder.codingPath.append(key)
defer { decoder.codingPath.removeLast() }
return try decoder.decodeAsDefaultValue()
}
}
decoder.codingPath.append(key)
defer { decoder.codingPath.removeLast() }
let decodeObject = { (decoder: _CleanJSONDecoder) -> T in
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.valueNotFound(type, codingPath: decoder.codingPath)
case .useDefaultValue:
return try decoder.decodeAsDefaultValue()
case .custom:
decoder.storage.push(container: entry)
defer { decoder.storage.popContainer() }
return try decoder.decode(type)
}
}
let decodeJSONString = { (decoder: _CleanJSONDecoder) -> T in
if let _ = String.defaultValue as? T { return try decodeObject(decoder) }
if let string = try decoder.unbox(entry, as: String.self),
let object = string.decode(to: type, options: decoder.options) {
return object
}
return try decodeObject(decoder)
}
switch decoder.options.jsonStringDecodingStrategy {
case .containsKeys(let keys):
guard !keys.isEmpty else { return try decodeObject(decoder) }
guard keys.contains(where: { $0.stringValue == key.stringValue }) else {
return try decodeObject(decoder)
}
return try decodeJSONString(decoder)
case .all:
return try decodeJSONString(decoder)
}
}
@inline(__always)
public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
switch decoder.options.nestedContainerDecodingStrategy.keyNotFound {
case .throw:
throw DecodingError.Nested.keyNotFound(key, codingPath: codingPath)
case .useEmptyContainer:
return nestedContainer()
}
}
guard let dictionary = value as? [String : Any] else {
switch decoder.options.nestedContainerDecodingStrategy.typeMismatch {
case .throw:
throw DecodingError._typeMismatch(
at: self.codingPath,
expectation: [String : Any].self,
reality: value)
case .useEmptyContainer:
return nestedContainer()
}
}
return nestedContainer(wrapping: dictionary)
}
@inline(__always)
private func nestedContainer<NestedKey>(wrapping dictionary: [String: Any] = [:])
-> KeyedDecodingContainer<NestedKey> {
let container = CleanJSONKeyedDecodingContainer<NestedKey>(
referencing: decoder,
wrapping: dictionary)
return KeyedDecodingContainer(container)
}
@inline(__always)
public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
switch decoder.options.nestedContainerDecodingStrategy.keyNotFound {
case .throw:
throw DecodingError.Nested.keyNotFound(key, codingPath: codingPath, isUnkeyed: true)
case .useEmptyContainer:
return CleanJSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: [])
}
}
guard let array = value as? [Any] else {
switch decoder.options.nestedContainerDecodingStrategy.typeMismatch {
case .throw:
throw DecodingError._typeMismatch(
at: self.codingPath,
expectation: [Any].self, reality: value)
case .useEmptyContainer:
return CleanJSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: [])
}
}
return CleanJSONUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
@inline(__always)
private func _superDecoder(forKey key: CodingKey) throws -> Decoder {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
let value: Any = self.container[key.stringValue] ?? NSNull()
return _CleanJSONDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
@inline(__always)
public func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: CleanJSONKey.super)
}
@inline(__always)
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
}
extension CleanJSONKeyedDecodingContainer {
@inline(__always)
func decodeIfPresent(_ type: Bool.Type, forKey key: K) throws -> Bool? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: Int.Type, forKey key: K) throws -> Int? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: Int8.Type, forKey key: K) throws -> Int8? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: Int16.Type, forKey key: K) throws -> Int16? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: Int32.Type, forKey key: K) throws -> Int32? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: Int64.Type, forKey key: K) throws -> Int64? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: UInt.Type, forKey key: K) throws -> UInt? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: UInt8.Type, forKey key: K) throws -> UInt8? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: UInt16.Type, forKey key: K) throws -> UInt16? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: UInt32.Type, forKey key: K) throws -> UInt32? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: UInt64.Type, forKey key: K) throws -> UInt64? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: Float.Type, forKey key: K) throws -> Float? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: Double.Type, forKey key: K) throws -> Double? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent(_ type: String.Type, forKey key: K) throws -> String? {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if let value = try decoder.unbox(entry, as: type) { return value }
switch decoder.options.valueNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return nil
case .custom(let adapter):
return try adapter.adaptIfPresent(decoder)
}
}
@inline(__always)
func decodeIfPresent<T>(_ type: T.Type, forKey key: K) throws -> T? where T : Decodable {
guard contains(key), let entry = container[key.stringValue] else { return nil }
if type == Date.self || type == NSDate.self {
return try decoder.decodeIfPresent(entry, as: Date.self, forKey: key) as? T
} else if type == Data.self || type == NSData.self {
return try decoder.decodeIfPresent(entry, as: Data.self, forKey: key) as? T
} else if type == URL.self || type == NSURL.self {
return try decoder.decodeIfPresent(entry, as: URL.self, forKey: key) as? T
} else if type == Decimal.self || type == NSDecimalNumber.self {
return try decoder.decodeIfPresent(entry, as: Decimal.self, forKey: key) as? T
}
if try decodeNil(forKey: key) { return nil }
return try decoder.unbox(entry, as: type)
}
}
private extension CleanJSONDecoder.KeyDecodingStrategy {
static func _convertFromSnakeCase(_ stringKey: String) -> String {
guard !stringKey.isEmpty else { return stringKey }
// Find the first non-underscore character
guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else {
// Reached the end without finding an _
return stringKey
}
// Find the last non-underscore character
var lastNonUnderscore = stringKey.index(before: stringKey.endIndex)
while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" {
stringKey.formIndex(before: &lastNonUnderscore)
}
let keyRange = firstNonUnderscore...lastNonUnderscore
let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore
let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex
let components = stringKey[keyRange].split(separator: "_")
let joinedString : String
if components.count == 1 {
// No underscores in key, leave the word as is - maybe already camel cased
joinedString = String(stringKey[keyRange])
} else {
joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined()
}
// Do a cheap isEmpty check before creating and appending potentially empty strings
let result : String
if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) {
result = joinedString
} else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) {
// Both leading and trailing underscores
result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange])
} else if (!leadingUnderscoreRange.isEmpty) {
// Just leading
result = String(stringKey[leadingUnderscoreRange]) + joinedString
} else {
// Just trailing
result = joinedString + String(stringKey[trailingUnderscoreRange])
}
return result
}
}
private extension CleanJSONKeyedDecodingContainer {
func decodeIfKeyNotFound<T>(_ key: Key) throws -> T where T: Decodable, T: Defaultable {
switch decoder.options.keyNotFoundDecodingStrategy {
case .throw:
throw DecodingError.Keyed.keyNotFound(key, codingPath: decoder.codingPath)
case .useDefaultValue:
return T.defaultValue
}
}
}
private extension String {
func decode<T: Decodable>(to type: T.Type, options: CleanJSONDecoder.Options) -> T? {
guard hasPrefix("{") || hasPrefix("[") else { return nil }
guard let data = data(using: .utf8),
let topLevel = try? JSONSerialization.jsonObject(with: data) else { return nil }
let decoder = _CleanJSONDecoder(referencing: topLevel, options: options)
#if swift(<5)
guard let obj = try? decoder.unbox(topLevel, as: type) else { return nil }
return obj
#else
return try? decoder.unbox(topLevel, as: type)
#endif
}
}
| mit | 8615f6bebee4d8def0092d08fcd72a0a | 37.984145 | 153 | 0.59928 | 5.050323 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/DataSync/DataSync_Paginator.swift | 1 | 14270 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension DataSync {
/// Returns a list of agents owned by an AWS account in the AWS Region specified in the request. The returned list is ordered by agent Amazon Resource Name (ARN). By default, this operation returns a maximum of 100 agents. This operation supports pagination that enables you to optionally reduce the number of agents returned in a response. If you have more agents than are returned in a response (that is, the response returns only a truncated list of your agents), the response contains a marker that you can specify in your next request to fetch the next page of agents.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listAgentsPaginator<Result>(
_ input: ListAgentsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListAgentsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listAgents,
tokenKey: \ListAgentsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listAgentsPaginator(
_ input: ListAgentsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListAgentsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listAgents,
tokenKey: \ListAgentsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of source and destination locations. If you have more locations than are returned in a response (that is, the response returns only a truncated list of your agents), the response contains a token that you can specify in your next request to fetch the next page of locations.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listLocationsPaginator<Result>(
_ input: ListLocationsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListLocationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listLocations,
tokenKey: \ListLocationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listLocationsPaginator(
_ input: ListLocationsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListLocationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listLocations,
tokenKey: \ListLocationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns all the tags associated with a specified resource.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTagsForResourcePaginator<Result>(
_ input: ListTagsForResourceRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTagsForResourceResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTagsForResource,
tokenKey: \ListTagsForResourceResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTagsForResourcePaginator(
_ input: ListTagsForResourceRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTagsForResourceResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTagsForResource,
tokenKey: \ListTagsForResourceResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of executed tasks.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTaskExecutionsPaginator<Result>(
_ input: ListTaskExecutionsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTaskExecutionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTaskExecutions,
tokenKey: \ListTaskExecutionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTaskExecutionsPaginator(
_ input: ListTaskExecutionsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTaskExecutionsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTaskExecutions,
tokenKey: \ListTaskExecutionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of all the tasks.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTasksPaginator<Result>(
_ input: ListTasksRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTasks,
tokenKey: \ListTasksResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTasksPaginator(
_ input: ListTasksRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTasksResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTasks,
tokenKey: \ListTasksResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension DataSync.ListAgentsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> DataSync.ListAgentsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension DataSync.ListLocationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> DataSync.ListLocationsRequest {
return .init(
filters: self.filters,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension DataSync.ListTagsForResourceRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> DataSync.ListTagsForResourceRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
resourceArn: self.resourceArn
)
}
}
extension DataSync.ListTaskExecutionsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> DataSync.ListTaskExecutionsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
taskArn: self.taskArn
)
}
}
extension DataSync.ListTasksRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> DataSync.ListTasksRequest {
return .init(
filters: self.filters,
maxResults: self.maxResults,
nextToken: token
)
}
}
| apache-2.0 | 39b3b1adcc043a610c13c16091951c57 | 42.907692 | 578 | 0.643588 | 5.044185 | false | false | false | false |
Darren-chenchen/yiyiTuYa | testDemoSwift/View/PencilChooseView.swift | 1 | 2887 | //
// PencilChooseView.swift
// testDemoSwift
//
// Created by 陈亮陈亮 on 2017/5/23.
// Copyright © 2017年 陈亮陈亮. All rights reserved.
//
import UIKit
typealias clickPencilImageClouse = (UIImage) -> ()
class PencilChooseView: UIView {
var scrollView: UIScrollView!
var clickPencilImage: clickPencilImageClouse?
var currentImage: UIImageView?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(white: 0, alpha: 0.8)
scrollView = UIScrollView()
scrollView?.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
scrollView.showsHorizontalScrollIndicator = false
self.addSubview(scrollView!)
let imageArr = ["11","12","clr_red","clr_orange","clr_blue","clr_green","clr_purple","clr_black"]
let imgW: CGFloat = 20
let imgH: CGFloat = 20
let imgY: CGFloat = 0.5*(self.cl_height-imgH)
let magin: CGFloat = (KScreenWidth-CGFloat(imageArr.count)*imgW)/CGFloat(imageArr.count+1)
for i in 0..<imageArr.count {
let imgX: CGFloat = magin + (magin+imgW)*CGFloat(i)
let img = UIImageView.init(frame: CGRect(x: imgX, y: imgY, width: imgW, height: imgH))
img.image = UIImage(named: imageArr[i])
img.isUserInteractionEnabled = true
HDViewsBorder(img, borderWidth: 1.5, borderColor: UIColor.white, cornerRadius: 3)
scrollView.addSubview(img)
img.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(PencilChooseView.clickPencilImageView(tap:))))
// 默认选中黑色
if i == imageArr.count-1 {
self.currentImage = img
self.currentImage?.alpha = 0.5
HDViewsBorder(self.currentImage!, borderWidth: 0, borderColor: UIColor.white, cornerRadius: 3)
}
}
scrollView.contentSize = CGSize(width: magin*CGFloat(imageArr.count+1)+imgW*CGFloat(imageArr.count)-KScreenWidth, height: 0)
}
func clickPencilImageView(tap:UITapGestureRecognizer) {
if clickPencilImage != nil {
self.currentImage?.alpha = 1
HDViewsBorder(self.currentImage!, borderWidth: 1.5, borderColor: UIColor.white, cornerRadius: 3)
let imageView = tap.view as! UIImageView
imageView.alpha = 0.5
HDViewsBorder(imageView, borderWidth: 0, borderColor: UIColor.white, cornerRadius: 3)
self.currentImage = imageView
self.clickPencilImage!(imageView.image!)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | b5f2929bb48f142e227661bd4e18bf74 | 36.090909 | 143 | 0.609594 | 4.333839 | false | false | false | false |
gyro-n/PaymentsIos | Example/Tests/Tests.swift | 1 | 1173 | // https://github.com/Quick/Quick
import Quick
import Nimble
@testable import GyronPayments
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | a5012ccfb905bdebcad2b847681de439 | 22.34 | 60 | 0.363325 | 5.530806 | false | false | false | false |
cailingyun2010/swift-weibo | 微博-S/Classes/Newfeature/NewfeatureCollectionViewController.swift | 1 | 6565 | //
// NewfeatureCollectionViewController.swift
// DSWeibo
//
// Created by xiaomage on 15/9/10.
// Copyright © 2015年 小码哥. All rights reserved.
//
import UIKit
private let reuseIdentifier = "reuseIdentifier"
class NewfeatureCollectionViewController: UICollectionViewController {
/// 页面个数
private let pageCount = 4
/// 布局对象
private var layout: UICollectionViewFlowLayout = NewfeatureLayout()
// 因为系统指定的初始化构造方法是带参数的(collectionViewLayout), 而不是不带参数的, 所以不用写override
init(){
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// 1.注册一个cell
// OC : [UICollectionViewCell class]
collectionView?.registerClass(NewfeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/*
// 1.设置layout布局
layout.itemSize = UIScreen.mainScreen().bounds.size
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
// 2.设置collectionView的属性
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.bounces = false
collectionView?.pagingEnabled = true
*/
}
// MARK: - UICollectionViewDataSource
// 1.返回一个有多少个cell
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pageCount
}
// 2.返回对应indexPath的cell
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// 1.获取cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewfeatureCell
// 2.设置cell的数据
// cell.backgroundColor = UIColor.redColor()
cell.imageIndex = indexPath.item
cell.startButton.hidden = true
// 3.返回cell
return cell
}
// 完全显示一个cell之后调用
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
// 传递给我们的是上一页的索引
// print(indexPath)
// 1.拿到当前显示的cell对应的索引
let path = collectionView.indexPathsForVisibleItems().last!
print(path)
if path.item == (pageCount - 1)
{
// 2.拿到当前索引对应的cell
let cell = collectionView.cellForItemAtIndexPath(path) as! NewfeatureCell
// 3.让cell执行按钮动画
cell.startBtnAnimation()
} else {
let cell = collectionView.cellForItemAtIndexPath(path) as! NewfeatureCell
// 3.让cell执行按钮动画
cell.startButton.hidden = true
}
}
}
// Swift中一个文件中是可以定义多个类的
// 如果当前类需要监听按钮的点击方法, 那么当前类不是是私有的
class NewfeatureCell: UICollectionViewCell
{
/// 保存图片的索引
// Swift中被private休息的东西, 如果是在同一个文件中是可以访问的
private var imageIndex:Int? {
didSet{
iconView.image = UIImage(named: "new_feature_\(imageIndex! + 1)")
}
}
/**
让按钮做动画
*/
func startBtnAnimation()
{
startButton.hidden = false
// 执行动画
startButton.transform = CGAffineTransformMakeScale(0.0, 0.0)
startButton.userInteractionEnabled = false
// UIViewAnimationOptions(rawValue: 0) == OC knilOptions
UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
// 清空形变
self.startButton.transform = CGAffineTransformIdentity
}, completion: { (_) -> Void in
self.startButton.userInteractionEnabled = true
})
}
override init(frame: CGRect) {
super.init(frame: frame)
// 1.初始化UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func customBtnClick() {
// 新特性看完去主页
NSNotificationCenter.defaultCenter().postNotificationName(XMGSwitchRootViewControllerKey, object: true)
}
private func setupUI(){
// 1.添加子控件到contentView上
contentView.addSubview(iconView)
contentView.addSubview(startButton)
// 2.布局子控件的位置
iconView.xmg_Fill(contentView)
startButton.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
}
// MARK: - 懒加载
private lazy var iconView = UIImageView()
private lazy var startButton: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: UIControlState.Highlighted)
btn.hidden = true
btn.addTarget(self, action: "customBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
}
private class NewfeatureLayout: UICollectionViewFlowLayout {
// 准备布局
// 什么时候调用? 1.先调用一个有多少行cell 2.调用准备布局 3.调用返回cell
override func prepareLayout()
{
// 1.设置layout布局
itemSize = UIScreen.mainScreen().bounds.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
// 2.设置collectionView的属性
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.bounces = false
collectionView?.pagingEnabled = true
}
}
| apache-2.0 | f08199e09f3c8a233de02f386b2a7d01 | 31.699454 | 177 | 0.645555 | 5.110162 | false | false | false | false |
wesj/Project105 | Project105/UIReadingListController.swift | 1 | 3093 | //
// UIReadingListController.swift
// Project105
//
// Created by Wes Johnston on 10/17/14.
// Copyright (c) 2014 Wes Johnston. All rights reserved.
//
import UIKit
class UIReadingListController: UITableViewController {
var list: [NSURL] = []
override func viewDidLoad() {
super.viewDidLoad()
list = ReadingList.getAll();
}
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 list.count
}
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
cell.textLabel?.text = list[indexPath.item].absoluteString
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.
}
*/
}
| mpl-2.0 | 1e2106328d8aafcc72e2713079ea6705 | 33.366667 | 157 | 0.681862 | 5.407343 | false | false | false | false |
LOTUM/EventHub | EventHub/ApplicationState.swift | 1 | 3949 | /*
Copyright (c) 2017 LOTUM GmbH
Licensed under Apache License v2.0
See https://github.com/LOTUM/EventHub/blob/master/LICENSE for license information
*/
import UIKit
public enum ApplicationStatus: String, CustomStringConvertible {
case active, inactive, background
public var description: String { return rawValue }
fileprivate init(applicationState state: UIApplicationState) {
switch state {
case .active: self = .active
case .inactive: self = .inactive
case .background: self = .background
}
}
}
final public class ApplicationState {
public typealias ListenerBlock = (ApplicationStatus, ApplicationStatus)->Void
//MARK: Public
public static let shared = ApplicationState()
public var callbackQueue = DispatchQueue.main
public func addChangeListener(_ listener: @escaping (ApplicationStatus)->Void) -> Disposable {
let completeListener: ListenerBlock = { (newStatus, oldStatus) in listener(newStatus) }
defer { fire(listener: completeListener) }
return hub.on("change", action: completeListener)
}
public func addChangeListener(_ listener: @escaping ListenerBlock) -> Disposable {
defer { fire(listener: listener) }
return hub.on("change", action: listener)
}
//MARK: Private
private let hub = EventHub<String, (ApplicationStatus, ApplicationStatus)>()
private var applicationState: UIApplicationState {
didSet {
if applicationState != oldValue {
fire(newState: applicationState, oldState: oldValue)
}
}
}
private init() {
applicationState = UIApplication.shared.applicationState
registerLifecycleEvents()
}
private func registerLifecycleEvents() {
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationWillEnterForeground,
object: nil)
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationDidBecomeActive,
object: nil)
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationWillResignActive,
object: nil)
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationDidEnterBackground,
object: nil)
}
@objc private func lifecycleDidChange(notification: Notification) {
updateState()
}
private func updateState() {
applicationState = UIApplication.shared.applicationState
DispatchQueue.main.async {
self.applicationState = UIApplication.shared.applicationState
}
}
private func fireApplicationEvent(_ event: (ApplicationStatus, ApplicationStatus)) {
hub.emit("change", on: callbackQueue, with: event)
}
private func fire(listener: ListenerBlock? = nil) {
fire(newState: applicationState, oldState: applicationState, toListener: listener)
}
private func fire(newState: UIApplicationState,
oldState: UIApplicationState,
toListener: ListenerBlock? = nil)
{
let payload = (ApplicationStatus(applicationState: newState), ApplicationStatus(applicationState: oldState))
if let listener = toListener {
listener(payload.0, payload.1)
} else {
fireApplicationEvent(payload)
}
}
}
| apache-2.0 | e4cfe99f09572a4819813422189e7d27 | 29.851563 | 116 | 0.604963 | 5.798825 | false | false | false | false |
ohde-sg/SQLiteSwift | SQLiteSwift/SQLiteSwift.swift | 1 | 10078 | //
// SQLiteSwift.swift
// SQLiteSwift
//
// Created by 大出喜之 on 2016/02/21.
// Copyright © 2016年 yoshiyuki ohde. All rights reserved.
//
import Foundation
public protocol SSMappable {
static var table:String { get }
func dbMap(connector:SSConnector)
init()
}
public class SQLiteConnection{
internal var conn: SQLite
public var isOutput:Bool {
set{ conn.isOutput = newValue }
get{ return conn.isOutput }
}
public init(filePath:String){
conn = SQLite(filePath)
}
deinit {
print("SQLiteConnection is deinit!!!")
}
public func isExistTable<T:SSMappable>() -> SSResult<T> {
return executeInTransaction{
[unowned self] in
return SSResult<T>(result: self.conn.isExistTable([T.table]).result)
}
}
public func createTable<T:SSMappable>() -> SSResult<T>{
let model = T()
let connector = SSConnector(type: .Scan)
model.dbMap(connector)
return executeInTransaction{
[unowned self] in
return SSResult<T>(result: self.conn.createTable(self.makeCreateStatement(connector, model: model)))
}
}
public func deleteTable<T:SSMappable>() -> SSResult<T> {
return executeInTransaction{
[unowned self] in
return SSResult<T>(result:self.conn.deleteTable([T.table]))
}
}
private func executeInTransaction<T>(execute:()->T) -> T{
if !conn.inTransaction {
conn.beginTransaction()
defer {
conn.commit()
}
return execute()
}
return execute()
}
public func table<T:SSMappable>() -> SSTable<T>{
let connector = SSConnector(type: .Map)
return executeInTransaction{
[unowned self] in
let table = SSTable<T>()
let results = self.conn.select(self.makeSelectAllStatement(T()), values: nil)
for result in results {
connector.values = result
let model = T()
model.dbMap(connector)
table.records.append(model)
}
return table
}
}
public func insert<T:SSMappable>(model:T) -> SSResult<T> {
let connector = SSConnector(type:.Scan)
model.dbMap(connector)
return executeInTransaction{
[unowned self] in
return SSResult<T>(result:self.conn.insert(self.makeInsertStatement(connector,model: model), values:self.getValues(connector)))
}
}
public func update<T:SSMappable>(model:T) -> SSResult<T> {
let connector = SSConnector(type:.Scan)
model.dbMap(connector)
guard let thePKey = getPrimaryKey(connector)?.value else{
return SSResult<T>(result: false)
}
return executeInTransaction{
[unowned self] in
var values = self.getAllValue(connector)
values.append(thePKey)
return SSResult<T>(result:self.conn.update(
self.makeUpdateStatement(connector,model: model),values:values)
)
}
}
public func query<T:SSMappable>(query:String,params:[AnyObject]) -> SSTable<T>{
let connector = SSConnector(type: .Map)
return executeInTransaction{
[unowned self] in
let table = SSTable<T>()
let results = self.conn.select(query, values: params)
for result in results {
connector.values = result
let model = T()
model.dbMap(connector)
table.records.append(model)
}
return table
}
}
public func delete<T:SSMappable>(model:T) -> SSResult<T> {
let connector = SSConnector(type:.Scan)
model.dbMap(connector)
guard let theKey = getPrimaryKey(connector)?.value else{
return SSResult<T>(result: false)
}
return executeInTransaction{
[unowned self] in
return SSResult<T>(result:self.conn.delete(self.makeDeleteStatement(connector,model: model),values: [theKey]))
}
}
public func beginTransaction(){
conn.beginTransaction()
}
public func commit(){
conn.commit()
}
public func rollback(){
conn.rollback()
}
private func getPrimaryKey(connector:SSConnector) -> SSScan? {
for item in connector.scans{
if item.isPrimaryKey && item.value != nil {
return item
}
}
return nil
}
private func makeUpdateStatement<T:SSMappable>(connector:SSConnector, model:T) -> String {
var columns = String.empty
let scans = removePrimaryKey(connector)
let count = scans.count
scans.enumerate().forEach{
let separator = count-1 == $0.index ? String.empty : ","+String.whiteSpace
columns += "\($0.element.name)=?" + separator
}
let theKey = getPrimaryKey(connector)!
return "UPDATE \(T.table) SET \(columns) WHERE \(theKey.name)=?;"
}
private func makeCreateStatement<T:SSMappable>(connector:SSConnector,model:T) -> String {
var columns:String = String.empty
connector.scans.enumerate().forEach{
let separator = (connector.scans.count-1) == $0.index ? String.empty : ","+String.whiteSpace
columns += $0.element.createColumnStatement() + separator
}
return "CREATE TABLE \(T.table)(\(columns));"
}
private func makeSelectAllStatement<T:SSMappable>(model:T) -> String {
return "SELECT * From \(T.table);"
}
private func makeInsertStatement<T:SSMappable>(connector:SSConnector, model:T) -> String {
var columns = String.empty
let count = connector.scans.count{ $0.value != nil }
connector.scans.select{ $0.value != nil }.enumerate().forEach{
let separator = count-1 == $0.index ? String.empty : ","+String.whiteSpace
columns += $0.element.name + separator
}
return "INSERT INTO \(T.table)(\(columns)) VALUES(\(makePlaceholderStatement(count)));"
}
private func makeDeleteStatement<T:SSMappable>(connector:SSConnector,model:T) -> String {
let theKey = getPrimaryKey(connector)!
return "DELETE FROM \(T.table) WHERE \(theKey.name)=?;"
}
private func getValues(connector:SSConnector) -> [AnyObject] {
var values: [AnyObject] = []
connector.scans.enumerate().forEach{
if let theValue = $0.element.value {
values.append(theValue)
}
}
return values
}
private func getAllValue(connector:SSConnector) -> [AnyObject] {
return removePrimaryKey(connector).map{
if let theValue = $0.value {
return theValue
}
return NSNull()
}
}
private func removePrimaryKey(connector:SSConnector) -> [SSScan] {
var scans = connector.scans
for scan in scans.enumerate() {
if scan.element.isPrimaryKey { scans.removeAtIndex(scan.index) }
}
return scans
}
private func makePlaceholderStatement(count:Int) -> String {
var rtn = String.empty
for i in 0..<count {
rtn += "?"
if i != count-1 {
rtn.append(Character(","))
}
}
return rtn
}
func scan<T:SSMappable>() -> (SSConnector,T){
let model = T()
let connector = SSConnector(type: .Scan)
model.dbMap(connector)
return (connector,model)
}
func mapping<T:SSMappable>() -> T{
let model = T()
let connector = SSConnector(type: .Scan)
model.dbMap(connector)
var values:[String:AnyObject] = [:]
for item in connector.scans.enumerate() {
switch item.element.type! {
case .CL_Integer:
values[item.element.name] = 0
case .CL_Text:
values[item.element.name] = "sample\(item.index)"
default:
break
}
}
connector.values = values
connector.type = .Map
model.dbMap(connector)
return model
}
}
/// Use for let work to column. e.g) scan column info, mapping value to column variables
public protocol SSWorker{
var value: AnyObject? { get set }
func work<T>(inout lhs:T?)
}
public class SSConnector {
var values:[String:AnyObject?]=[:]
var scans:[SSScan] = []
var type:SSType
public init(type:SSType){
self.type = type
}
public subscript (name:String,attrs:CLAttr...) -> SSWorker{
switch self.type {
case .Map: // return map worker
let map = SSMap()
if let theValue = values[name]{
map.value = theValue
}
return map
case .Scan: // return scan worker
let scan = SSScan(name,attrs: attrs)
scans.append(scan)
return scan
}
}
}
public enum SSType {
case Scan
case Map
}
public enum CLType{
case CL_Integer
case CL_Text
case CL_Real
// case CL_BLOB
}
public enum CLAttr{
case PrimaryKey
case AutoIncrement
case NotNull
case Unique
case Default(AnyObject)
case Check(String)
}
public func == (lhs:CLAttr,rhs:CLAttr) -> Bool{
switch (lhs,rhs) {
case (.PrimaryKey,.PrimaryKey):
return true
case (.AutoIncrement,.AutoIncrement):
return true
case (.NotNull,.NotNull):
return true
case (.Unique,.Unique):
return true
case (.Default,.Default):
return true
case (.Check,.Check):
return true
default:
return false
}
}
infix operator <- {
precedence 20
associativity none
}
public func <- <T>(inout lhs:T?,rhs:SSWorker){
rhs.work(&lhs)
}
| mit | 4227d75076e3620fc0865e25c6ab88d3 | 28.696165 | 139 | 0.569087 | 4.274735 | false | false | false | false |
NachoSoto/Carthage | Source/CarthageKit/Project.swift | 1 | 25222 | //
// Project.swift
// Carthage
//
// Created by Alan Rogers on 12/10/2014.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import LlamaKit
import ReactiveCocoa
/// Carthage’s bundle identifier.
public let CarthageKitBundleIdentifier = NSBundle(forClass: Project.self).bundleIdentifier!
// TODO: remove this once we’ve bumped LlamaKit.
private func try<T>(f: NSErrorPointer -> T?) -> Result<T> {
var error: NSError?
let because = -1
return f(&error).map(success) ?? failure(error ?? NSError(domain: CarthageKitBundleIdentifier, code: because, userInfo: nil))
}
/// ~/Library/Caches/org.carthage.CarthageKit/
private let CarthageUserCachesURL: NSURL = {
let URL = try { error in
NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.CachesDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true, error: error)
}
let fallbackDependenciesURL = NSURL.fileURLWithPath("~/.carthage".stringByExpandingTildeInPath, isDirectory:true)!
switch URL {
case .Success:
NSFileManager.defaultManager().removeItemAtURL(fallbackDependenciesURL, error: nil)
case let .Failure(error):
NSLog("Warning: No Caches directory could be found or created: \(error.localizedDescription). (\(error))")
}
return URL.value()?.URLByAppendingPathComponent(CarthageKitBundleIdentifier, isDirectory: true) ?? fallbackDependenciesURL
}()
/// The file URL to the directory in which downloaded release binaries will be
/// stored.
///
/// ~/Library/Caches/org.carthage.CarthageKit/binaries/
public let CarthageDependencyAssetsURL = CarthageUserCachesURL.URLByAppendingPathComponent("binaries", isDirectory: true)
/// The file URL to the directory in which cloned dependencies will be stored.
///
/// ~/Library/Caches/org.carthage.CarthageKit/dependencies/
public let CarthageDependencyRepositoriesURL = CarthageUserCachesURL.URLByAppendingPathComponent("dependencies", isDirectory: true)
/// The relative path to a project's Cartfile.
public let CarthageProjectCartfilePath = "Cartfile"
/// The relative path to a project's Cartfile.private.
public let CarthageProjectPrivateCartfilePath = "Cartfile.private"
/// The relative path to a project's Cartfile.resolved.
public let CarthageProjectResolvedCartfilePath = "Cartfile.resolved"
/// The text that needs to exist in a GitHub Release asset's name, for it to be
/// tried as a binary framework.
public let CarthageProjectBinaryAssetPattern = ".framework"
/// MIME types allowed for GitHub Release assets, for them to be considered as
/// binary frameworks.
public let CarthageProjectBinaryAssetContentTypes = [
"application/zip"
]
/// Describes an event occurring to or with a project.
public enum ProjectEvent {
/// The project is beginning to clone.
case Cloning(ProjectIdentifier)
/// The project is beginning a fetch.
case Fetching(ProjectIdentifier)
/// The project is being checked out to the specified revision.
case CheckingOut(ProjectIdentifier, String)
/// Any available binaries for the specified release of the project are
/// being downloaded. This may still be followed by `CheckingOut` event if
/// there weren't any viable binaries after all.
case DownloadingBinaries(ProjectIdentifier, String)
}
/// Represents a project that is using Carthage.
public final class Project {
/// File URL to the root directory of the project.
public let directoryURL: NSURL
/// The file URL to the project's Cartfile.
public var cartfileURL: NSURL {
return directoryURL.URLByAppendingPathComponent(CarthageProjectCartfilePath, isDirectory: false)
}
/// The file URL to the project's Cartfile.resolved.
public var resolvedCartfileURL: NSURL {
return directoryURL.URLByAppendingPathComponent(CarthageProjectResolvedCartfilePath, isDirectory: false)
}
/// Whether to prefer HTTPS for cloning (vs. SSH).
public var preferHTTPS = true
/// Whether to use submodules for dependencies, or just check out their
/// working directories.
public var useSubmodules = false
/// Whether to download binaries for dependencies, or just check out their
/// repositories.
public var useBinaries = false
/// Sends each event that occurs to a project underneath the receiver (or
/// the receiver itself).
public let projectEvents: HotSignal<ProjectEvent>
private let _projectEventsSink: SinkOf<ProjectEvent>
public init(directoryURL: NSURL) {
precondition(directoryURL.fileURL)
let (signal, sink) = HotSignal<ProjectEvent>.pipe()
projectEvents = signal
_projectEventsSink = sink
self.directoryURL = directoryURL
}
/// Caches versions to avoid expensive lookups, and unnecessary
/// fetching/cloning.
private var cachedVersions: [ProjectIdentifier: [PinnedVersion]] = [:]
private let cachedVersionsScheduler = QueueScheduler()
/// Reads the current value of `cachedVersions` on the appropriate
/// scheduler.
private func readCachedVersions() -> ColdSignal<[ProjectIdentifier: [PinnedVersion]]> {
return ColdSignal.lazy {
return .single(self.cachedVersions)
}
.evaluateOn(cachedVersionsScheduler)
.deliverOn(QueueScheduler())
}
/// Adds a given version to `cachedVersions` on the appropriate scheduler.
private func addCachedVersion(version: PinnedVersion, forProject project: ProjectIdentifier) {
self.cachedVersionsScheduler.schedule {
if var versions = self.cachedVersions[project] {
versions.append(version)
self.cachedVersions[project] = versions
} else {
self.cachedVersions[project] = [ version ]
}
}
}
/// Attempts to load Cartfile or Cartfile.private from the given directory,
/// merging their dependencies.
public func loadCombinedCartfile() -> ColdSignal<Cartfile> {
let cartfileURL = directoryURL.URLByAppendingPathComponent(CarthageProjectCartfilePath, isDirectory: false)
let privateCartfileURL = directoryURL.URLByAppendingPathComponent(CarthageProjectPrivateCartfilePath, isDirectory: false)
let isNoSuchFileError = { (error: NSError) -> Bool in
return error.domain == NSCocoaErrorDomain && error.code == NSFileReadNoSuchFileError
}
let cartfile = ColdSignal.lazy {
.fromResult(Cartfile.fromFile(cartfileURL))
}
.catch { error -> ColdSignal<Cartfile> in
if isNoSuchFileError(error) && NSFileManager.defaultManager().fileExistsAtPath(privateCartfileURL.path!) {
return .single(Cartfile())
}
return .error(error)
}
let privateCartfile = ColdSignal.lazy {
.fromResult(Cartfile.fromFile(privateCartfileURL))
}
.catch { error -> ColdSignal<Cartfile> in
if isNoSuchFileError(error) {
return .single(Cartfile())
}
return .error(error)
}
return cartfile.zipWith(privateCartfile)
.tryMap { (var cartfile, privateCartfile) -> Result<Cartfile> in
let duplicateDeps = cartfile.duplicateProjects().map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectCartfilePath)"]) }
+ privateCartfile.duplicateProjects().map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectPrivateCartfilePath)"]) }
+ duplicateProjectsInCartfiles(cartfile, privateCartfile).map { DuplicateDependency(project: $0, locations: ["\(CarthageProjectCartfilePath)", "\(CarthageProjectPrivateCartfilePath)"]) }
if duplicateDeps.count == 0 {
cartfile.appendCartfile(privateCartfile)
return success(cartfile)
}
return failure(CarthageError.DuplicateDependencies(duplicateDeps).error)
}
}
/// Reads the project's Cartfile.resolved.
public func loadResolvedCartfile() -> ColdSignal<ResolvedCartfile> {
return ColdSignal.lazy {
var error: NSError?
let resolvedCartfileContents = NSString(contentsOfURL: self.resolvedCartfileURL, encoding: NSUTF8StringEncoding, error: &error)
if let resolvedCartfileContents = resolvedCartfileContents {
return .fromResult(ResolvedCartfile.fromString(resolvedCartfileContents))
} else {
return .error(error ?? CarthageError.ReadFailed(self.resolvedCartfileURL).error)
}
}
}
/// Writes the given Cartfile.resolved out to the project's directory.
public func writeResolvedCartfile(resolvedCartfile: ResolvedCartfile) -> Result<()> {
var error: NSError?
if resolvedCartfile.description.writeToURL(resolvedCartfileURL, atomically: true, encoding: NSUTF8StringEncoding, error: &error) {
return success(())
} else {
return failure(error ?? CarthageError.WriteFailed(resolvedCartfileURL).error)
}
}
/// A scheduler used to serialize all Git operations within this project.
private let gitOperationScheduler = QueueScheduler()
/// Runs the given Git operation, blocking the `gitOperationScheduler` until
/// it has completed.
private func runGitOperation<T>(operation: ColdSignal<T>) -> ColdSignal<T> {
return ColdSignal { (sink, disposable) in
let schedulerDisposable = self.gitOperationScheduler.schedule {
let results = operation
.reduce(initial: []) { $0 + [ $1 ] }
.first()
switch results {
case let .Success(values):
ColdSignal.fromValues(values.unbox).startWithSink { valuesDisposable in
disposable.addDisposable(valuesDisposable)
return sink
}
case let .Failure(error):
sink.put(.Error(error))
}
}
disposable.addDisposable(schedulerDisposable)
}.deliverOn(QueueScheduler())
}
/// Clones the given dependency to the global repositories folder, or fetches
/// inside it if it has already been cloned.
///
/// Returns a signal which will send the URL to the repository's folder on
/// disk once cloning or fetching has completed.
private func cloneOrFetchDependency(project: ProjectIdentifier) -> ColdSignal<NSURL> {
let operation = cloneOrFetchProject(project, preferHTTPS: self.preferHTTPS)
.on(next: { event, _ in
self._projectEventsSink.put(event)
})
.map { _, URL in URL }
.takeLast(1)
return runGitOperation(operation)
}
/// Sends all versions available for the given project.
///
/// This will automatically clone or fetch the project's repository as
/// necessary.
private func versionsForProject(project: ProjectIdentifier) -> ColdSignal<PinnedVersion> {
let fetchVersions = cloneOrFetchDependency(project)
.map { repositoryURL in listTags(repositoryURL) }
.merge(identity)
.map { PinnedVersion($0) }
.on(next: { self.addCachedVersion($0, forProject: project) })
return readCachedVersions()
.map { versionsByProject -> ColdSignal<PinnedVersion> in
if let versions = versionsByProject[project] {
return .fromValues(versions)
} else {
return fetchVersions
}
}
.merge(identity)
}
/// Attempts to resolve a Git reference to a version.
private func resolvedGitReference(project: ProjectIdentifier, reference: String) -> ColdSignal<PinnedVersion> {
// We don't need the version list, but this takes care of
// cloning/fetching for us, while avoiding duplication.
return versionsForProject(project)
.then(resolveReferenceInRepository(repositoryFileURLForProject(project), reference))
.map { PinnedVersion($0) }
}
/// Attempts to determine the latest satisfiable version of the project's
/// Carthage dependencies.
///
/// This will fetch dependency repositories as necessary, but will not check
/// them out into the project's working directory.
public func updatedResolvedCartfile() -> ColdSignal<ResolvedCartfile> {
let resolver = Resolver(versionsForDependency: versionsForProject, cartfileForDependency: cartfileForDependency, resolvedGitReference: resolvedGitReference)
return loadCombinedCartfile()
.mergeMap { cartfile in resolver.resolveDependenciesInCartfile(cartfile) }
.reduce(initial: []) { $0 + [ $1 ] }
.map { ResolvedCartfile(dependencies: $0) }
}
/// Updates the dependencies of the project to the latest version. The
/// changes will be reflected in the working directory checkouts and
/// Cartfile.resolved.
public func updateDependencies() -> ColdSignal<()> {
return updatedResolvedCartfile()
.tryMap { resolvedCartfile -> Result<()> in
return self.writeResolvedCartfile(resolvedCartfile)
}
.then(checkoutResolvedDependencies())
}
/// Installs binaries for the given project, if available.
///
/// Sends a boolean indicating whether binaries were installed.
private func installBinariesForProject(project: ProjectIdentifier, atRevision revision: String) -> ColdSignal<Bool> {
return ColdSignal.lazy {
if !self.useBinaries {
return .single(false)
}
let checkoutDirectoryURL = self.directoryURL.URLByAppendingPathComponent(project.relativePath, isDirectory: true)
switch project {
case let .GitHub(repository):
return self.downloadMatchingBinariesForProject(project, atRevision: revision, fromRepository: repository, withCredentials: nil)
.catch { error in
// If we were unable to fetch releases, try loading credentials from Git.
if error.domain == NSURLErrorDomain {
return GitHubCredentials.loadFromGit()
.mergeMap { credentials in
if let credentials = credentials {
return self.downloadMatchingBinariesForProject(project, atRevision: revision, fromRepository: repository, withCredentials: credentials)
} else {
return .error(error)
}
}
} else {
return .error(error)
}
}
.concatMap(unzipArchiveToTemporaryDirectory)
.concatMap { directoryURL in
return frameworksInDirectory(directoryURL)
.mergeMap(self.copyFrameworkToBuildFolder)
.on(completed: {
_ = NSFileManager.defaultManager().trashItemAtURL(checkoutDirectoryURL, resultingItemURL: nil, error: nil)
})
.then(.single(directoryURL))
}
.tryMap { (temporaryDirectoryURL: NSURL, error: NSErrorPointer) -> Bool? in
if NSFileManager.defaultManager().removeItemAtURL(temporaryDirectoryURL, error: error) {
return true
} else {
return nil
}
}
.concat(.single(false))
.take(1)
case .Git:
return .single(false)
}
}
}
/// Downloads any binaries that may be able to be used instead of a
/// repository checkout.
///
/// Sends the URL to each downloaded zip, after it has been moved to a
/// less temporary location.
private func downloadMatchingBinariesForProject(project: ProjectIdentifier, atRevision revision: String, fromRepository repository: GitHubRepository, withCredentials credentials: GitHubCredentials?) -> ColdSignal<NSURL> {
return releaseForTag(revision, repository, credentials)
.filter(binaryFrameworksCanBeProvidedByRelease)
.on(next: { release in
self._projectEventsSink.put(.DownloadingBinaries(project, release.name))
})
.concatMap { release in
return ColdSignal
.fromValues(release.assets)
.filter(binaryFrameworksCanBeProvidedByAsset)
.concatMap { asset in
let fileURL = fileURLToCachedBinary(project, release, asset)
return ColdSignal<NSURL>.lazy {
if NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
return .single(fileURL)
} else {
return downloadAsset(asset, credentials)
.concatMap { downloadURL in cacheDownloadedBinary(downloadURL, toURL: fileURL) }
}
}
}
}
}
/// Copies the framework at the given URL into the current project's build
/// folder.
///
/// Sends the URL to the framework after copying.
private func copyFrameworkToBuildFolder(frameworkURL: NSURL) -> ColdSignal<NSURL> {
return architecturesInFramework(frameworkURL)
.filter { arch in arch.hasPrefix("arm") }
.map { _ in SDK.iPhoneOS }
.concat(ColdSignal.single(SDK.MacOSX))
.take(1)
.map { sdk in sdk.platform }
.map { platform in self.directoryURL.URLByAppendingPathComponent(platform.relativePath, isDirectory: true) }
.map { platformFolderURL in platformFolderURL.URLByAppendingPathComponent(frameworkURL.lastPathComponent!) }
.mergeMap { destinationFrameworkURL in copyFramework(frameworkURL, destinationFrameworkURL) }
}
/// Checks out the given project into its intended working directory,
/// cloning it first if need be.
private func checkoutOrCloneProject(project: ProjectIdentifier, atRevision revision: String, submodulesByPath: [String: Submodule]) -> ColdSignal<()> {
let repositoryURL = repositoryFileURLForProject(project)
let workingDirectoryURL = directoryURL.URLByAppendingPathComponent(project.relativePath, isDirectory: true)
let checkoutSignal = ColdSignal<()>.lazy {
var submodule: Submodule?
if var foundSubmodule = submodulesByPath[project.relativePath] {
foundSubmodule.URL = repositoryURLForProject(project, preferHTTPS: self.preferHTTPS)
foundSubmodule.SHA = revision
submodule = foundSubmodule
} else if self.useSubmodules {
submodule = Submodule(name: project.relativePath, path: project.relativePath, URL: repositoryURLForProject(project, preferHTTPS: self.preferHTTPS), SHA: revision)
}
if let submodule = submodule {
return self.runGitOperation(addSubmoduleToRepository(self.directoryURL, submodule, GitURL(repositoryURL.path!)))
} else {
return checkoutRepositoryToDirectory(repositoryURL, workingDirectoryURL, revision: revision)
}
}
.on(started: {
self._projectEventsSink.put(.CheckingOut(project, revision))
})
return commitExistsInRepository(repositoryURL, revision: revision)
.map { exists -> ColdSignal<NSURL> in
if exists {
return .empty()
} else {
return self.cloneOrFetchDependency(project)
}
}
.merge(identity)
.then(checkoutSignal)
}
/// Checks out the dependencies listed in the project's Cartfile.resolved.
public func checkoutResolvedDependencies() -> ColdSignal<()> {
/// Determine whether the repository currently holds any submodules (if
/// it even is a repository).
let submodulesSignal = submodulesInRepository(self.directoryURL)
.reduce(initial: [:]) { (var submodulesByPath: [String: Submodule], submodule) in
submodulesByPath[submodule.path] = submodule
return submodulesByPath
}
return loadResolvedCartfile()
.zipWith(submodulesSignal)
.map { (resolvedCartfile, submodulesByPath) -> ColdSignal<()> in
return ColdSignal.fromValues(resolvedCartfile.dependencies)
.mergeMap { dependency in
let project = dependency.project
let revision = dependency.version.commitish
return self.installBinariesForProject(project, atRevision: revision)
.mergeMap { installed in
if installed {
return .empty()
} else {
return self.checkoutOrCloneProject(project, atRevision: revision, submodulesByPath: submodulesByPath)
}
}
}
}
.merge(identity)
.then(.empty())
}
/// Attempts to build each Carthage dependency that has been checked out.
///
/// Returns a signal of all standard output from `xcodebuild`, and a
/// signal-of-signals representing each scheme being built.
public func buildCheckedOutDependenciesWithConfiguration(configuration: String, forPlatform platform: Platform?) -> (HotSignal<NSData>, ColdSignal<BuildSchemeSignal>) {
let (stdoutSignal, stdoutSink) = HotSignal<NSData>.pipe()
let schemeSignals = loadResolvedCartfile()
.map { resolvedCartfile in ColdSignal.fromValues(resolvedCartfile.dependencies) }
.merge(identity)
.map { dependency -> ColdSignal<BuildSchemeSignal> in
return ColdSignal.lazy {
let dependencyPath = self.directoryURL.URLByAppendingPathComponent(dependency.project.relativePath, isDirectory: true).path!
if !NSFileManager.defaultManager().fileExistsAtPath(dependencyPath) {
return .empty()
}
let (buildOutput, schemeSignals) = buildDependencyProject(dependency.project, self.directoryURL, withConfiguration: configuration, platform: platform)
buildOutput.observe(stdoutSink)
return schemeSignals
}
}
.concat(identity)
return (stdoutSignal, schemeSignals)
}
}
/// Constructs a file URL to where the binary corresponding to the given
/// arguments should live.
private func fileURLToCachedBinary(project: ProjectIdentifier, release: GitHubRelease, asset: GitHubRelease.Asset) -> NSURL {
// ~/Library/Caches/org.carthage.CarthageKit/binaries/ReactiveCocoa/v2.3.1/1234-ReactiveCocoa.framework.zip
return CarthageDependencyAssetsURL.URLByAppendingPathComponent("\(project.name)/\(release.tag)/\(asset.ID)-\(asset.name)", isDirectory: false)
}
/// Caches the downloaded binary at the given URL, moving it to the other URL
/// given.
///
/// Sends the final file URL upon success.
private func cacheDownloadedBinary(downloadURL: NSURL, toURL cachedURL: NSURL) -> ColdSignal<NSURL> {
return ColdSignal
.single(cachedURL)
.try { fileURL, error in
let parentDirectoryURL = fileURL.URLByDeletingLastPathComponent!
return NSFileManager.defaultManager().createDirectoryAtURL(parentDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: error)
}
.try { newDownloadURL, error in
if rename(downloadURL.fileSystemRepresentation, newDownloadURL.fileSystemRepresentation) == 0 {
return true
} else {
error.memory = NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil)
return false
}
}
}
/// Sends the URL to each framework bundle found in the given directory.
private func frameworksInDirectory(directoryURL: NSURL) -> ColdSignal<NSURL> {
return NSFileManager.defaultManager()
.carthage_enumeratorAtURL(directoryURL, includingPropertiesForKeys: [ NSURLTypeIdentifierKey ], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles | NSDirectoryEnumerationOptions.SkipsPackageDescendants, catchErrors: true)
.map { enumerator, URL in URL }
.filter { URL in
var typeIdentifier: AnyObject?
if URL.getResourceValue(&typeIdentifier, forKey: NSURLTypeIdentifierKey, error: nil) {
if let typeIdentifier: AnyObject = typeIdentifier {
if UTTypeConformsTo(typeIdentifier as String, kUTTypeFramework) != 0 {
return true
}
}
}
return false
}
}
/// Determines whether a Release is a suitable candidate for binary frameworks.
private func binaryFrameworksCanBeProvidedByRelease(release: GitHubRelease) -> Bool {
return !release.draft && !release.prerelease && !release.assets.isEmpty
}
/// Determines whether a release asset is a suitable candidate for binary
/// frameworks.
private func binaryFrameworksCanBeProvidedByAsset(asset: GitHubRelease.Asset) -> Bool {
let name = asset.name as NSString
if name.rangeOfString(CarthageProjectBinaryAssetPattern).location == NSNotFound {
return false
}
return contains(CarthageProjectBinaryAssetContentTypes, asset.contentType)
}
/// Returns the file URL at which the given project's repository will be
/// located.
private func repositoryFileURLForProject(project: ProjectIdentifier) -> NSURL {
return CarthageDependencyRepositoriesURL.URLByAppendingPathComponent(project.name, isDirectory: true)
}
/// Loads the Cartfile for the given dependency, at the given version.
private func cartfileForDependency(dependency: Dependency<PinnedVersion>) -> ColdSignal<Cartfile> {
let repositoryURL = repositoryFileURLForProject(dependency.project)
return contentsOfFileInRepository(repositoryURL, CarthageProjectCartfilePath, revision: dependency.version.commitish)
.catch { _ in .empty() }
.tryMap { Cartfile.fromString($0) }
}
/// Returns the URL that the project's remote repository exists at.
private func repositoryURLForProject(project: ProjectIdentifier, #preferHTTPS: Bool) -> GitURL {
switch project {
case let .GitHub(repository):
if preferHTTPS {
return repository.HTTPSURL
} else {
return repository.SSHURL
}
case let .Git(URL):
return URL
}
}
/// Clones the given project to the global repositories folder, or fetches
/// inside it if it has already been cloned.
///
/// Returns a signal which will send the operation type once started, and
/// the URL to where the repository's folder will exist on disk, then complete
/// when the operation completes.
public func cloneOrFetchProject(project: ProjectIdentifier, #preferHTTPS: Bool) -> ColdSignal<(ProjectEvent, NSURL)> {
let repositoryURL = repositoryFileURLForProject(project)
return ColdSignal.lazy {
var error: NSError?
if !NSFileManager.defaultManager().createDirectoryAtURL(CarthageDependencyRepositoriesURL, withIntermediateDirectories: true, attributes: nil, error: &error) {
return .error(error ?? CarthageError.WriteFailed(CarthageDependencyRepositoriesURL).error)
}
let remoteURL = repositoryURLForProject(project, preferHTTPS: preferHTTPS)
if NSFileManager.defaultManager().createDirectoryAtURL(repositoryURL, withIntermediateDirectories: false, attributes: nil, error: nil) {
// If we created the directory, we're now responsible for
// cloning it.
let cloneSignal = cloneRepository(remoteURL, repositoryURL)
return ColdSignal.single((ProjectEvent.Cloning(project), repositoryURL))
.concat(cloneSignal.then(.empty()))
} else {
let fetchSignal = fetchRepository(repositoryURL, remoteURL: remoteURL, refspec: "+refs/heads/*:refs/heads/*") /* lol syntax highlighting */
return ColdSignal.single((ProjectEvent.Fetching(project), repositoryURL))
.concat(fetchSignal.then(.empty()))
}
}
}
| mit | f07f1117ae9976c2d873b87db98295c5 | 37.856703 | 229 | 0.748275 | 4.369023 | false | false | false | false |
netcosports/Gnomon | Sources/Core/Common.swift | 1 | 8891 | //
// Created by Vladimir Burdukov on 7/6/16.
// Copyright © 2016 NetcoSports. All rights reserved.
//
import Foundation
import RxSwift
extension String: Error {
}
@available(*, deprecated, renamed: "Gnomon.Error")
public enum CommonError: Swift.Error {
case none
}
public extension Gnomon {
enum Error: Swift.Error {
case undefined(message: String?)
case nonHTTPResponse(response: URLResponse)
case invalidResponse
case unableToParseModel(Swift.Error)
case errorStatusCode(Int, Data)
}
}
extension HTTPURLResponse {
private static var cacheFlagKey = "X-ResultFromHttpCache"
var httpCachedResponse: HTTPURLResponse? {
guard let url = url else { return nil }
var headers = allHeaderFields as? [String: String] ?? [:]
headers[HTTPURLResponse.cacheFlagKey] = "true"
return HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers)
}
var resultFromHTTPCache: Bool {
guard let headers = allHeaderFields as? [String: String] else { return false }
return headers[HTTPURLResponse.cacheFlagKey] == "true"
}
}
func cachePolicy<U>(for request: Request<U>, localCache: Bool) throws -> URLRequest.CachePolicy {
if localCache {
guard !request.disableLocalCache else { throw "local cache was disabled in request" }
return .returnCacheDataDontLoad
} else {
return request.disableHttpCache ? .reloadIgnoringLocalCacheData : .useProtocolCachePolicy
}
}
func prepareURLRequest<U>(from request: Request<U>, cachePolicy: URLRequest.CachePolicy,
interceptors: [AsyncInterceptor]) throws -> Observable<URLRequest> {
var urlRequest = URLRequest(url: request.url, cachePolicy: cachePolicy, timeoutInterval: request.timeout)
urlRequest.httpMethod = request.method.description
if let headers = request.headers {
for (key, value) in headers {
urlRequest.setValue(value, forHTTPHeaderField: key)
}
}
switch (request.method.hasBody, request.params) {
case (_, .skipURLEncoding):
urlRequest.url = request.url
case (_, .none):
urlRequest.url = try prepareURL(with: request.url, params: nil)
case let (_, .query(params)):
urlRequest.url = try prepareURL(with: request.url, params: params)
case (false, _):
throw "\(request.method.description) request can't have a body"
case (true, let .urlEncoded(params)):
let queryItems = prepare(value: params, with: nil)
var components = URLComponents()
components.queryItems = queryItems
urlRequest.httpBody = components.percentEncodedQuery?.data(using: String.Encoding.utf8)
urlRequest.url = try prepareURL(with: request.url, params: nil)
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
case (true, let .json(params)):
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: params, options: [])
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.url = try prepareURL(with: request.url, params: nil)
case (true, let .multipart(form, files)):
let (data, contentType) = try prepareMultipartData(with: form, files)
urlRequest.httpBody = data
urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
urlRequest.url = try prepareURL(with: request.url, params: nil)
case (true, let .data(data, contentType)):
urlRequest.httpBody = data
urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
urlRequest.url = try prepareURL(with: request.url, params: nil)
}
urlRequest.httpShouldHandleCookies = request.shouldHandleCookies
return process(urlRequest, for: request, with: interceptors)
}
private func process<U>(_ urlRequest: URLRequest, for request: Request<U>,
with interceptors: [AsyncInterceptor]) -> Observable<URLRequest> {
if let asynInterceptor = request.asyncInterceptor ?? request.interceptor.map { interceptor in { urlRequest in
Observable<URLRequest>.deferred { .just(interceptor(urlRequest)) }
}} {
if request.isInterceptorExclusive {
return asynInterceptor(urlRequest)
} else {
var urlRequest = asynInterceptor(urlRequest)
urlRequest = interceptors.reduce(urlRequest) { request, interceptor in
request.flatMap { interceptor($0) }
}
return urlRequest
}
} else {
return interceptors.reduce(.just(urlRequest)) { request, interceptor in
request.flatMap { interceptor($0) }
}
}
}
func prepareURL(with url: URL, params: [String: Any]?) throws -> URL {
var queryItems = [URLQueryItem]()
if let params = params {
queryItems.append(contentsOf: prepare(value: params, with: nil))
}
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else {
throw "can't parse provided URL \"\(url)\""
}
queryItems.append(contentsOf: components.queryItems ?? [])
components.queryItems = queryItems.count > 0 ? queryItems : nil
guard let url = components.url else { throw "can't prepare URL from components: \(components)" }
return url
}
private func prepare(value: Any, with key: String?) -> [URLQueryItem] {
switch value {
case let dictionary as [String: Any]:
return dictionary.sorted { $0.0 < $1.0 }.flatMap { nestedKey, nestedValue -> [URLQueryItem] in
if let key = key {
return prepare(value: nestedValue, with: "\(key)[\(nestedKey)]")
} else {
return prepare(value: nestedValue, with: nestedKey)
}
}
case let array as [Any]:
if let key = key {
return array.flatMap { prepare(value: $0, with: "\(key)[]") }
} else {
return []
}
case let string as String:
if let key = key {
return [URLQueryItem(name: key, value: string)]
} else {
return []
}
case let stringConvertible as CustomStringConvertible:
if let key = key {
return [URLQueryItem(name: key, value: stringConvertible.description)]
} else {
return []
}
default: return []
}
}
func prepareMultipartData(with form: [String: String],
_ files: [String: MultipartFile]) throws -> (data: Data, contentType: String) {
let boundary = "__X_NST_BOUNDARY__"
var data = Data()
guard let boundaryData = "--\(boundary)\r\n".data(using: .utf8) else { throw "can't encode boundary" }
try form.keys.sorted().forEach { key in
guard let value = form[key] else {
throw "can't encode key \(key)"
}
data.append(boundaryData)
guard let dispositionData = "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8) else {
throw "can't encode key \(key)"
}
data.append(dispositionData)
guard let valueData = (value + "\r\n").data(using: .utf8) else { throw "can't encode value \(value)" }
data.append(valueData)
}
try files.keys.sorted().forEach { key in
guard let file = files[key] else {
throw "can't find file for key \(key)"
}
data.append(boundaryData)
guard let dispositionData = "Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(file.filename)\"\r\n"
.data(using: .utf8) else { throw "can't encode key \(key)" }
data.append(dispositionData)
guard let contentTypeData = "Content-Type: \(file.contentType)\r\n\r\n".data(using: .utf8) else {
throw "can't encode content-type \(file.contentType)"
}
data.append(contentTypeData)
data.append(file.data)
guard let carriageReturnData = "\r\n".data(using: .utf8) else {
throw "can't encode carriage return"
}
data.append(carriageReturnData)
}
guard let closingBoundaryData = "--\(boundary)--\r\n".data(using: .utf8) else {
throw "can't encode closing boundary"
}
data.append(closingBoundaryData)
return (data, "multipart/form-data; boundary=\(boundary)")
}
func processedResult<U>(from data: Data, for request: Request<U>) throws -> U {
let container = try U.dataContainer(with: data, at: request.xpath)
return try U(container)
}
public typealias Interceptor = (URLRequest) -> URLRequest
public typealias AsyncInterceptor = (URLRequest) -> Observable<URLRequest>
public func + (left: @escaping (URLRequest) -> URLRequest,
right: @escaping (URLRequest) -> URLRequest) -> (URLRequest) -> URLRequest {
return { input in
return right(left(input))
}
}
extension Result {
var value: Success? {
switch self {
case let .success(value): return value
case .failure: return nil
}
}
}
extension ObservableType {
func asResult() -> Observable<Result<Element, Error>> {
return materialize().map { event -> Event<Result<Element, Error>> in
switch event {
case let .next(element): return .next(.success(element))
case let .error(error): return .next(.failure(error))
case .completed: return .completed
}
}.dematerialize()
}
}
| mit | 841670c5ec544c6aa7ef649a0f0f7d9d | 33.862745 | 116 | 0.680765 | 4.093002 | false | false | false | false |
adrian-kubala/MyPlaces | MyPlaces/CustomMapView.swift | 1 | 1207 | //
// CustomMapView.swift
// Places
//
// Created by Adrian on 29.09.2016.
// Copyright © 2016 Adrian Kubała. All rights reserved.
//
import MapKit
class CustomMapView: MKMapView {
let pinView = UIImageView(image: UIImage(named: "map-location"))
override func draw(_ rect: CGRect) {
setupAnnotation()
}
func setupMapRegion(_ location: CLLocation) {
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
setupRegion(center)
}
func setupMapRegionWithCoordinate(_ coordinate: CLLocationCoordinate2D) {
setupRegion(coordinate)
}
fileprivate func setupRegion(_ center: CLLocationCoordinate2D) {
let span = MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)
let region = MKCoordinateRegion(center: center, span: span)
setRegion(region, animated: true)
}
fileprivate func setupAnnotation() {
addSubview(pinView)
centerPin()
}
fileprivate func centerPin() {
pinView.center = convert(center, from: superview)
}
func hideAnnotationIfNeeded() {
pinView.isHidden = true
}
func showAnnotation() {
pinView.isHidden = false
}
}
| mit | 019696947f3278db2888ff1b2eb8d7cd | 23.1 | 121 | 0.702905 | 4.303571 | false | false | false | false |
rain2540/Play-with-Algorithms-in-Swift | Swift-100-Questions/Question00.playground/Contents.swift | 1 | 876 | //: Question 00
//:
//: 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
//:
//: 1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去掉不满足条件的排列。
//:
//: 2.程序源代码:
import Foundation
print("for loop: ")
for i in 1 ..< 5 {
for j in 1 ..< 5 {
for k in 1 ..< 5 {
if (i != j) && (i != k) && (j != k) { // 确保i, j, k互不相同
print("\(i)\(j)\(k)")
}
}
}
}
print("")
print("function forEach: ")
let nums = [1, 2, 3, 4]
nums.forEach { (i) in
nums.forEach({ (j) in
nums.forEach({ (k) in
if (i != j) && (i != k) && (j != k) { // 确保i, j, k互不相同
print("\(i)\(j)\(k)")
}
})
})
}
| mit | 40aae9ca1f88d5566566c11739ebd87d | 18.882353 | 69 | 0.402367 | 2.380282 | false | false | false | false |
lando2319/ParseLoginExample | pleDir/SignUpVC.swift | 1 | 1373 | //
// SignUpVC.swift
// fourHourSocietyActual
//
// Created by MIKE LAND on 8/21/15.
// Copyright (c) 2015 Parse. All rights reserved.
//
import UIKit
import Parse
class SignUpVC: UIViewController {
@IBOutlet weak var userEmail: UITextField!
@IBOutlet weak var userPassword: UITextField!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var username: UITextField!
@IBAction func signUpUser(sender: AnyObject) {
var user = PFUser()
user.username = username.text
user.email = userEmail.text
user.password = userPassword.text
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? String
self.errorLabel.text = errorString
// Show the errorString somewhere and let the user try again.
} else {
// Hooray! Let them use the app now.
self.performSegueWithIdentifier("goHomeFromSignUp", sender: self)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Title HERE"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} | apache-2.0 | 51d009a0c48b6c6f5a260690198c22d9 | 29.533333 | 81 | 0.616169 | 4.783972 | false | false | false | false |
IvanVorobei/RequestPermission | Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Other/SPGradientView.swift | 1 | 3122 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([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 UIKit
class SPGradientView: SPView {
var gradientLayer: CAGradientLayer = CAGradientLayer()
var startColor = UIColor.white { didSet { self.updateGradient() }}
var endColor = UIColor.black { didSet { self.updateGradient() }}
var startColorPosition = Position.topLeft { didSet { self.updateGradient() }}
var endColorPosition = Position.bottomRight { didSet { self.updateGradient() }}
override func commonInit() {
super.commonInit()
self.layer.insertSublayer(self.gradientLayer, at: 0)
}
private func updateGradient() {
self.gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
self.gradientLayer.locations = [0.0, 1.0]
self.gradientLayer.startPoint = self.startColorPosition.point
self.gradientLayer.endPoint = self.endColorPosition.point
}
override func layoutSublayers(of layer: CALayer) {
self.gradientLayer.frame = self.bounds
super.layoutSublayers(of: layer)
}
enum Position {
case topLeft
case topCenter
case topRight
case bottomLeft
case bottomCenter
case bottomRight
case mediumLeft
case mediumRight
var point: CGPoint {
switch self {
case .topLeft:
return CGPoint.init(x: 0, y: 0)
case .topCenter:
return CGPoint.init(x: 0.5, y: 0)
case .topRight:
return CGPoint.init(x: 1, y: 0)
case .bottomLeft:
return CGPoint.init(x: 0, y: 1)
case .bottomCenter:
return CGPoint.init(x: 0.5, y: 1)
case .bottomRight:
return CGPoint.init(x: 1, y: 1)
case .mediumLeft:
return CGPoint.init(x: 0, y: 0.5)
case .mediumRight:
return CGPoint.init(x: 1, y: 0.5)
}
}
}
}
| mit | 47bc2c73c810a060cf945799df3ea0b8 | 37.060976 | 83 | 0.643063 | 4.610044 | false | false | false | false |
duming91/Hear-You | Pods/RAMAnimatedTabBarController/RAMAnimatedTabBarController/Animations/BounceAnimation/RAMBounceAnimation.swift | 2 | 3035 | // RAMBounceAnimation.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.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
public class RAMBounceAnimation : RAMItemAnimation {
override public func playAnimation(icon : UIImageView, textLabel : UILabel) {
playBounceAnimation(icon)
textLabel.textColor = textSelectedColor
}
override public func deselectAnimation(icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor, defaultIconColor: UIColor) {
textLabel.textColor = defaultTextColor
if let iconImage = icon.image {
let renderMode = CGColorGetAlpha(defaultIconColor.CGColor) == 0 ? UIImageRenderingMode.AlwaysOriginal :
UIImageRenderingMode.AlwaysTemplate
let renderImage = iconImage.imageWithRenderingMode(renderMode)
icon.image = renderImage
icon.tintColor = defaultIconColor
}
}
override public func selectedState(icon : UIImageView, textLabel : UILabel) {
textLabel.textColor = textSelectedColor
if let iconImage = icon.image {
let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = iconSelectedColor
}
}
func playBounceAnimation(icon : UIImageView) {
let bounceAnimation = CAKeyframeAnimation(keyPath: Constants.AnimationKeys.Scale)
bounceAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
bounceAnimation.duration = NSTimeInterval(duration)
bounceAnimation.calculationMode = kCAAnimationCubic
icon.layer.addAnimation(bounceAnimation, forKey: nil)
if let iconImage = icon.image {
let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = iconSelectedColor
}
}
}
| gpl-3.0 | c1fe7a5daa101e8c90ef7d5791657c70 | 41.746479 | 140 | 0.693575 | 5.278261 | false | false | false | false |
kpham13/SpaceshipGameTutorial | SpaceshipGameTutorial/GameScene.swift | 1 | 5399 | //
// GameScene.swift
// SpaceshipGameTutorial
//
// Created by Kevin Pham on 11/28/14.
// Copyright (c) 2014 Kevin Pham. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var ship = SKSpriteNode()
var actionMoveUp = SKAction()
var actionMoveDown = SKAction()
var lastMissileAdded : NSTimeInterval = 0.0
let shipCategory = 0x1 << 1
let obstacleCategory = 0x1 << 2
let backgroundVelocity : CGFloat = 3.0
let missileVelocity : CGFloat = 5.0
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.backgroundColor = SKColor.whiteColor()
self.initializingScrollingBackground()
self.addShip()
self.addMissile()
// Making self delegate of physics world
self.physicsWorld.gravity = CGVectorMake(0, 0)
self.physicsWorld.contactDelegate = self
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if location.y > ship.position.y {
if ship.position.y < 300 {
ship.runAction(actionMoveUp)
}
} else {
if ship.position.y > 50 {
ship.runAction(actionMoveDown)
}
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if currentTime - self.lastMissileAdded > 1 {
self.lastMissileAdded = currentTime + 1
self.addMissile()
}
self.moveBackground()
self.moveObstacle()
}
func addShip() {
// Initializing spaceship node
ship = SKSpriteNode(imageNamed: "spaceship")
ship.setScale(0.5)
ship.zRotation = CGFloat(-M_PI/2)
// Adding SpriteKit physics body for collision detection
ship.physicsBody = SKPhysicsBody(rectangleOfSize: ship.size)
ship.physicsBody?.categoryBitMask = UInt32(shipCategory)
ship.physicsBody?.dynamic = true
ship.physicsBody?.contactTestBitMask = UInt32(obstacleCategory)
ship.physicsBody?.collisionBitMask = 0
ship.name = "ship"
ship.position = CGPointMake(120, 160)
self.addChild(ship)
actionMoveUp = SKAction.moveByX(0, y: 30, duration: 0.2)
actionMoveDown = SKAction.moveByX(0, y: -30, duration: 0.2)
}
func initializingScrollingBackground() {
for var index = 0; index < 2; ++index {
let bg = SKSpriteNode(imageNamed: "bg")
bg.position = CGPoint(x: index * Int(bg.size.width), y: 0)
bg.anchorPoint = CGPointZero
bg.name = "background"
self.addChild(bg)
}
}
func moveBackground() {
self.enumerateChildNodesWithName("background", usingBlock: { (node, stop) -> Void in
if let bg = node as? SKSpriteNode {
bg.position = CGPoint(x: bg.position.x - self.backgroundVelocity, y: bg.position.y)
// Checks if bg node is completely scrolled off the screen, if yes, then puts it at the end of the other node.
if bg.position.x <= -bg.size.width {
bg.position = CGPointMake(bg.position.x + bg.size.width * 2, bg.position.y)
}
}
})
}
func addMissile() {
// Initializing missile node
var missile = SKSpriteNode(imageNamed: "red-missile")
missile.setScale(0.15)
// Adding SpriteKit physics body for collision detection
missile.physicsBody = SKPhysicsBody(rectangleOfSize: missile.size)
missile.physicsBody?.categoryBitMask = UInt32(obstacleCategory)
missile.physicsBody?.dynamic = true
missile.physicsBody?.contactTestBitMask = UInt32(shipCategory)
missile.physicsBody?.collisionBitMask = 0
missile.physicsBody?.usesPreciseCollisionDetection = true
missile.name = "missile"
// Selecting random y position for missile
var random : CGFloat = CGFloat(arc4random_uniform(300))
missile.position = CGPointMake(self.frame.size.width + 20, random)
self.addChild(missile)
}
func moveObstacle() {
self.enumerateChildNodesWithName("missile", usingBlock: { (node, stop) -> Void in
if let obstacle = node as? SKSpriteNode {
obstacle.position = CGPoint(x: obstacle.position.x - self.missileVelocity, y: obstacle.position.y)
if obstacle.position.x < 0 {
obstacle.removeFromParent()
}
}
})
}
func didBeginContact(contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & UInt32(shipCategory)) != 0 && (secondBody.categoryBitMask & UInt32(obstacleCategory)) != 0 {
ship.removeFromParent()
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = GameOverScene(size: self.size)
self.view?.presentScene(scene, transition: reveal)
}
}
} | mit | 0f9592c7e788717930a3a6ff5b84c5ba | 32.962264 | 130 | 0.625301 | 4.610589 | false | false | false | false |
skbylife/git-swift-todo-tutorial | Todo/Todo/TodoListTableTableViewController.swift | 1 | 2435 | //
// ToDoListTableTableViewController.swift
// Todo
//
import UIKit
class TodoListTableViewController: UITableViewController {
var todoItems: [TodoItem] = []
@IBAction func unwindAndAddToList(segue: UIStoryboardSegue) {
let source = segue.sourceViewController as AddTodoItemViewController
let todoItem:TodoItem = source.todoItem
if todoItem.itemName != "" {
self.todoItems.append(todoItem)
self.tableView.reloadData()
}
}
@IBAction func unwindToList(segue: UIStoryboardSegue) {
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func loadInitialData() {
todoItems = [
TodoItem(itemName: "Go to the dentist"),
TodoItem(itemName: "Fetch groceries"),
TodoItem(itemName: "Sleep")
]
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let tappedItem = todoItems[indexPath.row] as TodoItem
tappedItem.completed = !tappedItem.completed
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let tempCell = tableView.dequeueReusableCellWithIdentifier("ListPrototypeCell") as UITableViewCell
let todoItem = todoItems[indexPath.row]
// Downcast from UILabel? to UILabel
let cell = tempCell.textLabel as UILabel!
cell.text = todoItem.itemName
if (todoItem.completed) {
tempCell.accessoryType = UITableViewCellAccessoryType.Checkmark;
} else {
tempCell.accessoryType = UITableViewCellAccessoryType.None;
}
return tempCell
}
override func viewDidLoad() {
super.viewDidLoad()
loadInitialData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return todoItems.count
}
}
| mit | 0546086de06345484603f28acc82db93 | 29.061728 | 118 | 0.648871 | 5.597701 | false | false | false | false |
jlainog/Messages | Messages/Messages/ChannelViewController.swift | 1 | 4166 | //
// ChannelViewController.swift
// Messages
//
// Created by Gustavo Mario Londoño Correa on 3/9/17.
// Copyright © 2017 JLainoG. All rights reserved.
//
import UIKit
class ChannelViewController: UIViewController {
@IBOutlet weak var channelsTable: UITableView!
@IBOutlet weak var newItemTxtField: UITextField!
fileprivate var channels: [Channel]?
var user: User! = SessionCache.sharedInstance.user
override func viewDidLoad() {
super.viewDidLoad()
channelsTable.delegate = self
newItemTxtField.delegate = self
channelsTable.dataSource = self
channelsTable.register(UINib(nibName: "ChannelCell", bundle: nil), forCellReuseIdentifier: "cell")
channels = [Channel]()
//TODO - Handle nils
ChannelFacade.listAndObserveChannels() {
[weak self] channel in
self?.channels!.append(channel)
self?.channelsTable.reloadData()
}
//TODO - Handle nils
ChannelFacade.didRemoveChannel() {
[weak self] channel in
if let channels = self?.channels {
self?.channels = channels.filter() { $0.id != channel.id }
self?.channelsTable.reloadData()
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
newItemTxtField.becomeFirstResponder()
self.hideKeyboardWhenTappedAround()
}
deinit {
ChannelFacade.dismmissChannelObservers()
}
@IBAction func createChannel(_ sender: UIButton) {
guard newItemTxtField.text != "" else { return newItemTxtField.shake() }
ChannelFacade.create(channel: Channel(name: newItemTxtField.text!))
textFieldClear(newItemTxtField)
channelsTable.reloadData()
}
}
extension ChannelViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Public Channels"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return channels?.count ?? 0
}
private func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let channel = channels?[indexPath.row]
let cell = channelsTable.dequeueReusableCell(withIdentifier:"cell",for: indexPath) as! ChannelCell
cell.titleLbl.text = channel?.name as String?
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let channel = channels?[indexPath.row]
ChannelFacade.delete(channel: channel!)
ChatFacade.removeMessages(channelId: channel!.id!)
}
}
}
extension ChannelViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let chatViewController = storyboard.instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController
chatViewController.user = self.user
chatViewController.channel = channels?[indexPath.row]
self.navigationController?.pushViewController(chatViewController, animated: true)
}
}
extension ChannelViewController: UITextFieldDelegate {
func textFieldClear(_ textField: UITextField) {
textField.text = ""
textField.resignFirstResponder()
}
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ChannelViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
| mit | ac735c65dddd47c62f0cfb42f678b988 | 31.787402 | 136 | 0.657301 | 5.393782 | false | false | false | false |
jnross/Bluetility | Bluetility/Device.swift | 1 | 6291 | //
// Device.swift
// Bluetility
//
// Created by Joseph Ross on 7/1/20.
// Copyright © 2020 Joseph Ross. All rights reserved.
//
import CoreBluetooth
protocol DeviceDelegate: AnyObject {
func deviceDidConnect(_ device: Device)
func deviceDidDisconnect(_ device: Device)
func deviceDidUpdateName(_ device: Device)
func device(_ device: Device, updated services: [CBService])
func device(_ device: Device, updated characteristics: [CBCharacteristic], for service: CBService)
func device(_ device: Device, updatedValueFor characteristic: CBCharacteristic)
}
class Device : NSObject {
let peripheral: CBPeripheral
unowned var scanner: Scanner
var advertisingData: [String:Any]
var rssi: Int
weak var delegate: DeviceDelegate? = nil
// Transient data
var manufacturerName: String? = nil
var modelName: String? = nil
init(scanner: Scanner, peripheral: CBPeripheral, advertisingData: [String: Any], rssi: Int) {
self.scanner = scanner
self.peripheral = peripheral
self.advertisingData = advertisingData
self.rssi = rssi
super.init()
peripheral.delegate = self
}
deinit {
peripheral.delegate = nil
}
var friendlyName : String {
if let advertisedName = advertisingData[CBAdvertisementDataLocalNameKey] as? String {
return advertisedName
}
if let peripheralName = peripheral.name {
return peripheralName
}
let infoFields = [manufacturerName, modelName].compactMap({$0})
if infoFields.count > 0 {
return infoFields.joined(separator: " ")
}
return "Untitled"
}
var services: [CBService] {
return peripheral.services ?? []
}
func connect() {
scanner.central.connect(self.peripheral, options: [:])
}
func disconnect() {
scanner.central.cancelPeripheralConnection(self.peripheral)
}
func discoverCharacteristics(for service: CBService) {
peripheral.discoverCharacteristics(nil, for: service)
}
func read(characteristic: CBCharacteristic) {
peripheral.readValue(for: characteristic)
}
func write(data: Data, for characteristic: CBCharacteristic, type:CBCharacteristicWriteType) {
peripheral.writeValue(data, for: characteristic, type: type)
}
func setNotify(_ enabled: Bool, for characteristic: CBCharacteristic) {
peripheral.setNotifyValue(enabled, for: characteristic)
}
}
extension Device : CBPeripheralDelegate {
func peripheralDidConnect() {
peripheral.discoverServices(nil)
delegate?.deviceDidConnect(self)
}
func peripheralDidDisconnect(error: Error?) {
delegate?.deviceDidDisconnect(self)
}
func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
delegate?.deviceDidUpdateName(self)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
let services = peripheral.services ?? []
handleSpecialServices(services)
delegate?.device(self, updated: services)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
let characteristics = service.characteristics ?? []
handleSpecialCharacteristics(characteristics)
delegate?.device(self, updated: characteristics, for: service)
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
handleSpecialCharacteristic(characteristic)
delegate?.device(self, updatedValueFor: characteristic)
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
// TODO: report an error?
assertionFailure(error.localizedDescription)
}
// TODO: report successful write?
}
}
// MARK: Handle Special Characteristics
fileprivate let specialServiceUUIDs = [
CBUUID(string: "180A"), // Device Information Service
]
fileprivate let manufacturerNameUUID = CBUUID(string: "2A29")
fileprivate let modelNumberUUID = CBUUID(string: "2A24")
fileprivate let specialCharacteristicUUIDs = [
manufacturerNameUUID, // Manufacturer Name
modelNumberUUID, // Model Number
]
extension Device {
func handleSpecialServices(_ services: [CBService]) {
for service in services {
if specialServiceUUIDs.contains(service.uuid) {
peripheral.discoverCharacteristics(specialCharacteristicUUIDs, for: service)
}
}
}
func handleSpecialCharacteristics(_ characteristics: [CBCharacteristic]) {
for characteristic in characteristics {
if specialCharacteristicUUIDs.contains(characteristic.uuid) {
peripheral.readValue(for: characteristic)
handleSpecialCharacteristic(characteristic)
}
}
}
func handleSpecialCharacteristic(_ characteristic: CBCharacteristic) {
guard let value = characteristic.value else { return }
if specialCharacteristicUUIDs.contains(characteristic.uuid) {
switch characteristic.uuid {
case manufacturerNameUUID:
manufacturerName = String(bytes: value, encoding: .utf8)
case modelNumberUUID:
modelName = String(bytes: value, encoding: .utf8)
default:
assertionFailure("Forgot to handle one of the UUIDs in specialCharacteristicUUIDs: \(characteristic.uuid)")
}
delegate?.deviceDidUpdateName(self)
}
}
}
| mit | 5198a6ea6b4eb26835ad6a51175ab7b4 | 31.091837 | 123 | 0.647218 | 5.348639 | false | false | false | false |
digitwolf/SwiftFerrySkill | Sources/Ferry/Models/TerminalBasics.swift | 1 | 2565 | //
// TerminalBasics.swift
// FerrySkill
//
// Created by Shakenova, Galiya on 2/20/17.
//
//
import Foundation
import SwiftyJSON
public class TerminalBasics: Equatable {
public var terminalID : Int? = 0
public var terminalSubjectID : Int? = 0
public var regionID : Int? = 0
public var terminalName : String? = ""
public var terminalAbbrev : String? = ""
public var sortSeq : Int? = 0
public var overheadPassengerLoading : Bool? = false
public var elevator : Bool? = false
public var waitingRoom : Bool? = false
public var foodService : Bool? = false
public var restroom : Bool? = false
init() {
}
public init(_ json: JSON) {
terminalID = json["TerminalID"].intValue
terminalSubjectID = json["TerminalSubjectID"].intValue
regionID = json["RegionID"].intValue
terminalName = json["TerminalName"].stringValue
terminalAbbrev = json["TerminalAbbrev"].stringValue
sortSeq = json["SortSeq"].intValue
overheadPassengerLoading = json["OverheadPassengerLoading"].boolValue
elevator = json["Elevator"].boolValue
waitingRoom = json["WaitingRoom"].boolValue
foodService = json["FoodService"].boolValue
restroom = json["Restroom"].boolValue
}
public func toJson() -> JSON {
var json = JSON([])
json["TerminalID"].intValue = terminalID!
json["TerminalSubjectID"].intValue = terminalSubjectID!
json["RegionID"].intValue = regionID!
json["TerminalName"].stringValue = terminalName!
json["TerminalAbbrev"].stringValue = terminalAbbrev!
json["SortSeq"].intValue = sortSeq!
json["OverheadPassengerLoading"].boolValue = overheadPassengerLoading!
json["Elevator"].boolValue = elevator!
json["WaitingRoom"].boolValue = waitingRoom!
json["FoodService"].boolValue = foodService!
json["Restroom"].boolValue = restroom!
return json
}
public static func == (lhs: TerminalBasics, rhs: TerminalBasics) -> Bool {
return lhs.terminalID == rhs.terminalID && lhs.terminalSubjectID == rhs.terminalSubjectID && lhs.regionID == rhs.regionID && lhs.terminalName == rhs.terminalName && lhs.terminalAbbrev == rhs.terminalAbbrev && lhs.sortSeq == rhs.sortSeq && lhs.overheadPassengerLoading == rhs.overheadPassengerLoading && lhs.elevator == rhs.elevator && rhs.waitingRoom == lhs.waitingRoom && rhs.foodService == lhs.foodService && rhs.restroom == lhs.restroom
}
}
| apache-2.0 | 0ff1b22d6bae213c2060645330808fb4 | 38.461538 | 447 | 0.65614 | 4.318182 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Tests/StellarKitTests/StellarTestData.swift | 1 | 770 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
enum StellarTestData {
// MARK: Base
static let address = "GBIRQUDJO7JT4FIG53BD22DJ4BYO7R5ERHWQMXRLDDF7UZUJQYWQPDOM"
static let memo = "memo-memo"
static let label = "account-label"
// MARK: Address Memo
static let addressColonMemo = "\(address):\(memo)"
// MARK: URL
static let urlString = "web+stellar:pay?destination=\(address)"
static let urlStringWithMemo = "web+stellar:pay?destination=\(address)&memo=\(memo)"
static let urlStringWithMemoType = "web+stellar:pay?destination=\(address)&memo=\(memo)&memo_type=MEMO_TEXT"
static let urlStringWithMemoAndAmount = "web+stellar:pay?destination=\(address)&amount=123456&memo=\(memo)"
}
| lgpl-3.0 | 5d8f7ff73e12008ddcff915f05c35236 | 32.434783 | 112 | 0.719116 | 3.697115 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/Intents/SiriShortcuts+Suggestions.swift | 1 | 4023 | //
// Xcore
// Copyright © 2018 Xcore
// MIT license, see LICENSE file for details
//
import Intents
extension SiriShortcuts {
/// Suggesting Shortcuts to Users.
///
/// Make suggestions for shortcuts the user may want to add to Siri.
///
/// After the user performs an action in your app, the app should donate a
/// shortcut that accelerates user access to the action. However, sometimes
/// there are actions in your app the user hasn’t performed that might be of
/// interest to them. For example, perhaps your soup-ordering app features a
/// special soup every day. The user has never ordered the daily soup special,
/// but they might be interested in the option to add a _soup-of-the-day_
/// shortcut to Siri. Your app can provide this option by making a shortcut
/// suggestion.
///
/// - Note: Shortcut suggestions are available to the user only in the
/// **Settings** app under the **Siri & Search** section. This differs from
/// donated shortcuts, which Siri shows to the user in places such as
/// Spotlight search, Lock Screen, and the Siri watch face.
///
/// - SeeAlso: https://developer.apple.com/documentation/sirikit/shortcut_management/suggesting_shortcuts_to_users
final class Suggestions: Appliable {
private var didUpdate = false
var intents: [INIntent] = [] {
didSet {
guard oldValue != intents else { return }
didUpdate = false
}
}
/// Suggest a shortcut to an action that the user hasn't performed but may want
/// to add to Siri.
func suggest() {
let suggestions = intents.compactMap {
INShortcut(intent: $0)
}
INVoiceShortcutCenter.shared.setShortcutSuggestions(suggestions)
}
func updateIfNeeded() {
guard !didUpdate else { return }
update()
}
func update() {
didUpdate = true
suggest()
}
/// Replace given intents for the intent group identifier.
func replace(intents: [INIntent], groupIdentifier: String) {
remove(groupIdentifier: groupIdentifier)
self.intents.append(contentsOf: intents)
}
/// Replace given intents for the intent custom identifier.
func replace(intents: [INIntent], identifiers: [String]) {
remove(identifiers: identifiers)
self.intents.append(contentsOf: intents)
}
/// Replace given intent for the intent custom identifier.
func replace(intent: INIntent, identifier: String) {
remove(identifier: identifier)
self.intents.append(contentsOf: intents)
}
/// Remove shortcuts using the intent custom identifier.
func remove(identifier: String) {
remove(identifiers: [identifier])
}
/// Remove shortcuts using the intent custom identifiers.
func remove(identifiers: [String]) {
intents.removeAll { intent -> Bool in
guard
let customIdentifier = intent.customIdentifier,
identifiers.contains(customIdentifier)
else {
return false
}
return true
}
}
/// Remove shortcuts using the intent group identifier.
func remove(groupIdentifier: String) {
intents.removeAll { intent -> Bool in
guard
let intentGroupIdentifier = intent.groupIdentifier,
intentGroupIdentifier == groupIdentifier
else {
return false
}
return true
}
}
/// Remove all shortcuts suggestions.
func removeAll() {
intents = []
INVoiceShortcutCenter.shared.setShortcutSuggestions([])
}
}
}
| mit | ca46343ee211e40da82a33bbc5dc3298 | 33.956522 | 118 | 0.58408 | 5.338645 | false | false | false | false |
Danappelxx/MuttonChop | Sources/MuttonChop/TemplateCollection.swift | 1 | 1575 | public enum TemplateCollectionError: Error {
case noSuchTemplate(named: String)
}
public struct TemplateCollection {
public var templates: [String: Template]
public init(templates: [String: Template] = [:]) {
self.templates = templates
}
public func get(template name: String) throws -> Template {
guard let template = templates[name] else {
throw TemplateCollectionError.noSuchTemplate(named: name)
}
return template
}
public func render(template name: String, with context: Context = .array([])) throws -> String {
return try get(template: name).render(with: context, partials: self.templates)
}
}
// MARK: IO
import Foundation
extension TemplateCollection {
public init(directory: String, fileExtensions: [String] = ["mustache"]) throws {
let files = try FileManager.default.contentsOfDirectory(atPath: directory)
.map { NSString(string: $0) }
var templates = [String: Template]()
for file in files where fileExtensions.contains(file.pathExtension) {
let path = NSString(string: directory).appendingPathComponent(String(file))
guard
let handle = FileHandle(forReadingAtPath: path),
let contents = String(data: handle.readDataToEndOfFile(), encoding: .utf8)
else {
continue
}
let template = try Template(contents)
templates[file.deletingPathExtension] = template
}
self.templates = templates
}
}
| mit | 306e1460c8f510aced6b147edda9420a | 31.8125 | 100 | 0.635556 | 4.937304 | false | false | false | false |
uias/Tabman | Sources/Tabman/Bar/BarButton/Badge/TMBadgeView.swift | 1 | 5191 | //
// TMBadgeView.swift
// Tabman
//
// Created by Merrick Sapsford on 22/02/2019.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
///
open class TMBadgeView: UIView {
// MARK: Defaults
private struct Defaults {
static let contentInset = UIEdgeInsets(top: 2.0, left: 4.0, bottom: 2.0, right: 4.0)
static let font = UIFont.systemFont(ofSize: 11, weight: .bold)
static let textColor = UIColor.white
static let tintColor = UIColor.red
}
// MARK: Properties
private let contentView = UIView()
private let label = UILabel()
private var labelLeading: NSLayoutConstraint!
private var labelTop: NSLayoutConstraint!
private var labelTrailing: NSLayoutConstraint!
private var labelBottom: NSLayoutConstraint!
/// Value to display.
internal var value: String? {
didSet {
if value != nil {
label.text = value
}
updateContentVisibility(for: value)
}
}
/// Attributed value to display.
internal var attributedValue: NSAttributedString? {
get {
return label.attributedText
}
set {
label.attributedText = newValue
}
}
/// Font for the label.
open var font: UIFont {
get {
return label.font
}
set {
label.font = newValue
}
}
/// Text color of the label.
open var textColor: UIColor {
get {
return label.textColor
}
set {
label.textColor = newValue
}
}
/// Tint which is used as background color.
open override var tintColor: UIColor! {
didSet {
contentView.backgroundColor = tintColor
}
}
/// Content Inset around the badge label.
///
/// Defaults to `UIEdgeInsets(top: 2.0, left: 4.0, bottom: 2.0, right: 4.0)`.
open var contentInset: UIEdgeInsets = Defaults.contentInset {
didSet {
updateContentInset()
}
}
// MARK: Init
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentView.leadingAnchor.constraint(equalTo: leadingAnchor),
contentView.topAnchor.constraint(equalTo: topAnchor),
trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
labelLeading = label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: contentInset.left)
labelTop = label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: contentInset.top)
labelTrailing = contentView.trailingAnchor.constraint(equalTo: label.trailingAnchor, constant: contentInset.right)
labelBottom = contentView.bottomAnchor.constraint(equalTo: label.bottomAnchor, constant: contentInset.bottom)
NSLayoutConstraint.activate([labelLeading, labelTop, labelTrailing, labelBottom])
NSLayoutConstraint.activate([
widthAnchor.constraint(greaterThanOrEqualTo: heightAnchor)
])
label.textAlignment = .center
label.font = Defaults.font
label.textColor = Defaults.textColor
tintColor = Defaults.tintColor
clipsToBounds = true
label.text = "."
updateContentVisibility(for: nil)
}
// MARK: Lifecycle
open override func layoutSubviews() {
super.layoutSubviews()
contentView.layer.cornerRadius = bounds.size.height / 2.0
}
}
// MARK: - Constraints
extension TMBadgeView {
private func updateContentInset() {
guard let labelLeading = labelLeading else {
assertionFailure("Trying to update contentInset before constraints have been set")
return
}
labelLeading.constant = contentInset.left
labelTop.constant = contentInset.top
labelTrailing.constant = contentInset.right
labelBottom.constant = contentInset.bottom
}
}
// MARK: - Animations
extension TMBadgeView {
private func updateContentVisibility(for value: String?) {
switch value {
case .none: // hidden
guard contentView.alpha == 1.0 else {
return
}
contentView.alpha = 0.0
contentView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
case .some: // visible
guard contentView.alpha == 0.0 else {
return
}
contentView.alpha = 1.0
contentView.transform = .identity
}
}
}
| mit | 5b36bef705c050adde4e785f42905c67 | 28.657143 | 122 | 0.604432 | 5.226586 | false | false | false | false |
eliasbagley/Pesticide | debugdrawer/RowControl.swift | 1 | 3520 | //
// RowControl.swift
// debugdrawer
//
// Created by Abraham Hunt on 11/21/14.
// Copyright (c) 2014 Rocketmade. All rights reserved.
//
import UIKit
enum ControlType : String {
case Switch = "SwitchCell"
case Slider = "SliderCell"
case Button = "ButtonCell"
case DropDown = "DropDownCell"
case Label = "LabelCell"
case TextInput = "TextFieldCell"
case Header = "HeaderCell"
}
class RowControl: NSObject {
var name : String
var type : ControlType
init (name : String, type : ControlType) {
self.name = name
self.type = type
super.init()
}
}
class SwitchControl : RowControl {
var block : Bool -> ()
var value : Bool
init (initialValue: Bool, name : String, block: Bool -> ()) {
self.block = block
self.value = initialValue
super.init(name: name, type: .Switch)
}
func executeBlock (switchOn : Bool) {
self.block(switchOn)
}
}
class SliderControl : RowControl {
var block : Float -> ()
var value : Float
init (initialValue: Float, name : String, block: Float -> ()) {
self.block = block
self.value = initialValue
super.init(name: name, type: .Slider)
}
func executeBlock (sliderValue : Float) {
self.block(sliderValue)
}
}
class ButtonControl : RowControl {
var block : () -> ()
init (name : String, block: () -> ()) {
self.block = block
super.init(name: name, type: .Button)
}
func executeBlock () {
self.block()
}
}
class LabelControl : RowControl {
var label :String
init (name : String, label: String) {
self.label = label
super.init(name: name, type: .Label)
}
}
class HeaderControl : RowControl {
init (name: String) {
super.init(name: name, type: .Header)
}
}
class TextInputControl : RowControl {
var block : String -> ()
var value = ""
init (name : String, block: (String) -> ()) {
self.block = block
if (Preferences.isSet(name)) {
// var val = Preferences.load(name) as String?
// var val: [NSString]? = Preferences.load(name) as? [NSString] //NSUserDefaults.standardUserDefaults().objectForKey("food") as? [NSString]
// self.value = val as String!
self.value = Preferences.loadString(name)
block(self.value)
print("VALUE: \(self.value)")
}
super.init(name: name, type: .TextInput)
}
init (name : String, type:ControlType, block: (String) -> ()) {
self.block = block
super.init(name: name, type: type)
}
func executeBlock (input: String) {
self.value = input
Preferences.save(self.name, object: self.value)
self.block(input)
}
}
class DropDownControl : RowControl {
var options : Dictionary<String,AnyObject>
var block : AnyObject -> ()
var value : String
var optionStrings : Array<String>
init (initialValue: NSString, name : String, options: Dictionary<String,AnyObject>, block : (option: AnyObject) -> ()) {
self.value = initialValue
self.options = options
self.optionStrings = [String](options.keys)
self.block = block
super.init(name: name, type: .DropDown)
}
func executeBlock(input: String) {
self.block(self.options[input]!)
}
}
| mit | 24d8e8a61dfc3cae579ebba60f8f8103 | 22.311258 | 150 | 0.571023 | 4.009112 | false | false | false | false |
StephenVinouze/FlickrGallery | FlickrGallery/Classes/ViewControllers/GalleryViewController.swift | 1 | 14955 | //
// GalleryViewController.swift
// FlickrGallery
//
// Created by Stephen Vinouze on 17/11/2015.
//
//
import UIKit
import CoreLocation
import CoreData
import FlickrKit
import MBProgressHUD
class GalleryViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, NSFetchedResultsControllerDelegate {
private let refreshControl = UIRefreshControl()
private let transitionDelegate = GalleryTransitionDelegate()
private var isLoading = false
private var isSharing = false
private var lastLocation : CLLocation?
@IBOutlet weak var cancelBarButton : UIBarButtonItem?
@IBOutlet weak var shareBarButton : UIBarButtonItem?
var photos = [Photo]()
var selectedPhotos = [Photo]()
deinit {
KBLocationProvider.instance().stopFetchLocation()
}
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.addTarget(self, action: "onRefresh", forControlEvents: .ValueChanged)
collectionView?.addSubview(refreshControl)
let pinchGesture = UIPinchGestureRecognizer(target: self, action: "onPinch:")
let rotateGesture = UIRotationGestureRecognizer(target: self, action: "onRotate:")
pinchGesture.delegate = self
rotateGesture.delegate = self
collectionView?.collectionViewLayout = PinchLayout()
collectionView?.addGestureRecognizer(pinchGesture)
collectionView?.addGestureRecognizer(rotateGesture)
updateShareState(false)
loadImages()
fetchLocation()
}
@IBAction func onCancel() {
resetSelection()
}
@IBAction func onShare() {
if !isSharing {
updateShareState(true)
return
}
if isSharing && selectedPhotos.count > 0 {
var selectedImages = [UIImage]()
for photo in selectedPhotos {
selectedImages.append(UIImage(data: photo.image!)!);
}
let shareScreen = UIActivityViewController(activityItems: selectedImages, applicationActivities: nil)
shareScreen.completionWithItemsHandler = {
(activityType, completed, returnedItems, activityError) in
if completed {
self.resetSelection()
}
}
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
let popover = UIPopoverController(contentViewController: shareScreen)
popover.presentPopoverFromBarButtonItem(navigationItem.rightBarButtonItems!.first! as UIBarButtonItem,
permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
else {
presentViewController(shareScreen, animated: true, completion: nil)
}
}
}
func updateShareState(editState : Bool) {
isSharing = editState
collectionView?.allowsMultipleSelection = editState
cancelBarButton?.enabled = editState
cancelBarButton?.tintColor = !editState ? UIColor.clearColor() : nil
UIView.performWithoutAnimation { () -> Void in
self.shareBarButton?.title = NSLocalizedString(editState ? "SharePhotos" : "SelectPhotos", comment: "")
}
updateShareSelection()
}
func updateShareSelection() {
var barTitle = NSLocalizedString(isSharing ? "PickPhotos" : "DisplayPhotos", comment: "")
let photoCount = selectedPhotos.count
if photoCount > 0 {
barTitle += " (" + String(photoCount) + ")"
}
shareBarButton?.enabled = !isSharing || photoCount > 0
navigationItem.title = barTitle
}
func updateCellSelection(cell: UICollectionViewCell) {
cell.backgroundColor = cell.selected ? UIColor.blueColor() : UIColor.clearColor()
}
func fetchLocation() {
KBLocationProvider.instance().startFetchLocation { (location, error) -> Void in
if location != nil {
if self.lastLocation == nil || location.distanceFromLocation(self.lastLocation!) > 50 {
self.fetchPhotos(location)
}
self.lastLocation = location
}
}
}
func resetSelection() {
if selectedPhotos.count > 0 {
let selectedItems = collectionView?.indexPathsForSelectedItems()
for indexPath in selectedItems! {
collectionView?.deselectItemAtIndexPath(indexPath, animated: false)
}
}
collectionView?.reloadData()
selectedPhotos.removeAll()
updateShareState(false)
}
func fetchPhotos(location : CLLocation) {
if !isLoading {
isLoading = true;
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.labelText = NSLocalizedString("LoadingPhotos", comment: "")
})
let photoSearch = FKFlickrPhotosSearch()
photoSearch.accuracy = String(11) // Accuracy set to a city level
photoSearch.lat = String(location.coordinate.latitude)
photoSearch.lon = String(location.coordinate.longitude)
let flickrKit = FlickrKit.sharedFlickrKit()
flickrKit.call(photoSearch) { (response, error) -> Void in
if (response != nil) {
let topPhotos = response["photos"] as! [NSObject: AnyObject]
let photoArray = topPhotos["photo"] as! [[NSObject: AnyObject]]
var counter = 0
for photoDictionary in photoArray {
var download = true
let imageUrl = flickrKit.photoURLForSize(FKPhotoSizeSmall240, fromPhotoDictionary: photoDictionary)
// Prevent downloading image from a known url in the database
for photo in self.photos {
let photoUrl = photo.url as String!
if photoUrl == imageUrl.absoluteString {
download = false
counter++
break
}
}
// Download new images if necessary
if download {
self.downloadImage(imageUrl, completion: { (image, error) -> Void in
counter++
// Save the downloaded images into the database
if image != nil {
self.saveImage(imageUrl, image: image!)
}
// Finalize the request by updating the UI
if counter == photoArray.count - 1 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.finalizeSync()
})
}
})
}
else {
// Finalize the request by updating the UI
if counter == photoArray.count - 1 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.finalizeSync()
})
}
}
}
}
else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.finalizeSync()
})
}
}
}
}
func loadImages() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Photo")
do {
photos = try managedContext.executeFetchRequest(fetchRequest) as! [Photo]
} catch let error as NSError {
print("Could not fetch photo from database \(error), \(error.userInfo)")
}
}
func downloadImage(url: NSURL, completion: ((image: UIImage?, error: NSError?) -> Void)) {
print("Start downloading image at url \(url)")
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
if data != nil {
completion(image: UIImage(data: data!), error: nil)
}
else {
completion(image: nil, error: error)
}
}.resume()
}
func saveImage(url: NSURL, image: UIImage) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("Photo", inManagedObjectContext:managedContext)
let photo = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) as! Photo
photo.url = url.absoluteString
photo.image = UIImageJPEGRepresentation(image, 1)
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save photo in database : \(error), \(error.userInfo)")
}
}
func finalizeSync() {
loadImages()
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.collectionView?.reloadData()
self.refreshControl.endRefreshing()
self.isLoading = false
}
func showZoomView(indexPath: NSIndexPath) {
let attributes = collectionView?.layoutAttributesForItemAtIndexPath(indexPath)
let attributesFrame = attributes?.frame
let frameToOpenFrom = collectionView?.convertRect(attributesFrame!, toView: collectionView?.superview)
transitionDelegate.openingFrame = frameToOpenFrom
let zoomViewController = storyboard?.instantiateViewControllerWithIdentifier("zoom_storyboard_id") as! ZoomViewController
zoomViewController.transitioningDelegate = transitionDelegate
zoomViewController.modalPresentationStyle = .Custom
let photo = photos[indexPath.row]
if photo.image != nil {
zoomViewController.image = UIImage(data: photo.image!)
}
presentViewController(zoomViewController, animated: true, completion: nil)
}
func handleGesture(gesture: UIGestureRecognizer) {
let pinchLayout = collectionView?.collectionViewLayout as! PinchLayout
if gesture.state == .Began {
let initialPoint = gesture.locationInView(collectionView)
pinchLayout.pinchedCellPath = collectionView?.indexPathForItemAtPoint(initialPoint)
}
else if gesture.state == .Changed {
pinchLayout.pinchedCellCenter = gesture.locationInView(collectionView)
if let pinchGesture = gesture as? UIPinchGestureRecognizer {
pinchLayout.pinchedCellScale = pinchGesture.scale
}
else if let rotationGesture = gesture as? UIRotationGestureRecognizer {
pinchLayout.pinchedCellRotationAngle = rotationGesture.rotation
}
}
else {
if pinchLayout.pinchedCellScale > 2 {
showZoomView(pinchLayout.pinchedCellPath)
}
collectionView?.performBatchUpdates({ () -> Void in
pinchLayout.pinchedCellPath = nil;
pinchLayout.pinchedCellScale = 1.0;
pinchLayout.pinchedCellRotationAngle = 0.0;
}, completion: nil)
}
}
func onPinch(gesture : UIPinchGestureRecognizer) {
handleGesture(gesture)
}
func onRotate(gesture : UIRotationGestureRecognizer) {
handleGesture(gesture)
}
func onRefresh() {
fetchPhotos(KBLocationProvider.lastLocation())
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIRotationGestureRecognizer)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let photoDimension : CGFloat = (UIDevice.currentDevice().userInterfaceIdiom == .Pad) ? 150 : 100
return CGSizeMake(photoDimension, photoDimension)
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("gallery_cell_identifier", forIndexPath: indexPath) as! GalleryCell
let photo = photos[indexPath.row]
if photo.image != nil {
cell.photo.image = UIImage(data: photo.image!)
}
updateCellSelection(cell)
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if isSharing {
selectedPhotos.append(photos[indexPath.row])
updateShareSelection()
updateCellSelection(collectionView.cellForItemAtIndexPath(indexPath)!)
}
else {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
showZoomView(indexPath)
}
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
if isSharing {
let selectedPhoto = photos[indexPath.row]
selectedPhotos.removeAtIndex(selectedPhotos.indexOf(selectedPhoto)!)
updateShareSelection()
updateCellSelection(collectionView.cellForItemAtIndexPath(indexPath)!)
}
}
}
| apache-2.0 | 1e7197b21e57debb99282e6594b8e2e6 | 38.355263 | 172 | 0.579204 | 6.223471 | false | false | false | false |
dvlproad/CJUIKit | CJBaseUIKit-Swift/CJAlert/CJAlertView.swift | 1 | 35236 | //
// CJAlertView.m
// CJUIKitDemo
//
// Created by ciyouzen on 2016/3/11.
// Copyright © 2016年 dvlproad. All rights reserved.
//
import UIKit
import CoreText
import SnapKit
class CJAlertView: UIView {
private var _flagImageViewHeight: CGFloat = 0.0
private var _titleLabelHeight: CGFloat = 0.0
private var _messageLabelHeight: CGFloat = 0.0
private var _bottomPartHeight: CGFloat = 0.0 //底部区域高度(包含底部按钮及可能的按钮上部的分隔线及按钮下部与边缘的距离)
private(set) var size: CGSize = CGSize.zero
//第一个视图(一般为flagImageView,如果flagImageView不存在,则为下一个即titleLabel,以此类推)与顶部的间隔
private(set) var firstVerticalInterval: CGFloat = 0
//第二个视图与第一个视图的间隔
private(set) var secondVerticalInterval: CGFloat = 0
//第三个视图与第二个视图的间隔
private(set) var thirdVerticalInterval: CGFloat = 0
//底部buttons视图与其上面的视图的最小间隔(上面的视图一般为message;如果不存在message,则是title;如果再不存在,则是flagImage)
private(set) var bottomMinVerticalInterval: CGFloat = 0
var flagImageView: UIImageView?
var titleLabel: UILabel?
var messageScrollView: UIScrollView?
var messageContainerView: UIView?
var messageLabel: UILabel?
var cancelButton: UIButton?
var okButton: UIButton?
var cancelHandle: (()->())?
var okHandle: (()->())?
// MARK: - ClassMethod
class func alertViewWithSize(size: CGSize,
flagImage: UIImage!,
title: String,
message: String,
cancelButtonTitle: String,
okButtonTitle: String,
cancelHandle:(()->())?,
okHandle: (()->())?) -> CJAlertView
{
//①创建
let alertView: CJAlertView = CJAlertView.init(size: size, firstVerticalInterval: 15, secondVerticalInterval: 10, thirdVerticalInterval: 10, bottomMinVerticalInterval: 10)
//②添加 flagImage、titleLabel、messageLabel
//[alertView setupFlagImage:flagImage title:title message:message configure:configure]; //已拆解成以下几个方法
if flagImage != nil {
alertView.addFlagImage(flagImage, CGSize(width: 38, height: 38))
}
if title.count > 0 {
alertView.addTitleWithText(title, font: UIFont.systemFont(ofSize: 18.0), textAlignment: .center, margin: 20, paragraphStyle: nil)
}
if message.count > 0 {
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byCharWrapping
paragraphStyle.lineSpacing = 4
alertView.addMessageWithText(message, font: UIFont.systemFont(ofSize: 14.0), textAlignment: .center, margin: 20, paragraphStyle: paragraphStyle)
}
//③添加 cancelButton、okButton
alertView.addBottomButtons(actionButtonHeight: 50, cancelButtonTitle: cancelButtonTitle, okButtonTitle: okButtonTitle, cancelHandle: cancelHandle, okHandle: okHandle)
return alertView;
}
// MARK: - Init
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
* 创建alertView
* @brief 这里所说的三个视图范围为:flagImageView(有的话,一定是第一个)、titleLabel(有的话,有可能一或二)、messageLabel(有的话,有可能一或二或三)
*
* @param size alertView的大小
* @param firstVerticalInterval 第一个视图(一般为flagImageView,如果flagImageView不存在,则为下一个即titleLabel,以此类推)与顶部的间隔
* @param secondVerticalInterval 第二个视图与第一个视图的间隔(如果少于两个视图,这个值设为0即可)
* @param thirdVerticalInterval 第三个视图与第二个视图的间隔(如果少于三个视图,这个值设为0即可)
* @param bottomMinVerticalInterval 底部buttons区域视图与其上面的视图的最小间隔(上面的视图一般为message;如果不存在message,则是title;如果再不存在,则是flagImage)
*
* @return alertView
*/
init(size: CGSize,
firstVerticalInterval: CGFloat,
secondVerticalInterval: CGFloat,
thirdVerticalInterval: CGFloat,
bottomMinVerticalInterval: CGFloat)
{
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.white
self.layer.cornerRadius = 3
self.size = size
self.firstVerticalInterval = firstVerticalInterval
self.secondVerticalInterval = secondVerticalInterval
self.thirdVerticalInterval = thirdVerticalInterval
self.bottomMinVerticalInterval = bottomMinVerticalInterval
}
/// 添加指示图标
func addFlagImage(_ flagImage: UIImage, _ imageViewSize: CGSize) {
if self.flagImageView == nil {
let flagImageView: UIImageView = UIImageView.init()
self.addSubview(flagImageView)
self.flagImageView = flagImageView;
}
self.flagImageView!.image = flagImage;
self.flagImageView?.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.width.equalTo(imageViewSize.width);
make.top.equalTo(self).offset(self.firstVerticalInterval);
make.height.equalTo(imageViewSize.height);
})
_flagImageViewHeight = imageViewSize.height;
if (self.titleLabel != nil) {
//由于约束部分不一样,使用update会增加一个新约束,又没设置优先级,从而导致约束冲突。而如果用remake的话,又需要重新设置之前已经设置过的,否则容易缺失。所以使用masnory时候,使用优先级比较合适
self.titleLabel!.snp.updateConstraints({ (make) in
make.top.equalTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
})
}
if self.messageScrollView != nil {
self.messageScrollView!.snp.updateConstraints { (make) in
if self.titleLabel != nil {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.greaterThanOrEqualTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
}
}
}
}
// MARK: - AddView
///添加title
func addTitleWithText(_ text: String? = "",
font: UIFont,
textAlignment: NSTextAlignment,
margin titleLabelLeftOffset: CGFloat,
paragraphStyle: NSMutableParagraphStyle?)
{
if self.size.equalTo(CGSize.zero) {
return
}
if self.titleLabel == nil {
let titleLabel: UILabel = UILabel(frame: CGRect.zero)
//titleLabel.backgroundColor = [UIColor purpleColor];
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.black
self.addSubview(titleLabel)
self.titleLabel = titleLabel
}
// if text == nil {
// text = ""
// //若为nil,则设置[[NSMutableAttributedString alloc] initWithString:labelText]的时候会崩溃
// }
let titleLabelMaxWidth: CGFloat = self.size.width-2*titleLabelLeftOffset
let titleLabelMaxSize: CGSize = CGSize(width: titleLabelMaxWidth, height: CGFloat.greatestFiniteMagnitude)
let titleTextSize: CGSize = CJAlertView.getTextSize(from: text!, with: font, maxSize: titleLabelMaxSize, lineBreakMode: .byCharWrapping, paragraphStyle: paragraphStyle)
var titleTextHeight: CGFloat = titleTextSize.height
let lineStringArray: [NSString] = CJAlertView.getLineStringArray(labelText: text!, font: font, maxTextWidth: titleLabelMaxWidth)
let lineCount: NSInteger = lineStringArray.count
var lineSpacing: CGFloat = paragraphStyle?.lineSpacing ?? 0
if lineSpacing == 0 {
lineSpacing = 2
}
titleTextHeight += CGFloat(lineCount)*lineSpacing
if paragraphStyle == nil {
self.titleLabel!.text = text
} else {
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font,
//NSAttributedString.Key.foregroundColor: textColor,
//NSAttributedString.Key.kern: 1.5f //字体间距
]
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text!)
attributedText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
//[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
self.titleLabel!.attributedText = attributedText
}
self.titleLabel!.font = font
self.titleLabel!.textAlignment = textAlignment
self.titleLabel!.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.left.equalTo(self).offset(titleLabelLeftOffset);
if self.flagImageView != nil {
make.top.equalTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
} else {
make.top.greaterThanOrEqualTo(self).offset(self.firstVerticalInterval);//优先级
}
make.height.equalTo(titleTextHeight);
})
_titleLabelHeight = titleTextHeight
if self.messageScrollView != nil {
self.messageScrollView?.snp.updateConstraints({ (make) in
if self.flagImageView != nil {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.secondVerticalInterval);
}
})
}
}
// MARK: - Private
//以下获取textSize方法取自NSString+CJTextSize
class func getTextSize(from string: String, with font: UIFont, maxSize: CGSize, lineBreakMode: NSLineBreakMode, paragraphStyle: NSMutableParagraphStyle?) -> CGSize {
var paragraphStyle = paragraphStyle
if (string.count == 0) {
return CGSize.zero
}
if paragraphStyle == nil {
paragraphStyle = NSParagraphStyle.default as? NSMutableParagraphStyle
paragraphStyle?.lineBreakMode = lineBreakMode
}
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font
]
let options: NSStringDrawingOptions = .usesLineFragmentOrigin
let textRect: CGRect = string.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
let size: CGSize = textRect.size
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
///获取每行的字符串组成的数组
class func getLineStringArray(labelText: String, font: UIFont, maxTextWidth: CGFloat) -> [NSString] {
//convert UIFont to a CTFont
let fontName: CFString = font.fontName as CFString
let fontSize: CGFloat = font.pointSize
let fontRef: CTFont = CTFontCreateWithName(fontName, fontSize, nil);
let attString: NSMutableAttributedString = NSMutableAttributedString.init(string: labelText)
attString.addAttribute(kCTFontAttributeName as NSAttributedString.Key, value: fontRef, range: NSMakeRange(0, attString.length))
let framesetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attString)
let path: CGMutablePath = CGMutablePath();
path.addRect(CGRect(x: 0, y: 0, width: maxTextWidth, height: 100000))
let frame: CTFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
let lines: NSArray = CTFrameGetLines(frame)
let lineStringArray: NSMutableArray = NSMutableArray.init()
for line in lines {
let lineRef: CTLine = line as! CTLine
let lineRange: CFRange = CTLineGetStringRange(lineRef)
let range: NSRange = NSRange(location: lineRange.location, length: lineRange.length)
let startIndex = labelText.index(labelText.startIndex, offsetBy: range.location)
let endIndex = labelText.index(startIndex, offsetBy: range.length)
let lineString: String = String(labelText[startIndex ..< endIndex])
lineStringArray.add(lineString)
}
return lineStringArray as! [NSString]
}
///添加message的方法(paragraphStyle:当需要设置message行距、缩进等的时候才需要设置,其他设为nil即可)
func addMessageWithText(_ text: String? = "",
font: UIFont,
textAlignment: NSTextAlignment,
margin messageLabelLeftOffset: CGFloat,
paragraphStyle: NSMutableParagraphStyle?)
{
//NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
//paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//paragraphStyle.lineSpacing = lineSpacing;
//paragraphStyle.headIndent = 10;
if self.size.equalTo(CGSize.zero) {
return
}
if self.messageScrollView == nil {
let scrollView: UIScrollView = UIScrollView()
//scrollView.backgroundColor = [UIColor redColor];
self.addSubview(scrollView)
self.messageScrollView = scrollView
let containerView: UIView = UIView()
//containerView.backgroundColor = [UIColor greenColor];
scrollView.addSubview(containerView)
self.messageContainerView = containerView
let messageTextColor: UIColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
//#888888
let messageLabel: UILabel = UILabel(frame: CGRect.zero)
messageLabel.numberOfLines = 0
//UITextView *messageLabel = [[UITextView alloc] initWithFrame:CGRectZero];
//messageLabel.editable = NO;
messageLabel.textAlignment = .center
messageLabel.textColor = messageTextColor
containerView.addSubview(messageLabel)
self.messageLabel = messageLabel
}
let messageLabelMaxWidth: CGFloat = self.size.width-2*messageLabelLeftOffset
let messageLabelMaxSize: CGSize = CGSize(width: messageLabelMaxWidth, height: CGFloat.greatestFiniteMagnitude)
let messageTextSize: CGSize = CJAlertView.getTextSize(from: text!, with: font, maxSize: messageLabelMaxSize, lineBreakMode: .byCharWrapping, paragraphStyle: paragraphStyle)
var messageTextHeight: CGFloat = messageTextSize.height
let lineStringArray: [NSString] = CJAlertView.getLineStringArray(labelText: text!, font: font, maxTextWidth: messageLabelMaxWidth)
let lineCount: NSInteger = lineStringArray.count
var lineSpacing: CGFloat = paragraphStyle!.lineSpacing
if lineSpacing == 0 {
lineSpacing = 2
}
messageTextHeight += CGFloat(lineCount)*lineSpacing
if (paragraphStyle == nil) {
self.messageLabel!.text = text;
} else {
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font,
//NSAttributedString.Key.foregroundColor: textColor,
//NSAttributedString.Key.kern: 1.5f //字体间距
]
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text!)
attributedText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
//[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
self.messageLabel!.attributedText = attributedText
}
self.messageLabel!.font = font
self.messageLabel!.textAlignment = textAlignment
self.messageScrollView?.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.left.equalTo(self).offset(messageLabelLeftOffset);
if (self.titleLabel != nil) {
if (self.flagImageView != nil) {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.secondVerticalInterval);
}
} else if (self.flagImageView != nil) {
make.top.greaterThanOrEqualTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);//优先级
} else {
make.top.greaterThanOrEqualTo(self).offset(self.firstVerticalInterval);//优先级
}
make.height.equalTo(messageTextHeight);
})
self.messageContainerView!.snp.makeConstraints({ (make) in
make.left.right.equalTo(self.messageScrollView!)
make.top.bottom.equalTo(self.messageScrollView!)
make.width.equalTo(self.messageScrollView!.snp_width)
make.height.equalTo(messageTextHeight)
})
self.messageLabel?.snp.makeConstraints({ (make) in
make.left.right.equalTo(self.messageContainerView!);
make.top.equalTo(self.messageContainerView!);
make.height.equalTo(messageTextHeight);
})
_messageLabelHeight = messageTextHeight;
}
///添加 message 的边框等(几乎不会用到)
func addMessageLayer(borderWidth: CGFloat, borderColor: CGColor?, cornerRadius: CGFloat) {
assert((self.messageScrollView != nil), "请先添加messageScrollView")
self.messageScrollView!.layer.borderWidth = borderWidth
if borderColor != nil {
self.messageScrollView!.layer.borderColor = borderColor
}
self.messageScrollView!.layer.cornerRadius = cornerRadius
}
///添加底部按钮
/**
* 添加底部按钮方法①:按指定布局添加底部按钮
*
* @param bottomButtons 要添加的按钮组合(得在外部额外实现点击后的关闭alert操作)
* @param actionButtonHeight 按钮高度
* @param bottomInterval 按钮与底部的距离
* @param axisType 横排还是竖排
* @param fixedSpacing 两个控件间隔
* @param leadSpacing 第一个控件与边缘的间隔
* @param tailSpacing 最后一个控件与边缘的间隔
*/
func addBottomButtons(bottomButtons: [UIButton],
actionButtonHeight: CGFloat, //withHeight
bottomInterval: CGFloat,
axisType: NSLayoutConstraint.Axis,
fixedSpacing: CGFloat,
leadSpacing: CGFloat,
tailSpacing: CGFloat
)
{
let buttonCount: Int = bottomButtons.count
if axisType == .horizontal {
_bottomPartHeight = 0+actionButtonHeight+bottomInterval
} else {
_bottomPartHeight = leadSpacing+CGFloat(buttonCount)*(actionButtonHeight+fixedSpacing)-fixedSpacing+tailSpacing
}
for bottomButton in bottomButtons {
self.addSubview(bottomButton)
}
// if buttonCount > 1 {
// bottomButtons.snp.makeConstraints { (make) in
// make.bottom.equalTo(-bottomInterval)
// make.height.equalTo(actionButtonHeight)
// }
// bottomButtons.snp.distributeViews(along: axisType, withFixedSpacing: fixedSpacing, leadSpacing: leadSpacing, tailSpacing: tailSpacing)
// } else {
// bottomButtons.snp.makeConstraints { (make) in
// make.bottom.equalTo(-bottomInterval)
// make.height.equalTo(actionButtonHeight)
// make.left.equalTo(self).offset(leadSpacing)
// make.right.equalTo(self).offset(-tailSpacing)
// }
// }
}
///只添加一个按钮
func addOnlyOneBottomButton(_ bottomButton: UIButton,
withHeight actionButtonHeight: CGFloat,
bottomInterval: CGFloat,
leftOffset: CGFloat,
rightOffset: CGFloat)
{
_bottomPartHeight = 0 + actionButtonHeight + bottomInterval
self.addSubview(bottomButton)
bottomButton.snp.makeConstraints { (make) in
make.bottom.equalTo(-bottomInterval);
make.height.equalTo(actionButtonHeight);
make.left.equalTo(self).offset(leftOffset);
make.right.equalTo(self).offset(-rightOffset);
}
}
func addBottomButtons(actionButtonHeight: CGFloat,
cancelButtonTitle: String,
okButtonTitle: String,
cancelHandle: (()->())?,
okHandle: (()->())?)
{
let lineColor: UIColor = UIColor(red: 229/255.0, green: 229/255.0, blue: 229/255.0, alpha: 1)
//#e5e5e5
let cancelTitleColor: UIColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
//#888888
let okTitleColor: UIColor = UIColor(red: 66/255.0, green: 135/255.0, blue: 255/255.0, alpha: 1)
//#4287ff
self.cancelHandle = cancelHandle
self.okHandle = okHandle
let existCancelButton: Bool = cancelButtonTitle.count > 0
let existOKButton: Bool = okButtonTitle.count > 0
if existCancelButton == false && existOKButton == false {
return
}
var cancelButton: UIButton?
if existCancelButton {
cancelButton = UIButton(type: .custom)
cancelButton!.backgroundColor = UIColor.clear
cancelButton!.setTitle(cancelButtonTitle, for: .normal)
cancelButton!.setTitleColor(cancelTitleColor, for: .normal)
cancelButton!.titleLabel!.font = UIFont.systemFont(ofSize: 14)
cancelButton!.addTarget(self, action: #selector(cancelButtonAction(button:)), for: .touchUpInside)
self.cancelButton = cancelButton
}
var okButton: UIButton?
if existOKButton {
okButton = UIButton(type: .custom)
okButton!.backgroundColor = UIColor.clear
okButton!.setTitle(okButtonTitle, for: .normal)
okButton!.setTitleColor(okTitleColor, for: .normal)
okButton!.titleLabel!.font = UIFont.systemFont(ofSize: 14)
okButton!.addTarget(self, action: #selector(okButtonAction(button:)), for: .touchUpInside)
self.okButton = okButton
}
let lineView: UIView = UIView()
lineView.backgroundColor = lineColor
self.addSubview(lineView)
lineView.snp.makeConstraints { (make) in
make.left.right.equalTo(self)
make.bottom.equalTo(self).offset(-actionButtonHeight-1)
make.height.equalTo(1)
}
_bottomPartHeight = actionButtonHeight+1
if (existCancelButton == true && existOKButton == true) {
self.addSubview(cancelButton!)
cancelButton!.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(0.5)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
let actionSeprateLineView: UIView = UIView.init()
actionSeprateLineView.backgroundColor = lineColor
self.addSubview(actionSeprateLineView)
actionSeprateLineView.snp.makeConstraints { (make) in
make.left.equalTo(cancelButton!.snp_right)
make.width.equalTo(1)
make.top.bottom.equalTo(cancelButton!)
}
self.addSubview(okButton!)
okButton!.snp.makeConstraints { (make) in
make.left.equalTo(actionSeprateLineView.snp_right)
make.right.equalTo(self)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
} else if (existCancelButton == true) {
self.addSubview(cancelButton!)
cancelButton!.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(1)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
} else if (existOKButton == true) {
self.addSubview(okButton!)
okButton!.snp.makeConstraints { (make) in
make.right.equalTo(self)
make.width.equalTo(self).multipliedBy(1)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
}
}
// MARK: - 文字颜色等Option
///更改 Title 文字颜色
func updateTitleTextColor(_ textColor: UIColor) {
self.titleLabel?.textColor = textColor
}
///更改 Message 文字颜色
func updateMessageTextColor(_ textColor: UIColor) {
self.messageLabel?.textColor = textColor
}
///更改底部 Cancel 按钮的文字颜色
func updateCancelButtonTitleColor(normalTitleColor: UIColor, highlightedTitleColor: UIColor) {
self.cancelButton?.setTitleColor(normalTitleColor, for: .normal)
self.cancelButton?.setTitleColor(highlightedTitleColor, for: .highlighted)
}
///更改底部 OK 按钮的文字颜色
func updateOKButtonTitleColor(normalTitleColor: UIColor, highlightedTitleColor: UIColor) {
self.okButton?.setTitleColor(normalTitleColor, for: .normal)
self.okButton?.setTitleColor(highlightedTitleColor, for: .highlighted)
}
// MARK: - Event
/**
* 显示 alert 弹窗
*
* @param shouldFitHeight 是否需要自动适应高度(否:会以之前指定的size的height来显示)
* @param blankBGColor 空白区域的背景颜色
*/
func showWithShouldFitHeight(_ shouldFitHeight: Bool, blankBGColor: UIColor) {
self.checkAndUpdateVerticalInterval()
var fixHeight: CGFloat = 0
if (shouldFitHeight == true) {
let minHeight: CGFloat = self.getMinHeight()
fixHeight = minHeight
} else {
fixHeight = self.size.height
}
self.showWithFixHeight(&fixHeight, blankBGColor: blankBGColor)
}
/**
* 显示弹窗并且是以指定高度显示的
*
* @param fixHeight 高度
* @param blankBGColor 空白区域的背景颜色
*/
func showWithFixHeight(_ fixHeight: inout CGFloat, blankBGColor: UIColor) {
self.checkAndUpdateVerticalInterval()
let minHeight: CGFloat = self.getMinHeight()
if fixHeight < minHeight {
let warningString: String = String(format: "CJ警告:您设置的size高度小于视图本身的最小高度%.2lf,会导致视图显示不全,请检查", minHeight)
print("\(warningString)")
}
let maxHeight: CGFloat = UIScreen.main.bounds.height-60
if fixHeight > maxHeight {
fixHeight = maxHeight
//NSString *warningString = [NSString stringWithFormat:@"CJ警告:您设置的size高度超过视图本身的最大高度%.2lf,会导致视图显示不全,已自动缩小", maxHeight];
//NSLog(@"%@", warningString);
if self.messageScrollView != nil {
let minHeightWithoutMessageLabel: CGFloat = self.firstVerticalInterval + _flagImageViewHeight + self.secondVerticalInterval + _titleLabelHeight + self.thirdVerticalInterval + self.bottomMinVerticalInterval + _bottomPartHeight;
_messageLabelHeight = fixHeight - minHeightWithoutMessageLabel
self.messageScrollView?.snp.updateConstraints({ (make) in
make.height.equalTo(_messageLabelHeight)
})
}
}
let popupViewSize: CGSize = CGSize(width: self.size.width, height: fixHeight)
self.cj_popupInCenterWindow(animationType: .normal, popupViewSize: popupViewSize, blankBGColor: blankBGColor, showPopupViewCompleteBlock: nil, tapBlankViewCompleteBlock: nil)
}
///获取当前alertView最小应有的高度值
func getMinHeight() -> CGFloat {
var minHeightWithMessageLabel: CGFloat = self.firstVerticalInterval + _flagImageViewHeight + self.secondVerticalInterval + _titleLabelHeight + self.thirdVerticalInterval + _messageLabelHeight + self.bottomMinVerticalInterval + _bottomPartHeight
minHeightWithMessageLabel = ceil(minHeightWithMessageLabel);
return minHeightWithMessageLabel;
}
/**
* 通过检查位于bottomButtons上view的个数来判断并修正之前设置的VerticalInterval(防止比如有时候只设置两个view,thirdVerticalInterval却不为0)
* @brief 问题来源:比如少于三个视图,thirdVerticalInterval却没设为0,此时如果不通过此方法检查并修正,则容易出现高度计算错误的问题
*/
func checkAndUpdateVerticalInterval() {
var upViewCount: Int = 0
if self.flagImageView != nil {
upViewCount += 1
}
if self.titleLabel != nil {
upViewCount += 1
}
if self.messageScrollView != nil {
upViewCount += 1
}
if upViewCount == 2 {
self.thirdVerticalInterval = 0
} else if upViewCount == 1 {
self.secondVerticalInterval = 0
}
}
// MARK: - Private
@objc func cancelButtonAction(button: UIButton) {
self.dismiss(0)
self.cancelHandle?()
}
@objc func okButtonAction(button: UIButton) {
self.dismiss(0)
self.okHandle?()
}
func dismiss(_ delay: CGFloat) {
let time = DispatchTime.now() + 1.5
DispatchQueue.main.asyncAfter(deadline: time) {
self.cj_hidePopupView(.normal)
}
}
}
//
//@implementation CJAlertView
//
//
//
//
///* //已拆解成以下几个方法
//- (void)setupFlagImage:(UIImage *)flagImage
// title:(NSString *)title
// message:(NSString *)message
//{
// if (CGSizeEqualToSize(self.size, CGSizeZero)) {
// return;
// }
//
// UIColor *messageTextColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1]; //#888888
//
//
// if (flagImage) {
// UIImageView *flagImageView = [[UIImageView alloc] init];
// flagImageView.image = flagImage;
// [self addSubview:flagImageView];
// [flagImageView mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.width.equalTo(38);
// make.top.equalTo(self).offset(25);
// make.height.equalTo(38);
// }];
// _flagImageView = flagImageView;
// }
//
//
// // titleLabel
// CGFloat titleLabelLeftOffset = 20;
// UIFont *titleLabelFont = [UIFont systemFontOfSize:18.0];
// CGFloat titleLabelMaxWidth = self.size.width - 2*titleLabelLeftOffset;
// CGSize titleLabelMaxSize = CGSizeMake(titleLabelMaxWidth, CGFLOAT_MAX);
// CGSize titleTextSize = [CJAlertView getTextSizeFromString:title withFont:titleLabelFont maxSize:titleLabelMaxSize mode:NSLineBreakByCharWrapping];
// CGFloat titleTextHeight = titleTextSize.height;
//
// UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
// //titleLabel.backgroundColor = [UIColor clearColor];
// titleLabel.numberOfLines = 0;
// titleLabel.textAlignment = NSTextAlignmentCenter;
// titleLabel.font = titleLabelFont;
// titleLabel.textColor = [UIColor blackColor];
// titleLabel.text = title;
// [self addSubview:titleLabel];
// [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.left.equalTo(self).offset(titleLabelLeftOffset);
// if (self.flagImageView) {
// make.top.equalTo(self.flagImageView.mas_bottom).offset(10);
// } else {
// make.top.equalTo(self).offset(25);
// }
// make.height.equalTo(titleTextHeight);
// }];
// _titleLabel = titleLabel;
//
//
// // messageLabel
// CGFloat messageLabelLeftOffset = 20;
// UIFont *messageLabelFont = [UIFont systemFontOfSize:15.0];
// CGFloat messageLabelMaxWidth = self.size.width - 2*messageLabelLeftOffset;
// CGSize messageLabelMaxSize = CGSizeMake(messageLabelMaxWidth, CGFLOAT_MAX);
// CGSize messageTextSize = [CJAlertView getTextSizeFromString:message withFont:messageLabelFont maxSize:messageLabelMaxSize mode:NSLineBreakByCharWrapping];
// CGFloat messageTextHeight = messageTextSize.height;
//
// UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
// //messageLabel.backgroundColor = [UIColor clearColor];
// messageLabel.numberOfLines = 0;
// messageLabel.textAlignment = NSTextAlignmentCenter;
// messageLabel.font = messageLabelFont;
// messageLabel.textColor = messageTextColor;
// messageLabel.text = message;
// [self addSubview:messageLabel];
// [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.left.equalTo(self).offset(messageLabelLeftOffset);
// make.top.equalTo(titleLabel.mas_bottom).offset(10);
// make.height.equalTo(messageTextHeight);
// }];
// _messageLabel = messageLabel;
//}
//*/
//
//
//
//@end
| mit | 7a64e2984dce5bcd1886a13a6182f58c | 39.98773 | 252 | 0.621943 | 4.77897 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Conversation/ConversationLayout.swift | 1 | 1825 | //
// ConversationLayout.swift
// Yep
//
// Created by NIX on 15/3/25.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
final class ConversationLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
minimumLineSpacing = YepConfig.ChatCell.lineSpacing
}
var insertIndexPathSet = Set<NSIndexPath>()
override func prepareForCollectionViewUpdates(updateItems: [UICollectionViewUpdateItem]) {
super.prepareForCollectionViewUpdates(updateItems)
var insertIndexPathSet = Set<NSIndexPath>()
for updateItem in updateItems {
switch updateItem.updateAction {
case .Insert:
if let indexPath = updateItem.indexPathAfterUpdate {
insertIndexPathSet.insert(indexPath)
}
default:
break
}
}
self.insertIndexPathSet = insertIndexPathSet
}
// override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
//
// let attribute = super.layoutAttributesForItemAtIndexPath(indexPath)
//
// attribute?.alpha = 1.0
//
// return attribute
// }
override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = layoutAttributesForItemAtIndexPath(itemIndexPath)
if insertIndexPathSet.contains(itemIndexPath) && insertIndexPathSet.count == 1{
attributes?.frame.origin.y += 30
// attributes?.alpha = 0
insertIndexPathSet.remove(itemIndexPath)
}
return attributes
}
}
| mit | e4086612390d0c90f687f618cc3227c6 | 27.046154 | 158 | 0.65277 | 5.661491 | false | false | false | false |
ohadh123/MuscleUp- | MuscleUp!/ShopViewController.swift | 1 | 2389 | //
// ShopViewController.swift
// MuscleUp!
//
// Created by Ohad Koronyo on 5/27/17.
// Copyright © 2017 Ohad Koronyo. All rights reserved.
//
import CoreData
import UIKit
import SwiftyButton
class ShopViewController: UIViewController {
var coinAmount: Int = 500
override func viewDidLoad() {
super.viewDidLoad()
setupShopScreen()
}
func setupShopScreen(){
createBackgroundImage()
let backButton = PressableButton(frame: CGRect(x: 0, y: 0, width: 75, height: 40))
backButton.center.x = view.frame.width/8
backButton.center.y = view.frame.height/10
backButton.setTitle("Back", for: .normal)
//backButton.backgroundColor = .blue
backButton.shadowHeight = 4
backButton.addTarget(self, action: #selector(backButtonMethod), for: .touchUpInside)
backButton.titleLabel!.font = UIFont(name: "Verdana", size: 20)
view.addSubview(backButton)
createCoinDisplay()
}
func createBackgroundImage(){
let backImage = #imageLiteral(resourceName: "SkyBackNoCloud")
let backImageResize = ViewController.resizeImage(image: backImage, newWidth: view.frame.width, newHeight: view.frame.height)
//backImage.height = view.frame.width
self.view.backgroundColor = UIColor(patternImage: backImageResize)
}
func createCoinDisplay(){
let coinImagePic = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
coinImagePic.image = #imageLiteral(resourceName: "empty-gold-coin")
coinImagePic.center.x = view.frame.width/1.2
coinImagePic.center.y = view.frame.height/10
view.addSubview(coinImagePic)
let coinLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 25))
coinLabel.center.x = view.frame.width/1.09
coinLabel.center.y = view.frame.height/10
coinLabel.textAlignment = .center
coinLabel.text = String(coinAmount)
coinLabel.font = UIFont(name: "Verdana-Bold", size: 20)
//coinLabel.font = coinLabel.font.withSize(20)
view.addSubview(coinLabel)
}
func backButtonMethod(){
print("Back pressed")
ViewController.backgroundMusicPlayer.play()
self.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | 32f092efe551b2b22daccc619d8b1f82 | 31.27027 | 132 | 0.64196 | 4.153043 | false | false | false | false |
kylef/RxHyperdrive | RxHyperdrive/RxHyperdrive.swift | 1 | 1617 | import RxSwift
import Hyperdrive
import Representor
extension Hyperdrive {
public func enter(uri:String) -> Observable<Representor<HTTPTransition>> {
return create { observer in
self.enter(uri) { result in
switch result {
case .Success(let representor):
observer.on(.Next(representor))
observer.on(.Completed)
case .Failure(let error):
observer.on(.Error(error))
}
}
return AnonymousDisposable {}
}
}
public func request(transition:HTTPTransition, parameters:[String:AnyObject]? = nil, attributes:[String:AnyObject]? = nil) -> Observable<Representor<HTTPTransition>> {
return create { observer in
self.request(transition, parameters: parameters, attributes: attributes) { result in
switch result {
case .Success(let representor):
observer.on(.Next(representor))
observer.on(.Completed)
case .Failure(let error):
observer.on(.Error(error))
}
}
return AnonymousDisposable {}
}
}
public func request(transition:HTTPTransition?, parameters:[String:AnyObject]? = nil, attributes:[String:AnyObject]? = nil) -> Observable<Representor<HTTPTransition>> {
if let transition = transition {
return request(transition, parameters: parameters, attributes: attributes)
}
return create { observer in
let error = NSError(domain: Hyperdrive.errorDomain, code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: "Given transition was nil."])
observer.on(.Error(error))
return AnonymousDisposable {}
}
}
}
| mit | 65be0685be5e2cfe77a0d440ec43113e | 32 | 170 | 0.664193 | 4.67341 | false | false | false | false |
crazypoo/Tuan | Tuan/Kingfisher/UIImage+Decode.swift | 8 | 2014 | //
// UIImage+Decode.swift
// Kingfisher-Demo
//
// Created by Wei Wang on 15/4/7.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension UIImage {
func kf_decodedImage() -> UIImage? {
let imageRef = self.CGImage
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
if let context = context {
let rect = CGRectMake(0, 0, CGFloat(CGImageGetWidth(imageRef)), CGFloat(CGImageGetHeight(imageRef)))
CGContextDrawImage(context, rect, imageRef)
let decompressedImageRef = CGBitmapContextCreateImage(context)
return UIImage(CGImage: decompressedImageRef)
} else {
return nil
}
}
} | mit | 69ced9dc3303f8b64e056473224bd70e | 44.795455 | 133 | 0.719464 | 4.65127 | false | false | false | false |
CodePath2017Group4/travel-app | RoadTripPlanner/DirectionsTableView.swift | 1 | 4307 | //
// DirectionsTableView.swift
// RoadTripPlanner
//
// Created by Deepthy on 10/20/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
import MapKit
class DirectionsTableView: UITableView {
var directionsArray: [(startingAddress: String, endingAddress: String, route: MKRoute)]!
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
extension DirectionsTableView: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.font = UIFont(name: "HoeflerText-Regular", size: 15)
label.numberOfLines = 5
setLabelBackgroundColor(label, section: section)
label.text = "SEGMENT #\(section+1)\n\nStarting point: \(directionsArray[section].startingAddress)\n"
return label
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let label = UILabel()
label.font = UIFont(name: "HoeflerText-Regular", size: 14)
label.numberOfLines = 8
setLabelBackgroundColor(label, section: section)
// 1
let route = directionsArray[section].route
// 2
let time = route.expectedTravelTime.formatted()
// 3
let miles = route.distance.miles()
//4
label.text = "Ending point: \(directionsArray[section].endingAddress)\n\nDistance: \(miles) miles\n\nExpected Travel Time: \(time)"
return label
}
func setLabelBackgroundColor(_ label: UILabel, section: Int) {
label.backgroundColor = Constants.Colors.ColorPalette3314Color3//UIColor.blue.withAlphaComponent(0.75)
/* switch section {
case 0:
label.backgroundColor = Constants.Colors.ColorPalette3314Color3//UIColor.blue.withAlphaComponent(0.75)
case 1:
label.backgroundColor = UIColor.green.withAlphaComponent(0.75)
default:
label.backgroundColor = UIColor.red.withAlphaComponent(0.75)
}*/
}
}
extension DirectionsTableView: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return directionsArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return directionsArray[section].route.steps.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DirectionCell") as UITableViewCell!
cell?.textLabel?.numberOfLines = 4
cell?.textLabel?.font = UIFont(name: "HoeflerText-Regular", size: 12)
cell?.isUserInteractionEnabled = false
let steps = directionsArray[indexPath.section].route.steps
let step = steps[indexPath.row]
let instructions = step.instructions
print("instructions \(instructions)")
let distance = step.distance.miles()
print("distance \(distance)")
cell?.textLabel?.text = "\(indexPath.row+1). \((instructions)) - \((distance)) miles"
return cell!
}
}
extension Float {
func format(_ f: String) -> String {
return NSString(format: "%\(f)f" as NSString, self) as String
}
}
extension CLLocationDistance {
func miles() -> String {
let miles = Float(self)/1609.344
return miles.format(".2")
}
}
extension TimeInterval {
func formatted() -> String {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [NSCalendar.Unit.hour, NSCalendar.Unit.minute, NSCalendar.Unit.second]
return formatter.string(from: self)!
}
}
| mit | 73c9b39972a37585c5e5d6ae882d4da4 | 31.870229 | 139 | 0.651649 | 4.773836 | false | false | false | false |
nodes-ios/ModelBoiler | ModelBoilerTests/ModelBoilerTests.swift | 1 | 7293 | //
// ModelBoilerTests.swift
// ModelBoilerTests
//
// Created by Jakob Mygind on 09/03/2020.
// Copyright © 2020 Nodes. All rights reserved.
//
import XCTest
@testable import Model_Boiler
class ModelBoilerTests: XCTestCase {
func testParsing() throws {
struct TestStruct: Codable, Equatable {
init(
string: String,
optionalString: String?,
dictionary: [String: Int],
optionalDictionary: [String: Int]?
) {
self.string = string
self.optionalString = optionalString
self.dictionary = dictionary
self.optionalDictionary = optionalDictionary
}
let string: String
let optionalString: String?
let dictionary: [String: Int]
let optionalDictionary: [String: Int]?
enum CodingKeys: String, CodingKey {
case string = "string"
case optionalString = "optionalString"
case dictionary = "dictionary"
case optionalDictionary = "optionalDictionary"
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(string, forKey: .string)
try container.encode(optionalString, forKey: .optionalString)
try container.encode(dictionary, forKey: .dictionary)
try container.encode(optionalDictionary, forKey: .optionalDictionary)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
string = try container.decode(String.self, forKey: .string)
optionalString = try container.decodeIfPresent(String.self, forKey: .optionalString)
dictionary = try container.decode([String: Int].self, forKey: .dictionary)
optionalDictionary = try container.decodeIfPresent([String: Int].self, forKey: .optionalDictionary)
}
}
do {
let str = """
{
"string": "Test",
"dictionary": { "Test": 1 }
}
"""
let test = try JSONDecoder().decode(TestStruct.self, from: str.data(using: .utf8)!)
let compare = TestStruct(string: "Test", optionalString: nil, dictionary: ["Test": 1], optionalDictionary: nil)
XCTAssertEqual(test, compare)
}
let str = """
{
"string": "Test",
"dictionary": { "Test": 1 },
"optionalDictionary": { "Test": 2 },
"optionalString": "MyOptional"
}
"""
let test = try JSONDecoder().decode(TestStruct.self, from: str.data(using: .utf8)!)
let compare = TestStruct(string: "Test", optionalString: "MyOptional", dictionary: ["Test": 1], optionalDictionary: ["Test": 2])
XCTAssertEqual(test, compare)
}
func testEmbedded() {
struct TestStruct: Codable, Equatable {
init(
string: String,
optionalString: String?,
dictionary: [String: Int],
optionalDictionary: [String: Int]?
) {
self.string = string
self.optionalString = optionalString
self.dictionary = dictionary
self.optionalDictionary = optionalDictionary
}
let string: String
let optionalString: String?
let dictionary: [String: Int]
let optionalDictionary: [String: Int]?
}
}
func testTypeInference() throws {
let str = """
struct Test {
var custom = CustomType()
var custom2 = [CustomType]()
var intVal = 1
var doubleVal = 2.33
var stringVal = "Hello"
var boolVal = true
}
"""
let expected = """
enum CodingKeys: String, CodingKey {
case custom = "custom"
case custom2 = "custom2"
case intVal = "intVal"
case doubleVal = "doubleVal"
case stringVal = "stringVal"
case boolVal = "boolVal"
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(custom, forKey: .custom)
try container.encode(custom2, forKey: .custom2)
try container.encode(intVal, forKey: .intVal)
try container.encode(doubleVal, forKey: .doubleVal)
try container.encode(stringVal, forKey: .stringVal)
try container.encode(boolVal, forKey: .boolVal)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
custom = try container.decode(CustomType.self, forKey: .custom)
custom2 = try container.decode([CustomType].self, forKey: .custom2)
intVal = try container.decode(Int.self, forKey: .intVal)
doubleVal = try container.decode(Double.self, forKey: .doubleVal)
stringVal = try container.decode(String.self, forKey: .stringVal)
boolVal = try container.decode(Bool.self, forKey: .boolVal)
}
"""
let res = try XCTUnwrap(try Generator(source: str).generate())
XCTAssertEqual(res, expected)
}
func testCamelCaseToUnderscore() throws {
let str = """
struct Test {
var intVal = 1
var doubleVal = 2.33
var stringVal = "Hello"
var boolVal = true
var imageURL: URL
}
"""
let expected = """
enum CodingKeys: String, CodingKey {
case intVal = "int_val"
case doubleVal = "double_val"
case stringVal = "string_val"
case boolVal = "bool_val"
case imageURL = "image_url"
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(intVal, forKey: .intVal)
try container.encode(doubleVal, forKey: .doubleVal)
try container.encode(stringVal, forKey: .stringVal)
try container.encode(boolVal, forKey: .boolVal)
try container.encode(imageURL, forKey: .imageURL)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
intVal = try container.decode(Int.self, forKey: .intVal)
doubleVal = try container.decode(Double.self, forKey: .doubleVal)
stringVal = try container.decode(String.self, forKey: .stringVal)
boolVal = try container.decode(Bool.self, forKey: .boolVal)
imageURL = try container.decode(URL.self, forKey: .imageURL)
}
"""
let res = try XCTUnwrap(try Generator(source: str, mapUnderscoreToCamelCase: true).generate())
XCTAssertEqual(res, expected)
}
}
| mit | 8c430e1a81ce3a5cb9105a6e88453045 | 36.015228 | 136 | 0.561026 | 4.960544 | false | true | false | false |
universonic/shadowsocks-macos | Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift | 3 | 2688 | //
// NSTextField+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 5/17/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(macOS)
import Cocoa
import RxSwift
/// Delegate proxy for `NSTextField`.
///
/// For more information take a look at `DelegateProxyType`.
open class RxTextFieldDelegateProxy
: DelegateProxy<NSTextField, NSTextFieldDelegate>
, DelegateProxyType
, NSTextFieldDelegate {
/// Typed parent object.
public weak private(set) var textField: NSTextField?
/// Initializes `RxTextFieldDelegateProxy`
///
/// - parameter textField: Parent object for delegate proxy.
init(textField: NSTextField) {
self.textField = textField
super.init(parentObject: textField, delegateProxy: RxTextFieldDelegateProxy.self)
}
public static func registerKnownImplementations() {
self.register { RxTextFieldDelegateProxy(textField: $0) }
}
fileprivate let textSubject = PublishSubject<String?>()
// MARK: Delegate methods
open override func controlTextDidChange(_ notification: Notification) {
let textField: NSTextField = castOrFatalError(notification.object)
let nextValue = textField.stringValue
self.textSubject.on(.next(nextValue))
_forwardToDelegate?.controlTextDidChange?(notification)
}
// MARK: Delegate proxy methods
/// For more information take a look at `DelegateProxyType`.
open class func currentDelegate(for object: ParentObject) -> NSTextFieldDelegate? {
return object.delegate
}
/// For more information take a look at `DelegateProxyType`.
open class func setCurrentDelegate(_ delegate: NSTextFieldDelegate?, to object: ParentObject) {
object.delegate = delegate
}
}
extension Reactive where Base: NSTextField {
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<NSTextField, NSTextFieldDelegate> {
return RxTextFieldDelegateProxy.proxy(for: base)
}
/// Reactive wrapper for `text` property.
public var text: ControlProperty<String?> {
let delegate = RxTextFieldDelegateProxy.proxy(for: base)
let source = Observable.deferred { [weak textField = self.base] in
delegate.textSubject.startWith(textField?.stringValue)
}.takeUntil(deallocated)
let observer = Binder(base) { (control, value: String?) in
control.stringValue = value ?? ""
}
return ControlProperty(values: source, valueSink: observer.asObserver())
}
}
#endif
| gpl-3.0 | 33e68bef6ca4e23924e5dd0b481d27d8 | 29.534091 | 99 | 0.688872 | 5.207364 | false | false | false | false |
tuffz/pi-weather-app | Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftPropertyTypeTest.swift | 1 | 8986 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
#if swift(>=3.0)
class SwiftPropertyTypeTest: RLMTestCase {
func testLongType() {
let longNumber: Int64 = 17179869184
let intNumber: Int64 = 2147483647
let negativeLongNumber: Int64 = -17179869184
let updatedLongNumber: Int64 = 8589934592
let realm = realmWithTestPath()
realm.beginWriteTransaction()
_ = SwiftLongObject.create(in: realm, withValue: [NSNumber(value: longNumber)])
_ = SwiftLongObject.create(in: realm, withValue: [NSNumber(value: intNumber)])
_ = SwiftLongObject.create(in: realm, withValue: [NSNumber(value: negativeLongNumber)])
try! realm.commitWriteTransaction()
let objects = SwiftLongObject.allObjects(in: realm)
XCTAssertEqual(objects.count, UInt(3), "3 rows expected")
XCTAssertEqual((objects[0] as! SwiftLongObject).longCol, longNumber, "2 ^ 34 expected")
XCTAssertEqual((objects[1] as! SwiftLongObject).longCol, intNumber, "2 ^ 31 - 1 expected")
XCTAssertEqual((objects[2] as! SwiftLongObject).longCol, negativeLongNumber, "-2 ^ 34 expected")
realm.beginWriteTransaction()
(objects[0] as! SwiftLongObject).longCol = updatedLongNumber
try! realm.commitWriteTransaction()
XCTAssertEqual((objects[0] as! SwiftLongObject).longCol, updatedLongNumber, "After update: 2 ^ 33 expected")
}
func testIntSizes() {
let realm = realmWithTestPath()
let v8 = Int8(1) << 5
let v16 = Int16(1) << 12
let v32 = Int32(1) << 30
// 1 << 40 doesn't auto-promote to Int64 on 32-bit platforms
let v64 = Int64(1) << 40
try! realm.transaction {
let obj = SwiftAllIntSizesObject()
obj.int8 = v8
XCTAssertEqual(obj.int8, v8)
obj.int16 = v16
XCTAssertEqual(obj.int16, v16)
obj.int32 = v32
XCTAssertEqual(obj.int32, v32)
obj.int64 = v64
XCTAssertEqual(obj.int64, v64)
realm.add(obj)
}
let obj = SwiftAllIntSizesObject.allObjects(in: realm)[0] as! SwiftAllIntSizesObject
XCTAssertEqual(obj.int8, v8)
XCTAssertEqual(obj.int16, v16)
XCTAssertEqual(obj.int32, v32)
XCTAssertEqual(obj.int64, v64)
}
func testIntSizes_objc() {
let realm = realmWithTestPath()
let v16 = Int16(1) << 12
let v32 = Int32(1) << 30
// 1 << 40 doesn't auto-promote to Int64 on 32-bit platforms
let v64 = Int64(1) << 40
try! realm.transaction {
let obj = AllIntSizesObject()
obj.int16 = v16
XCTAssertEqual(obj.int16, v16)
obj.int32 = v32
XCTAssertEqual(obj.int32, v32)
obj.int64 = v64
XCTAssertEqual(obj.int64, v64)
realm.add(obj)
}
let obj = AllIntSizesObject.allObjects(in: realm)[0] as! AllIntSizesObject
XCTAssertEqual(obj.int16, v16)
XCTAssertEqual(obj.int32, v32)
XCTAssertEqual(obj.int64, v64)
}
func testLazyVarProperties() {
let realm = realmWithTestPath()
let succeeded : Void? = try? realm.transaction {
realm.add(SwiftLazyVarObject())
}
XCTAssertNotNil(succeeded, "Writing an NSObject-based object with an lazy property should work.")
}
func testIgnoredLazyVarProperties() {
let realm = realmWithTestPath()
let succeeded : Void? = try? realm.transaction {
realm.add(SwiftIgnoredLazyVarObject())
}
XCTAssertNotNil(succeeded, "Writing an object with an ignored lazy property should work.")
}
func testObjectiveCTypeProperties() {
let realm = realmWithTestPath()
var object: SwiftObjectiveCTypesObject!
let now = NSDate()
let data = "fizzbuzz".data(using: .utf8)! as Data as NSData
try! realm.transaction {
object = SwiftObjectiveCTypesObject()
realm.add(object)
object.stringCol = "Hello world!"
object.dateCol = now
object.dataCol = data
object.numCol = 42
}
XCTAssertEqual("Hello world!", object.stringCol)
XCTAssertEqual(now, object.dateCol)
XCTAssertEqual(data, object.dataCol)
XCTAssertEqual(42, object.numCol)
}
}
#else
class SwiftPropertyTypeTest: RLMTestCase {
func testLongType() {
let longNumber: Int64 = 17179869184
let intNumber: Int64 = 2147483647
let negativeLongNumber: Int64 = -17179869184
let updatedLongNumber: Int64 = 8589934592
let realm = realmWithTestPath()
realm.beginWriteTransaction()
SwiftLongObject.createInRealm(realm, withValue: [NSNumber(longLong: longNumber)])
SwiftLongObject.createInRealm(realm, withValue: [NSNumber(longLong: intNumber)])
SwiftLongObject.createInRealm(realm, withValue: [NSNumber(longLong: negativeLongNumber)])
try! realm.commitWriteTransaction()
let objects = SwiftLongObject.allObjectsInRealm(realm)
XCTAssertEqual(objects.count, UInt(3), "3 rows expected")
XCTAssertEqual((objects[0] as! SwiftLongObject).longCol, longNumber, "2 ^ 34 expected")
XCTAssertEqual((objects[1] as! SwiftLongObject).longCol, intNumber, "2 ^ 31 - 1 expected")
XCTAssertEqual((objects[2] as! SwiftLongObject).longCol, negativeLongNumber, "-2 ^ 34 expected")
realm.beginWriteTransaction()
(objects[0] as! SwiftLongObject).longCol = updatedLongNumber
try! realm.commitWriteTransaction()
XCTAssertEqual((objects[0] as! SwiftLongObject).longCol, updatedLongNumber, "After update: 2 ^ 33 expected")
}
func testIntSizes() {
let realm = realmWithTestPath()
let v8 = Int8(1) << 5
let v16 = Int16(1) << 12
let v32 = Int32(1) << 30
// 1 << 40 doesn't auto-promote to Int64 on 32-bit platforms
let v64 = Int64(1) << 40
try! realm.transactionWithBlock() {
let obj = SwiftAllIntSizesObject()
obj.int8 = v8
XCTAssertEqual(obj.int8, v8)
obj.int16 = v16
XCTAssertEqual(obj.int16, v16)
obj.int32 = v32
XCTAssertEqual(obj.int32, v32)
obj.int64 = v64
XCTAssertEqual(obj.int64, v64)
realm.addObject(obj)
}
let obj = SwiftAllIntSizesObject.allObjectsInRealm(realm)[0] as! SwiftAllIntSizesObject
XCTAssertEqual(obj.int8, v8)
XCTAssertEqual(obj.int16, v16)
XCTAssertEqual(obj.int32, v32)
XCTAssertEqual(obj.int64, v64)
}
func testIntSizes_objc() {
let realm = realmWithTestPath()
let v16 = Int16(1) << 12
let v32 = Int32(1) << 30
// 1 << 40 doesn't auto-promote to Int64 on 32-bit platforms
let v64 = Int64(1) << 40
try! realm.transactionWithBlock() {
let obj = AllIntSizesObject()
obj.int16 = v16
XCTAssertEqual(obj.int16, v16)
obj.int32 = v32
XCTAssertEqual(obj.int32, v32)
obj.int64 = v64
XCTAssertEqual(obj.int64, v64)
realm.addObject(obj)
}
let obj = AllIntSizesObject.allObjectsInRealm(realm)[0] as! AllIntSizesObject
XCTAssertEqual(obj.int16, v16)
XCTAssertEqual(obj.int32, v32)
XCTAssertEqual(obj.int64, v64)
}
func testLazyVarProperties() {
let realm = realmWithTestPath()
let succeeded : Void? = try? realm.transactionWithBlock() {
realm.addObject(SwiftLazyVarObject())
}
XCTAssertNotNil(succeeded, "Writing an NSObject-based object with an lazy property should work.")
}
func testIgnoredLazyVarProperties() {
let realm = realmWithTestPath()
let succeeded : Void? = try? realm.transactionWithBlock() {
realm.addObject(SwiftIgnoredLazyVarObject())
}
XCTAssertNotNil(succeeded, "Writing an object with an ignored lazy property should work.")
}
}
#endif
| mit | c66010c1a14ba662f57dddad45ca01a9 | 35.088353 | 116 | 0.611396 | 4.270913 | false | true | false | false |
achiwhane/ReadHN | ReadHN/StoriesTableViewController.swift | 1 | 6364 | //
// StoriesTableViewController.swift
// ReadHN
//
// Created by Akshay Chiwhane on 8/7/15.
// Copyright (c) 2015 Akshay Chiwhane. All rights reserved.
//
import UIKit
class StoriesTableViewController: UITableViewController, StoryCategoryDelegate {
var storyTableCellData: [Int: Int] = [Int:Int]() // key - rowIndex, val - id
var numberStories = 20
var categoryUrl: String = "https://hacker-news.firebaseio.com/v0/topstories.json"
var brain = HackerNewsBrain()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.layoutMargins = UIEdgeInsetsZero
//tableView.estimatedRowHeight = tableView.rowHeight
//tableView.rowHeight = UITableViewAutomaticDimension
initDelegate(categoryUrl)
initRefreshControl()
//refresh()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
refresh()
}
// refreshes the table view
func refresh() {
tableView.reloadData()
self.tableView.layoutMargins = UIEdgeInsetsZero
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
brain.startConnection() {
for i in 0..<self.brain.submissionIDs.count {
if i < self.numberStories {
let id = self.brain.submissionIDs[i]
self.storyTableCellData[i] = id
self.brain.generateSubmissionForID(id) {
if i == self.numberStories - 1 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.reformatCells()
})
}
}
} else { break }
}
}
refreshControl?.endRefreshing()
}
// sets up the pull-down to refresh control -- used only in viewDidLoad()
func initRefreshControl() {
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
}
func initDelegate(url: String) {
categoryUrl = url
brain.delegate = self
}
// MARK: - format cell funcs
func refreshCell(row: Int) {
let indexPath = NSIndexPath(forRow: row, inSection: 0)
if isCellVisible(row) {
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
tableView.endUpdates()
}
}
func isCellVisible(index: Int) -> Bool {
let visibleRows = tableView.indexPathsForVisibleRows!
if let indices = visibleRows as? [NSIndexPath] {
for rowIndex in indices {
if rowIndex.row == index {
return true
}
}
}
return false
}
// formats a cell's title and subtitle at a given row
private func generateHeadingsforID(id: Int) -> (title: String?, subtitle: String?){
if let s = Submission.loadSaved(id) {
return (s.title, "\(s.score ?? -1) points | by \(s.by) | \(formatURL(s.url))")
}
return (nil, nil)
}
private func formatURL(url: String) -> String {
return NSURL(string: url)?.host ?? ""
}
private func reformatCells() {
for i in 0..<numberStories {
refreshCell(i)
}
}
// MARK: - tableView funcs
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CGFloat(80.0)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return numberStories + 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let dequeued: AnyObject = tableView.dequeueReusableCellWithIdentifier("storyCell", forIndexPath: indexPath)
let cell = dequeued as! UITableViewCell
if indexPath.row == numberStories {
cell.textLabel?.text = "LOAD MORE STUFF"
cell.detailTextLabel?.text = ""
cell.contentView.backgroundColor? = UIColor.redColor()
} else {
// get the id associated with the row
// pull the title and subtitle from the id
// and format cell
let headings = generateHeadingsforID(storyTableCellData[indexPath.row] ?? 0)
if let title = headings.title, subtitle = headings.subtitle {
cell.textLabel?.text = title
cell.textLabel?.font = UIFont.boldSystemFontOfSize(CGFloat(16.0))
cell.detailTextLabel?.text = subtitle
} else {
cell.textLabel?.text = "Loading..."
cell.detailTextLabel?.text = "Loading..."
}
}
return cell
}
override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("View Content", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "View Content":
if let wvc = segue.destinationViewController as? WebViewController {
if let cell = sender as? UITableViewCell {
wvc.pageTitle = cell.textLabel?.text
if let cellIndexPath = self.tableView.indexPathForCell(cell) {
if cellIndexPath.row != numberStories {
if let data = Submission.loadSaved(storyTableCellData[cellIndexPath.row] ?? 0){
wvc.pageUrl = data.url
}
}
}
}
}
default: break
}
}
}
}
| mit | 4e89d37e1493a1ecaca0233fc1986d8b | 35.365714 | 121 | 0.56851 | 5.384095 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/ObjectMapper/ObjectMapperTests/CustomTransformTests.swift | 4 | 6177 | //
// CustomTransformTests.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-03-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// 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 XCTest
import ObjectMapper
class CustomTransformTests: XCTestCase {
let mapper = Mapper<Transforms>()
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 testDateTransform() {
let transforms = Transforms()
transforms.date = NSDate(timeIntervalSince1970: 946684800)
transforms.dateOpt = NSDate(timeIntervalSince1970: 946684912)
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
XCTAssertNotNil(parsedTransforms)
XCTAssertEqual(parsedTransforms?.date, transforms.date)
XCTAssertEqual(parsedTransforms?.dateOpt, transforms.dateOpt)
}
func testISO8601DateTransform() {
let transforms = Transforms()
transforms.ISO8601Date = NSDate(timeIntervalSince1970: 1398956159)
transforms.ISO8601DateOpt = NSDate(timeIntervalSince1970: 1398956159)
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
XCTAssertNotNil(parsedTransforms)
XCTAssertEqual(parsedTransforms?.ISO8601Date, transforms.ISO8601Date)
XCTAssertEqual(parsedTransforms?.ISO8601DateOpt, transforms.ISO8601DateOpt)
}
func testISO8601DateTransformWithInvalidInput() {
var JSON: [String: AnyObject] = ["ISO8601Date": ""]
let transforms = mapper.map(JSON)
XCTAssertNil(transforms?.ISO8601DateOpt)
JSON["ISO8601Date"] = "incorrect format"
let transforms2 = mapper.map(JSON)
XCTAssertNil(transforms2?.ISO8601DateOpt)
}
func testCustomFormatDateTransform(){
let dateString = "2015-03-03T02:36:44"
let JSON: [String: AnyObject] = ["customFormateDate": dateString]
let transform: Transforms! = mapper.map(JSON)
XCTAssertNotNil(transform)
let JSONOutput = mapper.toJSON(transform)
XCTAssertEqual(JSONOutput["customFormateDate"] as? String, dateString)
}
func testIntToStringTransformOf() {
let intValue = 12345
let JSON: [String: AnyObject] = ["intWithString": "\(intValue)"]
let transforms = mapper.map(JSON)
XCTAssertEqual(transforms?.intWithString, intValue)
}
func testInt64MaxValue() {
let transforms = Transforms()
transforms.int64Value = INT64_MAX
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
XCTAssertNotNil(parsedTransforms)
XCTAssertEqual(parsedTransforms?.int64Value, transforms.int64Value)
}
func testURLTranform() {
let transforms = Transforms()
transforms.URL = NSURL(string: "http://google.com/image/1234")!
transforms.URLOpt = NSURL(string: "http://google.com/image/1234")
let JSON = mapper.toJSON(transforms)
let parsedTransforms = mapper.map(JSON)
XCTAssertNotNil(parsedTransforms)
XCTAssertEqual(parsedTransforms?.URL, transforms.URL)
XCTAssertEqual(parsedTransforms?.URLOpt, transforms.URLOpt)
}
func testEnumTransform() {
let JSON: [String: AnyObject] = ["firstImageType" : "cover", "secondImageType" : "thumbnail"]
let transforms = mapper.map(JSON)
let imageType = Transforms.ImageType.self
XCTAssertEqual(transforms?.firstImageType, imageType.Cover)
XCTAssertEqual(transforms?.secondImageType, imageType.Thumbnail)
}
}
class Transforms: Mappable {
internal enum ImageType: String {
case Cover = "cover"
case Thumbnail = "thumbnail"
}
var date = NSDate()
var dateOpt: NSDate?
var ISO8601Date: NSDate = NSDate()
var ISO8601DateOpt: NSDate?
var customFormatDate = NSDate()
var customFormatDateOpt: NSDate?
var URL = NSURL()
var URLOpt: NSURL?
var intWithString: Int = 0
var int64Value: Int64 = 0
var firstImageType: ImageType?
var secondImageType: ImageType?
init(){
}
required init?(_ map: Map){
}
func mapping(map: Map) {
date <- (map["date"], DateTransform())
dateOpt <- (map["dateOpt"], DateTransform())
ISO8601Date <- (map["ISO8601Date"], ISO8601DateTransform())
ISO8601DateOpt <- (map["ISO8601DateOpt"], ISO8601DateTransform())
customFormatDate <- (map["customFormateDate"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss"))
customFormatDateOpt <- (map["customFormateDateOpt"], CustomDateFormatTransform(formatString: "yyyy-MM-dd'T'HH:mm:ss"))
URL <- (map["URL"], URLTransform())
URLOpt <- (map["URLOpt"], URLTransform())
intWithString <- (map["intWithString"], TransformOf<Int, String>(fromJSON: { $0 == nil ? nil : Int($0!) }, toJSON: { $0.map { String($0) } }))
int64Value <- (map["int64Value"], TransformOf<Int64, NSNumber>(fromJSON: { $0?.longLongValue }, toJSON: { $0.map { NSNumber(longLong: $0) } }))
firstImageType <- (map["firstImageType"], EnumTransform<ImageType>())
secondImageType <- (map["secondImageType"], EnumTransform<ImageType>())
}
}
| mit | 78fc327059d1e11ccd2902b0a5d77d3f | 31.171875 | 147 | 0.728671 | 3.83903 | false | true | false | false |
jhurray/Ladybug | Tree Example/ViewController.swift | 1 | 1515 | //
// ViewController.swift
// Tree Example
//
// Created by Jeffrey Hurray on 9/13/17.
// Copyright © 2017 jhurray. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var jsonData: Data!
override func viewDidLoad() {
super.viewDidLoad()
jsonData = treeJSON.data(using: .utf8)!
createCodableTree()
createJSONCodableTree()
}
func createCodableTree() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let tree = try! decoder.decode(Tree_Codable.self, from: jsonData)
print(tree)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(dateFormatter)
let data = try! encoder.encode(tree)
print(data)
let treeAgain = try! decoder.decode(Tree_Codable.self, from: data)
print(treeAgain)
}
func encodeCodableTree() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
}
func createJSONCodableTree() {
let tree = try! Tree_JSONCodable(data: jsonData)
print(tree)
let data = try! tree.toData()
print(data)
let treeAgain = try! Tree_JSONCodable(data: data)
print(treeAgain)
}
}
| mit | 23406f95710b4a0ac6ed9a0b32222023 | 23.419355 | 74 | 0.57926 | 4.701863 | false | false | false | false |
4np/UitzendingGemist | NPOKit/NPOKit/NPOManager+Generics.swift | 1 | 3833 | //
// NPOManager+Generics.swift
// NPOKit
//
// Created by Jeroen Wesbeek on 14/07/16.
// Copyright © 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
import RealmSwift
import CocoaLumberjack
extension NPOManager {
// MARK: Fetch Generic Models
//internal func fetchModels<T: Object where T: Mappable, T: NPOResource>
internal func fetchModels<T: Mappable>(ofType type: T.Type, fromPath path: String, withCompletion completed: @escaping (_ elements: [T]?, _ error: NPOError?) -> Void = { elements, error in }) -> Request? {
return self.fetchModels(ofType: type, fromPath: path, withKeyPath: nil, withCompletion: completed)
}
internal func fetchModels<T: Mappable>(ofType type: T.Type, fromPath path: String, withKeyPath keyPath: String?, withCompletion completed: @escaping (_ elements: [T]?, _ error: NPOError?) -> Void = { elements, error in }) -> Request? {
let url = self.getURL(forPath: path)
return self.fetchModels(ofType: type, fromURL: url, withKeyPath: keyPath, withCompletion: completed)
}
internal func fetchModels<T: Mappable>(ofType type: T.Type, fromURL url: String, withKeyPath keyPath: String?, withCompletion completed: @escaping (_ elements: [T]?, _ error: NPOError?) -> Void = { elements, error in }) -> Request? {
//DDLogDebug("fetch models of type \(type): \(url)")
return Alamofire.request(url, headers: self.getHeaders())
.responseArray(keyPath: keyPath) { (response: DataResponse<[T]>) in
switch response.result {
case .success(let elements):
completed(elements, nil)
break
case .failure(let error):
completed(nil, .networkError(error.localizedDescription))
break
}
}
}
// MARK: Fetch Single Model
internal func fetchModel<T: Mappable>(ofType type: T.Type, fromURL url: String, withCompletion completed: @escaping (_ element: T?, _ error: NPOError?) -> Void = { element, error in }) -> Request? {
return self.fetchModel(ofType: type, fromURL: url, withKeyPath: nil, withCompletion: completed)
}
internal func fetchModel<T: Mappable>(ofType type: T.Type, fromPath path: String, withCompletion completed: @escaping (_ element: T?, _ error: NPOError?) -> Void = { element, error in }) -> Request? {
return self.fetchModel(ofType: type, fromPath: path, withKeyPath: nil, withCompletion: completed)
}
internal func fetchModel<T: Mappable>(ofType type: T.Type, fromPath path: String, withKeyPath keyPath: String?, withCompletion completed: @escaping (_ element: T?, _ error: NPOError?) -> Void = { element, error in }) -> Request? {
let url = self.getURL(forPath: path)
return self.fetchModel(ofType: type, fromURL: url, withKeyPath: keyPath, withCompletion: completed)
}
internal func fetchModel<T: Mappable>(ofType type: T.Type, fromURL url: String, withKeyPath keyPath: String?, withCompletion completed: @escaping (_ element: T?, _ error: NPOError?) -> Void = { element, error in }) -> Request? {
//DDLogDebug("fetch model of type \(type): \(url)")
return Alamofire.request(url, headers: self.getHeaders())
.responseObject(keyPath: keyPath) { (response: DataResponse<T>) in
switch response.result {
case .success(let element):
completed(element, nil)
break
case .failure(let error):
completed(nil, .networkError(error.localizedDescription))
break
}
}
}
}
| apache-2.0 | 301fca274a7260a97596aae7559b5271 | 51.493151 | 239 | 0.628653 | 4.60024 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/set-mismatch.swift | 2 | 509 | /**
* https://leetcode.com/problems/set-mismatch/
*
*
*/
// Date: Tue Mar 2 13:53:28 PST 2021
class Solution {
func findErrorNums(_ nums: [Int]) -> [Int] {
var cand: Set<Int> = []
var missing = -1
var sum = (1 + nums.count) * nums.count / 2
for x in nums {
if cand.contains(x) == false{
cand.insert(x)
sum -= x
} else {
missing = x
}
}
return [missing, sum]
}
} | mit | 0333b4a25c85a857b8cf134ed04a7dd8 | 22.181818 | 51 | 0.436149 | 3.609929 | false | false | false | false |
atl009/WordPress-iOS | WordPressKit/WordPressKit/PlanServiceRemote.swift | 1 | 3619 | import Foundation
import WordPressShared
import CocoaLumberjack
public class PlanServiceRemote: ServiceRemoteWordPressComREST {
public typealias SitePlans = (activePlan: RemotePlan, availablePlans: [RemotePlan])
public enum ResponseError: Error {
case decodingFailure
case unsupportedPlan
case noActivePlan
}
public func getPlansForSite(_ siteID: Int, success: @escaping (SitePlans) -> Void, failure: @escaping (Error) -> Void) {
let endpoint = "sites/\(siteID)/plans"
let path = self.path(forEndpoint: endpoint, withVersion: ._1_2)
let locale = WordPressComLanguageDatabase().deviceLanguage.slug
let parameters = ["locale": locale]
wordPressComRestApi.GET(path!,
parameters: parameters as [String : AnyObject]?,
success: {
response, _ in
do {
try success(mapPlansResponse(response))
} catch {
DDLogError("Error parsing plans response for site \(siteID)")
DDLogError("\(error)")
DDLogDebug("Full response: \(response)")
failure(error)
}
}, failure: {
error, _ in
failure(error)
})
}
}
private func mapPlansResponse(_ response: AnyObject) throws -> (activePlan: RemotePlan, availablePlans: [RemotePlan]) {
guard let json = response as? [[String: AnyObject]] else {
throw PlanServiceRemote.ResponseError.decodingFailure
}
let parsedResponse: (RemotePlan?, [RemotePlan]) = try json.reduce((nil, []), {
(result, planDetails: [String: AnyObject]) in
guard let planId = planDetails["product_id"] as? Int,
let title = planDetails["product_name_short"] as? String,
let fullTitle = planDetails["product_name"] as? String,
let tagline = planDetails["tagline"] as? String,
let featureGroupsJson = planDetails["features_highlight"] as? [[String: AnyObject]] else {
throw PlanServiceRemote.ResponseError.decodingFailure
}
guard let icon = planDetails["icon"] as? String,
let iconUrl = URL(string: icon),
let activeIcon = planDetails["icon_active"] as? String,
let activeIconUrl = URL(string: activeIcon) else {
return result
}
let productIdentifier = (planDetails["apple_sku"] as? String).flatMap({ $0.nonEmptyString() })
let featureGroups = try parseFeatureGroups(featureGroupsJson)
let plan = RemotePlan(id: planId, title: title, fullTitle: fullTitle, tagline: tagline, iconUrl: iconUrl, activeIconUrl: activeIconUrl, productIdentifier: productIdentifier, featureGroups: featureGroups)
let plans = result.1 + [plan]
if let isCurrent = planDetails["current_plan"] as? Bool,
isCurrent {
return (plan, plans)
} else {
return (result.0, plans)
}
})
guard let activePlan = parsedResponse.0 else {
throw PlanServiceRemote.ResponseError.noActivePlan
}
let availablePlans = parsedResponse.1
return (activePlan, availablePlans)
}
private func parseFeatureGroups(_ json: [[String: AnyObject]]) throws -> [RemotePlanFeatureGroupPlaceholder] {
return try json.flatMap { groupJson in
guard let slugs = groupJson["items"] as? [String] else { throw PlanServiceRemote.ResponseError.decodingFailure }
return RemotePlanFeatureGroupPlaceholder(title: groupJson["title"] as? String, slugs: slugs)
}
}
| gpl-2.0 | a3ac11729337758a98c05938a8e159a4 | 40.125 | 211 | 0.63139 | 4.730719 | false | false | false | false |
chris-hatton/SwiftImage | Sources/Model/Impl/GenericImage.swift | 1 | 1742 | //
// GenericImage.swift
// SwiftVision
//
// Created by Christopher Hatton on 20/07/2015.
// Copyright © 2015 Chris Hatton. All rights reserved.
//
import Foundation
public final class GenericImage<TP :Color> : MutableImage
{
public typealias PixelColor = TP
public typealias ImageType = GenericImage
public typealias PixelColorSource = ()->TP?
public var pixels : ContiguousArray<PixelColor>
public var
width : Int,
height : Int
// TODO: Create another constructor which uses a PixelColorSource for the initial fill
public init(width: Int, height: Int, fill: PixelColor)
{
pixels = ContiguousArray<PixelColor>(repeating: fill, count: Int( width * height ))
self.width = width
self.height = height
}
public func read( region: ImageRegion ) -> PixelColorSource
{
var i : Int = Int( ( region.y * self.width ) + region.x )
let widthOutsideRegion = Int( self.width - region.width )
let nextLine = { i += widthOutsideRegion }
let nextPixel = { return self.pixels[ i ] }
i += 1
return regionRasterSource( region, nextPixel: nextPixel, nextLine: nextLine )
}
public func write( region: ImageRegion, pixelColorSource: @escaping PixelColorSource )
{
for y : Int in region.y ..< (region.y + region.height)
{
for x : Int in region.x ..< (region.x + region.width)
{
guard let pixel : PixelColor = pixelColorSource() else { fatalError() }
self.pixels[ Int( ( y * width ) + x ) ] = pixel
}
}
}
}
| gpl-2.0 | e25c0d3e28755de8a37daa6ad3c71356 | 28.016667 | 91 | 0.576106 | 4.418782 | false | false | false | false |
atuooo/notGIF | notGIF/Controllers/Intro/IntroViewController.swift | 1 | 4114 | //
// IntroViewController.swift
// notGIF
//
// Created by Atuooo on 24/06/2017.
// Copyright © 2017 xyz. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController {
static var isFromHelp: Bool = false
fileprivate var currentIndex = 0
@IBOutlet var rightSwipeGes: UISwipeGestureRecognizer!
@IBOutlet var leftSwipeGes: UISwipeGestureRecognizer!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var sloganView: IntroView!
fileprivate var introViews: [Intro] = []
@IBAction func backButtonClicked(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
@IBAction func leftSwipeGesHandler(_ sender: UISwipeGestureRecognizer) {
guard currentIndex < introViews.count - 1 else { return }
view.isUserInteractionEnabled = false
let toShowView = introViews[currentIndex+1]
let toHideView = introViews[currentIndex]
currentIndex += 1
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: {
toShowView.show()
toHideView.hide(toLeft: true)
}) { _ in }
DispatchQueue.main.after(0.5) {
toShowView.animate()
toHideView.restore()
self.view.isUserInteractionEnabled = true
}
}
@IBAction func rightSwipeGesHandler(_ sender: UISwipeGestureRecognizer) {
guard currentIndex > 0 else { return }
view.isUserInteractionEnabled = false
let toShowView = introViews[currentIndex-1]
let toHideView = introViews[currentIndex]
currentIndex -= 1
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: {
toShowView.show()
toHideView.hide(toLeft: false)
}) { _ in }
DispatchQueue.main.after(0.5) {
toShowView.animate()
toHideView.restore()
self.view.isUserInteractionEnabled = true
}
}
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.barTint
if !IntroViewController.isFromHelp {
backButton.isHidden = true
}
let introTagView = IntroTagView()
let introDetailView = IntroDetailView()
let introShareView = IntroShareView()
introTagView.transform = CGAffineTransform(translationX: kScreenWidth, y: 0)
introTagView.alpha = 0.3
introDetailView.transform = CGAffineTransform(translationX: kScreenWidth, y: 0)
introDetailView.alpha = 0.3
introShareView.transform = CGAffineTransform(translationX: kScreenWidth, y: 0)
introShareView.alpha = 0.3
introShareView.goMainHandler = { [weak self] in
if IntroViewController.isFromHelp {
self?.navigationController?.popViewController(animated: true)
} else {
NGUserDefaults.haveShowIntro = true
UIApplication.shared.keyWindow?.set(rootViewController: UIStoryboard.main)
}
}
view.addSubview(introTagView)
view.addSubview(introDetailView)
view.addSubview(introShareView)
view.bringSubview(toFront: backButton)
introViews = [sloganView, introTagView, introDetailView, introShareView]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
}
deinit {
printLog("deinited")
}
}
| mit | 12530294b64205cd3994dacf4e58faf0 | 30.638462 | 131 | 0.621444 | 5.32772 | false | false | false | false |
ellipse43/v2ex | v2ex/TabViewController.swift | 1 | 6117 | //
// TabViewController.swift
// v2ex
//
// Created by ellipse42 on 15/8/16.
// Copyright (c) 2015年 ellipse42. All rights reserved.
//
import UIKit
import SnapKit
import SwiftyJSON
import Alamofire
import Kanna
import Kingfisher
class TabViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let CELLNAME = "tabViewCell"
var parentNavigationController: UINavigationController?
var tabCategory: String?
var currentIdx: Int?
var isRefresh = false
var infos: JSON = [] {
didSet {
tableView.reloadData()
}
}
lazy var tableView: UITableView = {
var v = UITableView()
v.delegate = self
v.dataSource = self
v.register(TabViewCell.self, forCellReuseIdentifier: self.CELLNAME)
v.estimatedRowHeight = 100
v.rowHeight = UITableViewAutomaticDimension
v.separatorStyle = UITableViewCellSeparatorStyle.none
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
setup()
if currentIdx == 0 {
refresh()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func refresh() {
isRefresh = true
let simpleAnimator = SimpleAnimator(frame: CGRect(x: 0, y: 0, width: 320, height: 60))
tableView.addPullToRefreshWithAction({
self.getInfos()
}, withAnimator: simpleAnimator)
tableView.startPullToRefresh()
}
func getInfos() {
let uri: String = String(format: Config.tabUrl, self.tabCategory!)
Alamofire.request(uri)
.response { response in
if let _ = response.error {
NSLog("Error")
} else {
if let doc = Kanna.HTML(html: response.data!, encoding: String.Encoding.utf8) {
var _infos = [JSON]()
for node in doc.css("#Main > div:nth-child(2) > div.item") {
var d = Dictionary<String, String>()
if let title = node.at_css("table > tr > td:nth-child(3) > span.item_title > a") {
if let id = title["href"] {
if let match = id.range(of: "\\d+", options: .regularExpression) {
d["id"] = id[match]
}
}
d["title"] = title.text
}
if let username = node.at_css("table > tr > td:nth-child(3) > span.small.fade > strong:nth-child(3) > a") {
d["username"] = username.text
}
if let node = node.at_css("table > tr > td:nth-child(3) > span.small.fade > a") {
d["node"] = node.text
}
if let created = node.at_css("table > tr > td:nth-child(3) > span.small.fade") {
if let msg = created.text {
let v = msg.characters.split {$0 == "•"}.map { String($0) }
d["created"] = v.count == 4 ? v[2]: nil
}
}
if let replies = node.at_css("table > tr > td:nth-child(4) > a") {
d["replies"] = replies.text
} else {
d["replies"] = "0"
}
if let avatar = node.at_css("table > tr > td:nth-child(1) > a > img") {
d["avatar"] = avatar["src"]
}
_infos.append(JSON(d))
}
self.infos = JSON(_infos)
OperationQueue.main.addOperation {
self.tableView.stopPullToRefresh()
}
}
}
}
}
func setup() {
view.addSubview(tableView)
tableView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, 0, 0))
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return infos.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = TabDetailViewController()
let indexPath = tableView.indexPathForSelectedRow
if let index = indexPath {
vc.info = infos[index.row]
}
parentNavigationController!.pushViewController(vc, animated: true)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CELLNAME, for: indexPath) as! TabViewCell
let index = indexPath.row as Int
if let id = infos[index]["avatar"].string {
if let url = URL(string: "http:\(id)") {
cell.avatar.kf.setImage(with: ImageResource.init(downloadURL: url))
}
}
if let id = infos[index]["title"].string {
cell.title.numberOfLines = 0
cell.title.text = id
}
if let id = infos[index]["username"].string {
cell.username.text = id
}
if let id = infos[index]["created"].string {
cell.created.text = id
}
if let id = infos[index]["node"].string {
cell.node.text = "# \(id)"
}
if let id = infos[index]["replies"].string {
cell.replies.text = id
}
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
}
| mit | 7574e462e55b2b51fc8af808b78ebe02 | 35.171598 | 135 | 0.475871 | 5.027138 | false | false | false | false |
S2dentik/Taylor | TaylorFramework/Modules/Printer/Printer.swift | 4 | 1001 | //
// Printer.swift
// Printer
//
// Created by Andrei Raifura on 9/10/15.
// Copyright © 2015 YOPESO. All rights reserved.
//
import Foundation
enum VerbosityLevel {
case info, warning, error
}
protocol Printing {
func printMessage(_ text: String)
}
struct DefaultReporter: Printing {
func printMessage(_ text: String) {
print(text)
}
}
struct Printer {
fileprivate let reporter: Printing
let verbosity: VerbosityLevel
init(verbosityLevel: VerbosityLevel, reporter: Printing = DefaultReporter()) {
verbosity = verbosityLevel
self.reporter = reporter
}
func printInfo(_ text: String) {
if verbosity == .info {
reporter.printMessage(text)
}
}
func printWarning(_ text: String) {
if [.warning, .info].contains(verbosity) {
reporter.printMessage(text)
}
}
func printError(_ text: String) {
reporter.printMessage(text)
}
}
| mit | e3244522a4b3fa47e29f89fa71ca513e | 17.867925 | 82 | 0.609 | 4.201681 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/Protocols/CSProperty.swift | 1 | 3956 | //
// Created by Rene Dohan on 11/22/20.
//
import Foundation
public protocol CSPropertyProtocol: CSVariableProtocol {
@discardableResult
func onChange(_ function: @escaping (T) -> Void) -> CSEventRegistration
}
extension CSPropertyProtocol {
@discardableResult
public func onChange(_ function: @escaping Func) -> CSEventRegistration {
self.onChange { _ in function() }
}
}
open class CSProperty<T>: CSPropertyProtocol where T: Equatable {
private let eventChange: CSEvent<T> = event()
private var onApply: ((T) -> ())?
private var _value: T
public var value: T {
get { _value }
set { value(newValue, fireEvents: true) }
}
public init(value: T, onApply: ((T) -> ())? = nil) {
_value = value
self.onApply = onApply
}
@discardableResult
public func value(_ newValue: T, fireEvents: Bool = true) -> Self {
if _value == newValue { return self }
_value = newValue
if (fireEvents) {
onApply?(newValue)
eventChange.fire(newValue)
}
return self
}
@discardableResult
public func onChange(_ function: @escaping ArgFunc<T>) -> CSEventRegistration {
eventChange.listen { function($0) }
}
@discardableResult
public func apply() -> Self {
onApply?(value)
eventChange.fire(value)
return self
}
}
public extension CSPropertyProtocol where T: CSAnyProtocol {
var isSet: Bool {
get { value.notNil }
}
}
public extension CSPropertyProtocol where T == Bool {
@discardableResult
func toggle() -> Self { value = !value; return self }
@discardableResult
func setFalse() -> Self { value = false; return self }
@discardableResult
func setTrue() -> Self { value = true; return self }
@discardableResult
func onFalse(function: @escaping () -> Unit) -> CSEventRegistration {
onChange { if $0.isFalse { function() } }
}
@discardableResult
func onTrue(function: @escaping () -> Unit) -> CSEventRegistration {
onChange { if $0.isTrue { function() } }
}
var isTrue: Bool {
get { value }
set { value = newValue }
}
var isFalse: Bool {
get { !value }
set { value = !newValue }
}
}
public extension CSProperty where T == String? {
var string: T {
get { value.asString }
set { value = newValue }
}
func text(_ string: T) { value = string }
func string(_ string: T) { value = string }
func clear() { value = nil } // TODO: How to make this generic for any optional ?
}
public func property<T>(_ value: T, _ onApply: ((T) -> ())? = nil) -> CSProperty<T> {
CSProperty(value: value, onApply: onApply)
}
//func property<T>(_ key: T, _ default: String, _ onApply: ((T) -> Unit)? = nil) -> CSProperty<T> {
// application.store.property(key, default, onApply)
//}
//fun property(key: String, default: String, onApply: ((value: String) -> Unit)? = null) =
// application.store.property(key, default, onApply)
//
//fun property(key: String, default: Float, onApply: ((value: Float) -> Unit)? = null) =
// application.store.property(key, default, onApply)
//
//fun property(key: String, default: Int, onApply: ((value: Int) -> Unit)? = null) =
// application.store.property(key, default, onApply)
//
//fun property(
// key: String, default: Boolean,
// onApply: ((value: Boolean) -> Unit)? = null
//) = application.store.property(key, default, onApply)
//
//fun <T> property(
// key: String, values: List<T>, default: T,
// onApply: ((value: T) -> Unit)? = null
//) = application.store.property(key, values, default, onApply)
//
//fun <T> property(
// key: String, values: List<T>, defaultIndex: Int = 0,
// onApply: ((value: T) -> Unit)? = null
//) = application.store.property(key, values, values[defaultIndex], onApply)
| mit | 3a219c0d1e92fa03aecca3f17b37c62e | 27.460432 | 100 | 0.603134 | 3.760456 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Extensions/UIAlertControllerExtensions.swift | 2 | 8814 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
typealias UIAlertActionCallback = (UIAlertAction) -> Void
// MARK: - Extension methods for building specific UIAlertController instances used across the app
extension UIAlertController {
/**
Builds the Alert view that asks the user if they wish to opt into crash reporting.
- parameter sendReportCallback: Send report option handler
- parameter alwaysSendCallback: Always send option handler
- parameter dontSendCallback: Dont send option handler
- parameter neverSendCallback: Never send option handler
- returns: UIAlertController for opting into crash reporting after a crash occurred
*/
class func crashOptInAlert(
_ sendReportCallback: @escaping UIAlertActionCallback,
alwaysSendCallback: @escaping UIAlertActionCallback,
dontSendCallback: @escaping UIAlertActionCallback) -> UIAlertController {
let alert = UIAlertController(
title: NSLocalizedString("Oops! Cliqz crashed", comment: "Title for prompt displayed to user after the app crashes"),
message: NSLocalizedString("Send a crash report so Cliqz can fix the problem?", comment: "Message displayed in the crash dialog above the buttons used to select when sending reports"),
preferredStyle: UIAlertControllerStyle.alert
)
let sendReport = UIAlertAction(
title: NSLocalizedString("Send Report", comment: "Used as a button label for crash dialog prompt"),
style: UIAlertActionStyle.default,
handler: sendReportCallback
)
let alwaysSend = UIAlertAction(
title: NSLocalizedString("Always Send", comment: "Used as a button label for crash dialog prompt"),
style: UIAlertActionStyle.default,
handler: alwaysSendCallback
)
let dontSend = UIAlertAction(
title: NSLocalizedString("Don't Send", comment: "Used as a button label for crash dialog prompt"),
style: UIAlertActionStyle.default,
handler: dontSendCallback
)
alert.addAction(sendReport)
alert.addAction(alwaysSend)
alert.addAction(dontSend)
return alert
}
/**
Builds the Alert view that asks the user if they wish to restore their tabs after a crash.
- parameter okayCallback: Okay option handler
- parameter noCallback: No option handler
- returns: UIAlertController for asking the user to restore tabs after a crash
*/
class func restoreTabsAlert(_ okayCallback: @escaping UIAlertActionCallback, noCallback: @escaping UIAlertActionCallback) -> UIAlertController {
let alert = UIAlertController(
title: NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title"),
message: NSLocalizedString("Looks like Cliqz crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description"),
preferredStyle: UIAlertControllerStyle.alert
)
let noOption = UIAlertAction(
title: NSLocalizedString("No", comment: "Restore Tabs Negative Action"),
style: UIAlertActionStyle.cancel,
handler: noCallback
)
let okayOption = UIAlertAction(
title: NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action"),
style: UIAlertActionStyle.default,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
class func clearPrivateDataAlert(_ okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController {
let alert = UIAlertController(
title: "",
message: NSLocalizedString("This action will clear all of your private data. It cannot be undone.", tableName: "ClearPrivateDataConfirm", comment: "Description of the confirmation dialog shown when a user tries to clear their private data."),
preferredStyle: UIAlertControllerStyle.actionSheet
)
let noOption = UIAlertAction(
title: NSLocalizedString("Cancel", tableName: "ClearPrivateDataConfirm", comment: "The cancel button when confirming clear private data."),
style: UIAlertActionStyle.cancel) { (action) in
// Cliqz: log telemetry signal
let cancelSignal = TelemetryLogEventType.Settings("private_data", "click", "cancel", nil, nil)
TelemetryLogger.sharedInstance.logEvent(cancelSignal)
}
let okayOption = UIAlertAction(
title: Strings.SettingsClearPrivateDataTitle,
style: UIAlertActionStyle.destructive,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
/**
Builds the Alert view that asks if the users wants to also delete history stored on their other devices.
- parameter okayCallback: Okay option handler.
- returns: UIAlertController for asking the user to restore tabs after a crash
*/
class func clearSyncedHistoryAlert(_ okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController {
let alert = UIAlertController(
title: "",
message: NSLocalizedString("This action will clear all of your private data, including history from your synced devices.", tableName: "ClearHistoryConfirm", comment: "Description of the confirmation dialog shown when a user tries to clear history that's synced to another device."),
preferredStyle: UIAlertControllerStyle.alert
)
let noOption = UIAlertAction(
title: NSLocalizedString("Cancel", tableName: "ClearHistoryConfirm", comment: "The cancel button when confirming clear history."),
style: UIAlertActionStyle.cancel,
handler: nil
)
let okayOption = UIAlertAction(
title: NSLocalizedString("OK", tableName: "ClearHistoryConfirm", comment: "The confirmation button that clears history even when Sync is connected."),
style: UIAlertActionStyle.destructive,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
/**
Creates an alert view to warn the user that their logins will either be completely deleted in the
case of local-only logins or deleted across synced devices in synced account logins.
- parameter deleteCallback: Block to run when delete is tapped.
- parameter hasSyncedLogins: Boolean indicating the user has logins that have been synced.
- returns: UIAlertController instance
*/
class func deleteLoginAlertWithDeleteCallback(
_ deleteCallback: @escaping UIAlertActionCallback,
hasSyncedLogins: Bool) -> UIAlertController {
let areYouSureTitle = NSLocalizedString("Are you sure?",
tableName: "LoginManager",
comment: "Prompt title when deleting logins")
let deleteLocalMessage = NSLocalizedString("Logins will be permanently removed.",
tableName: "LoginManager",
comment: "Prompt message warning the user that deleting non-synced logins will permanently remove them")
let deleteSyncedDevicesMessage = NSLocalizedString("Logins will be removed from all connected devices.",
tableName: "LoginManager",
comment: "Prompt message warning the user that deleted logins will remove logins from all connected devices")
let cancelActionTitle = NSLocalizedString("Cancel",
tableName: "LoginManager",
comment: "Prompt option for cancelling out of deletion")
let deleteActionTitle = NSLocalizedString("Delete",
tableName: "LoginManager",
comment: "Label for the button used to delete the current login.")
let deleteAlert: UIAlertController
if hasSyncedLogins {
deleteAlert = UIAlertController(title: areYouSureTitle, message: deleteSyncedDevicesMessage, preferredStyle: .alert)
} else {
deleteAlert = UIAlertController(title: areYouSureTitle, message: deleteLocalMessage, preferredStyle: .alert)
}
let cancelAction = UIAlertAction(title: cancelActionTitle, style: .cancel, handler: nil)
let deleteAction = UIAlertAction(title: deleteActionTitle, style: .destructive, handler: deleteCallback)
deleteAlert.addAction(cancelAction)
deleteAlert.addAction(deleteAction)
return deleteAlert
}
}
| mpl-2.0 | 2c42e70d19e0816978ed76594eb1b06a | 44.668394 | 294 | 0.686408 | 5.798684 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.