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
IBM-Swift/Kitura-net
Sources/KituraNet/HTTP/HTTPServerResponse.swift
1
8867
/* * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation // MARK: HTTPServerResponse /** This class implements the `ServerResponse` protocol for outgoing server responses via the HTTP protocol. Data and Strings can be written. The example below uses this in its `response` parameter, with the example requesting a connection be upgraded and catch any errors that occur. ### Usage Example: ### ````swift func upgradeConnection(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) { guard let protocols = request.headers["Upgrade"] else { do { response.statusCode = HTTPStatusCode.badRequest try response.write(from: "No protocol specified in the Upgrade header") try response.end() } catch { Log.error("Failed to send error response to Upgrade request") } return } } ```` */ public class HTTPServerResponse : ServerResponse { /// Size of buffer private static let bufferSize = 2000 /// Buffer for HTTP response line, headers, and short bodies private var buffer: NSMutableData /// Whether or not the HTTP response line and headers have been flushed. private var startFlushed = false /** The HTTP headers to be sent to the client as part of the response. ### Usage Example: ### ````swift ServerResponse.headers["Content-Type"] = ["text/plain"] ```` */ public var headers = HeadersContainer() /// Status code private var status = HTTPStatusCode.OK.rawValue /// Corresponding socket processor private weak var processor : IncomingHTTPSocketProcessor? let request: HTTPServerRequest? /** HTTP status code of the response. ### Usage Example: ### ````swift ServerResponse.statusCode = HTTPStatusCode.badRequest ```` */ public var statusCode: HTTPStatusCode? { get { return HTTPStatusCode(rawValue: status) } set (newValue) { if let newValue = newValue, !startFlushed { status = newValue.rawValue } } } /// Initializes a HTTPServerResponse instance init(processor: IncomingHTTPSocketProcessor, request: HTTPServerRequest?) { self.processor = processor buffer = NSMutableData(capacity: HTTPServerResponse.bufferSize) ?? NSMutableData() headers["Date"] = [SPIUtils.httpDate()] self.request = request } /** Write a string as a response. - Parameter from: String data to be written. - Throws: Socket.error if an error occurred while writing to a socket. ### Usage Example: ### ````swift try ServerResponse.write(from: "Some string") ```` */ public func write(from string: String) throws { try flushStart() try writeToSocketThroughBuffer(text: string) } /** Write data as a response. - Parameter from: Data object that contains the data to be written. - Throws: Socket.error if an error occurred while writing to a socket. ### Usage Example: ### ````swift try ServerResponse.write(from: someData) ```` */ public func write(from data: Data) throws { if let processor = processor { try flushStart() if buffer.length + data.count > HTTPServerResponse.bufferSize && buffer.length != 0 { processor.write(from: buffer) buffer.length = 0 } if data.count > HTTPServerResponse.bufferSize { let dataToWrite = NSData(data: data) processor.write(from: dataToWrite) } else { buffer.append(data) } } } /** Write a String to the body of a HTTP response and complete sending the HTTP response. - Parameter text: String to write to a socket. - Throws: Socket.error if an error occurred while writing to a socket. ### Usage Example: ### ````swift try ServerResponse.end("Some string") ```` */ public func end(text: String) throws { try write(from: text) try end() } /** Complete sending the HTTP response. - Throws: Socket.error if an error occurred while writing to a socket. ### Usage Example: ### ````swift try ServerResponse.end() ```` */ public func end() throws { if let processor = processor { try flushStart() if buffer.length > 0 { processor.write(from: buffer) } let keepAlive = processor.isKeepAlive if !keepAlive && !processor.isUpgrade { processor.close() } if let request = request { Monitor.delegate?.finished(request: request, response: self) } // Ordering is important here. Keepalive allows the processor to continue // processing further requests, so must only be called once monitoring // has completed, as the HTTPParser for this connection is reused. if keepAlive { processor.keepAlive() } } } /// Begin flushing the buffer /// /// - Throws: Socket.error if an error occurred while writing to a socket private func flushStart() throws { if startFlushed { return } var headerData = "" headerData.reserveCapacity(254) headerData.append("HTTP/1.1 ") headerData.append(String(status)) headerData.append(" ") var statusText = HTTP.statusCodes[status] if statusText == nil { statusText = "" } headerData.append(statusText!) headerData.append("\r\n") for (_, entry) in headers.headers { for value in entry.value { headerData.append(entry.key) headerData.append(": ") headerData.append(value) headerData.append("\r\n") } } let upgrade = processor?.isUpgrade ?? false let keepAlive = processor?.isKeepAlive ?? false if !upgrade { if keepAlive { headerData.append("Connection: Keep-Alive\r\n") headerData.append("Keep-Alive: timeout=\(Int(IncomingHTTPSocketProcessor.keepAliveTimeout))") if let numberOfRequests = processor?.keepAliveState.requestsRemaining { headerData.append(", max=\(numberOfRequests)") } headerData.append("\r\n") } else { headerData.append("Connection: Close\r\n") } } headerData.append("\r\n") try writeToSocketThroughBuffer(text: headerData) startFlushed = true } /// Function to write Strings to the socket through the buffer /// /// Throws: Socket.error if an error occurred while writing to a socket private func writeToSocketThroughBuffer(text: String) throws { guard let processor = processor else { return } let utf8Length = text.utf8.count var utf8: [CChar] = Array<CChar>(repeating: 0, count: utf8Length + 10) // A little bit of padding guard text.getCString(&utf8, maxLength: utf8Length + 10, encoding: .utf8) else { return } if buffer.length + utf8.count > HTTPServerResponse.bufferSize && buffer.length != 0 { processor.write(from: buffer) buffer.length = 0 } if utf8.count > HTTPServerResponse.bufferSize { processor.write(from: utf8, length: utf8Length) } else { buffer.append(UnsafePointer(utf8), length: utf8Length) } } /** Reset this response object back to its initial state. ### Usage Example: ### ````swift try ServerResponse.reset() ```` */ public func reset() { status = HTTPStatusCode.OK.rawValue buffer.length = 0 startFlushed = false headers.removeAll() headers["Date"] = [SPIUtils.httpDate()] } }
apache-2.0
77b18ba3edf25671bcbf6c5ff3bb6a7c
30.003497
142
0.591519
4.931591
false
false
false
false
hooman/swift
test/SILOptimizer/specialize_unconditional_checked_cast.swift
4
16464
// RUN: %target-swift-frontend -module-name specialize_unconditional_checked_cast -Xllvm -sil-disable-pass=FunctionSignatureOpts -emit-sil -o - -O %s | %FileCheck %s ////////////////// // Declarations // ////////////////// public class C {} public class D : C {} public class E {} public struct NotUInt8 { var value: UInt8 } public struct NotUInt64 { var value: UInt64 } var b = NotUInt8(value: 0) var c = C() var d = D() var e = E() var f = NotUInt64(value: 0) var o : AnyObject = c //////////////////////////// // Archetype To Archetype // //////////////////////////// @inline(never) public func ArchetypeToArchetype<T1, T2>(t t: T1, t2: T2) -> T2 { return t as! T2 } ArchetypeToArchetype(t: b, t2: b) ArchetypeToArchetype(t: c, t2: c) ArchetypeToArchetype(t: b, t2: c) ArchetypeToArchetype(t: c, t2: b) ArchetypeToArchetype(t: c, t2: d) ArchetypeToArchetype(t: d, t2: c) ArchetypeToArchetype(t: c, t2: e) ArchetypeToArchetype(t: b, t2: f) // x -> x where x is not a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt8) -> NotUInt8 { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC{{.*}}Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x is not a class but y is. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_AA1CCTg5 : $@convention(thin) (NotUInt8, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast_addr // CHECK-NOT: unconditional_checked_cast_addr // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast_addr // y -> x where x is not a class but y is. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA8NotUInt8VTg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8 { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x is a super class of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA1DCTg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D { // CHECK: [[STACK:%[0-9]+]] = alloc_stack $C // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK: unconditional_checked_cast_addr C in [[STACK]] : $*C to D in // y -> x where x is a super class of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1DC_AA1CCTg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: upcast {{%[0-9]+}} : $D to $C // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x and y are unrelated classes. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA1CC_AA1ECTg5 : $@convention(thin) (@guaranteed C, @guaranteed E) -> @owned E { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // x -> y where x and y are unrelated non classes. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast011ArchetypeToE0{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_AA0H6UInt64VTg5 : $@convention(thin) (NotUInt8, NotUInt64) -> NotUInt64 { // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK-NOT: unconditional_checked_cast archetype_to_archetype // CHECK: builtin "int_trap" // CHECK-NOT: unconditional_checked_cast archetype_to_archetype /////////////////////////// // Archetype To Concrete // /////////////////////////// @inline(never) public func ArchetypeToConcreteConvertUInt8<T>(t t: T) -> NotUInt8 { return t as! NotUInt8 } ArchetypeToConcreteConvertUInt8(t: b) ArchetypeToConcreteConvertUInt8(t: c) ArchetypeToConcreteConvertUInt8(t: f) // x -> x where x is not a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 : $@convention(thin) (NotUInt8) -> NotUInt8 { // CHECK: bb0 // CHECK-NEXT: debug_value %0 // CHECK-NEXT: return %0 // x -> y where y is a class but x is not. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x,y are not classes and x is a different type from y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed C) -> @owned C { // CHECK: bb0([[ARG:%.*]] : $C) // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: strong_retain [[ARG]] // CHECK-NEXT: return [[ARG]] // x -> y where x is a class but y is not. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x,y are classes and x is a super class of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@guaranteed D) -> @owned C { // CHECK: bb0([[ARG:%.*]] : $D): // CHECK: [[UPCAST:%.*]] = upcast [[ARG]] : $D to $C // CHECK: strong_retain [[ARG]] // CHECK: return [[UPCAST]] // CHECK: } // end sil function '$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5' // x -> y where x,y are classes, but x is unrelated to y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{[_0-9a-zA-Z]*}}FAA1EC_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } @inline(never) public func ArchetypeToConcreteConvertC<T>(t t: T) -> C { return t as! C } ArchetypeToConcreteConvertC(t: c) ArchetypeToConcreteConvertC(t: b) ArchetypeToConcreteConvertC(t: d) ArchetypeToConcreteConvertC(t: e) @inline(never) public func ArchetypeToConcreteConvertD<T>(t t: T) -> D { return t as! D } ArchetypeToConcreteConvertD(t: c) // x -> y where x,y are classes and x is a sub class of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed C) -> @owned D { // CHECK: bb0(%0 : $C): // CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C // CHECK-DAG: store {{.*}} to [[STACK_C]] // CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK-DAG: unconditional_checked_cast_addr C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D // CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]] // CHECK: return [[LOAD]] @inline(never) public func ArchetypeToConcreteConvertE<T>(t t: T) -> E { return t as! E } ArchetypeToConcreteConvertE(t: c) // x -> y where x,y are classes, but y is unrelated to x. The idea is // to make sure that the fact that y is concrete does not affect the // result. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertE{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } /////////////////////////// // Concrete to Archetype // /////////////////////////// @inline(never) public func ConcreteToArchetypeConvertUInt8<T>(t t: NotUInt8, t2: T) -> T { return t as! T } ConcreteToArchetypeConvertUInt8(t: b, t2: b) ConcreteToArchetypeConvertUInt8(t: b, t2: c) ConcreteToArchetypeConvertUInt8(t: b, t2: f) // x -> x where x is not a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}3Not{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt8) -> NotUInt8 { // CHECK: bb0(%0 : $NotUInt8, %1 : $NotUInt8): // CHECK: debug_value %0 // CHECK: return %0 // x -> y where x is not a class but y is a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (NotUInt8, @guaranteed C) -> @owned C { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x,y are different non class types. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{[_0-9a-zA-Z]*}}Not{{.*}}Tg5 : $@convention(thin) (NotUInt8, NotUInt64) -> NotUInt64 { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } @inline(never) public func ConcreteToArchetypeConvertC<T>(t t: C, t2: T) -> T { return t as! T } ConcreteToArchetypeConvertC(t: c, t2: c) ConcreteToArchetypeConvertC(t: c, t2: b) ConcreteToArchetypeConvertC(t: c, t2: d) ConcreteToArchetypeConvertC(t: c, t2: e) // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C { // CHECK: bb0(%0 : $C, %1 : $C): // CHECK: return %0 // x -> y where x is a class but y is not. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}Not{{.*}}Tg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8 { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } // x -> y where x is a super class of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D { // CHECK: bb0(%0 : $C, %1 : $D): // CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C // CHECK-DAG: store %0 to [[STACK_C]] // CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK-DAG: unconditional_checked_cast_addr C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D // CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]] // CHECK: return [[LOAD]] // x -> y where x and y are unrelated classes. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{[_0-9a-zA-Z]*}}FAA1EC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed E) -> @owned E { // CHECK: bb0(%0 : $C, %1 : $E): // CHECK: builtin "int_trap" // CHECK-NEXT: unreachable // CHECK-NEXT: } @inline(never) public func ConcreteToArchetypeConvertD<T>(t t: D, t2: T) -> T { return t as! T } ConcreteToArchetypeConvertD(t: d, t2: c) // x -> y where x is a subclass of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C { // CHECK: bb0(%0 : $D, %1 : $C): // CHECK-DAG: [[UC:%[0-9]+]] = upcast %0 // CHECK: return [[UC]] //////////////////////// // Super To Archetype // //////////////////////// @inline(never) public func SuperToArchetypeC<T>(c c : C, t : T) -> T { return c as! T } SuperToArchetypeC(c: c, t: c) SuperToArchetypeC(c: c, t: d) SuperToArchetypeC(c: c, t: b) // x -> x where x is a class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed C, @guaranteed C) -> @owned C { // CHECK: bb0(%0 : $C, %1 : $C): // CHECK: return %0 // x -> y where x is a super class of y. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}FAA1DC_Tg5 : $@convention(thin) (@guaranteed C, @guaranteed D) -> @owned D { // CHECK: bb0 // CHECK: unconditional_checked_cast_addr C in // x -> y where x is a class and y is not. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast17SuperToArchetypeC{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 : $@convention(thin) (@guaranteed C, NotUInt8) -> NotUInt8 { // CHECK: bb0 // CHECK: builtin "int_trap" // CHECK: unreachable // CHECK-NEXT: } @inline(never) public func SuperToArchetypeD<T>(d d : D, t : T) -> T { return d as! T } SuperToArchetypeD(d: d, t: c) SuperToArchetypeD(d: d, t: d) // *NOTE* The frontend is smart enough to turn this into an upcast. When this // test is converted to SIL, this should be fixed appropriately. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast17SuperToArchetypeD{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed D, @guaranteed C) -> @owned C { // CHECK-NOT: unconditional_checked_cast super_to_archetype // CHECK: upcast // CHECK-NOT: unconditional_checked_cast super_to_archetype // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast17SuperToArchetypeD{{[_0-9a-zA-Z]*}}Tg5 : $@convention(thin) (@guaranteed D, @guaranteed D) -> @owned D { // CHECK: bb0(%0 : $D, %1 : $D): // CHECK: return %0 ////////////////////////////// // Existential To Archetype // ////////////////////////////// @inline(never) public func ExistentialToArchetype<T>(o o : AnyObject, t : T) -> T { return o as! T } // AnyObject -> Class. // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}FAA1CC_Tg5 : $@convention(thin) (@guaranteed AnyObject, @guaranteed C) -> @owned C { // CHECK: unconditional_checked_cast_addr AnyObject in {{%.*}} : $*AnyObject to C // AnyObject -> Non Class (should always fail) // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}FAA8NotUInt8V_Tg5 : $@convention(thin) (@guaranteed AnyObject, NotUInt8) -> NotUInt8 { // CHECK-NOT: builtin "int_trap"() // CHECK-NOT: unreachable // CHECK: return // AnyObject -> AnyObject // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast22ExistentialToArchetype{{[_0-9a-zA-Z]*}}yXl{{.*}}Tg5 : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject) -> @owned AnyObject { // CHECK: bb0(%0 : $AnyObject, %1 : $AnyObject): // CHECK: return %0 ExistentialToArchetype(o: o, t: c) ExistentialToArchetype(o: o, t: b) ExistentialToArchetype(o: o, t: o) // Ensure that a downcast from an Optional source is not promoted to a // value cast. We could do the promotion, but the optimizer would need // to insert the Optional unwrapping logic before the cast. // // CHECK-LABEL: sil shared [noinline] @$s37specialize_unconditional_checked_cast15genericDownCastyq_x_q_mtr0_lFAA1CCSg_AA1DCTg5 : $@convention(thin) (@guaranteed Optional<C>, @thick D.Type) -> @owned D { // CHECK: bb0(%0 : $Optional<C>, %1 : $@thick D.Type): // CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D // CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $Optional<C> // CHECK-DAG: store [[ARG]] to [[STACK_C]] // CHECK-DAG: retain_value [[ARG]] // TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038 // CHECK-DAG: unconditional_checked_cast_addr Optional<C> in [[STACK_C]] : $*Optional<C> to D in [[STACK_D]] : $*D // CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]] // CHECK: return [[LOAD]] @inline(never) public func genericDownCast<T, U>(_ a: T, _ : U.Type) -> U { return a as! U } public func callGenericDownCast(_ c: C?) -> D { return genericDownCast(c, D.self) }
apache-2.0
7f039e29b25629a9591ab7bf52c02089
42.212598
223
0.681608
3.244777
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/Controller/About/AboutViewController.swift
1
3396
// // AboutViewController.swift // WISData.JunZheng // // Created by Allen on 16/8/31. // Copyright © 2016 Wisdri. All rights reserved. // import UIKit import Ruler class AboutViewController: UIViewController { @IBOutlet private weak var appLogoImageView: UIImageView! @IBOutlet private weak var appLogoImageViewTopConstraint: NSLayoutConstraint! @IBOutlet private weak var appNameLabel: UILabel! @IBOutlet private weak var appNameLabelTopConstraint: NSLayoutConstraint! @IBOutlet private weak var appVersionLabel: UILabel! @IBOutlet weak var aboutTextView: UITextView! @IBOutlet weak var aboutTextViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var aboutTextViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var aboutTextViewWidthConstraint: NSLayoutConstraint! @IBOutlet private weak var copyrightLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() title = "关于" setSubViewConstraints() appNameLabel.textColor = UIColor.wisLogoColor() let infoDictionary = NSBundle.mainBundle().infoDictionary let versionShortString = infoDictionary!["CFBundleShortVersionString"] as! String let buildString = infoDictionary!["CFBundleVersion"] as! String var app_version = "Version: " + versionShortString + " (Build: " + buildString + ")" #if DEBUG app_version += " - " + "Debug" #endif self.appVersionLabel.text = app_version } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .All } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition({ _ in self.setSubViewConstraints() }, completion: nil) } private func setSubViewConstraints() { if self.traitCollection.verticalSizeClass == .Regular { appLogoImageViewTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 70).value appNameLabelTopConstraint.constant = Ruler.iPhoneVertical(20, 30, 30, 30).value aboutTextViewTopConstraint.constant = Ruler.iPhoneVertical(40, 40, 50, 70).value } else { appLogoImageViewTopConstraint.constant = Ruler.iPhoneVertical(10, 20, 40, 40).value appNameLabelTopConstraint.constant = Ruler.iPhoneVertical(5, 15, 15, 15).value aboutTextViewTopConstraint.constant = Ruler.iPhoneVertical(10, 15, 15, 25).value } if currentDevice.isPad { aboutTextView.font = UIFont.systemFontOfSize(18.0) aboutTextViewWidthConstraint.constant = Ruler.iPad(600, 600).value } else { if self.traitCollection.verticalSizeClass == .Regular { aboutTextViewWidthConstraint.constant = Ruler.iPhoneHorizontal(270, 290, 310).value aboutTextViewHeightConstraint.constant = Ruler.iPhoneVertical(190, 190, 180, 180).value } else { aboutTextViewWidthConstraint.constant = Ruler.iPhoneHorizontal(520, 560, 600).value aboutTextViewHeightConstraint.constant = Ruler.iPhoneVertical(80, 80, 70, 70).value } } } }
mit
a6e1208ad540c3225335aed99a012e48
37.534091
136
0.674432
5.531811
false
false
false
false
cosmo1234/MobilePassport-Express-Swift
MobilePassport-Express/ViewController.swift
1
1814
// // ViewController.swift // MobilePassport-Express // // Created by Sagaya Abdulhafeez on 21/08/2016. // Copyright © 2016 sagaya Abdulhafeez. All rights reserved. // import UIKit import SwiftyGif class ViewController: UIViewController { @IBOutlet weak var gifImageView: UIImageView! @IBOutlet weak var loginButt: UIButton! @IBOutlet weak var password: UITextField! @IBOutlet weak var username: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let gifmanager = SwiftyGifManager(memoryLimit:20) let gif = UIImage(gifName: "railway") self.gifImageView.setGifImage(gif) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func segue(){ self.performSegueWithIdentifier("LOGGED", sender: self) } @IBAction func login(sender: AnyObject) { if let username = username.text where username != "", let password = password.text where password != ""{ // Dataservice.ds.callSH(username, password: password, f: segue()) segue() }else{ let alertView = UIAlertController(title: "UWOTM8", message: "Fam, what you tryna pull?", preferredStyle: .Alert) let OK = UIAlertAction(title: "Is it 2 l8 2 say sorry", style: .Default, handler: nil) alertView.addAction(OK) self.presentViewController(alertView, animated: true, completion: nil); } } }
mit
42849003f5ad82c187b98b46703e24a7
28.721311
124
0.632653
4.809019
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/mix_any_object/main.swift
2
847
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- import Foundation class MyClass : NSObject { var text: String init(_ text: String) { self.text = text } } func main() { var cls: MyClass = MyClass("Instance of MyClass") var any: AnyObject = cls var opt: AnyObject? = cls var dict: [String: AnyObject] = ["One" : MyClass("Instance One"), "Two" : MyClass("Instance Two"), "Three" : cls] print(cls) // break here } main()
apache-2.0
c3da370f73960c8e66707eb16967a458
27.233333
115
0.618654
4.033333
false
false
false
false
mozilla-mobile/firefox-ios
Tests/ClientTests/Mocks/MockTelemetryWrapper.swift
2
950
// 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/ @testable import Client class MockTelemetryWrapper: TelemetryWrapperProtocol { var recordEventCallCount = 0 var recordedCategories = [TelemetryWrapper.EventCategory]() var recordedMethods = [TelemetryWrapper.EventMethod]() var recordedObjects = [TelemetryWrapper.EventObject]() func recordEvent(category: TelemetryWrapper.EventCategory, method: TelemetryWrapper.EventMethod, object: TelemetryWrapper.EventObject, value: TelemetryWrapper.EventValue?, extras: [String: Any]?) { recordEventCallCount += 1 recordedCategories.append(category) recordedMethods.append(method) recordedObjects.append(object) } }
mpl-2.0
fa9b748931510610b14ba6da0a7b0bc5
37
70
0.683158
5.163043
false
false
false
false
morizotter/MZRViewOnUITextViewSample
MZRViewOnTextViewSample/ViewController.swift
1
2519
// // ViewController.swift // MZRViewOnTextViewSample // // Created by MORITA NAOKI on 2014/10/28. // Copyright (c) 2014年 molabo. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() self.textView.textContainerInset = UIEdgeInsetsMake(100.0, 0.0, 0.0, 0.0) let view = UIView(frame: CGRectMake(0.0, 0.0, CGRectGetWidth(self.textView.frame), 100.0)) view.backgroundColor = UIColor.greenColor() self.textView.addSubview(view) let button = UIButton.buttonWithType(.Custom) as UIButton button.frame = CGRectMake(10.0, 10.0, 100.0, 44.0) button.backgroundColor = UIColor.grayColor() button.setTitle("Push Me!", forState: .Normal) button.addTarget(self, action: "push:", forControlEvents: .TouchUpInside) view.addSubview(button) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let notifications = [UIKeyboardWillShowNotification, UIKeyboardWillChangeFrameNotification, UIKeyboardWillHideNotification]; for notification in notifications { NSNotificationCenter.defaultCenter().addObserver(self, selector: "fitKeyboard:", name: notification, object: nil) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func fitKeyboard(notification: NSNotification) { let userInfo = notification.userInfo let duration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue let curve = (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as NSNumber).unsignedIntegerValue let keyboardFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue() let keyboardHeight = CGRectGetHeight(self.view.frame) - CGRectGetMinY(keyboardFrame) self.textViewBottomConstraint.constant = keyboardHeight let options = UIViewAnimationOptions(UInt(curve)) UIView.animateWithDuration(duration, delay: 0.0, options: options, animations: { () -> Void in self.view.layoutIfNeeded() }, completion: nil) } func push(sender: UIButton) { println("button pushed!") } }
mit
4afe7f8a33258b02371213e721621ce7
38.328125
132
0.688915
5.157787
false
false
false
false
minaatefmaf/Meme-Me
Meme Me/CoreDataTableViewController.swift
1
3859
// // CoreDataTableViewController.swift // Meme Me // // Created by Mina Atef on 3/29/17. // Copyright © 2017 minaatefmaf. All rights reserved. // import UIKit import CoreData class CoreDataTableViewController: UITableViewController { var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>? { didSet { // Whenever the fetchedResultsController changes, we execute the search and reload the table fetchedResultsController?.delegate = self executeSearch() tableView.reloadData() } } // MARK: Initializers init(fetchedResultsController fetchController: NSFetchedResultsController<NSFetchRequestResult>, style: UITableViewStyle = .plain) { fetchedResultsController = fetchController super.init(style: style) } // This initializer has to be implemented because of the way Swift interfaces with the Objective C protocol NSArchiving. required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: - CoreDataTableViewController Method that Subclass Must Implement extension CoreDataTableViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { fatalError("This method MUST be implemented by a subclass of CoreDataTableViewController") } } // MARK: - Table Data Source Methods extension CoreDataTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let fetchedResultsController = fetchedResultsController { return fetchedResultsController.sections![section].numberOfObjects } else { return 0 } } } // MARK: - Fetches extension CoreDataTableViewController { func executeSearch() { if let fetchedResultsController = fetchedResultsController { do { try fetchedResultsController.performFetch() } catch let e as NSError { print("Error while trying to perform a search: \n\(e)\n\(fetchedResultsController)") } } } } // MARK: - NSFetchedResultsControllerDelegate Methods extension CoreDataTableViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { let set = IndexSet(integer: sectionIndex) switch (type) { case .insert: tableView.insertSections(set, with: .fade) case .delete: tableView.deleteSections(set, with: .fade) default: // irrelevant in our case break } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch(type) { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: tableView.reloadRows(at: [indexPath!], with: .fade) case .move: tableView.deleteRows(at: [indexPath!], with: .fade) tableView.insertRows(at: [newIndexPath!], with: .fade) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } }
mit
66449dfaec847cdc2cd56f00ec1fbca8
32.258621
209
0.670295
5.872146
false
false
false
false
jisudong/study
RxSwift-master/Rx.playground/Pages/Playground.xcplaygroundpage/Contents.swift
1
20881
/*: > # IMPORTANT: To use **Rx.playground**: 1. Open **Rx.xcworkspace**. 1. Build the **RxSwift-macOS** scheme (**Product** → **Build**). 1. Open **Rx** playground in the **Project navigator**. 1. Show the Debug Area (**View** → **Debug Area** → **Show Debug Area**). */ import RxSwift /*: # Try Yourself It's time to play with Rx 🎉 */ playgroundShouldContinueIndefinitely() example("Try yourself") { // let disposeBag = DisposeBag() _ = Observable.just("Hello, RxSwift!") .debug("Observable") .subscribe() // .disposed(by: disposeBag) // If dispose bag is used instead, sequence will terminate on scope exit } // MARK: Creating and Subscribing to Observables example("never") { let disposeBag = DisposeBag() Observable<String>.never() .subscribe { _ in print("this will never be printed") } .disposed(by: disposeBag) } example("empty") { let disposeBag = DisposeBag() Observable<Int>.empty() .subscribe { event in print(event) } .disposed(by: disposeBag) } example("just") { let disposeBag = DisposeBag() Observable.just("🔴") .subscribe({ (event) in print(event) }) .disposed(by: disposeBag) } example("of") { let disposeBag = DisposeBag() Observable.of("🐶", "🐱", "🐭", "🐹") .subscribe(onNext: { element in print(element) }) .disposed(by: disposeBag) } example("from") { let disposeBag = DisposeBag() Observable.from(["🐶", "🐱", "🐭", "🐹"]) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("create") { let disposeBag = DisposeBag() let myJust = { (element: String) -> Observable<String> in return Observable.create { observer in observer.on(.next(element)) observer.on(.completed) return Disposables.create() } } myJust("🔴") .subscribe({ print($0) }) .disposed(by: disposeBag) } example("range") { let disposeBag = DisposeBag() Observable.range(start: 1, count: 10) .subscribe { print($0) } .disposed(by: disposeBag) } example("repeatElement") { let disposeBag = DisposeBag() Observable.repeatElement("🔴") .take(3) .subscribe { print($0) } .disposed(by: disposeBag) } example("generate") { let disposeBag = DisposeBag() Observable.generate( initialState: 0, condition: { $0 < 3 }, iterate: { $0 + 1 } ) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("deferred") { let disposeBag = DisposeBag() var count = 1 let deferredSequence = Observable<String>.deferred { print("creating \(count)") count += 1 return Observable.create { observer in observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐵") return Disposables.create() } } deferredSequence .subscribe { print($0) } .disposed(by: disposeBag) deferredSequence .subscribe { print($0) } .disposed(by: disposeBag) } example("error") { let disposeBag = DisposeBag() Observable<Int>.error(TestError.test) .subscribe { print($0) } .disposed(by: disposeBag) } example("doOn") { let disposeBag = DisposeBag() Observable.of("🍎", "🍐", "🍊", "🍋") .do( onNext: { print("Intercepted", $0) }, onError: { print("Intercepted error", $0) }, onCompleted: { print("Completed") } ) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } // MARK: Working with Subject extension ObservableType { func addObserver(_ id: String) -> Disposable { return subscribe { print("Subscription;", id, "Event:", $0) } } } example("PublishSubject") { let disposeBag = DisposeBag() let subject = PublishSubject<String>() subject.addObserver("1").disposed(by: disposeBag) subject.onNext("🐶") subject.onNext("🐱") subject.addObserver("2").disposed(by: disposeBag) subject.onNext("🅰️") subject.onNext("🅱️") } example("ReplaySubject") { let disposeBag = DisposeBag() let subject = ReplaySubject<String>.create(bufferSize: 1) subject.addObserver("1").disposed(by: disposeBag) subject.onNext("🐶") subject.onNext("🐱") subject.addObserver("2").disposed(by: disposeBag) subject.onNext("🅰️") subject.onNext("🅱️") } example("BehaviorSubject") { let disposeBag = DisposeBag() let subject = BehaviorSubject(value: "🔴"); subject.addObserver("1").disposed(by: disposeBag) subject.onNext("🐶") subject.onNext("🐱") subject.addObserver("2").disposed(by: disposeBag) subject.onNext("🅰️") subject.onNext("🅱️") subject.addObserver("3").disposed(by: disposeBag) subject.onNext("🍐") subject.onNext("🍊") } example("Variable") { let disposeBag = DisposeBag() let variable = Variable("🔴") variable.asObservable().addObserver("1").disposed(by: disposeBag) variable.value = "🐶" variable.value = "🐱" variable.asObservable().addObserver("2").disposed(by: disposeBag) variable.value = "🅰️" variable.value = "🅱️" } // MARK: Combination Operators example("startWith") { let disposeBag = DisposeBag() Observable.of("🐶", "🐱", "🐭", "🐹") .startWith("1️⃣") .startWith("2️⃣") .startWith("3️⃣", "🅰️", "🅱️") .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("merge") { let disposeBag = DisposeBag() let subject1 = PublishSubject<String>() let subject2 = PublishSubject<String>() Observable.of(subject1, subject2) .merge() .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) subject1.onNext("🅰️") subject1.onNext("🅱️") subject2.onNext("①") subject2.onNext("②") subject1.onNext("🆎") subject2.onNext("③") } example("zip") { let disposeBag = DisposeBag() let stringSubject = PublishSubject<String>() let intSubject = PublishSubject<Int>() Observable.zip(stringSubject, intSubject) { stringElement, intElement in "\(stringElement) \(intElement)" } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) stringSubject.onNext("🅰️") stringSubject.onNext("🅱️") intSubject.onNext(1) intSubject.onNext(2) stringSubject.onNext("🆎") intSubject.onNext(3) } example("combineLatest") { let disposeBag = DisposeBag() let stringSubject = PublishSubject<String>() let intSubject = PublishSubject<Int>() Observable.combineLatest(stringSubject, intSubject) { stringElement, intElement in "\(stringElement) \(intElement)" } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) stringSubject.onNext("🅰️") stringSubject.onNext("🅱️") intSubject.onNext(1) intSubject.onNext(2) stringSubject.onNext("🆎") } example("Array.combineLatest") { let disposeBag = DisposeBag() let stringObservable = Observable.just("🔴") let fruitObservable = Observable.from(["🍎", "🍐", "🍊"]) let animalObservable = Observable.of("🐶", "🐱", "🐭", "🐹") Observable.combineLatest([stringObservable, fruitObservable, animalObservable]) { "\($0[0]) \($0[1]) \($0[2])" } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("switchLatest") { let disposeBag = DisposeBag() let subject1 = BehaviorSubject(value: "⚽️") let subject2 = BehaviorSubject(value: "🍎") let variable = Variable(subject1) variable.asObservable() .switchLatest() .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) subject1.onNext("🏈") subject1.onNext("🏀") variable.value = subject2 subject1.onNext("⚾️") subject2.onNext("🍐") } // MARK: Transforming Operators example("map") { let disposeBag = DisposeBag() Observable.of(1, 2, 3) .map { $0 * $0 } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("flatMap and flatMapLatest") { let disposeBag = DisposeBag() struct Player { var score: Variable<Int> } let 👦🏻 = Player(score: Variable(80)) let 👧🏼 = Player(score: Variable(90)) let ren = Player(score: Variable(91)) let player = Variable(👦🏻) player.asObservable() .flatMap { $0.score.asObservable() } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) 👦🏻.score.value = 85 player.value = 👧🏼 👦🏻.score.value = 95 👧🏼.score.value = 100 player.value = ren 👦🏻.score.value = 92 👧🏼.score.value = 93 ren.score.value = 94 } // MARK: Filtering and Conditional Operators example("filter") { let disposeBag = DisposeBag() Observable.of( "🐱", "🐰", "🐶", "🐸", "🐱", "🐰", "🐹", "🐸", "🐱") .filter { $0 == "🐱" } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("distinctUntilChanged") { let disposeBag = DisposeBag() Observable.of("🐱", "🐷", "🐱", "🐱", "🐱", "🐵", "🐱") .distinctUntilChanged() .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("elementAt") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .elementAt(3) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("single") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .single() .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("single with conditions") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .single { $0 == "🐸" } .subscribe { print($0) } .disposed(by: disposeBag) Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .single { $0 == "🐰" } .subscribe { print($0) } .disposed(by: disposeBag) Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .single { $0 == "🔵" } .subscribe { print($0) } .disposed(by: disposeBag) } example("take") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .take(3) .subscribe { print($0) } .disposed(by: disposeBag) } example("takeLast") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .takeLast(3) .subscribe { print($0) } .disposed(by: disposeBag) } example("takeWhile") { let disposeBag = DisposeBag() Observable.of(1, 2, 3, 4, 5, 6) .takeWhile { $0 < 4 } .subscribe { print($0) } .disposed(by: disposeBag) } example("takeUntil") { let disposeBag = DisposeBag() let sourceSequence = PublishSubject<String>() let referenceSequence = PublishSubject<String>() sourceSequence .takeUntil(referenceSequence) .subscribe { print($0) } .disposed(by: disposeBag) sourceSequence.onNext("🐱") sourceSequence.onNext("🐰") sourceSequence.onNext("🐶") referenceSequence.onNext("🔴") sourceSequence.onNext("🐸") sourceSequence.onNext("🐷") sourceSequence.onNext("🐵") } example("skip") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .skip(2) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("skipWhile") { let disposeBag = DisposeBag() Observable.of(1, 2, 3, 4, 5, 6) .skipWhile { $0 < 4 } .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("skipWhileWithIndex") { let disposeBag = DisposeBag() Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵") .skipWhileWithIndex({ (element, index) in index < 3 }) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("skipUntil") { let disposeBag = DisposeBag() let sourceSequence = PublishSubject<String>() let referenceSequence = PublishSubject<String>() sourceSequence .skipUntil(referenceSequence) .subscribe(onNext: { print($0)}) .disposed(by: disposeBag) sourceSequence.onNext("🐱") sourceSequence.onNext("🐱") sourceSequence.onNext("🐶") referenceSequence.onNext("🔴") sourceSequence.onNext("🐸") sourceSequence.onNext("🐷") sourceSequence.onNext("🐵") } // MARK: Mathematical and Aggregate Operators example("toArray") { let disposeBag = DisposeBag() Observable.range(start: 1, count: 10) .toArray() .subscribe { print($0) } .disposed(by: disposeBag) } example("reduce") { let disposeBag = DisposeBag() Observable.of(10, 100, 1000) .reduce(1, accumulator: +) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("concat") { let disposeBag = DisposeBag() let subject1 = BehaviorSubject(value: "🍎") let subject2 = BehaviorSubject(value: "🐶") let variable = Variable(subject1) variable.asObservable() .concat() .subscribe { print($0) } .disposed(by: disposeBag) subject1.onNext("🍐") subject1.onNext("🍊") variable.value = subject2 subject2.onNext("I would be ignored") subject2.onNext("🐱") subject1.onCompleted() subject2.onNext("🐭") } // MARK: Connectable Operators func sampleWithoutConnectableOperators() { printExampleHeader(#function) let interval = Observable<Int>.interval(1, scheduler: MainScheduler.instance) _ = interval .subscribe(onNext: { print("Subscription: 1, Event: \($0)") }) delay(5) { _ = interval .subscribe(onNext: { print("Subscription: 2, Event: \($0)") }) } } //sampleWithoutConnectableOperators() func sampleWithPublish() { printExampleHeader(#function) let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .publish() _ = intSequence .subscribe(onNext: { print("Subscription 1:, Event: \($0)") }) delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence .subscribe(onNext: { print("Subscription 2:, Event: \($0)") }) } delay(6) { _ = intSequence .subscribe(onNext: { print("Subscription 3:, Event: \($0)") }) } } //sampleWithPublish() func sampleWithReplayBuffer() { printExampleHeader(#function) let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .replay(3) _ = intSequence .subscribe(onNext: { print("Subscription 1:, Event: \($0)") }) delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence .subscribe(onNext: { print("Subscription 2:, Event: \($0)") }) } delay(8) { _ = intSequence .subscribe(onNext: { print("Subscription 3:, Event: \($0)") }) } } //sampleWithReplayBuffer() func sampleWithMulticast() { printExampleHeader(#function) let subject = PublishSubject<Int>() _ = subject .subscribe(onNext: { print("Subject: \($0)") }) let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance) .multicast(subject) _ = intSequence .subscribe(onNext: { print("\tSubscription 1:, Event: \($0)") }) delay(2) { _ = intSequence.connect() } delay(4) { _ = intSequence .subscribe(onNext: { print("\tSubscription 2:, Event: \($0)") }) } delay(6) { _ = intSequence .subscribe(onNext: { print("\tSubscription 3:, Event: \($0)") }) } } //sampleWithMulticast() // MARK: Error Handling Operators example("catchErrorJustReturn") { let disposeBag = DisposeBag() let sequenceThatFails = PublishSubject<String>() sequenceThatFails .catchErrorJustReturn("😊") .subscribe { print($0) } .disposed(by: disposeBag) sequenceThatFails.onNext("😬") sequenceThatFails.onNext("😨") sequenceThatFails.onNext("😡") sequenceThatFails.onNext("🔴") sequenceThatFails.onError(TestError.test) } example("catchError") { let disposeBag = DisposeBag() let sequenceThatFails = PublishSubject<String>() let recoverySequence = PublishSubject<String>() sequenceThatFails .catchError { print("Error:", $0) return recoverySequence } .subscribe { print($0) } .disposed(by: disposeBag) sequenceThatFails.onNext("😬") sequenceThatFails.onNext("😨") sequenceThatFails.onNext("😡") sequenceThatFails.onNext("🔴") sequenceThatFails.onError(TestError.test) recoverySequence.onNext("😊") } example("retry") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<String>.create({ observer in observer.onNext("🍎"); observer.onNext("🍐"); observer.onNext("🍊") if count == 1 { observer.onError(TestError.test) print("Error encountered") count += 1 } observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐭") observer.onCompleted() return Disposables.create() }) sequenceThatErrors .retry() .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } example("retry maxAttemptCount") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<String>.create { observer in observer.onNext("🍎") observer.onNext("🍐"); observer.onNext("🍊") if count < 5 { observer.onError(TestError.test) print("Error encountered") count += 1 } observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐭") observer.onCompleted() return Disposables.create() } sequenceThatErrors .retry(3) .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } // MARK: Debugging Operators example("debug") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<String>.create({ observer in observer.onNext("🍎") observer.onNext("🍐"); observer.onNext("🍊") if count < 5 { observer.onError(TestError.test) print("Error encountered") count += 1 } observer.onNext("🐶") observer.onNext("🐱") observer.onNext("🐭") observer.onCompleted() return Disposables.create() }) sequenceThatErrors .retry(3) .debug() .subscribe(onNext: { print($0) }) .disposed(by: disposeBag) } #if NOT_IN_PLAYGROUND #else example("RxSwift.Resources.total", action: { print(RxSwift.Resources.total) let disposeBag = DisposeBag() print(RxSwift.Resources.total) let variable = Variable("🍎") let subscription1 = variable.asObservable().subscribe(onNext: { print($0) }) print(RxSwift.Resources.total) let subscription2 = variable.asObservable().subscribe(onNext: { print($0) }) print(RxSwift.Resources.total) subscription1.dispose() print(RxSwift.Resources.total) subscription2.dispose() print(RxSwift.Resources.total) }) print(RxSwift.Resources.total) #endif
mit
ad5082f4844f2122aa9ee98eca0aff80
22.187141
105
0.558279
4.403838
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/UltraDrawerView/Sources/Demo/ShapeCell.swift
1
3834
import UIKit final class ShapeCell: UITableViewCell { struct Info { var title: String var subtitle: String var shape: UIBezierPath } enum Layout { static let inset: CGFloat = 18 static let shapeSize: CGFloat = 48 static let estimatedHeight: CGFloat = 40 } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(with info: Info) { self.info = info titleLabel.text = info.title subtitleLabel.text = info.subtitle shapeLayer.path = info.shape.cgPath } // MARK: - UIView override func layoutSubviews() { super.layoutSubviews() shapeLayer.frame = shapeButton.bounds } // MARK: - Private private let shapeButton = UIButton() private let shapeLayer = CAShapeLayer() private let titleLabel = UILabel() private let subtitleLabel = UILabel() private var info: Info? private func setupViews() { backgroundColor = .white contentView.addSubview(shapeButton) shapeButton.addTarget(self, action: #selector(handleShapeButton), for: .touchUpInside) shapeButton.layer.addSublayer(shapeLayer) shapeLayer.lineWidth = 5 shapeLayer.lineJoin = .round updateShapeColors() contentView.addSubview(titleLabel) titleLabel.font = .boldSystemFont(ofSize: UIFont.labelFontSize) titleLabel.numberOfLines = 0 titleLabel.textColor = .black contentView.addSubview(subtitleLabel) subtitleLabel.font = .systemFont(ofSize: UIFont.systemFontSize) subtitleLabel.numberOfLines = 0 subtitleLabel.textColor = .darkGray setupLayout() } private func setupLayout() { let inset = Layout.inset let shapeSize = Layout.shapeSize shapeButton.translatesAutoresizingMaskIntoConstraints = false shapeButton.widthAnchor.constraint(equalToConstant: shapeSize).isActive = true shapeButton.heightAnchor.constraint(equalToConstant: shapeSize).isActive = true shapeButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: inset).isActive = true shapeButton.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: inset).isActive = true titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.leftAnchor.constraint(equalTo: shapeButton.rightAnchor, constant: inset).isActive = true titleLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -inset).isActive = true titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: inset).isActive = true subtitleLabel.translatesAutoresizingMaskIntoConstraints = false subtitleLabel.leftAnchor.constraint(equalTo: shapeButton.rightAnchor, constant: inset).isActive = true subtitleLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -inset).isActive = true subtitleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -inset).isActive = true subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8).isActive = true } private func updateShapeColors() { shapeLayer.fillColor = UIColor.randomLight.cgColor shapeLayer.strokeColor = UIColor.randomDark.cgColor } @objc private func handleShapeButton() { updateShapeColors() } }
mit
19c8e6679a181285630f3dd9cdba9e27
35.169811
114
0.676839
5.646539
false
false
false
false
mightydeveloper/swift
test/Interpreter/SDK/dictionary_pattern_matching.swift
11
4890
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation struct State { let name: String let population: Int let abbrev: String } func stateFromPlistLame(plist: Dictionary<String, AnyObject>) -> State? { if let name = plist["name"] as? NSString { if let population = plist["population"] as? NSNumber { if let abbrev = plist["abbrev"] as? NSString { if abbrev.length == 2 { return State(name: name as String, population: population.integerValue, abbrev: abbrev as String) } } } } return nil } func stateFromPlistCool(plist: Dictionary<String, AnyObject>) -> State? { switch (plist["name"], plist["population"], plist["abbrev"]) { case let (name as String, pop as Int, abbr as String) where abbr.characters.count == 2: return State(name: name, population: pop, abbrev: abbr) default: return nil } } let goodStatePlist: Dictionary<String, AnyObject> = [ "name": "California", "population": 38_040_000, "abbrev": "CA", ] let invalidStatePlist1: Dictionary<String, AnyObject> = [ "name": "California", "population": "hella", "abbrev": "CA", ] let invalidStatePlist2: Dictionary<String, AnyObject> = [ "name": "California", "population": 38_040_000, "abbrev": "Cali", ] let invalidStatePlist3: Dictionary<String, AnyObject> = [ "name": "California", "population": 38_040_000, ] // CHECK-LABEL: Some: // CHECK: name: California // CHECK: population: 38040000 // CHECK: abbrev: CA dump(stateFromPlistLame(goodStatePlist)) // CHECK-LABEL: Some: // CHECK: name: California // CHECK: population: 38040000 // CHECK: abbrev: CA dump(stateFromPlistCool(goodStatePlist)) // CHECK-LABEL: nil dump(stateFromPlistLame(invalidStatePlist1)) // CHECK-LABEL: nil dump(stateFromPlistCool(invalidStatePlist1)) // CHECK-LABEL: nil dump(stateFromPlistLame(invalidStatePlist2)) // CHECK-LABEL: nil dump(stateFromPlistCool(invalidStatePlist2)) // CHECK-LABEL: nil dump(stateFromPlistLame(invalidStatePlist3)) // CHECK-LABEL: nil dump(stateFromPlistCool(invalidStatePlist3)) struct Country { let name: String let population: Int } enum Statistic: _Reflectable { case ForState(State) case ForCountry(Country) func _getMirror() -> _MirrorType { return StatMirror(_value: self) } } struct StatMirror: _MirrorType { let _value: Statistic var value: Any { return _value } var valueType: Any.Type { return value.dynamicType } var objectIdentifier: ObjectIdentifier? { return nil } var count: Int { return 1 } subscript(i: Int) -> (String, _MirrorType) { assert(i == 0) switch _value { case .ForState(let state): return ("State", _reflect(state)) case .ForCountry(let country): return ("Country", _reflect(country)) } } var summary: String { switch _value { case .ForState: return "State" case .ForCountry: return "Country" } } var quickLookObject: PlaygroundQuickLook? { return nil } var disposition: _MirrorDisposition { return .Enum } } func statisticFromPlist(plist: Dictionary<String, AnyObject>) -> Statistic? { switch (plist["kind"], plist["name"], plist["population"], plist["abbrev"]) { case let ("state" as String, name as String, population as Int, abbrev as String) where abbrev.characters.count == 2: return Statistic.ForState(State(name: name, population: population, abbrev: abbrev)) case let ("country" as String, name as String, population as Int, .None): return Statistic.ForCountry(Country(name: name, population: population)) default: return nil } } let goodStatePlist2: Dictionary<String, AnyObject> = [ "kind": "state", "name": "California", "population": 38_040_000, "abbrev": "CA" ] let goodCountryPlist: Dictionary<String, AnyObject> = [ "kind": "country", "name": "India", "population": 1_23_70_00_000, ] let invalidCountryPlist1: Dictionary<String, AnyObject> = [ "kind": "country", "name": "India", "population": 1_23_70_00_000, "abbrev": "IN" ] let invalidCountryPlist2: Dictionary<String, AnyObject> = [ "kind": "country", "name": "India", "population": "123 crore", ] let invalidKindPlist: Dictionary<String, AnyObject> = [ "kind": "planet", "name": "Mercury", "population": 0 ] // CHECK-LABEL: Some: State dump(statisticFromPlist(goodStatePlist2)) // CHECK-LABEL: Some: Country dump(statisticFromPlist(goodCountryPlist)) // CHECK-LABEL: nil dump(statisticFromPlist(invalidCountryPlist1)) // CHECK-LABEL: nil dump(statisticFromPlist(invalidCountryPlist2)) // CHECK-LABEL: nil dump(statisticFromPlist(invalidKindPlist))
apache-2.0
13a8811c848964cc6c0c66175772c4ce
26.016575
83
0.657669
3.850394
false
false
false
false
chayelheinsen/GamingStreams-tvOS-App
StreamCenter/LoadingView.swift
3
1761
// // LoadingView.swift // GamingStreamsTVApp // // Created by Olivier Boucher on 2015-09-16. import UIKit import Foundation class LoadingView : UIView { private var label : UILabel! private var activityIndicator : UIActivityIndicatorView! override init(frame: CGRect) { super.init(frame: frame) let labelBounds = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.bounds.width, height: self.bounds.height * 0.3)) self.label = UILabel(frame: labelBounds) self.label.font = UIFont.systemFontOfSize(45) self.label.text = "Loading..." self.label.textColor = UIColor.whiteColor() self.label.textAlignment = NSTextAlignment.Center let indicatorBounds = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.bounds.width, height: self.bounds.height * 0.7)) self.activityIndicator = UIActivityIndicatorView(frame: indicatorBounds) self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge self.activityIndicator.sizeToFit() self.activityIndicator.startAnimating() //Center the views correctly self.activityIndicator.center = CGPoint(x: self.bounds.width/2, y: self.activityIndicator.bounds.height/2) self.label.center = CGPoint(x: self.bounds.width/2 + 10, y: self.activityIndicator.bounds.height + self.label!.bounds.height/2) self.addSubview(self.activityIndicator) self.addSubview(self.label) } convenience init(frame: CGRect, text: String) { self.init(frame: frame) self.label.text = text } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
b5bb5d1886eb51ec60e76e3eaf648b94
36.489362
139
0.673481
4.316176
false
false
false
false
grpc/grpc-swift
Sources/GRPC/AsyncAwaitSupport/GRPCAsyncRequestStreamWriter.swift
1
3570
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if compiler(>=5.6) import NIOCore /// An object allowing the holder -- a client -- to send requests on an RPC. /// /// Requests may be sent using ``send(_:compression:)``. After all requests have been sent /// the user is responsible for closing the request stream by calling ``finish()``. /// /// ``` /// // Send a request on the request stream, use the compression setting configured for the RPC. /// try await stream.send(request) /// /// // Send a request and explicitly disable compression. /// try await stream.send(request, compression: .disabled) /// /// // Finish the stream to indicate that no more messages will be sent. /// try await stream.finish() /// ``` @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public struct GRPCAsyncRequestStreamWriter<Request: Sendable>: Sendable { @usableFromInline typealias AsyncWriter = NIOAsyncWriter< (Request, Compression), GRPCAsyncWriterSinkDelegate<(Request, Compression)> > @usableFromInline /* private */ internal let asyncWriter: AsyncWriter @inlinable internal init(asyncWriter: AsyncWriter) { self.asyncWriter = asyncWriter } /// Send a single request. /// /// It is safe to send multiple requests concurrently by sharing the ``GRPCAsyncRequestStreamWriter`` across tasks. /// /// Callers must call ``finish()`` when they have no more requests left to send. /// /// - Parameters: /// - request: The request to send. /// - compression: Whether the request should be compressed or not. Ignored if compression was /// not enabled for the RPC. /// - Throws: If the request stream has already been finished. @inlinable public func send( _ request: Request, compression: Compression = .deferToCallDefault ) async throws { try await self.asyncWriter.yield((request, compression)) } /// Send a sequence of requests. /// /// It is safe to send multiple requests concurrently by sharing the ``GRPCAsyncRequestStreamWriter`` across tasks. /// /// Callers must call ``finish()`` when they have no more requests left to send. /// /// - Parameters: /// - requests: The requests to send. /// - compression: Whether the requests should be compressed or not. Ignored if compression was /// not enabled for the RPC. /// - Throws: If the request stream has already been finished. @inlinable public func send<S: Sequence>( _ requests: S, compression: Compression = .deferToCallDefault ) async throws where S.Element == Request { try await self.asyncWriter.yield(contentsOf: requests.lazy.map { ($0, compression) }) } /// Finish the request stream for the RPC. This must be called when there are no more requests to be sent. public func finish() { self.asyncWriter.finish() } /// Finish the request stream for the RPC with the given error. internal func finish(_ error: Error) { self.asyncWriter.finish(error: error) } } #endif // compiler(>=5.6)
apache-2.0
1b2cb6be50872a308edae36708215d68
35.060606
117
0.69916
4.353659
false
false
false
false
seandavidmcgee/HumanKontactBeta
src/HumanKontact Extension/TimelineKit.swift
1
14427
// // TimelineKit.swift // // The MIT License (MIT) // // Copyright (c) 2015 Adrian Zubarev (a.k.a. DevAndArtist) // // 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 /** * Defining custom type names. */ typealias TimelineTimeInterval = Double typealias Block = () -> Void /** * Enumeration to determinate blocks execution position. */ enum TimelineBlockAction { case WillExecuteMainBlock case DidExecuteMainBlock case WillExecuteOptionalCompletionBlock case DidExecuteOptinalCompletionBlock } /** * A helper class to create unchained blocks with delays. */ private class TimelineBlock { /// This property is needed to force strong reference to the timeline, /// so the timeline object won't be deallocated while the block is executing. /// This also provides a possibility for delegation. var timeline: Timeline! /// This property will contain the computed block which will be executed. var block: Block! /// This property can hold a reference to the successor block which is appended /// to the end of the 'block's execution. var successor: Block! /// Property that determinates the number of the block inside the queue. var number: Int = 0 /** Main initializer to create a TimelineBlock object and compute the 'block' property. :param: delay Time to wait before 'execution' block is triggered. :param: duration Time assumed by the developer the 'execution' block will take. :param: execution The main block. :param: completion An optional completion block which is triggered after duration time. :returns: TimelineBlock object. */ init(delay: TimelineTimeInterval, duration: TimelineTimeInterval, execution: Block, completion: Block!) { let completionAndSuccessorBlock: Block = { [weak self] in if let weakSelf = self { weakSelf.timeline.notifyDelagesWithBlock(number: weakSelf.number, action: .WillExecuteOptionalCompletionBlock) if let completionBlock = completion { completionBlock() } weakSelf.timeline.notifyDelagesWithBlock(number: weakSelf.number, action: .DidExecuteOptinalCompletionBlock) if let successor = weakSelf.successor { successor() } } } let blockToExecute: Block = { [weak self] in if let weakSelf = self { weakSelf.timeline.notifyDelagesWithBlock(number: weakSelf.number, action: .WillExecuteMainBlock) execution() weakSelf.timeline.notifyDelagesWithBlock(number: weakSelf.number, action: .DidExecuteMainBlock) if duration <= 0.0 { completionAndSuccessorBlock(); return } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { completionAndSuccessorBlock() } } } self.block = { [weak self] in if let _ = self { if delay <= 0.0 { blockToExecute(); return } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { blockToExecute() } } } } /** Deinitializer to show that the object is released when it is no more needed. Add "-D DEBUG" at 'Build Settings' -> 'Swift Compiler - Custom Flags' -> 'Other Swift Flags'. */ deinit { #if DEBUG print(" ◎--○--: Deallocated (\(number + 1)) TimelineBlock") #endif } } /** * A queue to create TimelineBlocks array from inside a timeline block. */ class TimelineQueue { /** Adds an execution block and maybe adds a completion block if it is not nil with a delay and duration to the queue. :param: delay Time to wait before 'execution' block is triggered. :param: duration Time assumed by the developer the 'execution' block will take. :param: execution The main block. :param: completion An optional completion block which is triggered after duration time. */ final func add(delay delay: TimelineTimeInterval, duration: TimelineTimeInterval, execution: Block, completion: Block!) { let timelineBlock = TimelineBlock(delay: delay, duration: duration, execution: execution, completion: completion) timelineBlock.number = blocks.count blocks.append(timelineBlock) } /** Adds an execution block with a delay and duration to the queue. :param: delay Time to wait before 'execution' block is triggered. :param: duration Time assumed by the developer the 'execution' block will take. :param: execution The main block. */ final func add(delay delay: TimelineTimeInterval, duration: TimelineTimeInterval, execution: Block) { self.add(delay: delay, duration: duration, execution: execution, completion: nil) } final private var blocks = [TimelineBlock]() /** Adds an execution block with a delay to the queue. :param: delay Time to wait before 'execution' block is triggered. :param: execution The main block. */ final func add(delay delay: TimelineTimeInterval, execution: Block) { self.add(delay: delay, duration: 0.0, execution: execution, completion: nil) } /** Deinitializer to show that the object is released when it is no more needed. Add "-D DEBUG" at 'Build Settings' -> 'Swift Compiler - Custom Flags' -> 'Other Swift Flags'. */ deinit { #if DEBUG print(" ◎--○--: Deallocated TimelineQueue") #endif } } /** * A timeline delegation protocol. */ protocol TimelineDelegate { /** This method is called while the timeline is executing all blocks and returns all block actions. :param: timeline Timeline object reference. :param: identifier An optional timeline identifier. :param: blockNumber The number which determinates the block index inside the queue. :param: blockAction Block action to derminate execution position. */ func timeline(timeline: Timeline, identifier: String?, blockNumber: Int, blockAction: TimelineBlockAction) } /** * Timeline class. */ class Timeline { /** Creates a standalone timeline with a single execution block after a delay for specified duration time with an optional completion block. :param: identifier Optional timeline identifier. :param: delay Time to wait before 'execution' block is triggered. :param: duration Time assumed by the developer the 'execution' block will take. :param: execution The main block. :param: completion An optional completion block which is triggered after duration time. :returns: Returns the timeline object. */ final class func with(identifier: String! = nil, delay: TimelineTimeInterval, duration: TimelineTimeInterval, execution: Block, completion: Block) -> Timeline { let timeline = Timeline() timeline.identifier = identifier timeline.queue.add(delay: delay, duration: duration, execution: execution, completion: completion) return timeline } /** Creates a standalone timeline with a single execution block after a delay. :param: identifier Optional timeline identifier. :param: delay Time to wait before 'execution' block is triggered. :param: execution The main block. :returns: Returns the timeline object. */ final class func with(identifier: String! = nil, delay: TimelineTimeInterval, execution: Block) -> Timeline { let timeline = Timeline() timeline.identifier = identifier timeline.queue.add(delay: delay, duration: 0.0, execution: execution) return timeline } /** Creates a standalone timeline from a timeline queue. :param: identifier Optional timeline identifier. :param: block Block where you can add blocks to a queue. :returns: Returns the timeline object. */ final class func with(identifier: String! = nil, block: (queue: TimelineQueue) -> Void) -> Timeline { let timeline = Timeline() timeline.identifier = identifier block(queue: timeline.queue) return timeline } /// Property with all delates. final private var delegates = [TimelineDelegate]() /// Queue property final private var queue = TimelineQueue() /// Amout of timeline runs (is > 1 if .start is called to quickly and to often) final private var runs = 0 /// Flag that determinates if the blocks are executing. final private var isRunning = false /// The optional identifier property. final private var identifier: String? /// Property which is used as a starting function for the timeline. final internal var start: Void { runs += 1 run() } /** Main starting function which chains the blocks to gether and executes the root block. */ private func run() { if !isRunning { for index in 0 ..< queue.blocks.count { let timelineBlock = queue.blocks[index] timelineBlock.timeline = self if index < queue.blocks.count - 1 { if timelineBlock.successor == nil { timelineBlock.successor = queue.blocks[index + 1].block } } } queue.blocks[0].block() isRunning = true } } /** Adds a delate to the timeline object. :param: delegate Delegate reference. */ func addDelegate(delegate: TimelineDelegate) { if !delegates.containsObject(delegate) // uses a custom array extension { delegates.append(delegate) } } /** Removes a delage from the timeline object. :param: delegate Delegate reference. */ func removeDeleage(delegate: TimelineDelegate) { if delegates.containsObject(delegate) // uses a custom array extension { delegates.removeObject(delegate) // uses a custom array extension } } /** Private method which is called from each block to notify a possible delagate with its action. :param: number Block index in the timeline queue. :param: action Action of the block. */ private func notifyDelagesWithBlock(number number: Int, action: TimelineBlockAction) { for delegate in delegates { delegate.timeline(self, identifier: identifier, blockNumber: number, blockAction: action) } if action == .DidExecuteOptinalCompletionBlock { queue.blocks[number].timeline = nil if number == queue.blocks.count - 1 { runs -= 1 isRunning = false if runs > 0 { run() } } } } /** Deinitializer to show that the object is released when it is no more needed. Add "-D DEBUG" at 'Build Settings' -> 'Swift Compiler - Custom Flags' -> 'Other Swift Flags'. */ deinit { #if DEBUG print("◎--○--: Deallocated Timeline") #endif } } /** * Custom Array extention. */ extension Array { /** Checks if an array contains an object or not. :param: object Object to find inside the array. :returns: Returns a boolean to determinate if the object is inside the array or not. */ func containsObject(object: Any) -> Bool { if let anObject: AnyObject = object as? AnyObject { for obj in self { if let anObj: AnyObject = obj as? AnyObject { if anObj === anObject { return true } } } } return false } /** Searches for an object inside the array and removes it if it was found. :param: object Object to find inside the array. */ mutating func removeObject(object: Any) { if let anObject: AnyObject = object as? AnyObject { for index in 0 ..< self.count { if let anObj: AnyObject = self[index] as? AnyObject { if anObj === anObject { self.removeAtIndex(index) } } } } } }
mit
e6a3e023be06df1d9fde49b840c40423
30.964523
162
0.601318
5.043737
false
false
false
false
RxSwiftCommunity/RxRealm
Sources/RxRealm/RxRealm.swift
1
20923
// // RxRealm extensions // // Copyright (c) 2016 RxSwiftCommunity. All rights reserved. // Check the LICENSE file for details // Created by Marin Todorov // import Foundation import RealmSwift import RxSwift public enum RxRealmError: Error { case objectDeleted case unknown } // MARK: Realm Collections type extensions /** `NotificationEmitter` is a protocol to allow for Realm's collections to be handled in a generic way. All collections already include a `addNotificationBlock(_:)` method - making them conform to `NotificationEmitter` just makes it easier to add Rx methods to them. The methods of essence in this protocol are `asObservable(...)`, which allow for observing for changes on Realm's collections. */ public protocol NotificationEmitter { associatedtype ElementType: RealmCollectionValue /** Returns a `NotificationToken`, which while retained enables change notifications for the current collection. - returns: `NotificationToken` - retain this value to keep notifications being emitted for the current collection. */ func observe(keyPaths: [String]?, on queue: DispatchQueue?, _ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken func toArray() -> [ElementType] func toAnyCollection() -> AnyRealmCollection<ElementType> } extension List: NotificationEmitter { public func toAnyCollection() -> AnyRealmCollection<Element> { return AnyRealmCollection<Element>(self) } public typealias ElementType = Element public func toArray() -> [Element] { return Array(self) } } extension AnyRealmCollection: NotificationEmitter { public func toAnyCollection() -> AnyRealmCollection<Element> { return AnyRealmCollection<ElementType>(self) } public typealias ElementType = Element public func toArray() -> [Element] { return Array(self) } } extension Results: NotificationEmitter { public func toAnyCollection() -> AnyRealmCollection<Element> { return AnyRealmCollection<ElementType>(self) } public typealias ElementType = Element public func toArray() -> [Element] { return Array(self) } } extension LinkingObjects: NotificationEmitter { public func toAnyCollection() -> AnyRealmCollection<Element> { return AnyRealmCollection<ElementType>(self) } public typealias ElementType = Element public func toArray() -> [Element] { return Array(self) } } /** `RealmChangeset` is a struct that contains the data about a single realm change set. It includes the insertions, modifications, and deletions indexes in the data set that the current notification is about. */ public struct RealmChangeset { /// the indexes in the collection that were deleted public let deleted: [Int] /// the indexes in the collection that were inserted public let inserted: [Int] /// the indexes in the collection that were modified public let updated: [Int] } public extension ObservableType where Element: NotificationEmitter { @available(*, deprecated, renamed: "collection(from:synchronousStart:)") static func from(_ collection: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Element> { return self.collection(from: collection) } /** Returns an `Observable<Element>` that emits each time the collection data changes. The observable emits an initial value upon subscription. - parameter from: A Realm collection of type `Element`: either `Results`, `List`, `LinkingObjects` or `AnyRealmCollection`. - parameter synchronousStart: whether the resulting `Observable` should emit its first element synchronously (e.g. better for UI bindings) - parameter keyPaths: Only properties contained in the key paths array will trigger the block when they are modified. See description above for more detail on linked properties. - parameter queue: The serial dispatch queue to receive notification on. If `nil`, notifications are delivered to the current thread. - returns: `Observable<Element>`, e.g. when called on `Results<Model>` it will return `Observable<Results<Model>>`, on a `List<User>` it will return `Observable<List<User>>`, etc. */ static func collection(from collection: Element, synchronousStart: Bool = true, keyPaths: [String]? = nil, on queue: DispatchQueue? = nil) -> Observable<Element> { return Observable.create { observer in if synchronousStart { observer.onNext(collection) } let token = collection.observe(keyPaths: keyPaths, on: queue) { changeset in let value: Element switch changeset { case let .initial(latestValue): guard !synchronousStart else { return } value = latestValue case let .update(latestValue, _, _, _): value = latestValue case let .error(error): observer.onError(error) return } observer.onNext(value) } return Disposables.create { token.invalidate() } } } @available(*, deprecated, renamed: "array(from:synchronousStart:)") static func arrayFrom(_ collection: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<[Element.ElementType]> { return array(from: collection) } /** Returns an `Observable<Array<Element.Element>>` that emits each time the collection data changes. The observable emits an initial value upon subscription. The result emits an array containing all objects from the source collection. - parameter from: A Realm collection of type `Element`: either `Results`, `List`, `LinkingObjects` or `AnyRealmCollection`. - parameter synchronousStart: whether the resulting Observable should emit its first element synchronously (e.g. better for UI bindings) - parameter queue: The serial dispatch queue to receive notification on. If `nil`, notifications are delivered to the current thread. - returns: `Observable<Array<Element.Element>>`, e.g. when called on `Results<Model>` it will return `Observable<Array<Model>>`, on a `List<User>` it will return `Observable<Array<User>>`, etc. */ static func array(from collection: Element, synchronousStart: Bool = true, on queue: DispatchQueue? = nil) -> Observable<[Element.ElementType]> { return Observable.collection(from: collection, synchronousStart: synchronousStart, on: queue) .map { $0.toArray() } } @available(*, deprecated, renamed: "changeset(from:synchronousStart:)") static func changesetFrom(_ collection: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<(AnyRealmCollection<Element.ElementType>, RealmChangeset?)> { return changeset(from: collection) } /** Returns an `Observable<(Element, RealmChangeset?)>` that emits each time the collection data changes. The observable emits an initial value upon subscription. When the observable emits for the first time (if the initial notification is not coalesced with an update) the second tuple value will be `nil`. Each following emit will include a `RealmChangeset` with the indexes inserted, deleted or modified. - parameter from: A Realm collection of type `Element`: either `Results`, `List`, `LinkingObjects` or `AnyRealmCollection`. - parameter synchronousStart: whether the resulting Observable should emit its first element synchronously (e.g. better for UI bindings) - parameter queue: The serial dispatch queue to receive notification on. If `nil`, notifications are delivered to the current thread. - returns: `Observable<(AnyRealmCollection<Element.Element>, RealmChangeset?)>` */ static func changeset(from collection: Element, synchronousStart: Bool = true, on queue: DispatchQueue? = nil) -> Observable<(AnyRealmCollection<Element.ElementType>, RealmChangeset?)> { return Observable.create { observer in if synchronousStart { observer.onNext((collection.toAnyCollection(), nil)) } let token = collection.toAnyCollection().observe(on: queue) { changeset in switch changeset { case let .initial(value): guard !synchronousStart else { return } observer.onNext((value, nil)) case let .update(value, deletes, inserts, updates): observer.onNext((value, RealmChangeset(deleted: deletes, inserted: inserts, updated: updates))) case let .error(error): observer.onError(error) return } } return Disposables.create { token.invalidate() } } } @available(*, deprecated, renamed: "arrayWithChangeset(from:synchronousStart:)") static func changesetArrayFrom(_ collection: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<([Element.ElementType], RealmChangeset?)> { return arrayWithChangeset(from: collection) } /** Returns an `Observable<(Array<Element.Element>, RealmChangeset?)>` that emits each time the collection data changes. The observable emits an initial value upon subscription. This method emits an `Array` containing all the realm collection objects, this means they all live in the memory. If you're using this method to observe large collections you might hit memory warnings. When the observable emits for the first time (if the initial notification is not coalesced with an update) the second tuple value will be `nil`. Each following emit will include a `RealmChangeset` with the indexes inserted, deleted or modified. - parameter from: A Realm collection of type `Element`: either `Results`, `List`, `LinkingObjects` or `AnyRealmCollection`. - parameter synchronousStart: whether the resulting Observable should emit its first element synchronously (e.g. better for UI bindings) - parameter queue: The serial dispatch queue to receive notification on. If `nil`, notifications are delivered to the current thread. - returns: `Observable<(Array<Element.Element>, RealmChangeset?)>` */ static func arrayWithChangeset(from collection: Element, synchronousStart: Bool = true, on queue: DispatchQueue? = nil) -> Observable<([Element.ElementType], RealmChangeset?)> { return Observable.changeset(from: collection, on: queue) .map { ($0.toArray(), $1) } } } public extension Observable { @available(*, deprecated, renamed: "from(realm:)") static func from(_ realm: Realm, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<(Realm, Realm.Notification)> { return from(realm: realm) } /** Returns an `Observable<(Realm, Realm.Notification)>` that emits each time the Realm emits a notification. The Observable you will get emits a tuple made out of: * the realm that emitted the event * the notification type: this can be either `.didChange` which occurs after a refresh or a write transaction ends, or `.refreshRequired` which happens when a write transaction occurs from a different thread on the same realm file For more information look up: [Realm.Notification](https://realm.io/docs/swift/latest/api/Enums/Notification.html) - parameter realm: A Realm instance - returns: `Observable<(Realm, Realm.Notification)>`, which you can subscribe to */ static func from(realm: Realm) -> Observable<(Realm, Realm.Notification)> { return Observable<(Realm, Realm.Notification)>.create { observer in let token = realm.observe { (notification: Realm.Notification, realm: Realm) in observer.onNext((realm, notification)) } return Disposables.create { token.invalidate() } } } } // MARK: Realm type extensions extension Realm: ReactiveCompatible {} public extension Reactive where Base == Realm { /** Returns bindable sink wich adds object sequence to the current Realm - parameter: update - update according to Realm.UpdatePolicy - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to */ func add<S: Sequence>(update: Realm.UpdatePolicy = .error, onError: ((S?, Error) -> Void)? = nil) -> AnyObserver<S> where S.Iterator.Element: Object { return RealmObserver(realm: base) { realm, elements, error in guard let realm = realm else { onError?(nil, error ?? RxRealmError.unknown) return } do { try realm.write { realm.add(elements, update: update) } } catch let e { onError?(elements, e) } } .asObserver() } /** Returns bindable sink wich adds an object to Realm - parameter: update - update according to Realm.UpdatePolicy - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to */ func add<O: Object>(update: Realm.UpdatePolicy = .error, onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> { return RealmObserver(realm: base) { realm, element, error in guard let realm = realm else { onError?(nil, error ?? RxRealmError.unknown) return } do { try realm.write { realm.add(element, update: update) } } catch let e { onError?(element, e) } }.asObserver() } /** Returns bindable sink wich deletes objects in sequence from Realm. - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to */ func delete<S: Sequence>(onError: ((S?, Error) -> Void)? = nil) -> AnyObserver<S> where S.Iterator.Element: Object { return RealmObserver(realm: base, binding: { realm, elements, error in guard let realm = realm else { onError?(nil, error ?? RxRealmError.unknown) return } do { try realm.write { realm.delete(elements) } } catch let e { onError?(elements, e) } }).asObserver() } /** Returns bindable sink wich deletes objects in sequence from Realm. - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to */ func delete<O: Object>(onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> { return RealmObserver(realm: base, binding: { realm, element, error in guard let realm = realm else { onError?(nil, error ?? RxRealmError.unknown) return } do { try realm.write { realm.delete(element) } } catch let e { onError?(element, e) } }).asObserver() } } public extension Reactive where Base == Realm { /** Returns bindable sink wich adds object sequence to a Realm - parameter: configuration (by default uses `Realm.Configuration.defaultConfiguration`) to use to get a Realm for the write operations - parameter: update - update according to Realm.UpdatePolicy - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to */ static func add<S: Sequence>(configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration, update: Realm.UpdatePolicy = .error, onError: ((S?, Error) -> Void)? = nil) -> AnyObserver<S> where S.Iterator.Element: Object { return RealmObserver(configuration: configuration) { realm, elements, error in guard let realm = realm else { onError?(nil, error ?? RxRealmError.unknown) return } do { try realm.write { realm.add(elements, update: update) } } catch let e { onError?(elements, e) } }.asObserver() } /** Returns bindable sink which adds an object to a Realm - parameter: configuration (by default uses `Realm.Configuration.defaultConfiguration`) to use to get a Realm for the write operations - parameter: update - update according to Realm.UpdatePolicy - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to */ static func add<O: Object>(configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration, update: Realm.UpdatePolicy = .error, onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> { return RealmObserver(configuration: configuration) { realm, element, error in guard let realm = realm else { onError?(nil, error ?? RxRealmError.unknown) return } do { try realm.write { realm.add(element, update: update) } } catch let e { onError?(element, e) } }.asObserver() } /** Returns bindable sink, which deletes objects in sequence from Realm. - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to */ static func delete<S: Sequence>(onError: ((S?, Error) -> Void)? = nil) -> AnyObserver<S> where S.Iterator.Element: Object { return AnyObserver { event in guard let elements = event.element, var generator = elements.makeIterator() as S.Iterator?, let first = generator.next(), let realm = first.realm else { onError?(nil, RxRealmError.unknown) return } do { try realm.write { realm.delete(elements) } } catch let e { onError?(elements, e) } } } /** Returns bindable sink, which deletes object from Realm - parameter: onError - closure to implement custom error handling - returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to */ static func delete<O: Object>(onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> { return AnyObserver { event in guard let element = event.element, let realm = element.realm else { onError?(nil, RxRealmError.unknown) return } do { try realm.write { realm.delete(element) } } catch let e { onError?(element, e) } } } } // MARK: Realm Object type extensions public extension Observable where Element: Object { @available(*, deprecated, renamed: "from(object:)") static func from(_ object: Element) -> Observable<Element> { return from(object: object) } /** Returns an `Observable<Object>` that emits each time the object changes. The observable emits an initial value upon subscription. - parameter object: A Realm Object to observe - parameter emitInitialValue: whether the resulting `Observable` should emit its first element synchronously (e.g. better for UI bindings) - parameter properties: changes to which properties would triger emitting a .next event - returns: `Observable<Object>` will emit any time the observed object changes + one initial emit upon subscription */ static func from(object: Element, emitInitialValue: Bool = true, properties: [String]? = nil) -> Observable<Element> { return Observable<Element>.create { observer in if emitInitialValue { observer.onNext(object) } let token = object.observe { change in switch change { case let .change(_, changedProperties): if let properties = properties, !changedProperties.contains(where: { properties.contains($0.name) }) { // if change property isn't an observed one, just return return } observer.onNext(object) case .deleted: observer.onError(RxRealmError.objectDeleted) case let .error(error): observer.onError(error) } } return Disposables.create { token.invalidate() } } } /** Returns an `Observable<PropertyChange>` that emits the object `PropertyChange`s. - parameter object: A Realm Object to observe - returns: `Observable<PropertyChange>` will emit any time a change is detected on the object */ static func propertyChanges(object: Element) -> Observable<PropertyChange> { return Observable<PropertyChange>.create { observer in let token = object.observe { change in switch change { case let .change(_, changes): for change in changes { observer.onNext(change) } case .deleted: observer.onError(RxRealmError.objectDeleted) case let .error(error): observer.onError(error) } } return Disposables.create { token.invalidate() } } } }
mit
136e2efa41a93ba97f8d7a122c051192
35.836268
204
0.680065
4.802157
false
false
false
false
brokenhandsio/SteamPress
Sources/SteamPress/Controllers/Admin/UserAdminController.swift
1
11704
import Vapor import Authentication struct UserAdminController: RouteCollection { // MARK: - Properties private let pathCreator: BlogPathCreator // MARK: - Initialiser init(pathCreator: BlogPathCreator) { self.pathCreator = pathCreator } // MARK: - Route setup func boot(router: Router) throws { router.get("createUser", use: createUserHandler) router.post("createUser", use: createUserPostHandler) router.get("users", BlogUser.parameter, "edit", use: editUserHandler) router.post("users", BlogUser.parameter, "edit", use: editUserPostHandler) router.post("users", BlogUser.parameter, "delete", use: deleteUserPostHandler) } // MARK: - Route handlers func createUserHandler(_ req: Request) throws -> EventLoopFuture<View> { let presenter = try req.make(BlogAdminPresenter.self) return try presenter.createUserView(on: req, editing: false, errors: nil, name: nil, nameError: false, username: nil, usernameErorr: false, passwordError: false, confirmPasswordError: false, resetPasswordOnLogin: false, userID: nil, profilePicture: nil, twitterHandle: nil, biography: nil, tagline: nil, pageInformation: req.adminPageInfomation()) } func createUserPostHandler(_ req: Request) throws -> EventLoopFuture<Response> { let data = try req.content.syncDecode(CreateUserData.self) return try validateUserCreation(data, on: req).flatMap { createUserErrors in if let errors = createUserErrors { let presenter = try req.make(BlogAdminPresenter.self) let view = try presenter.createUserView(on: req, editing: false, errors: errors.errors, name: data.name, nameError: errors.nameError, username: data.username, usernameErorr: errors.usernameError, passwordError: errors.passwordError, confirmPasswordError: errors.confirmPasswordError, resetPasswordOnLogin: data.resetPasswordOnLogin ?? false, userID: nil, profilePicture: data.profilePicture, twitterHandle: data.twitterHandle, biography: data.biography, tagline: data.tagline, pageInformation: req.adminPageInfomation()) return try view.encode(for: req) } guard let name = data.name, let username = data.username, let password = data.password else { throw Abort(.internalServerError) } let hasher = try req.make(PasswordHasher.self) let hashedPassword = try hasher.hash(password) let profilePicture = data.profilePicture.isEmptyOrWhitespace() ? nil : data.profilePicture let twitterHandle = data.twitterHandle.isEmptyOrWhitespace() ? nil : data.twitterHandle let biography = data.biography.isEmptyOrWhitespace() ? nil : data.biography let tagline = data.tagline.isEmptyOrWhitespace() ? nil : data.tagline let newUser = BlogUser(name: name, username: username.lowercased(), password: hashedPassword, profilePicture: profilePicture, twitterHandle: twitterHandle, biography: biography, tagline: tagline) if let resetPasswordRequired = data.resetPasswordOnLogin, resetPasswordRequired { newUser.resetPasswordRequired = true } let userRepository = try req.make(BlogUserRepository.self) return userRepository.save(newUser, on: req).map { _ in return req.redirect(to: self.pathCreator.createPath(for: "admin")) } } } func editUserHandler(_ req: Request) throws -> EventLoopFuture<View> { return try req.parameters.next(BlogUser.self).flatMap { user in let presenter = try req.make(BlogAdminPresenter.self) return try presenter.createUserView(on: req, editing: true, errors: nil, name: user.name, nameError: false, username: user.username, usernameErorr: false, passwordError: false, confirmPasswordError: false, resetPasswordOnLogin: user.resetPasswordRequired, userID: user.userID, profilePicture: user.profilePicture, twitterHandle: user.twitterHandle, biography: user.biography, tagline: user.tagline, pageInformation: req.adminPageInfomation()) } } func editUserPostHandler(_ req: Request) throws -> EventLoopFuture<Response> { return try req.parameters.next(BlogUser.self).flatMap { user in let data = try req.content.syncDecode(CreateUserData.self) guard let name = data.name, let username = data.username else { throw Abort(.internalServerError) } return try self.validateUserCreation(data, editing: true, existingUsername: user.username, on: req).flatMap { errors in if let editUserErrors = errors { let presenter = try req.make(BlogAdminPresenter.self) let view = try presenter.createUserView(on: req, editing: true, errors: editUserErrors.errors, name: data.name, nameError: errors?.nameError ?? false, username: data.username, usernameErorr: errors?.usernameError ?? false, passwordError: editUserErrors.passwordError, confirmPasswordError: editUserErrors.confirmPasswordError, resetPasswordOnLogin: data.resetPasswordOnLogin ?? false, userID: user.userID, profilePicture: data.profilePicture, twitterHandle: data.twitterHandle, biography: data.biography, tagline: data.tagline, pageInformation: req.adminPageInfomation()) return try view.encode(for: req) } user.name = name user.username = username.lowercased() let profilePicture = data.profilePicture.isEmptyOrWhitespace() ? nil : data.profilePicture let twitterHandle = data.twitterHandle.isEmptyOrWhitespace() ? nil : data.twitterHandle let biography = data.biography.isEmptyOrWhitespace() ? nil : data.biography let tagline = data.tagline.isEmptyOrWhitespace() ? nil : data.tagline user.profilePicture = profilePicture user.twitterHandle = twitterHandle user.biography = biography user.tagline = tagline if let resetPasswordOnLogin = data.resetPasswordOnLogin, resetPasswordOnLogin { user.resetPasswordRequired = true } if let password = data.password, password != "" { let hasher = try req.make(PasswordHasher.self) user.password = try hasher.hash(password) } let redirect = req.redirect(to: self.pathCreator.createPath(for: "admin")) let userRepository = try req.make(BlogUserRepository.self) return userRepository.save(user, on: req).transform(to: redirect) } } } func deleteUserPostHandler(_ req: Request) throws -> EventLoopFuture<Response> { let userRepository = try req.make(BlogUserRepository.self) return try flatMap(req.parameters.next(BlogUser.self), userRepository.getUsersCount(on: req)) { user, userCount in guard userCount > 1 else { let postRepository = try req.make(BlogPostRepository.self) return flatMap(postRepository.getAllPostsSortedByPublishDate(includeDrafts: true, on: req), userRepository.getAllUsers(on: req)) { posts, users in let presenter = try req.make(BlogAdminPresenter.self) let view = try presenter.createIndexView(on: req, posts: posts, users: users, errors: ["You cannot delete the last user"], pageInformation: req.adminPageInfomation()) return try view.encode(for: req) } } let loggedInUser = try req.requireAuthenticated(BlogUser.self) guard loggedInUser.userID != user.userID else { let postRepository = try req.make(BlogPostRepository.self) return flatMap(postRepository.getAllPostsSortedByPublishDate(includeDrafts: true, on: req), userRepository.getAllUsers(on: req)) { posts, users in let presenter = try req.make(BlogAdminPresenter.self) let view = try presenter.createIndexView(on: req, posts: posts, users: users, errors: ["You cannot delete yourself whilst logged in"], pageInformation: req.adminPageInfomation()) return try view.encode(for: req) } } let redirect = req.redirect(to: self.pathCreator.createPath(for: "admin")) return userRepository.delete(user, on: req).transform(to: redirect) } } // MARK: - Validators private func validateUserCreation(_ data: CreateUserData, editing: Bool = false, existingUsername: String? = nil, on req: Request) throws -> EventLoopFuture<CreateUserErrors?> { var createUserErrors = [String]() var passwordError = false var confirmPasswordError = false var nameErorr = false var usernameError = false if data.name.isEmptyOrWhitespace() { createUserErrors.append("You must specify a name") nameErorr = true } if data.username.isEmptyOrWhitespace() { createUserErrors.append("You must specify a username") usernameError = true } if !editing || !data.password.isEmptyOrWhitespace() { if data.password.isEmptyOrWhitespace() { createUserErrors.append("You must specify a password") passwordError = true } if data.confirmPassword.isEmptyOrWhitespace() { createUserErrors.append("You must confirm your password") confirmPasswordError = true } } if let password = data.password, password != "" { if password.count < 10 { createUserErrors.append("Your password must be at least 10 characters long") passwordError = true } if data.password != data.confirmPassword { createUserErrors.append("Your passwords must match") passwordError = true confirmPasswordError = true } } do { try data.validate() } catch { createUserErrors.append("The username provided is not valid") usernameError = true } var usernameUniqueError: EventLoopFuture<String?> let usersRepository = try req.make(BlogUserRepository.self) if let username = data.username { if editing && data.username == existingUsername { usernameUniqueError = req.future(nil) } else { usernameUniqueError = usersRepository.getUser(username: username.lowercased(), on: req).map { user in if user != nil { return "Sorry that username has already been taken" } else { return nil } } } } else { usernameUniqueError = req.future(nil) } return usernameUniqueError.map { usernameErrorOccurred in if let uniqueError = usernameErrorOccurred { createUserErrors.append(uniqueError) usernameError = true } if createUserErrors.count == 0 { return nil } let errors = CreateUserErrors(errors: createUserErrors, passwordError: passwordError, confirmPasswordError: confirmPasswordError, nameError: nameErorr, usernameError: usernameError) return errors } } }
mit
9f386ddf07fcd585cab55fe4192e97a8
51.720721
591
0.641405
5.303126
false
false
false
false
abelsanchezali/ViewBuilder
Source/View/LinearGradientView.swift
1
2490
// // LinearGradientView.swift // ViewBuilder // // Created by Abel Sanchez on 7/24/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit open class GradientStop: NSObject, DefaultConstructor { @objc open var color: UIColor @objc open var offset: Double public override required init() { color = UIColor.clear offset = 1 } } open class LinearGradientView: UIView { override open class var layerClass : AnyClass { return CAGradientLayer.self } public override init(frame: CGRect) { stops = nil startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x: 1, y: 1) super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { stops = nil startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x: 1, y: 1) super.init(coder: aDecoder) } @objc open var stops: [GradientStop]? { didSet { guard let gradientLayer = layer as? CAGradientLayer else { return } var colors: [AnyObject]? = nil var locations: [NSNumber]? = nil if var stops = self.stops { // Sort gradients stop monotonically increasing as required in CAGradientLayer stops.sort() { $0.offset < $1.offset } colors = stops.map { $0.color.cgColor } locations = stops.map { NSNumber(value: $0.offset as Double) } } gradientLayer.colors = colors gradientLayer.locations = locations } } @objc open var startPoint: CGPoint { didSet { guard let gradientLayer = layer as? CAGradientLayer else { return } gradientLayer.startPoint = startPoint } } @objc open var endPoint: CGPoint { didSet { guard let gradientLayer = layer as? CAGradientLayer else { return } gradientLayer.endPoint = endPoint } } // MARK: - DocumentChildsProcessor open override func processDocument(childs: DocumentChildVisitor) { super.processDocument(childs: childs) var stops = [GradientStop]() childs.visit { (child) -> Bool in if let stop = child as? GradientStop { stops.append(stop) return true } return false } self.stops = stops } }
mit
400af907715803af9c8e0059e3d9c051
26.351648
94
0.560064
4.768199
false
false
false
false
apple/swift-syntax
Tests/SwiftParserTest/translated/UnclosedStringInterpolationTests.swift
1
4388
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// // This test file has been translated from swift/test/Parse/unclosed-string-interpolation.swift import XCTest final class UnclosedStringInterpolationTests: XCTestCase { func testUnclosedStringInterpolation1() { AssertParse( #""" let mid = "pete" """# ) } func testUnclosedStringInterpolation2() { AssertParse( ##""" _ = 1️⃣"mid == \(pete" """##, diagnostics: [ // TODO: Old parser expected error on line 1: cannot find ')' to match opening '(' in string interpolation // TODO: Old parser expected error on line 1: unterminated string literal DiagnosticSpec(message: "expected expression"), DiagnosticSpec(message: #"extraneous code '"mid == \(pete"' at top level"#), ] ) } func testUnclosedStringInterpolation3() { AssertParse( ##""" let theGoat = 1️⃣"kanye \(" """##, diagnostics: [ // TODO: Old parser expected error on line 1: cannot find ')' to match opening '(' in string interpolation // TODO: Old parser expected error on line 1: unterminated string literal DiagnosticSpec(message: "expected expression in variable"), DiagnosticSpec(message: #"extraneous code '"kanye \("' at top level"#), ] ) } func testUnclosedStringInterpolation4() { AssertParse( ##""" let equation1 = 1️⃣"2 + 2 = \(2 + 2" """##, diagnostics: [ // TODO: Old parser expected error on line 1: cannot find ')' to match opening '(' in string interpolation // TODO: Old parser expected error on line 1: unterminated string literal DiagnosticSpec(message: "expected expression in variable"), DiagnosticSpec(message: #"extraneous code '"2 + 2 = \(2 + 2"' at top level"#), ] ) } func testUnclosedStringInterpolation5() { AssertParse( ##""" let s = 1️⃣"\(x"; print(x) """##, diagnostics: [ // TODO: Old parser expected error on line 1: cannot find ')' to match opening '(' in string interpolation // TODO: Old parser expected error on line 1: unterminated string literal DiagnosticSpec(message: "expected expression in variable"), DiagnosticSpec(message: #"extraneous code '"\(x"; print(x)' at top level"#), ] ) } func testUnclosedStringInterpolation6() { AssertParse( ##""" let zzz = 1️⃣"\(x; print(x) """##, diagnostics: [ // TODO: Old parser expected error on line 1: cannot find ')' to match opening '(' in string interpolation // TODO: Old parser expected error on line 1: unterminated string literal DiagnosticSpec(message: "expected expression in variable"), DiagnosticSpec(message: #"extraneous code '"\(x; print(x)' at top level"#), ] ) } func testUnclosedStringInterpolation7() { AssertParse( ##""" let goatedAlbum = 1️⃣"The Life Of \("Pablo" """##, diagnostics: [ // TODO: Old parser expected error on line 1: cannot find ')' to match opening '(' in string interpolation // TODO: Old parser expected error on line 1: unterminated string literal DiagnosticSpec(message: "expected expression in variable"), DiagnosticSpec(message: #"extraneous code '"The Life Of \("Pablo"' at top level"#), ] ) } func testUnclosedStringInterpolation8() { AssertParse( ##""" _ = 1️⃣""" \( """ """##, diagnostics: [ // TODO: Old parser expected error on line 1: unterminated string literal DiagnosticSpec(message: "expected expression"), DiagnosticSpec(message: "extraneous code at top level"), // TODO: Old parser expected error on line 2: cannot find ')' to match opening '(' in string interpolation ] ) } }
apache-2.0
7ead77691537399b74c8fa18afcadd1d
33.603175
114
0.597018
4.977169
false
true
false
false
milseman/swift
test/stdlib/TestNotification.swift
15
1416
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %target-clang %S/Inputs/FoundationBridge/FoundationBridge.m -c -o %t/FoundationBridgeObjC.o -g // RUN: %target-build-swift %s -I %S/Inputs/FoundationBridge/ -Xlinker %t/FoundationBridgeObjC.o -o %t/TestNotification // RUN: %target-run %t/TestNotification > %t.txt // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import FoundationBridgeObjC #if FOUNDATION_XCTEST import XCTest class TestNotificationSuper : XCTestCase { } #else import StdlibUnittest class TestNotificationSuper { } #endif class TestNotification : TestNotificationSuper { func test_unconditionallyBridgeFromObjectiveC() { expectEqual(Notification(name: Notification.Name("")), Notification._unconditionallyBridgeFromObjectiveC(nil)) } } #if !FOUNDATION_XCTEST var NotificationTests = TestSuite("TestNotification") NotificationTests.test("test_unconditionallyBridgeFromObjectiveC") { TestNotification().test_unconditionallyBridgeFromObjectiveC() } runAllTests() #endif
apache-2.0
8dfd271efddcae60c29964d47eddda09
32.714286
132
0.715395
4.538462
false
true
false
false
milseman/swift
stdlib/public/SDK/AVFoundation/AVCapturePhotoOutput.swift
3
3001
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import AVFoundation // Clang module import Foundation #if os(iOS) internal protocol _AVCapturePhotoOutputSwiftNativeTypes { var __supportedFlashModes: [NSNumber] { get } var __availablePhotoPixelFormatTypes: [NSNumber] { get } var __availableRawPhotoPixelFormatTypes: [NSNumber] { get } } extension _AVCapturePhotoOutputSwiftNativeTypes { @available(swift, obsoleted: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var supportedFlashModes: [NSNumber] { return __supportedFlashModes } @available(swift, introduced: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var supportedFlashModes: [AVCaptureDevice.FlashMode] { return __supportedFlashModes.map { AVCaptureDevice.FlashMode(rawValue: $0.intValue)! } } @available(swift, obsoleted: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var availablePhotoPixelFormatTypes: [NSNumber] { return __availablePhotoPixelFormatTypes } @available(swift, introduced: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var availablePhotoPixelFormatTypes: [OSType] { return __availablePhotoPixelFormatTypes.map { $0.uint32Value } as [OSType] } @available(swift, obsoleted: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var availableRawPhotoPixelFormatTypes: [NSNumber] { return __availableRawPhotoPixelFormatTypes } @available(swift, introduced: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var availableRawPhotoPixelFormatTypes: [OSType] { return __availableRawPhotoPixelFormatTypes.map { $0.uint32Value } as [OSType] } } @available(iOS, introduced: 10.0) extension AVCapturePhotoOutput : _AVCapturePhotoOutputSwiftNativeTypes { } internal protocol _AVCapturePhotoSettingsSwiftNativeTypes { var __availablePreviewPhotoPixelFormatTypes: [NSNumber] { get } } extension _AVCapturePhotoSettingsSwiftNativeTypes { @available(swift, obsoleted: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var availablePreviewPhotoPixelFormatTypes: [NSNumber] { return __availablePreviewPhotoPixelFormatTypes } @available(swift, introduced: 4.0) @available(iOS, introduced: 10.0) @nonobjc public var availablePreviewPhotoPixelFormatTypes: [OSType] { return __availablePreviewPhotoPixelFormatTypes.map { $0.uint32Value } as [OSType] } } @available(iOS, introduced: 10.0) extension AVCapturePhotoSettings : _AVCapturePhotoSettingsSwiftNativeTypes { } #endif
apache-2.0
6680d27c29f419c6506ba8454a64b001
29.622449
90
0.710097
4.472429
false
false
false
false
finder39/resumod
ResumodTests/DataManagerTest.swift
1
1437
// // DataManagerTest.swift // Resumod // // Created by Joseph Neuman on 7/23/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import UIKit import XCTest import Resumod class DataManagerTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // Helpers func createUniqueInstance() -> DataManager { return DataManager() } func getSharedInstance() -> DataManager { return DataManager.sharedInstance } // Tests func testSingletonSharedInstanceCreated() { XCTAssertNotNil(getSharedInstance()) } func testSingletonUniqueInstanceCreated() { XCTAssertNotNil(createUniqueInstance()) } func testSingletonReturnsSameSharedInstances() { var s1 = getSharedInstance() var s2 = getSharedInstance() XCTAssertEqual(s1, s2) } func testSingletonSharedInstanceSameAsUniqueInstance() { var s1 = getSharedInstance() var s2 = createUniqueInstance() XCTAssertNotEqual(s1, s2) } func testSingletonReturnsSameUniqueInstances() { var s1 = createUniqueInstance() var s2 = createUniqueInstance() XCTAssertNotEqual(s1, s2) } }
mit
a0a24ca75bd58440326bff22732e9f6a
22.557377
111
0.690327
4.696078
false
true
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Alerts/VersionUpdateAlertDisplaying.swift
1
2200
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import PlatformKit import PlatformUIKit /// Responsible for showing an alert for recommended update and force update if needed. protocol VersionUpdateAlertDisplaying { /** Notifies the user for any updates if necessary. - Parameter updateType: the type of the update */ func displayVersionUpdateAlertIfNeeded(for updateType: WalletOptions.UpdateType) } extension VersionUpdateAlertDisplaying { func displayVersionUpdateAlertIfNeeded(for updateType: WalletOptions.UpdateType) { guard let rawAppVersion = Bundle.applicationVersion, let appVersion = AppVersion(string: rawAppVersion) else { return } switch updateType { case .recommended(latestVersion: let version) where version > appVersion: displayRecommendedUpdateAlert(currentVersion: rawAppVersion) case .forced(latestVersion: let version) where version > appVersion: // Treat `forced` the same way as we treat `recommended` until a full support of force update is implemeneted. displayRecommendedUpdateAlert(currentVersion: rawAppVersion) case .none, .recommended, .forced: break // Arrives at this cases if value `.none` or other cases haven't been satisfied. } } private func displayRecommendedUpdateAlert(currentVersion: String) { let updateNowAction = AlertAction(style: .default(LocalizationConstants.VersionUpdate.updateNowButton)) let alert = AlertModel( headline: LocalizationConstants.VersionUpdate.title, body: LocalizationConstants.VersionUpdate.description, topNote: "\(LocalizationConstants.VersionUpdate.versionPrefix) \(currentVersion)", actions: [updateNowAction], image: UIImage(named: "logo_small"), style: .sheet ) let alertView = AlertView.make(with: alert) { action in switch action.style { case .default: UIApplication.shared.openAppStore() default: break } } alertView.show() } }
lgpl-3.0
a7e567c1db6ae7a35abc867aa5770736
39.722222
122
0.680309
5.350365
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/Backup/Accessibility+Backup.swift
1
1511
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformUIKit extension Accessibility.Identifier { enum Backup { enum IntroScreen { private static let prefix = "BackupFundsIntroScreen." static let body = "\(prefix)body" static let bodyWarning = "\(prefix)body.warning" static let notice = "\(prefix)notice" static let nextButton = "\(prefix)nextButton" } enum RecoveryPhrase { private static let prefix = "RecoveryPhraseScreen." static let titleLabel = "\(prefix)titleLabel" static let subtitleLabel = "\(prefix)subtitleLabel" static let descriptionLabel = "\(prefix)descriptionLabel" static let clipboardButton = "\(prefix)clipboardButton" enum View { private static let prefix = "RecoveryPhraseScreen.View." static let word = "\(prefix)word" } } enum VerifyBackup { private static let prefix = "VerifyBackupScreen." static let descriptionLabel = "\(prefix)descriptionLabel" static let firstNumberLabel = "\(prefix)firstNumberLabel" static let secondNumberLabel = "\(prefix)secondNumberLabel" static let thirdNumberLabel = "\(prefix)thirdNumberLabel" static let errorLabel = "\(prefix)errorLabel" static let verifyBackupButton = "\(prefix)verifyBackupButton" } } }
lgpl-3.0
745b2257f3e8217932e8e161bb638eb5
37.717949
73
0.613907
5.613383
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/ReplyTextView/ReplyBezierView.swift
1
2030
import Foundation import WordPressShared.WPStyleGuide // NOTE: // ReplyBezierView is a helper class, used to render the ReplyTextView bubble // class ReplyBezierView: UIView { @objc var outerColor = WPStyleGuide.Reply.backgroundColor { didSet { setNeedsDisplay() } } @objc var bezierColor = WPStyleGuide.Reply.separatorColor { didSet { setNeedsDisplay() } } @objc var bezierFillColor: UIColor? = nil { didSet { setNeedsDisplay() } } @objc var bezierRadius = CGFloat(5) { didSet { setNeedsDisplay() } } @objc var insets = UIEdgeInsets(top: 8, left: 1, bottom: 8, right: 1) { didSet { setNeedsDisplay() } } // MARK: - Initializers required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupView() } override init(frame: CGRect) { super.init(frame: frame) setupView() } fileprivate func setupView() { // Make sure this is re-drawn on rotation events layer.needsDisplayOnBoundsChange = true } // MARK: - View Methods override func draw(_ rect: CGRect) { // Draw the background, while clipping a rounded rect with the given insets var bezierRect = bounds bezierRect.origin.x += insets.left bezierRect.origin.y += insets.top bezierRect.size.height -= insets.top + insets.bottom bezierRect.size.width -= insets.left + insets.right let bezier = UIBezierPath(roundedRect: bezierRect, cornerRadius: bezierRadius) let outer = UIBezierPath(rect: bounds) if let fillColor = bezierFillColor { fillColor.set() bezier.fill() } bezierColor.set() bezier.stroke() outerColor.set() bezier.append(outer) bezier.usesEvenOddFillRule = true bezier.fill() } }
gpl-2.0
d2e2d16dcad568637043d061508c4fb5
25.710526
99
0.577833
4.799054
false
false
false
false
SirapatBoonyasiwapong/grader
Sources/App/Controllers/LoginController.swift
1
4311
import Vapor import HTTP import AuthProvider import Flash final class LoginController { let homepage = "/classes" let view: ViewRenderer init(_ view: ViewRenderer) { self.view = view } /// Landing /// /// - Parameter request: Request /// - Returns: Response public func landing(request: Request) -> Response { if request.auth.isAuthenticated(User.self) { return Response(redirect: homepage) } else { return Response(redirect: "/login") } } /// Login page public func loginForm(request: Request) throws -> ResponseRepresentable { return try render("Auth/login", for: request, with: view) } /// Login page submission func login(_ request: Request) throws -> ResponseRepresentable { guard let email = request.data["email"]?.string, let password = request.data["password"]?.string else { throw Abort.badRequest } let credentials = Password(username: email, password: password) do { let user = try User.authenticate(credentials) try request.auth.authenticate(user, persist: true) return Response(redirect: homepage) } catch { return Response(redirect: "/login").flash(.error, "Wrong email or password.") } } /// Register page public func registerForm(request: Request) throws -> ResponseRepresentable { return try render("Auth/register", for: request, with: view) } /// Register page submission func register(_ request: Request) throws -> ResponseRepresentable { guard let email = request.data["email"]?.string, let password = request.data["password"]?.string, let name = request.data["name"]?.string else { throw Abort.badRequest } let role = request.data["role"]?.string.flatMap { raw in Int(raw).flatMap({ Role(rawValue: $0) }) } ?? .student let user = User(name: name, username: email, password: password, role: role) try user.save() if let imageUser = request.formData?["image"] { let path = "\(uploadPath)\(user.id!.string!).jpg" _ = save(bytes: imageUser.bytes!, path: path) } let credentials = Password(username: email, password: password) do { let user = try User.authenticate(credentials) try request.auth.authenticate(user, persist: true) return Response(redirect: homepage) } catch { return Response(redirect: "/register").flash(.error, "Something bad happened.") } } func changePasswordForm(request: Request) throws -> ResponseRepresentable { return try render("change-password", [:], for: request, with: view) } func changePassword(request: Request) throws -> ResponseRepresentable { guard let oldPassword = request.data["oldpassword"]?.string, let newPassword = request.data["newpassword"]?.string, let confirmPassword = request.data["confirmpassword"]?.string else { throw Abort.badRequest } let user = request.user! guard let verifier = User.passwordVerifier, let oldHashedPassword = user.hashedPassword, let oldPasswordMatches = try? verifier.verify(password: oldPassword.makeBytes(), matches: oldHashedPassword.makeBytes()) else { throw Abort.serverError } if !oldPasswordMatches { return Response(redirect: "/changepassword").flash(.error, "Incorrect existing password") } if !User.passwordMeetsRequirements(newPassword) { return Response(redirect: "/changepassword").flash(.error, "Password does not meet requirements (4 or more characters)") } if newPassword != confirmPassword { return Response(redirect: "/changepassword").flash(.error, "New password does not match confirmed password") } user.setPassword(newPassword) try user.save() return Response(redirect: "/profile") } }
mit
08b2bd02fa55a7b72e0567330157f346
33.214286
139
0.593598
5.089728
false
false
false
false
wrcj12138aaa/SwiftWeather
Swift Weather/ViewController.swift
1
8407
// // ViewController.swift // Swift Weather // // Created by Jake Lin on 4/06/2014. // Copyright (c) 2014 rushjet. All rights reserved. // import UIKit import CoreLocation import Alamofire import SwiftyJSON import SwiftWeatherService class ViewController: UIViewController, CLLocationManagerDelegate { private let locationManager = CLLocationManager() @IBOutlet var loadingIndicator : UIActivityIndicatorView! = nil @IBOutlet var icon : UIImageView! @IBOutlet var temperature : UILabel! @IBOutlet var loading : UILabel! @IBOutlet var location : UILabel! @IBOutlet weak var time1: UILabel! @IBOutlet weak var time2: UILabel! @IBOutlet weak var time3: UILabel! @IBOutlet weak var time4: UILabel! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! @IBOutlet weak var temp1: UILabel! @IBOutlet weak var temp2: UILabel! @IBOutlet weak var temp3: UILabel! @IBOutlet weak var temp4: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest self.loadingIndicator.startAnimating() let background = UIImage(named: "background.png") self.view.backgroundColor = UIColor(patternImage: background!) let singleFingerTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:") self.view.addGestureRecognizer(singleFingerTap) locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func handleSingleTap(recognizer: UITapGestureRecognizer) { locationManager.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // It maybe a Xcode 6.2 beta Swift compiler's bug, it throws "command failed due to signal segmentation fault 11" error /* func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let service = SwiftWeatherService.WeatherService() service.retrieveForecast(latitude, longitude: longitude, success: { response in println(response) // self.updateUISuccess(response.object!) }, failure:{ response in println(response) println("Error: " + response.error!.localizedDescription) self.loading.text = "Internet appears down!" }) } */ // http://api.openweathermap.org/data/2.5/forecast?lat=30.251772&lon=120.139058 func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let url = "http://api.openweathermap.org/data/2.5/forecast" let params = ["lat":latitude, "lon":longitude] println(params) Alamofire.request(.GET, url, parameters: params) .responseJSON { (request, response, json, error) in if(error != nil) { println("Error: \(error)") println(request) println(response) self.loading.text = "Internet appears down!" } else { println("Success: \(url)") println(request) var json = JSON(json!) self.updateUISuccess(json) } } } func updateUISuccess(json: JSON) { self.loading.text = nil self.loadingIndicator.hidden = true self.loadingIndicator.stopAnimating() let service = SwiftWeatherService.WeatherService() // If we can get the temperature from JSON correctly, we assume the rest of JSON is correct. if let tempResult = json["list"][0]["main"]["temp"].double { // Get country let country = json["city"]["country"].stringValue // Get and convert temperature var temperature = service.convertTemperature(country, temperature: tempResult) self.temperature.text = "\(temperature)°" // Get city name self.location.text = json["city"]["name"].stringValue // Get and set icon let weather = json["list"][0]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: 0, callback: self.updatePictures) // Get forecast for index in 1...4 { println(json["list"][index]) if let tempResult = json["list"][index]["main"]["temp"].double { // Get and convert temperature var temperature = service.convertTemperature(country, temperature: tempResult) if (index==1) { self.temp1.text = "\(temperature)°" } else if (index==2) { self.temp2.text = "\(temperature)°" } else if (index==3) { self.temp3.text = "\(temperature)°" } else if (index==4) { self.temp4.text = "\(temperature)°" } // Get forecast time var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let rawDate = json["list"][index]["dt"].doubleValue let date = NSDate(timeIntervalSince1970: rawDate) let forecastTime = dateFormatter.stringFromDate(date) if (index==1) { self.time1.text = forecastTime } else if (index==2) { self.time2.text = forecastTime } else if (index==3) { self.time3.text = forecastTime } else if (index==4) { self.time4.text = forecastTime } // Get and set icon let weather = json["list"][index]["weather"][0] let condition = weather["id"].intValue var icon = weather["icon"].stringValue var nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: index, callback: self.updatePictures) } else { continue } } } else { self.loading.text = "Weather info is not available!" } } func updatePictures(index: Int, name: String) { if (index==0) { self.icon.image = UIImage(named: name) } if (index==1) { self.image1.image = UIImage(named: name) } if (index==2) { self.image2.image = UIImage(named: name) } if (index==3) { self.image3.image = UIImage(named: name) } if (index==4) { self.image4.image = UIImage(named: name) } } //MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var location:CLLocation = locations[locations.count-1] as! CLLocation if (location.horizontalAccuracy > 0) { self.locationManager.stopUpdatingLocation() println(location.coordinate) updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println(error) self.loading.text = "Can't get your location!" } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
mit
70d6954fce669642687270867ab6b054
37.190909
123
0.556891
5.372123
false
false
false
false
dvor/Antidote
Antidote/SettingsMainController.swift
2
4192
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import Foundation protocol SettingsMainControllerDelegate: class { func settingsMainControllerShowAboutScreen(_ controller: SettingsMainController) func settingsMainControllerShowFaqScreen(_ controller: SettingsMainController) func settingsMainControllerShowAdvancedSettings(_ controller: SettingsMainController) func settingsMainControllerChangeAutodownloadImages(_ controller: SettingsMainController) } class SettingsMainController: StaticTableController { weak var delegate: SettingsMainControllerDelegate? fileprivate let theme: Theme fileprivate let userDefaults = UserDefaultsManager() fileprivate let aboutModel = StaticTableDefaultCellModel() fileprivate let faqModel = StaticTableDefaultCellModel() fileprivate let autodownloadImagesModel = StaticTableInfoCellModel() fileprivate let notificationsModel = StaticTableSwitchCellModel() fileprivate let advancedSettingsModel = StaticTableDefaultCellModel() init(theme: Theme) { self.theme = theme super.init(theme: theme, style: .grouped, model: [ [ autodownloadImagesModel, ], [ notificationsModel, ], [ advancedSettingsModel, ], [ faqModel, aboutModel, ], ], footers: [ String(localized: "settings_autodownload_images_description"), String(localized: "settings_notifications_description"), nil, nil, ]) title = String(localized: "settings_title") updateModels() } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateModels() reloadTableView() } } private extension SettingsMainController{ func updateModels() { aboutModel.value = String(localized: "settings_about") aboutModel.didSelectHandler = showAboutScreen aboutModel.rightImageType = .arrow faqModel.value = String(localized: "settings_faq") faqModel.didSelectHandler = showFaqScreen faqModel.rightImageType = .arrow autodownloadImagesModel.title = String(localized: "settings_autodownload_images") autodownloadImagesModel.showArrow = true autodownloadImagesModel.didSelectHandler = changeAutodownloadImages switch userDefaults.autodownloadImages { case .Never: autodownloadImagesModel.value = String(localized: "settings_never") case .UsingWiFi: autodownloadImagesModel.value = String(localized: "settings_wifi") case .Always: autodownloadImagesModel.value = String(localized: "settings_always") } notificationsModel.title = String(localized: "settings_notifications_message_preview") notificationsModel.on = userDefaults.showNotificationPreview notificationsModel.valueChangedHandler = notificationsValueChanged advancedSettingsModel.value = String(localized: "settings_advanced_settings") advancedSettingsModel.didSelectHandler = showAdvancedSettings advancedSettingsModel.rightImageType = .arrow } func showAboutScreen(_: StaticTableBaseCell) { delegate?.settingsMainControllerShowAboutScreen(self) } func showFaqScreen(_: StaticTableBaseCell) { delegate?.settingsMainControllerShowFaqScreen(self) } func notificationsValueChanged(_ on: Bool) { userDefaults.showNotificationPreview = on } func changeAutodownloadImages(_: StaticTableBaseCell) { delegate?.settingsMainControllerChangeAutodownloadImages(self) } func showAdvancedSettings(_: StaticTableBaseCell) { delegate?.settingsMainControllerShowAdvancedSettings(self) } }
mit
232746d5401c732bccfce94004f4e059
35.137931
94
0.691078
5.988571
false
false
false
false
algolia/algoliasearch-client-swift
Tests/AlgoliaSearchClientTests/Helper/XCTest+Codable.swift
1
2928
// // XCTest+Codable.swift // // // Created by Vladislav Fitc on 11.03.2020. // import Foundation import XCTest @testable import AlgoliaSearchClient func AssertEncodeDecode<T: Codable>(_ value: T, _ rawValue: JSON, file: StaticString = #file, line: UInt = #line) throws { try AssertEncode(value, expected: rawValue, file: file, line: line) try AssertDecode(rawValue, expected: value, file: file, line: line) } func AssertMatch(_ data: Data, _ expected: JSON, file: StaticString = #file, line: UInt = #line) { let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = .swiftAPIClient do { let decoded = try jsonDecoder.decode(JSON.self, from: data) XCTAssertEqual(decoded, expected) } catch let error { XCTFail("Failed decoding: \(error)") } } func AssertDecode<T: Codable & Equatable>(_ input: JSON, expected: T, file: StaticString = #file, line: UInt = #line) throws { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .swiftAPIClient let data = try encoder.encode(input) let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = .swiftAPIClient let decoded = try jsonDecoder.decode(T.self, from: data) XCTAssertEqual(expected, decoded, file: (file), line: line) } func AssertDecode<T: Codable>(_ input: JSON, expected: T, file: StaticString = #file, line: UInt = #line) throws { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .swiftAPIClient let data = try encoder.encode(input) let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = .swiftAPIClient let decoded = try jsonDecoder.decode(T.self, from: data) let decodedJSON = try JSON(decoded) let expectedJSON = try JSON(expected) XCTAssertEqual(expectedJSON, decodedJSON, file: (file), line: line) } @discardableResult func AssertDecode<T: Decodable>(jsonFilename filename: String, expected: T.Type, file: StaticString = #file, line: UInt = #line) throws -> T { let data = try Data(filename: filename) return try JSONDecoder().decode(T.self, from: data) } func AssertEncode<T: Encodable>(_ value: T, expected: JSON, file: StaticString = #file, line: UInt = #line) throws { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .swiftAPIClient let valueData = try encoder.encode(value) let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = .swiftAPIClient let jsonFromValue = try jsonDecoder.decode(JSON.self, from: valueData) XCTAssertEqual(jsonFromValue, expected, file: (file), line: line) } func AssertEquallyEncoded<A: Encodable, B: Encodable>(_ l: A, _ r: B, file: StaticString = #file, line: UInt = #line) throws { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .swiftAPIClient let lData = try encoder.encode(l) let rData = try encoder.encode(r) let decoder = JSONDecoder() try XCTAssertEqual(decoder.decode(JSON.self, from: lData), decoder.decode(JSON.self, from: rData)) }
mit
d84b140f6c0cbc5516169d85a0729783
34.277108
161
0.726093
4
false
false
false
false
PedroTrujilloV/TIY-Assignments
23--Partly-Cloudy-Skies/DudeWhereIsMyCar_Parse/DudeWhereIsMyCar/MapViewController.swift
1
13369
// // ViewController.swift // DudeWhereIsMyCar // // Created by Pedro Trujillo on 11/3/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit import MapKit import CoreLocation //NSCoding contrains let kCitiesArrayKey = "CitiesArray" protocol PopoverViewControllerProtocol { func cityWasChosen(city:City) } class MapViewController: UIViewController,MKMapViewDelegate, UIPopoverPresentationControllerDelegate,PopoverViewControllerProtocol { @IBOutlet var mapView: MKMapView! var anotationsArray = Array<MKPointAnnotation>() var CitiesArray = Array<City>() var source : MKMapItem! var destination: MKMapItem! var drivingDistance:CLLocationDistance! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "Search map reloaded!" mapView.delegate = self //loadAnnotationsData() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if PFUser.currentUser() == nil { print("no currren user logged") performSegueWithIdentifier("unwindShowMapViewControllerSegue", sender: self) } else { loadAnnotationsData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func calculateLineOfSightDistance() { // if anotationsArray.count > 1 //{ let cityALocation = CLLocation(coordinate: anotationsArray[anotationsArray.count-2].coordinate, altitude: 0, horizontalAccuracy: 0, verticalAccuracy: 0, timestamp: NSDate()) let cityBLocation = CLLocation(coordinate: anotationsArray[anotationsArray.count-1].coordinate, altitude: 0, horizontalAccuracy: 0, verticalAccuracy: 0, timestamp: NSDate()) let lineOfSightDistance = cityALocation.distanceFromLocation(cityBLocation) // anotationsArray[anotationsArray.count-1].subtitle = "Distance from \(anotationsArray[anotationsArray.count-2].title!): "+String(format: "%.1f", lineOfSightDistance * 0.00062137)+" miles" ///to print only distance no driving print("Distance from \(anotationsArray[anotationsArray.count-1].title!) is: "+String(format: "%.2f", lineOfSightDistance * 0.00062137)+" miles") // } } func calculateDrivingDistance() { source = MKMapItem(placemark: MKPlacemark(coordinate: anotationsArray[anotationsArray.count-2].coordinate, addressDictionary: nil)) destination = MKMapItem(placemark: MKPlacemark(coordinate: anotationsArray[anotationsArray.count-1].coordinate, addressDictionary: nil)) let directionRequest = MKDirectionsRequest() directionRequest.transportType = MKDirectionsTransportType.Walking directionRequest.source = source directionRequest.destination = destination let directions = MKDirections(request: directionRequest) var routes = [] directions.calculateDirectionsWithCompletionHandler { ( response: MKDirectionsResponse?, error: NSError?) -> Void in print("error: \(error)") //print(response?.routes.first?.distance) // print("Driving Distance from \(self.anotationsArray[self.anotationsArray.count-1].title!) is: "+String(format: "%.2f", (response?.routes.first?.distance)! * 0.00062137)+" miles") self.drivingDistance = response?.routes.first?.distance if error == nil { routes = (response?.routes)! for route in routes { self.mapView.addOverlay((route as! MKRoute).polyline, level: MKOverlayLevel.AboveRoads) } self.anotationsArray[self.anotationsArray.count - 2].subtitle = "Distance to \(self.anotationsArray[self.anotationsArray.count - 1].title!): "+String(format: "%.1f", (self.drivingDistance)! * 0.00062137)+" miles🚶🏻" } else { print("error: "+(error?.localizedDescription)!) self.anotationsArray[self.anotationsArray.count - 2].subtitle = "There is no way to go walking..." } } } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { let polylineRender = MKPolylineRenderer(overlay: overlay) polylineRender.strokeColor = UIColor.magentaColor() polylineRender.lineWidth = 4.0 return polylineRender } func showMapAnnotations() { if anotationsArray.count > 1 { calculateLineOfSightDistance() mapView.camera.altitude *= 2.2 mapView.showAnnotations(anotationsArray, animated: true) //mapView.camera.altitude *= 2 calculateDrivingDistance() } else { self.mapView.showAnnotations(anotationsArray, animated: 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?) { if segue.identifier == "ShowPopoverAddCityViewControllerSegue" { let destVC = segue.destinationViewController as! PopoverAddCityViewController // 1 destVC.popoverPresentationController?.delegate = self // 2 destVC.delegator = self // 3 nescessary to get the value from the popover destVC.preferredContentSize = CGSizeMake(200.0, 65.0) } // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } //MARK: -Protocol function func cityWasChosen(city:City) { print("City Was Chosen: "+city.name) print(" latitudde: " + city.latitude.description) print(" longitude: " + city.longitude.description) CitiesArray.append(city) appendAnnotation(city) //self.mapView.addAnnotations(self.anotationsArray) self.showMapAnnotations() navigationController?.dismissViewControllerAnimated(true, completion: nil)// this thing hides the popover } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } //MARK: Store var functions func loadAnnotationsData() { // if let data = NSUserDefaults.standardUserDefaults().objectForKey(kCitiesArrayKey) as? NSData // { // if let savedAnnotations = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [City] // { // CitiesArray = savedAnnotations // savedCitiesToMapAnnotations() // self.showMapAnnotations() // mapView.camera.altitude *= 2 // } // } let query = PFQuery(className: "cityAnnotationsArray") query.whereKey("username", equalTo: (PFUser.currentUser()?.username)!) query.getFirstObjectInBackgroundWithBlock { (cityAnnotationsArray: PFObject?, error: NSError?) -> Void in if error != nil { print("IT WAS NOT POSIBLE LOAD VALUES FROM DATABASE, PARSE ERROR:") print(error?.localizedDescription) } else if let cityAnnotationsArray = cityAnnotationsArray { self.CitiesArray.removeAll()//be sure that the principal array of city annotations is clean to append the stored cities let savedAnnotations = cityAnnotationsArray["cities_array"] as! NSArray for savedAnnotation in savedAnnotations { if let annotation:NSDictionary = savedAnnotation as? NSDictionary { self.CitiesArray.append(City(name: annotation["name"] as! String, zip: annotation["zipCode"] as! String, lat: (annotation["lat"]?.doubleValue)!, lng: (annotation["lon"]?.doubleValue)!, state: annotation["state"] as! String)) } } self.savedCitiesToMapAnnotations() self.showMapAnnotations() self.mapView.camera.altitude *= 2 } } } func savedCitiesToMapAnnotations() { for city in CitiesArray { print("Stored: "+city.name) appendAnnotation(city) } } func appendAnnotation(city:City) { let annotation = MKPointAnnotation() //annotation.coordinate.latitude = city.latitude //annotation.coordinate.longitude = city.longitude annotation.coordinate = CLLocationCoordinate2DMake(city.latitude, city.longitude) annotation.title = city.name+", "+city.state annotation.subtitle = "Destination 🚗🏁"//"init point" self.anotationsArray.append(annotation) print(" test annotations: "+annotation.coordinate.longitude.description) mapView.addAnnotations(anotationsArray)// here the error // self.showMapAnnotations() } func saveAnnotationsData() { // let cityData = NSKeyedArchiver.archivedDataWithRootObject(CitiesArray) // NSUserDefaults.standardUserDefaults().setObject(cityData, forKey: kCitiesArrayKey) var arrayCitiesPFObject = Array<NSDictionary>() for city in CitiesArray { arrayCitiesPFObject.append(["name":city.name, "zipCode":city.zipCode, "lat":city.latitude, "lon":city.longitude, "state":city.state]) } let query = PFQuery(className: "cityAnnotationsArray") /// there is one array per user query.whereKey("username", equalTo: (PFUser.currentUser()?.username)!) //// so here prepare the condicion to search for that array by user query.getFirstObjectInBackgroundWithBlock // and here we ask for that unique value per user. { (cityAnnotationsArray: PFObject?, error: NSError?) -> Void in if error != nil { print("IT DIDN,T FIND ANY VALUE IN THE DATABASE TO UPDATE AFTER, PARSE ERROR:") print(error?.localizedDescription) let cityAnnotationsArrayNEW = PFObject(className: "cityAnnotationsArray") cityAnnotationsArrayNEW["username"] = PFUser.currentUser()?.username cityAnnotationsArrayNEW["cities_array"] = arrayCitiesPFObject print("SO..") cityAnnotationsArrayNEW.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in if success { print("YAY A > NEW! < ARRAY WAS SAVED!!!") } else { print("IT COULDN'T SAVE ANY NEW VALUE IN THE DATABASE") print(error?.localizedDescription) } } } else if let cityAnnotationsArray = cityAnnotationsArray { cityAnnotationsArray["username"] = PFUser.currentUser()?.username cityAnnotationsArray["cities_array"] = arrayCitiesPFObject cityAnnotationsArray.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in if success { print("YAY THE ARRAY WAS UPDATED!!!") } else { print("IT COULDN'T UPDATE ANY VALUE IN THE DATABASE") print(error?.localizedDescription) } } } } } //MARK: Action Handles @IBAction func saveDataButton(sender: UIBarButtonItem) { saveAnnotationsData() } }
cc0-1.0
527de763a6dffef0ebb0c9bbe383b223
36.728814
235
0.559524
5.967828
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/NSKeyedArchiverHelpers.swift
1
1325
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // @_implementationOnly import CoreFoundation extension CFKeyedArchiverUID : _NSBridgeable { typealias NSType = _NSKeyedArchiverUID internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } } internal class _NSKeyedArchiverUID : NSObject { typealias CFType = CFKeyedArchiverUID internal var _base = _CFInfo(typeID: _CFKeyedArchiverUIDGetTypeID()) internal var value : UInt32 = 0 internal var _cfObject : CFType { return unsafeBitCast(self, to: CFType.self) } override open var _cfTypeID: CFTypeID { return _CFKeyedArchiverUIDGetTypeID() } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject as CFTypeRef?)) } open override func isEqual(_ object: Any?) -> Bool { // no need to compare these? return false } init(value : UInt32) { self.value = value } deinit { _CFDeinit(self) } }
apache-2.0
a25a2eb70387257112ad3da43b6cc364
27.191489
82
0.669434
4.461279
false
false
false
false
nathawes/swift
validation-test/compiler_crashers_2_fixed/rdar62268062.swift
16
799
// RUN: %target-swift-frontend -emit-ir %s public protocol HorseSaddle {} public enum EnglishSaddle : HorseSaddle {} public enum WesternSaddle<A, B> : HorseSaddle {} public protocol Horse { associatedtype Body : Horse associatedtype Saddle: HorseSaddle var body: Body { get } } extension Horse { typealias Saddle = Body.Saddle } public struct DraftHorse<T> : Pony { public typealias Saddle = EnglishSaddle public typealias Body = Never var contents: T } // MARK: - Implementation detail extension Never : Horse { public typealias Saddle = EnglishSaddle public typealias Body = Never public var body: Never { switch self {} } } protocol Pony : Horse where Body == Never {} extension Pony { public var body: Never { fatalError() } }
apache-2.0
ff45b9a3bf6c3ee447d3c5923702f925
18.487805
48
0.685857
4.183246
false
false
false
false
Brightify/ReactantUI
Sources/Tokenizer/Contexts/GlobalContext.swift
1
3966
// // GlobalContext.swift // Tokenizer // // Created by Tadeas Kriz on 01/06/2018. // import Foundation #if canImport(Reactant) import Reactant #else extension Dictionary { public init(keyValueTuples: [(Key, Value)]) { var result: [Key: Value] = [:] for item in keyValueTuples { result[item.0] = item.1 } self = result } } #endif /** * The topmost context (disregarding `ReactantLiveUIWorker.Context` which serves LiveUI purposes only). * Any data to be shared throughout the whole application (bundle) should be located in this context. */ public struct GlobalContext: DataContext { private typealias StyleSheets = [String: [String: Style]] private typealias TemplateSheets = [String: [String: Template]] public var applicationDescription: ApplicationDescription public var currentTheme: ApplicationDescription.ThemeName public var resourceBundle: Bundle? private var styles: StyleSheets = [:] private var templates: TemplateSheets = [:] public init() { self.applicationDescription = ApplicationDescription() self.currentTheme = applicationDescription.defaultTheme self.resourceBundle = Bundle.main self.styles = [:] } public init( applicationDescription: ApplicationDescription, currentTheme: ApplicationDescription.ThemeName, resourceBundle: Bundle?, styleSheetDictionary: [String: StyleGroup]) { self.applicationDescription = applicationDescription self.currentTheme = currentTheme self.resourceBundle = resourceBundle setStyles(from: styleSheetDictionary) } public init( applicationDescription: ApplicationDescription, currentTheme: ApplicationDescription.ThemeName, styleSheets: [StyleGroup]) { self.applicationDescription = applicationDescription self.currentTheme = currentTheme setStyles(from: styleSheets) } public func resolvedStyleName(named styleName: StyleName) -> String { guard case .global(let groupName, let name) = styleName else { fatalError("Global context cannot resolve local style name \(styleName.name).") } return "\(groupName.capitalizingFirstLetter())Styles.\(name)" } public func style(named styleName: StyleName) -> Style? { guard case .global(let groupName, let name) = styleName else { return nil } return styles[groupName]?[name] } public func template(named templateName: TemplateName) -> Template? { guard case .global(let groupName, let name) = templateName else { return nil } return templates[groupName]?[name] } public func themed(image name: String) -> Image? { return applicationDescription.images[theme: currentTheme, item: name] } public func themed(color name: String) -> UIColorPropertyType? { return applicationDescription.colors[theme: currentTheme, item: name] } public func themed(font name: String) -> Font? { return applicationDescription.fonts[theme: currentTheme, item: name] } public mutating func setStyles(from styleSheetDictionary: [String: StyleGroup]) { styles = Dictionary(keyValueTuples: styleSheetDictionary.map { arg in let (key, value) = arg return (key, Dictionary(keyValueTuples: value.styles.map { ($0.name.name, $0) })) }) } public mutating func setStyles(from styleSheets: [StyleGroup]) { let groups = (styleSheets .flatMap { $0.styles } .groupBy { style -> String? in guard case .global(let groupName, _) = style.name else { return nil } return groupName } as [(name: String, styles: [Style])]) .map { ($0.name, Dictionary(keyValueTuples: $0.styles.map { ($0.name.name, $0) })) } styles = Dictionary(keyValueTuples: groups) } }
mit
407020c40c3ac3be2497f25226bff769
33.486957
103
0.663389
4.914498
false
false
false
false
nathawes/swift
test/SILOptimizer/definite_init_value_types_diagnostics.swift
20
1791
// RUN: %target-swift-frontend -emit-sil %s -o /dev/null -verify // RUN: %target-swift-frontend -emit-sil %s -o /dev/null -verify struct EmptyStruct {} struct ValueStruct { var ivar: EmptyStruct // expected-note {{'self.ivar' not initialized}} init() { ivar = EmptyStruct() } init(a: Int) { _ = ivar // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} self.init() } init(c: Bool) { if c { return } self.init() } // expected-error {{'self.init' isn't called on all paths before returning from initializer}} init(d: Bool) { if d { return // expected-error {{return from initializer without initializing all stored properties}} } self = ValueStruct() } } enum ValueEnum { case Dinosaur, Train, Truck init() { self = .Train } init(a: Int) { _ = self // expected-error {{'self' used before 'self.init' call or assignment to 'self'}} self.init() } init(c: Bool) { if c { return } self.init() } // expected-error {{'self.init' isn't called on all paths before returning from initializer}} init(d: Bool) { if d { return } self = ValueEnum() } // expected-error {{'self.init' isn't called on all paths before returning from initializer}} } struct AddressStruct { var ivar: EmptyStruct // expected-note {{'self.ivar' not initialized}} var any: Any? init() { ivar = EmptyStruct(); any = nil } init(c: Bool) { if c { return } self.init() } // expected-error {{'self.init' isn't called on all paths before returning from initializer}} init(d: Bool) { if d { return } self = AddressStruct() } // expected-error {{return from initializer without initializing all stored properties}} }
apache-2.0
6116df29bcd5491e1b5ae311caaad93a
21.111111
101
0.616974
3.700413
false
false
false
false
Logicalshift/SwiftRebound
SwiftRebound/Cocoa/ReactiveView.swift
1
10733
// // ReactiveView.swift // SwiftRebound // // Created by Andrew Hunter on 15/07/2016. // // import Cocoa open class ReactiveView : NSView { /// Trigger for the drawReactive() call fileprivate var _drawTrigger: Optional<() -> ()> = nil; /// Lifetime of the drawReactive() call fileprivate var _drawLifetime: Lifetime? = nil; /// Lifetime of the observer that updates the tracking rectangle fileprivate var _trackingObserverLifetime: Lifetime?; public override init(frame frameRect: NSRect) { super.init(frame: frameRect); setupObservers(); } public required init?(coder: NSCoder) { super.init(coder: coder); setupObservers(); } deinit { _drawLifetime?.done(); _trackingObserverLifetime?.done(); } fileprivate var _isDrawing = false; override open func draw(_ dirtyRect: NSRect) { _isDrawing = true; if let trigger = _drawTrigger { // Call the existing trigger trigger(); } else { // Create a new trigger let (trigger, lifetime) = Binding.trigger({ [unowned self] in self.drawReactive(); }, causeUpdate: { [unowned self] in if !self._isDrawing { self.triggerRedraw(); } else { RunLoop.current.perform(#selector(ReactiveView.triggerRedraw), target: self, argument: nil, order: 0, modes: [RunLoopMode.defaultRunLoopMode]); } }); _drawTrigger = trigger; _drawLifetime = lifetime; trigger(); } _isDrawing = false; } open func triggerRedraw() { self.setNeedsDisplay(self.bounds); } /// /// Should be overridden by subclasses; draws this view /// /// Any SwiftRebound values used here will be monitored and an update will be triggered if they change /// open func drawReactive() { // Implement in subclasses } /// The position of the mouse over this view open var mousePosition: Bound<NSPoint> { get { return _mousePosition; } } fileprivate let _mousePosition = Binding.create(NSPoint(x: 0, y: 0)); /// True if the mouse is over this view open var mouseOver: Bound<Bool> { get { return _mouseOver; } } fileprivate let _mouseOver = Binding.create(false); /// The pressure used by the stylus over this view open var pressure: Bound<Float> { get { return _pressure; } } fileprivate let _pressure = Binding.create(Float(0.0)); /// True if any mouse button is down open var anyMouseDown: Bound<Bool> { get { return _anyMouseDown; } } fileprivate let _anyMouseDown = Binding.create(false); /// True if the left mouse button has been clicked over this view open var leftMouseDown: Bound<Bool> { get { return _leftMouseDown; } } fileprivate let _leftMouseDown = Binding.create(false); /// True if the right mouse button has been clicked over this view open var rightMouseDown: Bound<Bool> { get { return _rightMouseDown; } } fileprivate let _rightMouseDown = Binding.create(false); /// The bounds for this view (bound object) open var reactiveBounds: Bound<NSRect> { get { return _reactiveBounds; } } fileprivate let _reactiveBounds = Binding.create(NSRect()); /// The frame for this view (bound object) open var reactiveFrame: Bound<NSRect> { get { return _reactiveFrame; } } fileprivate let _reactiveFrame = Binding.create(NSRect()); /// /// Updates mouse properties for this view from an event /// fileprivate func updateMouseProperties(_ event: NSEvent) { // Read from the event let newMousePos = convert(event.locationInWindow, from: nil); var leftDown = self.leftMouseDown.value; var rightDown = self.rightMouseDown.value; let pressure = event.pressure; switch (event.type) { case .leftMouseDown: leftDown = true; break; case .leftMouseUp: leftDown = false; break; case .rightMouseDown: rightDown = true; break; case .rightMouseUp: rightDown = false; break; default: break; } let anyDown = leftDown || rightDown; // Update the properties if newMousePos != self.mousePosition.value { self._mousePosition.value = newMousePos; } if leftDown != self.leftMouseDown.value { self._leftMouseDown.value = leftDown; } if rightDown != self.rightMouseDown.value { self._rightMouseDown.value = rightDown; } if anyDown != self.anyMouseDown.value { self._anyMouseDown.value = anyDown; } if pressure != self.pressure.value { self._pressure.value = pressure; } } override open func mouseDown(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func mouseUp(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func mouseDragged(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func rightMouseDown(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func rightMouseUp(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func rightMouseDragged(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func otherMouseDown(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func otherMouseUp(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func otherMouseDragged(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func mouseMoved(with theEvent: NSEvent) { updateMouseProperties(theEvent); } override open func mouseEntered(with theEvent: NSEvent) { if !self._mouseOver.value { self._mouseOver.value = true; self._mousePosition.value = self.convert(theEvent.locationInWindow, from: nil); } } override open func mouseExited(with theEvent: NSEvent) { if _mouseOver.value { _mouseOver.value = false; } } /// /// Updates the frame/bounds values, if they're different /// fileprivate func updateFrameAndBounds() { let newBounds = bounds; let newFrame = frame; if _reactiveBounds.value != newBounds { _reactiveBounds.value = newBounds; } if _reactiveFrame.value != newFrame { _reactiveFrame.value = newFrame; } } override open func setBoundsOrigin(_ newOrigin: NSPoint) { super.setBoundsOrigin(newOrigin); updateFrameAndBounds(); } override open func setBoundsSize(_ newSize: NSSize) { super.setBoundsSize(newSize); updateFrameAndBounds(); } override open func setFrameOrigin(_ newOrigin: NSPoint) { super.setFrameOrigin(newOrigin); updateFrameAndBounds(); } override open func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize); updateFrameAndBounds(); } /// /// Sets up the observers for this view /// fileprivate func setupObservers() { // Computed that works out whether or not we need a tracking rectangle enum NeedsTracking { case keepTracking case needTracking case trackEnterExitOnly case noTracking } let needsTracking = Binding.computed({ [unowned self] () -> NeedsTracking in // If something is observing the mouse position... if self.mousePosition.isBound.value { if !self.anyMouseDown.value { // Need to track the mouse if the mouse isn't clicked (we get positions anyway if it is down) return NeedsTracking.needTracking; } else if !self.mouseOver.isBound.value { // Leave the tracking as what it was if the mouse is clicked return NeedsTracking.keepTracking; } } // If something is observing whether or not we're over the window, then track only enter/exits if self.mouseOver.isBound.value { return NeedsTracking.trackEnterExitOnly; } // Don't need tracking otherwise return NeedsTracking.noTracking; }); // Tracking bounds tracks whether or not we need a tracking rectangle and whether or not it's active let trackingBounds = Binding.computed({ [unowned self] () -> (NSRect, NeedsTracking) in let boundsRect = self.reactiveBounds.value; return (boundsRect, needsTracking.value); }); // Add or remove a tracking rectangle if needsTracking changes or the size of the view changes var tracking: NSTrackingArea?; _trackingObserverLifetime = trackingBounds.observe({ [unowned self] (bounds, needsTracking) in switch needsTracking { case .keepTracking: break; case .needTracking: if let tracking = tracking { self.removeTrackingArea(tracking); } let newTracking = NSTrackingArea(rect: bounds, options: NSTrackingAreaOptions.mouseMoved.union(NSTrackingAreaOptions.mouseEnteredAndExited).union(NSTrackingAreaOptions.activeInKeyWindow), owner: self, userInfo: nil); tracking = newTracking; self.addTrackingArea(newTracking); break; case .trackEnterExitOnly: if let tracking = tracking { self.removeTrackingArea(tracking); } let newTracking = NSTrackingArea(rect: bounds, options: NSTrackingAreaOptions.mouseEnteredAndExited.union(NSTrackingAreaOptions.activeInKeyWindow), owner: self, userInfo: nil); tracking = newTracking; self.addTrackingArea(newTracking); break; case .noTracking: if let realTracking = tracking { self.removeTrackingArea(realTracking); tracking = nil; } } }); } }
apache-2.0
4996670b882ada2ae00f7e0efa4a0938
36.659649
232
0.598528
5.281988
false
false
false
false
haranicle/AlcatrazTour
Pods/OAuthSwift/OAuthSwift/String+OAuthSwift.swift
1
3309
// // String+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension String { internal func indexOf(sub: String) -> Int? { var pos: Int? if let range = self.rangeOfString(sub) { if !range.isEmpty { pos = self.startIndex.distanceTo(range.startIndex) } } return pos } internal subscript (r: Range<Int>) -> String { get { let startIndex = self.startIndex.advancedBy(r.startIndex) let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex) return self[Range(start: startIndex, end: endIndex)] } } func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String { let originalString: NSString = self let customAllowedSet = NSCharacterSet(charactersInString:":/?&=;+!@#$()',*=\"#%/<>?@\\^`{|}").invertedSet let escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) return escapedString! as String } func parametersFromQueryString() -> Dictionary<String, String> { var parameters = Dictionary<String, String>() let scanner = NSScanner(string: self) var key: NSString? var value: NSString? while !scanner.atEnd { key = nil scanner.scanUpToString("=", intoString: &key) scanner.scanString("=", intoString: nil) value = nil scanner.scanUpToString("&", intoString: &value) scanner.scanString("&", intoString: nil) if (key != nil && value != nil) { parameters.updateValue(value! as String, forKey: key! as String) } } return parameters } var safeStringByRemovingPercentEncoding: String { return self.stringByRemovingPercentEncoding ?? self } func split(s:String)->[String]{ if s.isEmpty{ var x=[String]() for y in self.characters{ x.append(String(y)) } return x } return self.componentsSeparatedByString(s) } func trim()->String{ return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } func has(s:String)->Bool{ if (self.rangeOfString(s) != nil) { return true }else{ return false } } func hasBegin(s:String)->Bool{ if self.hasPrefix(s) { return true }else{ return false } } func hasEnd(s:String)->Bool{ if self.hasSuffix(s) { return true }else{ return false } } func length()->Int{ return self.utf16.count } func size()->Int{ return self.utf16.count } func `repeat`(times: Int) -> String{ var result = "" for _ in 0..<times { result += self } return result } func reverse()-> String{ let s=Array(self.split("").reverse()) var x="" for y in s{ x+=y } return x } }
mit
81082aa1ffa0c631c8e29e2908945660
25.261905
114
0.540042
4.866176
false
false
false
false
attheodo/ATHMultiSelectionSegmentedControl
ATHMultiSelectionSegmentedControl/Classes/ATHMultiSelectionControlSegmentButton.swift
1
3112
// // ATHMultiSelectionControlSegmentButton.swift // Pods // // Created by Athanasios Theodoridis on 06/06/16. // // import Foundation import UIKit import QuartzCore internal class ATHMultiSelectionControlSegmentButton: UIButton { // MARK: - Private Properties fileprivate var _isButtonSelected: Bool = false fileprivate var _isButtonEnabled: Bool = true // MARK: - Public Properties /// Whether the button is currently in a selected state internal var isButtonSelected: Bool { return _isButtonSelected } /// Whether the button internal var isButtonEnabled: Bool { return _isButtonEnabled } override var isHighlighted: Bool { didSet { // ignore highlighting if button is disabled if !_isButtonEnabled { return } if isHighlighted { backgroundColor = tintColor.withAlphaComponent(0.1) } else { if _isButtonSelected { backgroundColor = tintColor } else { backgroundColor = UIColor.clear } } } } // MARK: - Initialisers override init(frame: CGRect) { super.init(frame: frame) _configureButton() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Private Methods /** Configures the initial style of the button - Sets title color - Clears background color - Adds a border of 0.5 px */ fileprivate func _configureButton() { setTitleColor(tintColor, for: .normal) backgroundColor = UIColor.clear layer.borderWidth = 0.5 layer.borderColor = tintColor.cgColor } /** Styles the button as selected */ fileprivate func _setSelectedState() { layer.borderColor = backgroundColor?.cgColor backgroundColor = tintColor setTitleColor(UIColor.white, for: .normal) } /** Styles the button as deselected */ fileprivate func _setDeselectedState() { backgroundColor = UIColor.clear setTitleColor(tintColor, for: .normal) layer.borderColor = tintColor.cgColor } // MARK: - Public Methods /** Toggles the receiver's selection state and styles it appropriately */ internal func setButtonSelected(_ isSelected: Bool) { _isButtonSelected = isSelected _isButtonSelected ? _setSelectedState() : _setDeselectedState() } /** Toggles the receiver's enabled/disabled state and styles it appropriately */ internal func setButtonEnabled(_ isEnabled: Bool) { if isEnabled { _setDeselectedState() } else { setTitleColor(UIColor.gray, for: .normal) backgroundColor = UIColor.clear } _isButtonEnabled = isEnabled } }
mit
331061a8f127b09f5969deb624d74ed1
23.124031
78
0.572301
5.567084
false
false
false
false
Moya/Moya
Sources/Moya/Plugins/AccessTokenPlugin.swift
1
2712
import Foundation // MARK: - AccessTokenAuthorizable /// A protocol for controlling the behavior of `AccessTokenPlugin`. public protocol AccessTokenAuthorizable { /// Represents the authorization header to use for requests. var authorizationType: AuthorizationType? { get } } // MARK: - AuthorizationType /// An enum representing the header to use with an `AccessTokenPlugin` public enum AuthorizationType { /// The `"Basic"` header. case basic /// The `"Bearer"` header. case bearer /// Custom header implementation. case custom(String) public var value: String { switch self { case .basic: return "Basic" case .bearer: return "Bearer" case .custom(let customValue): return customValue } } } extension AuthorizationType: Equatable { public static func == (lhs: AuthorizationType, rhs: AuthorizationType) -> Bool { switch (lhs, rhs) { case (.basic, .basic), (.bearer, .bearer): return true case let (.custom(value1), .custom(value2)): return value1 == value2 default: return false } } } // MARK: - AccessTokenPlugin /** A plugin for adding basic or bearer-type authorization headers to requests. Example: ``` Authorization: Basic <token> Authorization: Bearer <token> Authorization: <Сustom> <token> ``` */ public struct AccessTokenPlugin: PluginType { public typealias TokenClosure = (TargetType) -> String /// A closure returning the access token to be applied in the header. public let tokenClosure: TokenClosure /** Initialize a new `AccessTokenPlugin`. - parameters: - tokenClosure: A closure returning the token to be applied in the pattern `Authorization: <AuthorizationType> <token>` */ public init(tokenClosure: @escaping TokenClosure) { self.tokenClosure = tokenClosure } /** Prepare a request by adding an authorization header if necessary. - parameters: - request: The request to modify. - target: The target of the request. - returns: The modified `URLRequest`. */ public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { guard let authorizable = target as? AccessTokenAuthorizable, let authorizationType = authorizable.authorizationType else { return request } var request = request let realTarget = (target as? MultiTarget)?.target ?? target let authValue = authorizationType.value + " " + tokenClosure(realTarget) request.addValue(authValue, forHTTPHeaderField: "Authorization") return request } }
mit
ee719d534d5e6df309968ae244169ca4
25.841584
124
0.656584
4.823843
false
false
false
false
bryzinski/skype-ios-app-sdk-samples
GuestMeetingJoin/SfBDemo/Utils.swift
1
3469
//+---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // Module name: Utils.swift //---------------------------------------------------------------- import Foundation import UIKit import SkypeForBusiness var dateFormatter: NSDateFormatter { let formatter = NSDateFormatter() formatter.dateStyle = .NoStyle formatter.timeStyle = .ShortStyle return formatter } class KeyValueChange { private let change: [String : AnyObject] init(change: [String : AnyObject]) { self.change = change } var kind: NSKeyValueChange? { guard let value = change[NSKeyValueChangeKindKey] as? NSNumber else { return nil } return NSKeyValueChange(rawValue: value.unsignedLongValue) } var indexSet: NSIndexSet? { return change[NSKeyValueChangeIndexesKey] as? NSIndexSet } var new: AnyObject? { return change[NSKeyValueChangeNewKey] } } extension NSIndexSet { var indexPaths: [NSIndexPath] { var indexPaths: [NSIndexPath] = [] for index in self { indexPaths.append(NSIndexPath(forRow: index, inSection: 0)) } return indexPaths } } extension UITableView { func updateRowsWithChange(change: KeyValueChange) { switch change.kind! { case .Setting: reloadData() case .Insertion: insertRowsAtIndexPaths(change.indexSet!.indexPaths, withRowAnimation: .Automatic) case .Removal: deleteRowsAtIndexPaths(change.indexSet!.indexPaths, withRowAnimation: .Automatic) case .Replacement: reloadRowsAtIndexPaths(change.indexSet!.indexPaths, withRowAnimation: .Automatic) } } } extension SfBAlertType: CustomStringConvertible { public var description: String { switch (self) { case .SignIn: return "SignIn" case .ParticipantMute: return "ParticipantMute" case .ParticipantUnmute: return "ParticipantUnmute" case .Messaging: return "Messaging" case .ConferenceIsRecording: return "ConferenceIsRecording" case .ConferenceUnexpectedDisconnect: return "ConferenceUnexpectedDisconnect" default: return "Type \(self.rawValue)" } } } extension SfBAlertLevel: CustomStringConvertible { public var description: String { switch (self) { case .Error: return "Error" case .Warning: return "Warning" case .Info: return "Info" } } } extension SfBAlert { func show() { UIAlertView(title: "\(level): \(type)", message: "\(error)", delegate: nil, cancelButtonTitle: "OK").show() } } extension SfBMessageStatus { public var backgroundColor: UIColor { switch (self) { case .Failed: return UIColor.redColor() case .Pending: return UIColor.yellowColor() case .Succeeded: return UIColor.clearColor() } } } extension SfBAudioServiceMuteState: CustomStringConvertible { public var description: String { switch self { case .Unmuted: return "Unmuted" case .Muted: return "Muted" case .Unmuting: return "Unmuting" } } }
mit
ffd6d17ee0ecb44a120ec4249925aafa
22.126667
93
0.583742
5.162202
false
false
false
false
iOSDevLog/iOSDevLog
201. UI Test/Swift/ListerOSX/ColorPaletteView.swift
1
5063
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `ColorPaletteView` class is a view that allows the user to select a color defined in the `List.Color` enumeration. */ import Cocoa import ListerKit import QuartzCore /// Delegate protocol to let other objects know about changes to the selected color. @objc protocol ColorPaletteViewDelegate { func colorPaletteViewDidChangeSelectedColor(colorPaletteView: ColorPaletteView) } class ColorPaletteView: NSView { // MARK: Types struct ButtonTitles { static let expanded = "▶" static let collapsed = "◀" } // MARK: Properties @IBOutlet weak var delegate: ColorPaletteViewDelegate! @IBOutlet weak var grayButton: NSButton! @IBOutlet weak var blueButton: NSButton! @IBOutlet weak var greenButton: NSButton! @IBOutlet weak var yellowButton: NSButton! @IBOutlet weak var orangeButton: NSButton! @IBOutlet weak var redButton: NSButton! @IBOutlet weak var overlayButton: NSButton! @IBOutlet weak var overlayView: NSView! @IBOutlet weak var overlayLayoutConstraint: NSLayoutConstraint! var selectedColor = List.Color.Gray { didSet { overlayView.layer!.backgroundColor = selectedColor.colorValue.CGColor } } // Set in IB and saved to use for showing / hiding the overlay. var initialLayoutConstraintConstant: CGFloat = 0 // The overlay is expanded initially in the storyboard. var isOverlayExpanded = true // MARK: View Life Cycle override func awakeFromNib() { super.awakeFromNib() // Make the background of the color palette view white. layer = CALayer() layer!.backgroundColor = NSColor.whiteColor().CGColor // Make the overlay view color (i.e. `selectedColor`) gray by default. overlayView.layer = CALayer() selectedColor = .Gray initialLayoutConstraintConstant = overlayLayoutConstraint.constant hideOverlayWithSelectedColor(selectedColor, animated: false) // Set the background color for each button. let buttons = [grayButton, blueButton, greenButton, yellowButton, orangeButton, redButton] for button in buttons { button.layer = CALayer() let buttonColor = List.Color(rawValue: button.tag)! button.layer!.backgroundColor = buttonColor.colorValue.CGColor } } // MARK: IBActions @IBAction func colorButtonClicked(sender: NSButton) { // The tag for each color was set in the storyboard for each button based // on the type of color. let selectedColor = List.Color(rawValue: sender.tag)! hideOverlayWithSelectedColor(selectedColor, animated: true) } @IBAction func colorToggleButtonClicked(sender: NSButton) { if isOverlayExpanded { hideOverlayWithSelectedColor(selectedColor, animated: true) } else { showOverlay() } } // MARK: Convenience func showOverlay() { setLayoutConstant(initialLayoutConstraintConstant, buttonTitle: ButtonTitles.expanded, newSelectedColor: selectedColor, animated: true, expanded: true) } func hideOverlayWithSelectedColor(selectedColor: List.Color, animated: Bool) { setLayoutConstant(0, buttonTitle: ButtonTitles.collapsed, newSelectedColor: selectedColor, animated: animated, expanded: false) } func setLayoutConstant(layoutConstant: CGFloat, buttonTitle: String, newSelectedColor: List.Color, animated: Bool, expanded: Bool) { // Check to see if the selected colors are different. We only want to trigger the colorPaletteViewDidChangeSelectedColor() // delegate call if the colors have changed. let colorsAreDifferent = selectedColor != newSelectedColor isOverlayExpanded = expanded if animated { NSAnimationContext.runAnimationGroup({ context in // Customize the animation parameters. context.duration = 0.25 context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) self.overlayLayoutConstraint.animator().constant = layoutConstant self.overlayButton.animator().title = buttonTitle self.selectedColor = newSelectedColor }, completionHandler: { if colorsAreDifferent { self.delegate?.colorPaletteViewDidChangeSelectedColor(self) } }) } else { overlayLayoutConstraint.constant = layoutConstant overlayButton.title = buttonTitle selectedColor = newSelectedColor if colorsAreDifferent { delegate?.colorPaletteViewDidChangeSelectedColor(self) } } } }
mit
e8421afdd612513e9d01a684d7c45934
32.939597
159
0.65968
5.612653
false
false
false
false
firebase/FirebaseUI-iOS
samples/swift/FirebaseUI-demo-swift/Samples/StorageViewController.swift
1
4082
// // Copyright (c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import FirebaseStorageUI class StorageViewController: UIViewController { @IBOutlet fileprivate var imageView: UIImageView! @IBOutlet fileprivate var textField: UITextField! fileprivate var storageRef = Storage.storage().reference() override func viewDidLoad() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Clear Cache", style: .plain, target: self, action: #selector(flushCache)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.textField.autocorrectionType = .no self.textField.autocapitalizationType = .none self.imageView.contentMode = .scaleAspectFit // Notification boilerplate to handle keyboard appearance/disappearance NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @IBAction fileprivate func loadButtonPressed(_ sender: AnyObject) { self.imageView.image = nil guard let text = self.textField.text else { return } guard let url = URL(string: text) else { return } self.storageRef = Storage.storage().reference(withPath: url.path) self.imageView.sd_setImage(with: self.storageRef, maxImageSize: 10000000, placeholderImage: nil, options: [.progressiveLoad]) { (image, error, cacheType, storageRef) in if let error = error { print("Error loading image: \(error)") } } } @objc private func flushCache() { SDImageCache.shared.clearMemory() SDImageCache.shared.clearDisk() } // MARK: Keyboard boilerplate /// Used to shift textfield up when the keyboard appears. @IBOutlet fileprivate var bottomConstraint: NSLayoutConstraint! @objc fileprivate func keyboardWillShow(_ notification: Notification) { let userInfo = (notification as NSNotification).userInfo! let endFrameValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue let endHeight = endFrameValue.cgRectValue.size.height self.bottomConstraint.constant = endHeight let curve = UIView.AnimationCurve(rawValue: userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int)! let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double UIView.setAnimationCurve(curve) UIView.animate(withDuration: duration, animations: { self.view.layoutIfNeeded() }) } @objc fileprivate func keyboardWillHide(_ notification: Notification) { self.bottomConstraint.constant = 0 let userInfo = (notification as NSNotification).userInfo! let curve = UIView.AnimationCurve(rawValue: userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! Int)! let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double UIView.setAnimationCurve(curve) UIView.animate(withDuration: duration, animations: { self.view.layoutIfNeeded() }) } }
apache-2.0
9afd4f024c7a600273a2a557477a42ea
38.25
142
0.675404
5.399471
false
false
false
false
drodriguez56/lotifyMeSwift
LotifyMe/NewPickDateViewController.swift
1
7521
// // NewPickDateViewController.swift // LotifyMe // // Created by Daniel K. Chan on 1/25/15. // Copyright (c) 2015 LocoLabs. All rights reserved. // import UIKit class NewPickDateViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var submitButton: UIButton! // DATE PICKER @IBOutlet weak var datePicker: UIPickerView! let datePickerData = [ [Int](0...11), [Int](0...30), [Int](0...10) ] func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 3 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return datePickerData[component].count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return "\(dateConvert[component][datePickerData[component][row]])" } func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { var dateGlobalCharset = NSCharacterSet(charactersInString: "-") var dateGlobalAsArrayBeforeTranslate = dateGlobal.componentsSeparatedByCharactersInSet(dateGlobalCharset) var int = Int() if component == 2 { // Year int = datePickerData[component][row] + 2010 dateGlobalAsArrayBeforeTranslate[0] = "\(int)" } else if component == 1 { // Day int = datePickerData[component][row] + 1 dateGlobalAsArrayBeforeTranslate[2] = "\(int)" } else if component == 0 { // Month int = datePickerData[component][row] + 1 dateGlobalAsArrayBeforeTranslate[1] = "\(int)" } var year = dateGlobalAsArrayBeforeTranslate[0].toInt()! var month = dateGlobalAsArrayBeforeTranslate[1].toInt()! var day = dateGlobalAsArrayBeforeTranslate[2].toInt()! dateGlobal = "\(year)-\(month)-\(day)" println("dateGlobal dial has been moved, with a new value of \(dateGlobal)") // Report } // FORMAT PICKER VIEW func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView { let titleData = "\(dateConvert[component][datePickerData[component][row]])" let myTitle = NSAttributedString( string: titleData, attributes: [ NSFontAttributeName:UIFont( name: "HelveticaNeue", size: 23.0 )!, NSForegroundColorAttributeName:UIColor.whiteColor() ] ) let pickerLabel = UILabel() pickerLabel.textAlignment = .Center pickerLabel.backgroundColor = UIColor( red: 0.3, green: 0.7, blue: 0.95, alpha: 0.5) pickerLabel.attributedText = myTitle return pickerLabel } func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { if component == 0 { return 160 } else if component == 1 { return 70 } else { return 110 } } // NEXT BUTTON ACTION @IBAction func submitButton(sender: AnyObject) { captureValues() } // CAPTURE VALUES FUNCTION func captureValues() { // var dateString = "\(datePicker.date)" as NSString // dateGlobal = dateString.substringWithRange(NSRange(location: 0, length: 10)) // Report moved to viewWillDisappear() call } // DETECT SWIPE TO CONTINUE func leftSwiped() { performSegueWithIdentifier( "NewPickDateSegueToNewPickNumberViewController", sender: self ) } func rightSwiped() { navigationController?.popViewControllerAnimated(true) } // SETUP override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = layerBackgroundColorGlobal datePicker.delegate = self datePicker.dataSource = self if dateGlobal == "" { var dateString = "\(NSDate())" as NSString dateGlobal = dateString.substringWithRange(NSRange(location: 0, length: 10)) } var dateGlobalCharset = NSCharacterSet(charactersInString: "-") var dateGlobalAsTempArray = dateGlobal.componentsSeparatedByCharactersInSet(dateGlobalCharset) for (var i = 0; i < 3; i++) { if i == 0 { // Month datePicker.selectRow( dateGlobalAsTempArray[1].toInt()! - 1, inComponent: i, animated: true ) } else if i == 1 { // Day datePicker.selectRow( dateGlobalAsTempArray[2].toInt()! - 1, inComponent: i, animated: true ) } else if i == 2 { // Year datePicker.selectRow( dateGlobalAsTempArray[0].toInt()! - 2010, inComponent: i, animated: true ) } } // Layer Styling self.view.layer.borderColor = layerBorderColorGlobal self.view.layer.borderWidth = layerBorderWidth // Next Button Styling submitButton.titleLabel!.font = UIFont(name: "HelveticaNeue", size: 19) submitButton.setTitleColor(buttonTextColorGlobal, forState: UIControlState.Normal) submitButton.backgroundColor = mediumBlue submitButton.layer.cornerRadius = buttonCornerRadius submitButton.layer.borderColor = buttonBorderColorGlobal submitButton.layer.borderWidth = buttonBorderWidth // Nav Bar Styling self.navigationItem.title = "Date" // Swipe to Continue let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("leftSwiped")) swipeLeft.direction = UISwipeGestureRecognizerDirection.Left self.view.addGestureRecognizer(swipeLeft) let swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("rightSwiped")) swipeRight.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(swipeRight) } override func viewWillDisappear(animated: Bool) { captureValues() println("dateGlobal has been saved with a value of \(dateGlobal)") // Report } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
3d334b8c7bd6f7de1941f3f82d35b983
35.687805
138
0.531711
6.2675
false
false
false
false
mperovic/my41
my41cx-ios/Keys.swift
1
21725
// // Keys.swift // my41 // // Created by Miroslav Perovic on 6.1.21.. // Copyright © 2021 iPera. All rights reserved. // import Foundation import SwiftUI import UIKit final class Keys: ObservableObject { @Published var modeKeys: [CalcKey] = [ CalcKey(shiftText: getModeAttributedString(from: ""), upperText: getModeAttributedString(from: "ON"), keyCode: 128), CalcKey(shiftText: getModeAttributedString(from: ""), upperText: getModeAttributedString(from: "USER"), keyCode: 100), CalcKey(shiftText: getModeAttributedString(from: ""), upperText: getModeAttributedString(from: "PRGM"), keyCode: 84), CalcKey(shiftText: getModeAttributedString(from: ""), upperText: getModeAttributedString(from: "ALPHA"), keyCode: 68) ] @Published var keys1: [CalcKey] = [ CalcKey(shiftText: sigmaMinus, upperText: sigmaPlus, lowerText: getLowerAttributedString(from: "A"), keyCode: 0), CalcKey(shiftText: yx, upperText: oneX, lowerText: getLowerAttributedString(from: "B"), keyCode: 1), CalcKey(shiftText: xSquare, upperText: rootX, lowerText: getLowerAttributedString(from: "C"), keyCode: 2), CalcKey(shiftText: tenX, upperText: log,lowerText: getLowerAttributedString(from: "D"), keyCode: 3), CalcKey(shiftText: eX, upperText: ln, lowerText: getLowerAttributedString(from: "E"), keyCode: 4) ] @Published var keys2: [CalcKey] = [ CalcKey(shiftText: clSigma, upperText: xexy, lowerText: getLowerAttributedString(from: "F"), keyCode: 16), CalcKey(shiftText: percent, upperText: rArrow,lowerText: getLowerAttributedString(from: "G"), keyCode: 17), CalcKey(shiftText: sin1, upperText: sin, lowerText: getLowerAttributedString(from: "H"), keyCode: 18), CalcKey(shiftText: cos1, upperText: cos, lowerText: getLowerAttributedString(from: "I"), keyCode: 19), CalcKey(shiftText: tan1, upperText: tan, lowerText: getLowerAttributedString(from: "J"), keyCode: 20) ] @Published var keys3: [CalcKey] = [ CalcKey(shiftText: getModeAttributedString(from: ""), upperText: getModeAttributedString(from: ""), lowerText: nil, shiftButton: true, keyCode: 32), CalcKey(shiftText: asn, upperText: xeq, lowerText: getLowerAttributedString(from: "K"), keyCode: 33), CalcKey(shiftText: lbl, upperText: sto, lowerText: getLowerAttributedString(from: "L"), keyCode: 34), CalcKey(shiftText: gto, upperText: rcl, lowerText: getLowerAttributedString(from: "M"), keyCode: 35), CalcKey(shiftText: bst, upperText: sst, lowerText: getModeAttributedString(from: ""), keyCode: 36) ] @Published var keys4: [CalcKey] = [ CalcKey(shiftText: catalog, upperText: enter, lowerText: getLowerAttributedString(from: "N"), enter: true, keyCode: 48), CalcKey(shiftText: isg, upperText: chs, lowerText: getLowerAttributedString(from: "O"), keyCode: 50), CalcKey(shiftText: rtn, upperText: eex, lowerText: getLowerAttributedString(from: "P"), keyCode: 51), CalcKey(shiftText: clxa, upperText: back, lowerText: getLowerAttributedString(from: ""), keyCode: 52) ] @Published var keys5: [CalcKey] = [ CalcKey(shiftText: xeqy, upperText: minus, lowerText: getLowerAttributedString(from: "Q"), keyCode: 64), CalcKey(shiftText: sf, upperText: seven, lowerText: getLowerAttributedString(from: "R"), keyCode: 65), CalcKey(shiftText: cf, upperText: eight, lowerText: getLowerAttributedString(from: "S"), keyCode: 66), CalcKey(shiftText: fsQuestionMark, upperText: nine, lowerText: getLowerAttributedString(from: "T"), keyCode: 67) ] @Published var keys6: [CalcKey] = [ CalcKey(shiftText: xlessthany, upperText: plus, lowerText: getLowerAttributedString(from: "U"), keyCode: 80), CalcKey(shiftText: beep, upperText: four, lowerText: getLowerAttributedString(from: "V"), keyCode: 81), CalcKey(shiftText: ptor, upperText: five, lowerText: getLowerAttributedString(from: "W"), keyCode: 82), CalcKey(shiftText: rtop, upperText: six, lowerText: getLowerAttributedString(from: "X"), keyCode: 83) ] @Published var keys7: [CalcKey] = [ CalcKey(shiftText: xgreaterthany, upperText: multiply, lowerText: getLowerAttributedString(from: "Y"), keyCode: 96), CalcKey(shiftText: fix, upperText: one, lowerText: getLowerAttributedString(from: "Z"), keyCode: 97), CalcKey(shiftText: sci, upperText: two, lowerText: getLowerAttributedString(from: "="), keyCode: 98), CalcKey(shiftText: eng, upperText: three, lowerText: getLowerAttributedString(from: "?"), keyCode: 99) ] @Published var keys8: [CalcKey] = [ CalcKey(shiftText: xeqzero, upperText: divide, lowerText: getLowerAttributedString(from: ":"), keyCode: 112), CalcKey(shiftText: pi, upperText: zero, lowerText: getLowerAttributedString(from: "SPACE"), keyCode: 113), CalcKey(shiftText: lastX, upperText: dot, lowerText: getLowerAttributedString(from: "\u{0313}"), keyCode: 114), CalcKey(shiftText: view, upperText: rs, lowerText: getLowerAttributedString(from: ""), keyCode: 115) ] static private let yRatio = UIScreen.main.bounds.size.height / 800.0 static func getHelvetica(_ size: CGFloat) -> UIFont { return UIFont(name: "Helvetica", size: size * yRatio)! } static func getTimesNewRoman(_ size: CGFloat) -> UIFont { return UIFont(name: "Times New Roman", size: size * yRatio)! } static func getModeAttributedString(from text: String) -> NSAttributedString { let onString = mutableAttributedStringFromString(text, color: .white) let onAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getHelvetica(12.0), ] onString.addAttributes(convertToNSAttributedStringKeyDictionary(onAttributes as [String : Any]), range: NSMakeRange(0, text.count)) return onString } static func getLowerAttributedString(from text: String) -> NSAttributedString { let lowerText = mutableAttributedStringFromString(text, color: UIColor(Color.lowerColor), font: getHelvetica(text == "SPACE" ? 13.0 : 15.0)) if text.count == 1 { let lowerTextAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getHelvetica(11.0 * yRatio), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 1 ] as [String : Any] lowerText.addAttributes(convertToNSAttributedStringKeyDictionary(lowerTextAttributes), range: NSMakeRange(0, text.count)) } return lowerText } static var sigmaMinus: NSAttributedString { let sigmaMinusString = mutableAttributedStringFromString("Σ-", color: UIColor(Color.shiftColor)) let sigmaMinusAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getHelvetica(15.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 1 ] as [String : Any] sigmaMinusString.addAttributes(convertToNSAttributedStringKeyDictionary(sigmaMinusAttributes), range: NSMakeRange(1, 1)) return sigmaMinusString } static var sigmaPlus: NSAttributedString { let sigmaPlusString = mutableAttributedStringFromString("Σ+", color: .white) let sigmaPlusAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 1 ] sigmaPlusString.addAttributes(convertToNSAttributedStringKeyDictionary(sigmaPlusAttributes), range: NSMakeRange(1, 1)) return sigmaPlusString } static var yx: NSAttributedString { let yxString = mutableAttributedStringFromString("yx", color: UIColor(Color.shiftColor)) let yxAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(12.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 4 ] as [String : Any] yxString.addAttributes(convertToNSAttributedStringKeyDictionary(yxAttributes), range: NSMakeRange(1, 1)) return yxString } static var oneX: NSAttributedString { let oneXString = mutableAttributedStringFromString("1/x", color: .white) let oneXAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(12.0), ] oneXString.addAttributes(convertToNSAttributedStringKeyDictionary(oneXAttributes), range: NSMakeRange(2, 1)) return oneXString } static var xSquare: NSAttributedString { let xSquareString = mutableAttributedStringFromString("x\u{00B2}", color: UIColor(Color.shiftColor)) let xSquareAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(14.0), ] xSquareString.addAttributes(convertToNSAttributedStringKeyDictionary(xSquareAttributes), range: NSMakeRange(0, 2)) return xSquareString } static var rootX: NSAttributedString { let rootXString = mutableAttributedStringFromString("√x", color: .white) let rootXAttributes2 = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(12.0), ] rootXString.addAttributes(convertToNSAttributedStringKeyDictionary(rootXAttributes2), range: NSMakeRange(1, 1)) return rootXString } static var tenX: NSAttributedString { let tenXString = mutableAttributedStringFromString("10x", color: UIColor(Color.shiftColor)) let tenXAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(12.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 4 ] as [String : Any] tenXString.addAttributes(convertToNSAttributedStringKeyDictionary(tenXAttributes), range: NSMakeRange(2, 1)) return tenXString } static var log: NSAttributedString { mutableAttributedStringFromString("LOG", color: .white) } static var eX: NSAttributedString { let eXString = mutableAttributedStringFromString("ex", color: UIColor(Color.shiftColor)) let eXAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(12.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 4 ] as [String : Any] eXString.addAttributes(convertToNSAttributedStringKeyDictionary(eXAttributes), range: NSMakeRange(1, 1)) let eXAttributes2 = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getHelvetica(14.0) ] eXString.addAttributes(convertToNSAttributedStringKeyDictionary(eXAttributes2), range: NSMakeRange(0, 1)) return eXString } static var ln: NSAttributedString { mutableAttributedStringFromString("LN", color: .white) } static var clSigma: NSAttributedString { mutableAttributedStringFromString("CLΣ", color: UIColor(.shiftColor)) } static var xexy: NSAttributedString { let xexYString = mutableAttributedStringFromString("x≷y", color: .white) let xexYAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(16.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 1 ] as [String : Any] xexYString.addAttributes(convertToNSAttributedStringKeyDictionary(xexYAttributes), range: NSMakeRange(0, 3)) return xexYString } static var percent: NSAttributedString { mutableAttributedStringFromString("%", color: UIColor(.shiftColor)) } static var rArrow: NSAttributedString { mutableAttributedStringFromString("R↓", color: .white) } static var sin1: NSAttributedString { let sin1String = mutableAttributedStringFromString("SIN-1", color: UIColor(.shiftColor)) let sinAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(11.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 4 ] as [String : Any] sin1String.addAttributes(convertToNSAttributedStringKeyDictionary(sinAttributes), range: NSMakeRange(3, 2)) return sin1String } static var sin: NSAttributedString { mutableAttributedStringFromString("SIN", color: .white) } static var cos1: NSAttributedString { let cos1String = mutableAttributedStringFromString("COS-1", color: UIColor(.shiftColor)) let cosAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(11.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 4 ] as [String : Any] cos1String.addAttributes(convertToNSAttributedStringKeyDictionary(cosAttributes), range: NSMakeRange(3, 2)) return cos1String } static var cos: NSAttributedString { mutableAttributedStringFromString("COS", color: .white) } static var tan1: NSAttributedString { let tan1String = mutableAttributedStringFromString("TAN-1", color: UIColor(.shiftColor)) let tanAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(11.0), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): 4 ] as [String : Any] tan1String.addAttributes(convertToNSAttributedStringKeyDictionary(tanAttributes), range: NSMakeRange(3, 2)) return tan1String } static var tan: NSAttributedString { mutableAttributedStringFromString("TAN", color: .white) } static var asn: NSAttributedString { mutableAttributedStringFromString("ASN", color: UIColor(.shiftColor)) } static var xeq: NSAttributedString { mutableAttributedStringFromString("XEQ", color: .white) } static var lbl: NSAttributedString { mutableAttributedStringFromString("LBL", color: UIColor(.shiftColor)) } static var sto: NSAttributedString { mutableAttributedStringFromString("STO", color: .white) } static var gto: NSAttributedString { mutableAttributedStringFromString("GTO", color: UIColor(.shiftColor)) } static var rcl: NSAttributedString { mutableAttributedStringFromString("RCL", color: .white) } static var bst: NSAttributedString { mutableAttributedStringFromString("BST", color: UIColor(.shiftColor)) } static var sst: NSAttributedString { mutableAttributedStringFromString("SST", color: .white) } static var catalog: NSAttributedString { mutableAttributedStringFromString("CATALOG", color: UIColor(.shiftColor)) } static var enter: NSAttributedString { mutableAttributedStringFromString("ENTER ↑", color: .white) } static var isg: NSAttributedString { mutableAttributedStringFromString("ISG", color: UIColor(.shiftColor)) } static var chs: NSAttributedString { mutableAttributedStringFromString("CHS", color: .white) } static var rtn: NSAttributedString { mutableAttributedStringFromString("RTN", color: UIColor(.shiftColor)) } static var eex: NSAttributedString { mutableAttributedStringFromString("EEX", color: .white) } static var clxa: NSAttributedString { let clxaString = mutableAttributedStringFromString("CL X/A", color: UIColor(.shiftColor)) let clxaAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(13.0) ] clxaString.addAttributes(convertToNSAttributedStringKeyDictionary(clxaAttributes), range: NSMakeRange(3, 1)) return clxaString } static var back: NSAttributedString { mutableAttributedStringFromString("←", color: .white) } static var xeqy: NSAttributedString { let xeqyString = mutableAttributedStringFromString("x=y ?", color: UIColor(.shiftColor)) let xeqyAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(16.0) ] xeqyString.addAttributes(convertToNSAttributedStringKeyDictionary(xeqyAttributes), range: NSMakeRange(0, 3)) return xeqyString } static var minus: NSAttributedString { mutableAttributedStringFromString("━", color: .white, font: getHelvetica(11.0)) } static var sf: NSAttributedString { mutableAttributedStringFromString("SF", color: UIColor(.shiftColor)) } static var seven: NSAttributedString { mutableAttributedStringFromString("7", color: .white) } static var cf: NSAttributedString { mutableAttributedStringFromString("CF", color: UIColor(.shiftColor)) } static var eight: NSAttributedString { mutableAttributedStringFromString("8", color: .white) } static var fsQuestionMark: NSAttributedString { mutableAttributedStringFromString("FS?", color: UIColor(.shiftColor)) } static var nine: NSAttributedString { mutableAttributedStringFromString("9", color: .white) } static var xlessthany: NSAttributedString { let xlessthanyString = mutableAttributedStringFromString("x≤y ?", color: UIColor(.shiftColor)) let xlessthanyAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(15) ] xlessthanyString.addAttributes(convertToNSAttributedStringKeyDictionary(xlessthanyAttributes), range: NSMakeRange(0, 3)) return xlessthanyString } static var plus: NSAttributedString { mutableAttributedStringFromString("╋", color: .white, font: getHelvetica(9)) } static var beep: NSAttributedString { mutableAttributedStringFromString("BEEP", color: UIColor(.shiftColor)) } static var four: NSAttributedString { mutableAttributedStringFromString("4", color: .white) } static var ptor: NSAttributedString { mutableAttributedStringFromString("P→R", color: UIColor(.shiftColor)) } static var five: NSAttributedString { mutableAttributedStringFromString("5", color: .white) } static var rtop: NSAttributedString { mutableAttributedStringFromString("R→P", color: UIColor(.shiftColor)) } static var six: NSAttributedString { mutableAttributedStringFromString("6", color: .white) } static var xgreaterthany: NSAttributedString { let xgreaterthanyString = mutableAttributedStringFromString("x>y ?", color: UIColor(.shiftColor)) let xgreaterthanyAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(15), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): -1 ] as [String : Any] xgreaterthanyString.addAttributes(convertToNSAttributedStringKeyDictionary(xgreaterthanyAttributes), range: NSMakeRange(0, 3)) return xgreaterthanyString } static var multiply: NSAttributedString { mutableAttributedStringFromString("×", color: .white, font: getHelvetica(17)) } static var fix: NSAttributedString { mutableAttributedStringFromString("FIX", color: UIColor(.shiftColor)) } static var one: NSAttributedString { mutableAttributedStringFromString("1", color: .white) } static var sci: NSAttributedString { mutableAttributedStringFromString("SCI", color: UIColor(.shiftColor)) } static var two: NSAttributedString { mutableAttributedStringFromString("2", color: .white) } static var eng: NSAttributedString { mutableAttributedStringFromString("ENG", color: UIColor(.shiftColor)) } static var three: NSAttributedString { mutableAttributedStringFromString("3", color: .white) } static var xeqzero: NSAttributedString { let xeq0String = mutableAttributedStringFromString("x=0 ?", color: UIColor(.shiftColor)) let xeq0Attributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(15), convertFromNSAttributedStringKey(NSAttributedString.Key.baselineOffset): -1 ] as [String : Any] xeq0String.addAttributes(convertToNSAttributedStringKeyDictionary(xeq0Attributes), range: NSMakeRange(0, 5)) return xeq0String } static var divide: NSAttributedString { mutableAttributedStringFromString("÷", color: .white, font: getHelvetica(17)) } static var pi: NSAttributedString { mutableAttributedStringFromString("π", color: UIColor(.shiftColor), font: getTimesNewRoman(17 * yRatio)) } static var zero: NSAttributedString { mutableAttributedStringFromString("0", color: .white) } static var lastX: NSAttributedString { let lastxString = mutableAttributedStringFromString("LAST X", color: UIColor(.shiftColor)) let lastxAttributes = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : getTimesNewRoman(15) ] lastxString.addAttributes(convertToNSAttributedStringKeyDictionary(lastxAttributes), range: NSMakeRange(5, 1)) return lastxString } static var dot: NSAttributedString { mutableAttributedStringFromString("•", color: .white, font: getHelvetica(17)) } static var view: NSAttributedString { mutableAttributedStringFromString("VIEW", color: UIColor(.shiftColor)) } static var rs: NSAttributedString { mutableAttributedStringFromString("R/S", color: .white, font: getHelvetica(14)) } static func mutableAttributedStringFromString(_ aString: String, color: UIColor?, font: UIFont = getHelvetica(13)) -> NSMutableAttributedString { let textStyle: NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle textStyle.alignment = NSTextAlignment.center if let aColor = color { return NSMutableAttributedString( string: aString, attributes: convertToOptionalNSAttributedStringKeyDictionary([ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : font, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): aColor, convertFromNSAttributedStringKey(NSAttributedString.Key.paragraphStyle): textStyle ]) ) } else { return NSMutableAttributedString( string: aString, attributes: convertToOptionalNSAttributedStringKeyDictionary([ convertFromNSAttributedStringKey(NSAttributedString.Key.font) : font, convertFromNSAttributedStringKey(NSAttributedString.Key.paragraphStyle): textStyle ]) ) } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToNSAttributedStringKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.Key: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
bsd-3-clause
4e0e93c7723c902b9092700ff5b4ca1c
48.085973
150
0.777747
4.70527
false
false
false
false
AppLovin/iOS-SDK-Demo
Swift Demo App/iOS-SDK-Demo/ALDemoInterstitialBasicIntegrationViewController.swift
1
2219
// // ALDemoInterstitialSingleInstanceViewController.swift // iOS-SDK-Demo // // Created by Thomas So on 9/25/15. // Copyright © 2015 AppLovin. All rights reserved. // import UIKit class ALDemoInterstitialBasicIntegrationViewController : ALDemoBaseViewController { @IBOutlet weak var showButton: UIBarButtonItem! // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Alternatively, you can create an instance of `ALInterstitialAd`, but you must store it in a strong property ALInterstitialAd.shared().adLoadDelegate = self ALInterstitialAd.shared().adDisplayDelegate = self ALInterstitialAd.shared().adVideoPlaybackDelegate = self } // MARK: IB Action Methods @IBAction func showInterstitial(_ sender: AnyObject!) { self.showButton.isEnabled = false log("Showing...") ALInterstitialAd.shared().show() } } extension ALDemoInterstitialBasicIntegrationViewController : ALAdLoadDelegate { func adService(_ adService: ALAdService, didLoad ad: ALAd) { log("Interstitial Loaded") self.showButton.isEnabled = true } func adService(_ adService: ALAdService, didFailToLoadAdWithError code: Int32) { // Look at ALErrorCodes.h for list of error codes log("Interstitial failed to load with error code \(code)") self.showButton.isEnabled = true } } extension ALDemoInterstitialBasicIntegrationViewController : ALAdDisplayDelegate { func ad(_ ad: ALAd, wasDisplayedIn view: UIView) { log("Interstitial Displayed") } func ad(_ ad: ALAd, wasHiddenIn view: UIView) { log("Interstitial Dismissed") } func ad(_ ad: ALAd, wasClickedIn view: UIView) { log("Interstitial Clicked") } } extension ALDemoInterstitialBasicIntegrationViewController : ALAdVideoPlaybackDelegate { func videoPlaybackBegan(in ad: ALAd) { log("Video Started") } func videoPlaybackEnded(in ad: ALAd, atPlaybackPercent percentPlayed: NSNumber, fullyWatched wasFullyWatched: Bool) { log("Video Ended") } }
mit
eeaaf12457d1cd6ce54b591a08d77880
25.404762
119
0.66817
4.699153
false
false
false
false
github/Nimble
Nimble/DSL.swift
77
2204
import Foundation // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func expect<T>(expression: @autoclosure () -> T?, file: String = __FILE__, line: UInt = __LINE__) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line))) } // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func expect<T>(file: String = __FILE__, line: UInt = __LINE__, expression: () -> T?) -> Expectation<T> { return Expectation( expression: Expression( expression: expression, location: SourceLocation(file: file, line: line))) } // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func waitUntil(#timeout: NSTimeInterval, action: (() -> Void) -> Void, file: String = __FILE__, line: UInt = __LINE__) -> Void { var completed = false dispatch_async(dispatch_get_main_queue()) { action() { completed = true } } let passed = _pollBlock(pollInterval: 0.01, timeoutInterval: timeout) { return completed } if !passed { let pluralize = (timeout == 1 ? "" : "s") fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line) } } // Begins an assertion on a given value. // file: and line: can be omitted to default to the current line this function is called on. public func waitUntil(action: (() -> Void) -> Void, file: String = __FILE__, line: UInt = __LINE__) -> Void { waitUntil(timeout: 1, action, file: file, line: line) } public func fail(message: String, #location: SourceLocation) { CurrentAssertionHandler.assert(false, message: message, location: location) } public func fail(message: String, file: String = __FILE__, line: UInt = __LINE__) { fail(message, location: SourceLocation(file: file, line: line)) } public func fail(file: String = __FILE__, line: UInt = __LINE__) { fail("fail() always fails") }
apache-2.0
a5d1d75158b909e98bcd643493fd17c3
40.603774
135
0.650181
3.985533
false
false
false
false
UroborosStudios/UOHelpers
UOHelpers/UIViewExtensions.swift
1
1754
// // UIViewExtensions.swift // UOHelpers // // Created by Jonathan Silva on 04/05/17. // Copyright © 2017 Uroboros Studios. All rights reserved. // import Foundation import UIKit public extension UIView { open var circle: UIView { self.layer.cornerRadius = self.frame.size.width/2 self.clipsToBounds = true return self } // USE this extension class when circular edges doesn't apply correctly in UIView // Normaly apply to larger sizes of UIView open var title: UIView { self.layer.cornerRadius = 10 self.clipsToBounds = true return self } open func getViewsByTag(tag:Int) -> Array<UIView?>{ return subviews.filter { ($0 as UIView).tag == tag } as [UIView] } } public extension UIViewController { open func showAlertOk(title t:String?,message m:String,okTitle:String, callback: ((UIAlertAction)->())?) { let alert = UIAlertController(title: t, message: m, preferredStyle: .alert) let ok = UIAlertAction(title: okTitle, style: .default, handler: callback) alert.addAction(ok) self.present(alert, animated: true, completion: nil) } open func showAlertOptions(title t:String?,message m:String,okTitle:String,cancelTitle:String, Okcallback: ((UIAlertAction)->())?,Cancelcallback: ((UIAlertAction)->())?) { let alert = UIAlertController(title: t, message: m, preferredStyle: .alert) let ok = UIAlertAction(title: okTitle, style: .default, handler: Okcallback) let cancel = UIAlertAction(title: cancelTitle, style: .default, handler: Cancelcallback) alert.addAction(ok) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } }
mit
126b7c3181ed1894f3575c22f173f283
35.520833
175
0.668568
4.254854
false
false
false
false
nua-schroers/mvvm-frp
20_Basic-App/MatchGame/MatchGameUITests/MatchGameUITests.swift
1
2052
// // MatchGameUITests.swift // MatchGameUITests // // Created by Dr. Wolfram Schroers on 6/21/16. // Copyright © 2016 Wolfram Schroers. All rights reserved. // import XCTest class MatchGameUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() } // MARK: UI workflow test /// Play and win a single game with default settings. func testPlayGame() { let app = XCUIApplication() // Assert we are on the main screen and the game is on. XCTAssertTrue(app.buttons["More Info"].exists) XCTAssertTrue(app.staticTexts["Removing the last match loses the game, use the info button to change settings."].exists) XCTAssertTrue(app.staticTexts["18 matches"].exists) // Play a game. let take1Button = app.buttons["Take 1"] let take3Button = app.buttons["Take 3"] XCTAssertTrue(take3Button.exists) XCTAssertTrue(take1Button.exists) XCTAssertTrue(take3Button.isEnabled) XCTAssertTrue(take1Button.isEnabled) take3Button.tap() take3Button.tap() take3Button.tap() take3Button.tap() XCTAssertFalse(take3Button.isEnabled) // Verify that "Take 3" is now disabled. XCTAssertTrue(take1Button.isEnabled) // But "Take 1" is still enabled. take1Button.tap() // End the game. let newGameButton = app.alerts["The game is over"].buttons["New game"] XCTAssertTrue(newGameButton.exists) newGameButton.tap() // Assert that a new game has started. XCTAssertTrue(app.staticTexts["18 matches"].exists) } }
mit
19bea53aad2bfc570cf7bce3c7197af8
33.762712
131
0.651877
4.537611
false
true
false
false
Josscii/iOS-Demos
ScrollTableViewDemo/ScrollTableViewDemo/ViewController.swift
1
3099
// // ViewController.swift // ScrollTableViewDemo // // Created by Josscii on 2017/10/1. // Copyright © 2017年 Josscii. All rights reserved. // import UIKit class ViewController: UIViewController { var scrollView1: UIScrollView! var tableView1: UITableView! var tableView2: UITableView! var headerView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. edgesForExtendedLayout = .init(rawValue: 0) headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 290)) headerView.backgroundColor = UIColor.green headerView.layer.zPosition = 1 view.addSubview(headerView) scrollView1 = UIScrollView(frame: view.bounds) scrollView1.contentSize = CGSize(width: view.bounds.width * 2, height: view.bounds.height) scrollView1.backgroundColor = .red scrollView1.delegate = self scrollView1.showsVerticalScrollIndicator = false scrollView1.bounces = false scrollView1.isPagingEnabled = true scrollView1.contentInsetAdjustmentBehavior = .never view.addSubview(scrollView1) tableView1 = UITableView(frame: view.bounds) tableView1.delegate = self tableView1.dataSource = self tableView1.contentInsetAdjustmentBehavior = .never // tableView1.showsVerticalScrollIndicator = false scrollView1.addSubview(tableView1) tableView2 = UITableView(frame: view.bounds) tableView2.contentInsetAdjustmentBehavior = .never tableView2.frame.origin.x = view.bounds.width tableView2.delegate = self tableView2.dataSource = self // tableView2.showsVerticalScrollIndicator = false scrollView1.addSubview(tableView2) tableView1.contentInset.top = 290 tableView2.contentInset.top = 290 tableView1.scrollIndicatorInsets.top = 300 tableView2.scrollIndicatorInsets.top = 300 } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView != scrollView1 { headerView.frame.origin.y = max(-(290 + scrollView.contentOffset.y), -250) if scrollView.contentOffset.y < -40 { if scrollView == tableView1 { tableView2.contentOffset = scrollView.contentOffset } if scrollView == tableView2 { tableView1.contentOffset = scrollView.contentOffset } } } } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "row \(indexPath.row)" return cell } }
mit
afb4ab293ebf750473756807e3ff8f83
33.021978
100
0.640181
5.274276
false
false
false
false
kay-kim/stitch-examples
todo/ios/MongoDBSample/Classes/Controllers/Authentication/EmailAuthViewController.swift
1
2716
// // EmailAuthViewController.swift // MongoDBSample // // import UIKit import StitchCore protocol EmailAuthViewControllerDelegate { func emailAuthViewControllerDidPressCloseEmail() } enum EmailAuthOperationType { case confirmEmail(token: String, tokenId: String) case resetPassword(token: String, tokenId: String) } class EmailAuthViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var infoLabel: UILabel! var stitchClient: StitchClient? var delegate: EmailAuthViewControllerDelegate? var operationType: EmailAuthOperationType? override func viewDidLoad() { super.viewDidLoad() if let operationType = operationType { switch operationType { case .confirmEmail(let token, let tokenId): confirmEmail(token: token, tokenId: tokenId) case .resetPassword(let token, let tokenId): resetPassword(token: token, tokenId: tokenId) } } else { activityIndicator.isHidden = true infoLabel.text = "Missing operation to perform" } } func confirmEmail(token: String, tokenId: String) { /* activityIndicator.isHidden = false infoLabel.text = "Confirming Email..." stitchClient?.emailConfirm(token: token, tokenId: tokenId) .response(completionHandler: { [weak self] (result) in self?.activityIndicator.isHidden = true switch result { case .success: self?.infoLabel.text = "Email Confirmed!" break case .failure(let error): self?.infoLabel.text = error.localizedDescription break } })*/ } func resetPassword(token: String, tokenId: String) { /* activityIndicator.isHidden = false infoLabel.text = "Resetting Password..." stitchClient?.resetPassword(token: token, tokenId: tokenId) .response(completionHandler: { [weak self] (result) in self?.activityIndicator.isHidden = true switch result { case .success: self?.infoLabel.text = "Password Reset!" break case .failure(let error): self?.infoLabel.text = error.localizedDescription break } }) */ } //MARK: - Actions @IBAction func closeButtonPressed(_ sender: Any) { delegate?.emailAuthViewControllerDidPressCloseEmail() } }
apache-2.0
da5371619ff4a05bef550e8d028bad06
28.521739
69
0.58542
5.520325
false
false
false
false
AngeloStavrow/Rewatch
Rewatch/Episode/EpisodeViewController.swift
1
6774
// // EpisodeViewController.swift // Rewatch // // Created by Romain Pouclet on 2015-10-28. // Copyright © 2015 Perfectly-Cooked. All rights reserved. // import UIKit import ReactiveCocoa import AVFoundation import Swifter class EpisodeWrapper: EpisodeViewData { typealias Element = StoredEpisode let wrapped: Element init(wrapped: Element) { self.wrapped = wrapped } var showName : String { get { return wrapped.show?.name ?? "" } } var title : String { get { return wrapped.title ?? "" } } var season : String { get { return String(wrapped.season) } } var number : String { get { return String(wrapped.episode) } } var description : String { get { return wrapped.summary ?? "" } } } class EpisodeViewController: UIViewController { let themes: [Theme] = [WhiteTheme(), RedTheme(), DarkTheme()] private var checkInitialContentToken: dispatch_once_t = 0 var episodeView: EpisodeView { get { return view as! EpisodeView } } lazy private(set) var randomSound: AVAudioPlayer? = { guard let path = NSBundle.mainBundle().pathForResource("pop_drip", ofType: "aif") else { return nil } let url = NSURL.fileURLWithPath(path) return try? AVAudioPlayer(contentsOfURL: url) }() lazy private(set) var shakeSignal = Signal<(), NoError>.pipe() let client: Client let persistenceController: PersistenceController let analyticsController: AnalyticsController var episodes: [StoredEpisode] = [] init(client: Client, persistenceController: PersistenceController, analyticsController: AnalyticsController) { self.client = client self.persistenceController = persistenceController self.analyticsController = analyticsController super.init(nibName: nil, bundle: nil) title = "REWATCH" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let leftButton = UIButton(type: .Custom) leftButton.setImage(UIImage(named: "Hamburger"), forState: .Normal) leftButton.addTarget(self, action: Selector("didTapCreditsButton:"), forControlEvents: .TouchUpInside) leftButton.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton) let rightButton = UIButton(type: .Custom) rightButton.setImage(UIImage(named: "Options"), forState: .Normal) rightButton.addTarget(self, action: Selector("didTapSettingsButton:"), forControlEvents: .TouchUpInside) rightButton.sizeToFit() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) episodeView.actionDelegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) episodes = persistenceController.allEpisodes() if episodes.count == 0 { dispatch_once(&checkInitialContentToken, { () -> Void in let downloadViewController = DownloadViewController(client: self.client, downloadController: DownloadController(client: self.client, persistenceController: self.persistenceController)) let navigation = UINavigationController(rootViewController: downloadViewController) self.rootViewController?.presentViewController(navigation, animated: true, completion: nil) }) } else { becomeFirstResponder() } } override func canBecomeFirstResponder() -> Bool { return true } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { if motion == .MotionShake { shakeSignal.1.sendNext(()) fetchRandomItem() } } func fetchRandomItem() { guard episodes.count > 0 else { return } let index = Int(arc4random_uniform(UInt32(episodes.count))) let randomEpisode = episodes[index] presentEpisode(randomEpisode) } func presentEpisode(randomEpisode: StoredEpisode) { let episode = EpisodeWrapper(wrapped: randomEpisode) self.randomSound?.play() episodeView.theme = themes[Int(arc4random_uniform(UInt32(themes.count)))] episodeView.episode = episode episodeView.pictureState = .Ready episodeView.shakeView.hidden = true episodeView.episodeContainerView.hidden = false episodeView.episodeImageView.hidden = false client.fetchPictureForEpisodeId(String(randomEpisode.id)) .takeUntil(shakeSignal.0) .on(started: { UIScheduler().schedule({ () -> () in self.episodeView.pictureState = .Loading }) }, completed: { self.analyticsController.trackEvent(.Shake) }) .flatMap(FlattenStrategy.Latest, transform: { (image) -> SignalProducer<(UIImage, UIImage), NSError> in return SignalProducer(value: (image, convertToBlackAndWhite(image))) }) .observeOn(UIScheduler()) .startWithNext { (image) -> () in self.episodeView.pictureState = .Loaded(image: image.0, bnwImage: image.1) } } func didTapSettingsButton(button: UIButton) { analyticsController.trackEvent(.Settings) let settings = UINavigationController(rootViewController: SettingsViewController(client: client, persistenceController: persistenceController, analyticsController: analyticsController, completion: { () -> Void in self.dismissViewControllerAnimated(true, completion: nil) })) presentViewController(settings, animated: true, completion: nil) } func didTapCreditsButton(button: UIButton) { rootViewController?.toogleCredits() } } extension EpisodeViewController: EpisodeViewDelegate { func didTapShareButton() { guard let episode = episodeView.episode as? EpisodeWrapper else { return } let activities: [UIActivity]? if NSUserDefaults.standardUserDefaults().boolForKey("enabled_deeplinking") { activities = [GenerateDeeplinkActivity()] } else { activities = nil } let activity = UIActivityViewController(activityItems: [String(format: NSLocalizedString("SHARING_MESSAGE", comment: "Sharing message"), "\(episode.showName) - \(episode.title)"), episode.wrapped], applicationActivities: activities) presentViewController(activity, animated: true, completion: nil) } }
mit
080b7678d2b90a297e1388a8415c8350
37.265537
240
0.652444
5.291406
false
false
false
false
gregomni/swift
test/Distributed/distributed_actor_accessor_thunks_64bit.swift
2
27804
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -module-name distributed_actor_accessors -emit-irgen -disable-availability-checking -I %t 2>&1 %s | %IRGenFileCheck %s -check-prefix CHECK-%target-import-type // UNSUPPORTED: back_deploy_concurrency // REQUIRES: concurrency // REQUIRES: distributed // REQUIRES: CPU=x86_64 || CPU=arm64 // UNSUPPORTED: OS=windows-msvc import Distributed import FakeDistributedActorSystems @available(SwiftStdlib 5.5, *) typealias DefaultDistributedActorSystem = FakeActorSystem enum SimpleE : Codable { case a } enum E : Codable { case a, b, c } enum IndirectE : Codable { case empty indirect case test(_: Int) } final class Obj : Codable, Sendable { let x: Int init(x: Int) { self.x = x } } struct LargeStruct : Codable { var a: Int var b: Int var c: String var d: Double } @available(SwiftStdlib 5.7, *) public distributed actor MyActor { distributed func simple1(_: Int) { } // `String` would be a direct result as a struct type distributed func simple2(_: Int) -> String { return "" } // `String` is an object that gets exploded into two parameters distributed func simple3(_: String) -> Int { return 42 } // Enum with a single case are special because they have an empty // native schema so they are dropped from parameters/result. distributed func single_case_enum(_ e: SimpleE) -> SimpleE { return e } distributed func with_indirect_enums(_: IndirectE, _: Int) -> IndirectE { return .empty } // Combination of multiple arguments, reference type and indirect result // // Note: Tuple types cannot be used here is either position because they // cannot conform to protocols. distributed func complex(_: [Int], _: Obj, _: String?, _: LargeStruct) -> LargeStruct { fatalError() } // Combination of direct and indirect arguments involving generic arguments. distributed func genericArgs<T: Codable, U: Codable>(_: T, _: [U]) { } } @available(SwiftStdlib 5.7, *) public distributed actor MyOtherActor { distributed func empty() { } } /// ---> Thunk and distributed method accessor for `simple1` /// Let's make sure that accessor loads the data from the buffer and calls expected accessor // CHECK: define hidden swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTE" // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTETF"(%swift.context* swiftasync %0, %swift.opaque* nocapture %1, i8* %2, i8* %3, {{.*}}, %T27distributed_actor_accessors7MyActorC* [[ACTOR:%.*]], %swift.type* [[DECODER_TYPE:%.*]], i8** [[DECODER_PROTOCOL_WITNESS:%.*]]) /// Read the current offset and cast an element to `Int` // CHECK: [[DECODER_PTR:%*]] = bitcast %swift.opaque* %1 to %T27FakeDistributedActorSystems0A17InvocationDecoderC** // CHECK-NEXT: [[DECODER:%.*]] = load %T27FakeDistributedActorSystems0A17InvocationDecoderC*, %T27FakeDistributedActorSystems0A17InvocationDecoderC** [[DECODER_PTR]] // CHECK-NEXT: [[DECODER_METADATA:%.*]] = bitcast %swift.type* [[DECODER_TYPE]] to void (%swift.opaque*, %swift.type*, i8**, i8**, %T27FakeDistributedActorSystems0A17InvocationDecoderC*, %swift.error**)** // CHECK-NEXT: [[DECODE_NEXT_ARG_REF:%.*]] = getelementptr inbounds void (%swift.opaque*, %swift.type*, i8**, i8**, %T27FakeDistributedActorSystems0A17InvocationDecoderC*, %swift.error**)*, void (%swift.opaque*, %swift.type*, i8**, i8**, %T27FakeDistributedActorSystems0A17InvocationDecoderC*, %swift.error**)** [[DECODER_METADATA]], i64 {{29|32}} // CHECK-NEXT: [[DECODE_NEXT_ARG:%.*]] = load void (%swift.opaque*, %swift.type*, i8**, i8**, %T27FakeDistributedActorSystems0A17InvocationDecoderC*, %swift.error**)*, void (%swift.opaque*, %swift.type*, i8**, i8**, %T27FakeDistributedActorSystems0A17InvocationDecoderC*, %swift.error**)** [[DECODE_NEXT_ARG_REF]] // CHECK-NEXT: [[ARG_TYPES:%.*]] = bitcast i8* %2 to %swift.type** // CHECK: [[ARG_0_TYPE_LOC:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[ARG_TYPES]], i64 0 // CHECK-NEXT: %arg_type = load %swift.type*, %swift.type** [[ARG_0_TYPE_LOC]] // CHECK: %size = load i64, i64* {{.*}} // CHECK: [[ARG_0_SIZE_ADJ:%.*]] = add i64 %size, 15 // CHECK-NEXT: [[ARG_0_SIZE:%.*]] = and i64 [[ARG_0_SIZE_ADJ]], -16 // CHECK-NEXT: [[ARG_0_VALUE_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_0_SIZE]]) // CHECK-NEXT: [[ARG_0_RES_SLOT:%.*]] = bitcast i8* [[ARG_0_VALUE_BUF]] to %swift.opaque* // CHECK-NEXT: [[ENCODABLE_WITNESS:%.*]] = call i8** @swift_conformsToProtocol(%swift.type* %arg_type, %swift.protocol* @"$sSeMp") // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[ENCODABLE_WITNESS]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %missing-witness, label [[CONT:%.*]] // CHECK: missing-witness: // CHECK-NEXT: call void @llvm.trap() // CHECK-NEXT: unreachable // CHECK: [[DECODABLE_WITNESS:%.*]] = call i8** @swift_conformsToProtocol(%swift.type* %arg_type, %swift.protocol* @"$sSEMp") // CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[DECODABLE_WITNESS]], null // CHECK-NEXT: br i1 [[IS_NULL]], label %missing-witness1, label [[CONT:%.*]] // CHECK: missing-witness1: // CHECK-NEXT: call void @llvm.trap() // CHECK-NEXT: unreachable // CHECK: call swiftcc void [[DECODE_NEXT_ARG]](%swift.opaque* noalias nocapture sret(%swift.opaque) [[ARG_0_RES_SLOT]], %swift.type* %arg_type, i8** [[ENCODABLE_WITNESS]], i8** [[DECODABLE_WITNESS]], %T27FakeDistributedActorSystems0A17InvocationDecoderC* swiftself [[DECODER]], %swift.error** noalias nocapture swifterror dereferenceable(8) %swifterror) // CHECK: store %swift.error* null, %swift.error** %swifterror // CHECK-NEXT: [[ARG_0_VAL_ADDR:%.*]] = bitcast i8* [[ARG_0_VALUE_BUF]] to %TSi* // CHECK-NEXT: %._value = getelementptr inbounds %TSi, %TSi* [[ARG_0_VAL_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[ARG_VAL:%.*]] = load i64, i64* %._value /// Setup task context for async call to `simple1` thunk // CHECK-DIRECT: [[CONTEXT_SIZE:%.*]] = load i32, i32* getelementptr inbounds (%swift.async_func_pointer, %swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTETu", i32 0, i32 1) // CHECK-INDIRECT: [[ADDR:%[0-9]+]] = load %swift.async_func_pointer*, %swift.async_func_pointer** inttoptr (i64 and (i64 ptrtoint (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTETu" to i64), i64 -2) to %swift.async_func_pointer**) // CHECK-INDIRECT-NEXT: [[SELECT:%[0-9]+]] = select i1 true, %swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTETu", %swift.async_func_pointer* [[ADDR]] // CHECK-INDIRECT-NEXT: [[LOAD:%[0-9]+]] = getelementptr inbounds %swift.async_func_pointer, %swift.async_func_pointer* [[SELECT]], i32 0, i32 1 // CHECK-INDIRECT-NEXT: [[CONTEXT_SIZE:%.*]] = load i32, i32* [[LOAD]] // CHECK-NEXT: [[CONTEXT_SIZE_64:%.*]] = zext i32 [[CONTEXT_SIZE]] to i64 // CHECK-NEXT: [[THUNK_ASYNC_CONTEXT:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[CONTEXT_SIZE_64]]) // CHECK: [[THUNK_CONTEXT_PTR:%.*]] = bitcast i8* [[THUNK_ASYNC_CONTEXT]] to %swift.context* /// Call distributed thunk for `simple1` and `end` async context without results // CHECK: [[THUNK_RESULT:%.*]] = call { i8*, %swift.error* } (i32, i8*, i8*, ...) @llvm.coro.suspend.async.sl_p0i8p0s_swift.errorss( // CHECK-SAME: i8* bitcast (void (%swift.context*, i64, %T27distributed_actor_accessors7MyActorC*)* @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTE" to i8*), // CHECK-SAME: %swift.context* [[THUNK_CONTEXT_PTR]], // CHECK-SAME: i64 [[ARG_VAL]], // CHECK-SAME: %T27distributed_actor_accessors7MyActorC* [[ACTOR]]) // CHECK-NEXT: [[TASK_REF:%.*]] = extractvalue { i8*, %swift.error* } [[THUNK_RESULT]], 0 // CHECK-NEXT: {{.*}} = call i8* @__swift_async_resume_project_context(i8* [[TASK_REF]]) // CHECK: {{.*}} = call i1 (i8*, i1, ...) @llvm.coro.end.async({{.*}}, %swift.context* {{.*}}, %swift.error* {{.*}}) /// ---> Thunk and distributed method accessor for `simple2` // CHECK: define hidden swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTE" // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTETF" /// !!! - We are not going to double-check argument extraction here since it's the same as `simple1`. // CHECK: [[NATIVE_ARG_VAL:%.*]] = load i64, i64* %._value /// Setup task context for async call to `simple2` thunk // CHECK-DIRECT: [[CONTEXT_SIZE:%.*]] = load i32, i32* getelementptr inbounds (%swift.async_func_pointer, %swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTETu", i32 0, i32 1) // CHECK-INDIRECT: [[ADDR:%[0-9]+]] = load %swift.async_func_pointer*, %swift.async_func_pointer** inttoptr (i64 and (i64 ptrtoint (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTETu" to i64), i64 -2) to %swift.async_func_pointer**), align 8 // CHECK-INDIRECT-NEXT: [[SELECT:%[0-9]+]] = select i1 true, %swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTETu", %swift.async_func_pointer* [[ADDR]] // CHECK-INDIRECT-NEXT: [[LOAD:%[0-9]+]] = getelementptr inbounds %swift.async_func_pointer, %swift.async_func_pointer* [[SELECT]], i32 0, i32 1 // CHECK-INDIRECT-NEXT: [[CONTEXT_SIZE:%.*]] = load i32, i32* [[LOAD]] // CHECK-NEXT: [[CONTEXT_SIZE_64:%.*]] = zext i32 [[CONTEXT_SIZE]] to i64 // CHECK-NEXT: [[THUNK_ASYNC_CONTEXT:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[CONTEXT_SIZE_64]]) // CHECK: [[THUNK_CONTEXT_PTR:%.*]] = bitcast i8* [[THUNK_ASYNC_CONTEXT]] to %swift.context* /// Call the thunk with extracted argument value // CHECK: [[THUNK_RESULT:%.*]] = call { i8*, i64, %swift.bridge*, %swift.error* } (i32, i8*, i8*, ...) @llvm.coro.suspend.async.sl_p0i8i64p0s_swift.bridgesp0s_swift.errorss( // CHECK-SAME: i8* bitcast (void (%swift.context*, i64, %T27distributed_actor_accessors7MyActorC*)* @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTE" to i8*), // CHECK-SAME: %swift.context* [[THUNK_CONTEXT_PTR]], // CHECK-SAME: i64 [[NATIVE_ARG_VAL]], // CHECK-SAME: %T27distributed_actor_accessors7MyActorC* [[ACTOR]]) // CHECK-NEXT: [[TASK_REF:%.*]] = extractvalue { i8*, i64, %swift.bridge*, %swift.error* } [[THUNK_RESULT]], 0 // CHECK-NEXT: {{.*}} = call i8* @__swift_async_resume_project_context(i8* [[TASK_REF]]) /// Extract information about `String` from result and call `end` // CHECK: [[STR_STRUCT:%.*]] = insertvalue { i64, %swift.bridge* } {{.*}}, %swift.bridge* {{.*}}, 1 // CHECK: [[STR_SIZE:%.*]] = extractvalue { i64, %swift.bridge* } [[STR_STRUCT]], 0 // CHECK-NEXT: [[STR_VAL:%.*]] = extractvalue { i64, %swift.bridge* } [[STR_STRUCT]], 1 /// Initialize the result buffer with values produced by the thunk // CHECK: store i64 [[STR_SIZE]], i64* %._guts._object._countAndFlagsBits._value // CHECK: store %swift.bridge* [[STR_VAL]], %swift.bridge** %._guts._object._object // CHECK: {{.*}} = call i1 (i8*, i1, ...) @llvm.coro.end.async({{.*}}, %swift.context* {{.*}}, %swift.error* {{.*}}) /// ---> Thunk and distributed method accessor for `simple3` // CHECK: define hidden swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTE" /// !!! in `simple3` interesting bits are: argument value extraction (because string is exploded into N arguments) and call to distributed thunk // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTETF"(%swift.context* swiftasync %0, %swift.opaque* nocapture [[ARG_DECODER:%.*]], i8* [[ARG_TYPES:%.*]], i8* [[RESULT_BUFF:%.*]], i8* [[SUBS:%.*]], i8* [[WITNESS_TABLES:%.*]], i64 [[NUM_WITNESS_TABLES:%.*]], %T27distributed_actor_accessors7MyActorC* [[ACTOR]], %swift.type* [[DECODER_TYPE:%.*]], i8** [[DECODER_PROTOCOL_WITNESS:%.*]]) // CHECK: [[TYPED_RESULT_BUFF:%.*]] = bitcast i8* [[RESULT_BUFF]] to %TSi* // CHECK: [[ARG_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK: [[ARG_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_SIZE]]) // CHECK: [[ARG_0_VALUE:%.*]] = bitcast i8* [[ARG_BUF]] to %TSS* // CHECK-NEXT: %._guts = getelementptr inbounds %TSS, %TSS* [[ARG_0_VALUE]], i32 0, i32 0 // CHECK: [[STR_SIZE:%.*]] = load i64, i64* %._guts._object._countAndFlagsBits._value // CHECK: [[STR_VAL:%.*]] = load %swift.bridge*, %swift.bridge** %._guts._object._object /// Setup task context for async call to `simple3` thunk // CHECK-INDIRECT: [[ADDR:%[0-9]+]] = load %swift.async_func_pointer*, %swift.async_func_pointer** inttoptr (i64 and (i64 ptrtoint (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTETu" to i64), i64 -2) to %swift.async_func_pointer**), align 8 // CHECK-INDIRECT-NEXT: [[SELECT:%[0-9]+]] = select i1 true, %swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTETu", %swift.async_func_pointer* [[ADDR]] // CHECK-INDIRECT-NEXT: [[LOAD:%[0-9]+]] = getelementptr inbounds %swift.async_func_pointer, %swift.async_func_pointer* [[SELECT]], i32 0, i32 1 // CHECK-INDIRECT-NEXT: [[CONTEXT_SIZE:%.*]] = load i32, i32* [[LOAD]] // CHECK-DIRECT: [[CONTEXT_SIZE:%.*]] = load i32, i32* getelementptr inbounds (%swift.async_func_pointer, %swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTETu", i32 0, i32 1) // CHECK-NEXT: [[CONTEXT_SIZE_64:%.*]] = zext i32 [[CONTEXT_SIZE]] to i64 // CHECK-NEXT: [[THUNK_ASYNC_CONTEXT:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[CONTEXT_SIZE_64]]) // CHECK: [[THUNK_CONTEXT_PTR:%.*]] = bitcast i8* [[THUNK_ASYNC_CONTEXT]] to %swift.context* /// Call distributed thunk with exploaded string value // CHECK: [[THUNK_RESULT:%.*]] = call { i8*, i64, %swift.error* } (i32, i8*, i8*, ...) @llvm.coro.suspend.async.sl_p0i8i64p0s_swift.errorss( // CHECK-SAME: i8* bitcast (void (%swift.context*, i64, %swift.bridge*, %T27distributed_actor_accessors7MyActorC*)* @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTE" to i8*), // CHECK-SAME: %swift.context* [[THUNK_CONTEXT_PTR]], // CHECK-SAME: i64 [[STR_SIZE]], // CHECK-SAME: %swift.bridge* [[STR_VAL]], // CHECK-SAME: %T27distributed_actor_accessors7MyActorC* [[ACTOR]]) // CHECK-NEXT: [[TASK_REF:%.*]] = extractvalue { i8*, i64, %swift.error* } [[THUNK_RESULT]], 0 // CHECK-NEXT: {{.*}} = call i8* @__swift_async_resume_project_context(i8* [[TASK_REF]]) // CHECK: [[INT_RES:%.*]] = extractvalue { i8*, i64, %swift.error* } [[THUNK_RESULT]], 1 // CHECK: %._value = getelementptr inbounds %TSi, %TSi* [[TYPED_RESULT_BUFF]], i32 0, i32 0 // CHECK: store i64 [[INT_RES]], i64* %._value // CHECK: {{.*}} = call i1 (i8*, i1, ...) @llvm.coro.end.async({{.*}}, %swift.context* {{.*}}, %swift.error* {{.*}}) /// --> Thunk and distributed method accessor for `single_case_enum` // CHECK: define hidden swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTE" // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTETF"(%swift.context* swiftasync %0, %swift.opaque* nocapture [[ARG_DECODER:%.*]], i8* [[ARG_TYPES:%.*]], i8* [[RESULT_BUFF:%.*]], i8* [[SUBS:%.*]], i8* [[WITNESS_TABLES:%.*]], i64 [[NUM_WITNESS_TABLES:%.*]], %T27distributed_actor_accessors7MyActorC* [[ACTOR]], %swift.type* [[DECODER_TYPE]], i8** [[DECODER_PROTOCOL_WITNESS:%.*]]) /// Let's check that the call doesn't have any arguments and returns nothing. // SKIP: [[THUNK_REF:%.*]] = bitcast void (%swift.context*, %T27distributed_actor_accessors7MyActorC*)* {{.*}} to i8* // SKIP: {{.*}} = call { i8*, %swift.error* } (i32, i8*, i8*, ...) @llvm.coro.suspend.async.sl_p0i8p0s_swift.errorss({{.*}}, i8* [[THUNK_REF]], %swift.context* {{.*}}, %T27distributed_actor_accessors7MyActorC* {{.*}}) // SKIP: {{.*}} = call i1 (i8*, i1, ...) @llvm.coro.end.async({{.*}}, i8* {{.*}}, %swift.context* {{.*}}, %swift.error* {{.*}}) /// --> Thunk and distributed method accessor for `with_indirect_enums` // CHECK: define hidden swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTE" // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTETF" /// First, Load both arguments from the buffer. // CHECK: [[TYPED_RESULT_BUFF:%.*]] = bitcast i8* [[RESULT_BUFF]] to %T27distributed_actor_accessors9IndirectEO* // CHECK: [[ARG_0_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_0_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_0_SIZE]]) // CHECK: [[ARG_0_VAL_ADDR:%.*]] = bitcast i8* [[ARG_0_BUF]] to %T27distributed_actor_accessors9IndirectEO* // CHECK-NEXT: [[NATIVE_ENUM_VAL_ADDR:%.*]] = bitcast %T27distributed_actor_accessors9IndirectEO* [[ARG_0_VAL_ADDR]] to i64* // CHECK-NEXT: [[NATIVE_ENUM_VAL:%.*]] = load i64, i64* [[NATIVE_ENUM_VAL_ADDR]] // CHECK: [[ARG_1_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_1_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_1_SIZE]]) // CHECK: [[ARG_1_VAL_ADDR:%.*]] = bitcast i8* [[ARG_1_BUF]] to %TSi* // CHECK-NEXT: %._value = getelementptr inbounds %TSi, %TSi* [[ARG_1_VAL_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[NATIVE_INT_VAL:%.*]] = load i64, i64* %._value /// Call distributed thunk with extracted arguments. // CHECK: [[THUNK_RESULT:%.*]] = call { i8*, i64, %swift.error* } (i32, i8*, i8*, ...) @llvm.coro.suspend.async.sl_p0i8i64p0s_swift.errorss({{.*}}, %swift.context* {{.*}}, i64 [[NATIVE_ENUM_VAL]], i64 [[NATIVE_INT_VAL]], %T27distributed_actor_accessors7MyActorC* {{.*}}) // CHECK-NEXT: [[TASK_REF:%.*]] = extractvalue { i8*, i64, %swift.error* } [[THUNK_RESULT]], 0 // CHECK-NEXT: {{.*}} = call i8* @__swift_async_resume_project_context(i8* [[TASK_REF]]) // CHECK: [[ENUM_RESULT:%.*]] = extractvalue { i8*, i64, %swift.error* } [[THUNK_RESULT]], 1 // CHECK: [[NATIVE_RESULT_PTR:%.*]] = bitcast %T27distributed_actor_accessors9IndirectEO* [[TYPED_RESULT_BUFF]] to i64* // CHECK-NEXT: store i64 [[ENUM_RESULT]], i64* [[NATIVE_RESULT_PTR]] // CHECK: {{.*}} = call i1 (i8*, i1, ...) @llvm.coro.end.async({{.*}}, %swift.context* {{.*}}, %swift.error* {{.*}}) /// ---> Thunk and distributed method for `complex` // CHECK: define hidden swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTE" // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTETF"(%swift.context* swiftasync {{.*}}, %swift.opaque* nocapture [[ARG_DECODER:%.*]], i8* [[ARG_TYPES:%.*]], i8* [[RESULT_BUFF:%.*]], i8* [[SUBS:%.*]], i8* [[WITNESS_TABLES:%.*]], i64 [[NUM_WITNESS_TABLES:%.*]], %T27distributed_actor_accessors7MyActorC* [[ACTOR]], %swift.type* [[DECODER_TYPE:%.*]], i8** [[DECODER_PROTOCOL_WITNESS:%.*]]) /// First, let's check that all of the different argument types here are loaded correctly. /// Cast result buffer to the expected result type (in this case its indirect opaque pointer) // CHECK: [[TYPED_RESULT_BUFF:%.*]] = bitcast i8* [[RESULT_BUFF]] to %swift.opaque* /// -> [Int] // CHECK: [[ARG_0_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_0_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_0_SIZE]]) // CHECK: [[ARG_0_VAL_ADDR:%.*]] = bitcast i8* [[ARG_0_BUF]] to %TSa* // CHECK-NEXT: %._buffer = getelementptr inbounds %TSa, %TSa* [[ARG_0_VAL_ADDR]], i32 0, i32 0 // CHECK: [[NATIVE_ARR_VAL:%.*]] = load [[ARR_STORAGE_TYPE:%.*]], [[ARR_STORAGE_TYPE]]* %._buffer._storage /// -> Obj // CHECK: [[ARG_1_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_1_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_1_SIZE]]) // CHECK: [[OBJ_PTR:%.*]] = bitcast i8* [[ARG_1_BUF]] to %T27distributed_actor_accessors3ObjC** // CHECK-NEXT: [[NATIVE_OBJ_VAL:%.*]] = load %T27distributed_actor_accessors3ObjC*, %T27distributed_actor_accessors3ObjC** [[OBJ_PTR]] /// -> String? // CHECK: [[ARG_2_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_2_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_2_SIZE]]) // CHECK: [[OPT_PTR:%.*]] = bitcast i8* [[ARG_2_BUF]] to %TSSSg* // CHECK-NEXT: [[NATIVE_OPT_PTR:%.*]] = bitcast %TSSSg* [[OPT_PTR]] to { i64, i64 }* // CHECK-NEXT: [[NATIVE_OPT_VAL_0_PTR:%.*]] = getelementptr inbounds { i64, i64 }, { i64, i64 }* [[NATIVE_OPT_PTR]], i32 0, i32 0 // CHECK-NEXT: [[NATIVE_OPT_VAL_0:%.*]] = load i64, i64* [[NATIVE_OPT_VAL_0_PTR]] // CHECK-NEXT: [[NATIVE_OPT_VAL_1_PTR:%.*]] = getelementptr inbounds { i64, i64 }, { i64, i64 }* [[NATIVE_OPT_PTR]], i32 0, i32 1 // CHECK-NEXT: [[NATIVE_OPT_VAL_1:%.*]] = load i64, i64* [[NATIVE_OPT_VAL_1_PTR]] /// -> LargeStruct (passed indirectly) // CHECK: [[ARG_3_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_3_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_3_SIZE]]) // CHECK-NEXT: [[ARG_3_OPAQUE_PTR:%.*]] = bitcast i8* [[ARG_3_BUF]] to %swift.opaque* // CHECK: [[INDIRECT_RESULT_BUFF:%.*]] = bitcast %swift.opaque* [[TYPED_RESULT_BUFF]] to %T27distributed_actor_accessors11LargeStructV* // CHECK: [[STRUCT_PTR:%.*]] = bitcast %swift.opaque* [[ARG_3_OPAQUE_PTR]] to %T27distributed_actor_accessors11LargeStructV* /// Now let's make sure that distributed thunk call uses the arguments correctly // CHECK: [[THUNK_RESULT:%.*]] = call { i8*, %swift.error* } (i32, i8*, i8*, ...) @llvm.coro.suspend.async.sl_p0i8p0s_swift.errorss({{.*}}, %T27distributed_actor_accessors11LargeStructV* [[INDIRECT_RESULT_BUFF]], %swift.context* {{.*}}, {{.*}} [[NATIVE_ARR_VAL]], %T27distributed_actor_accessors3ObjC* [[NATIVE_OBJ_VAL]], i64 [[NATIVE_OPT_VAL_0]], i64 [[NATIVE_OPT_VAL_1]], %T27distributed_actor_accessors11LargeStructV* [[STRUCT_PTR]], %T27distributed_actor_accessors7MyActorC* {{.*}}) /// RESULT is returned indirectly so there is nothing to pass to `end` // CHECK: {{.*}} = call i1 (i8*, i1, ...) @llvm.coro.end.async({{.*}}, %swift.context* {{.*}}, %swift.error* {{.*}}) /// ---> Accessor for `genericArgs` // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors7MyActorC11genericArgsyyx_Sayq_GtYaKSeRzSERzSeR_SER_r0_lFTETF"(%swift.context* swiftasync %0, %swift.opaque* nocapture [[ARG_DECODER:%.*]], i8* [[ARG_TYPES:%.*]], i8* [[RESULT_BUF:%.*]], i8* [[GENERIC_SUBS:%.*]], i8* [[WITNESS_TABLES:%.*]], i64 [[NUM_WITNESS_TABLES:%.*]], %T27distributed_actor_accessors7MyActorC* [[ACTOR:%.*]], %swift.type* [[DECODER_TYPE:%.*]], i8** [[DECODER_PROTOCOL_WITNESS:%.*]]) /// ---> Load `T` // CHECK: [[ARG_0_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_0_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_0_SIZE]]) // CHECK: [[TYPED_ARG_0:%.*]] = bitcast i8* [[ARG_0_BUF]] to %swift.opaque* /// ---> Load `[U]` // CHECK: [[ARG_1_SIZE:%.*]] = and i64 {{.*}}, -16 // CHECK-NEXT: [[ARG_1_BUF:%.*]] = call swiftcc i8* @swift_task_alloc(i64 [[ARG_1_SIZE]]) // CHECK: [[ARR_ARG_1:%.*]] = bitcast i8* [[ARG_1_BUF]] to %TSa* // CHECK-NEXT: %._buffer = getelementptr inbounds %TSa, %TSa* [[ARR_ARG_1]], i32 0, i32 0 // CHECK-NEXT: %._buffer._storage = getelementptr inbounds [[ARRAY_TYPE:%.*]], [[ARRAY_TYPE]]* %._buffer, i32 0, i32 0 // CHECK: [[TYPED_ARG_1:%.*]] = load [[ARG_STORAGE_TYPE:%.*]], [[ARG_STORAGE_TYPE]]* %._buffer._storage /// ---> Load generic argument substitutions from the caller-provided buffer // CHECK: [[GENERIC_SUBS_BUF:%.*]] = bitcast i8* [[GENERIC_SUBS]] to %swift.type** // CHECK-NEXT: [[SUB_T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[GENERIC_SUBS_BUF]], i64 0 // CHECK-NEXT: [[SUB_T:%.*]] = load %swift.type*, %swift.type** [[SUB_T_ADDR]] // CHECK-NEXT: [[SUB_U_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[GENERIC_SUBS_BUF]], i64 1 // CHECK-NEXT: [[SUB_U:%.*]] = load %swift.type*, %swift.type** [[SUB_U_ADDR]] /// --> Load witness tables from caller-provided buffer /// First, check whether the number of witness tables matches expected // CHECK: [[IS_INCORRECT_WITNESSES:%.*]] = icmp ne i64 [[NUM_WITNESS_TABLES]], 4 // CHECK-NEXT: br i1 [[IS_INCORRECT_WITNESSES]], label %incorrect-witness-tables, label [[LOAD_WITNESS_TABLES:%.*]] // CHECK: incorrect-witness-tables: // CHECK-NEXT: unreachable // CHECK: [[WITNESS_BUF:%.*]] = bitcast i8* [[WITNESS_TABLES]] to i8*** // CHECK-NEXT: [[T_ENCODABLE_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[WITNESS_BUF]], i64 0 // CHECK-NEXT: [[T_ENCODABLE:%.*]] = load i8**, i8*** [[T_ENCODABLE_ADDR]] // CHECK-NEXT: [[T_DECODABLE_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[WITNESS_BUF]], i64 1 // CHECK-NEXT: [[T_DECODABLE:%.*]] = load i8**, i8*** [[T_DECODABLE_ADDR]] // CHECK-NEXT: [[U_ENCODABLE_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[WITNESS_BUF]], i64 2 // CHECK-NEXT: [[U_ENCODABLE:%.*]] = load i8**, i8*** [[U_ENCODABLE_ADDR]] // CHECK-NEXT: [[U_DECODABLE_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[WITNESS_BUF]], i64 3 // CHECK-NEXT: [[U_DECODABLE:%.*]] = load i8**, i8*** [[U_DECODABLE_ADDR]] /// ---> Check that distributed thunk code is formed correctly // CHECK-MACHO: [[THUNK_RESULT:%.*]] = call { i8*, %swift.error* } (i32, i8*, i8*, ...) @llvm.coro.suspend.async.sl_p0i8p0s_swift.errorss({{.*}}, %swift.context* {{.*}}, %swift.opaque* [[TYPED_ARG_0]], %swift.bridge* [[TYPED_ARG_1]], %swift.type* [[SUB_T]], %swift.type* [[SUB_U]], i8** [[T_ENCODABLE]], i8** [[T_DECODABLE]], i8** [[U_ENCODABLE]], i8** [[U_DECODABLE]], %T27distributed_actor_accessors7MyActorC* [[ACTOR]]) /// ---> Thunk and distributed method for `MyOtherActor.empty` /// Let's check that there is argument decoding since parameter list is empty // CHECK: define internal swift{{(tail)?}}cc void @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTETF"(%swift.context* swiftasync {{.*}}, %swift.opaque* nocapture [[ARG_DECODER:%.*]], i8* [[ARG_TYPES:%.*]], i8* [[RESULT_BUFF:%.*]], i8* [[SUBS:%.*]], i8* [[WITNESS_TABLES:%.*]], i64 [[NUM_WITNESS_TABLES:%.*]], %T27distributed_actor_accessors12MyOtherActorC* {{.*}}, %swift.type* [[DECODER_TYPE:%.*]], i8** [[DECODER_PROTOCOL_WITNESS:%.*]]) // CHECK-NEXT: entry: // CHECK-NEXT: {{.*}} = alloca %swift.context* // CHECK-NEXT: %swifterror = alloca swifterror %swift.error* // CHECK-NEXT: {{.*}} = call token @llvm.coro.id.async(i32 16, i32 16, i32 0, i8* bitcast (%swift.async_func_pointer* @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTETFTu" to i8*)) // CHECK-NEXT: {{.*}} = call i8* @llvm.coro.begin(token {{%.*}}, i8* null) // CHECK-NEXT: store %swift.context* {{.*}}, %swift.context** {{.*}} // CHECK-NEXT: store %swift.error* null, %swift.error** %swifterror // CHECK-NEXT: {{.*}} = bitcast i8* [[RESULT_BUFF]] to %swift.opaque* // CHECK-DIRECT-NEXT: {{.*}} = load i32, i32* getelementptr inbounds (%swift.async_func_pointer, %swift.async_func_pointer* @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTETu", i32 0, i32 1) // CHECK-INDIRECT-NEXT: [[ADDR:%[0-9]+]] = load %swift.async_func_pointer*, %swift.async_func_pointer** inttoptr (i64 and (i64 ptrtoint (%swift.async_func_pointer* @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTETu" to i64), i64 -2) to %swift.async_func_pointer**), align 8 // CHECK-INDIRECT-NEXT: [[SELECT:%[0-9]+]] = select i1 true, %swift.async_func_pointer* @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTETu", %swift.async_func_pointer* [[ADDR]] // CHECK-INDIRECT-NEXT: [[LOAD:%[0-9]+]] = getelementptr inbounds %swift.async_func_pointer, %swift.async_func_pointer* [[SELECT]], i32 0, i32 1 // CHECK-INDIRECT-NEXT: {{.*}} = load i32, i32* [[LOAD]]
apache-2.0
c6d3fc56d305f512f2a74d0f33d4ac5b
65.676259
487
0.660768
3.271444
false
false
false
false
icylydia/PlayWithLeetCode
50. Pow(x, n)/solution.swift
1
738
class Solution { func myPow(x: Double, _ n: Int) -> Double { if n == 0 { return 1 } if n == 1 { return x } if n == -1 { return 1/x } let positive = n > 0 let n = positive ? n : -n var tower = [x] var pt = 2 while pt <= n { tower.append(tower.last! * tower.last!) pt *= 2 } var ans = 1.0 var m = n while m > 0 { var pt = 1 var idx = 0 while pt * 2 < m { pt *= 2 idx++ } ans *= tower[idx] m -= pt } return positive ? ans : 1/ans } }
mit
d722ecacd14e9581eed5d451a73d0479
20.735294
51
0.322493
4.032787
false
false
false
false
CapeTowniOSAcademy/meetup-nov-2015
Mojitter/MojiKit.swift
1
646
// // MojiKit.swift // Mojitter // // Created by Daniel Galasko on 2015/11/11. // Copyright © 2015 iOSAcademy. All rights reserved. // import UIKit public struct MojiStatus { public let title: String public let moji: Moji public init(title: String, moji: Moji) { self.title = title;self.moji = moji } } public struct Moji { public let name: String public let handle: String public let emoji: String public init(name: String, handle: String, emoji: String) { self.name = name;self.handle = handle;self.emoji = emoji } } public struct MojiFeed { public let statuses: [MojiStatus] }
mit
acbb13045fbc96860df9572fb0326b9d
19.806452
64
0.658915
3.486486
false
false
false
false
anilkumarbp/ringcentral-swift-NEW
ringcentral-swift-develop-anilkumarbp/lib/core/SDK.swift
1
2737
import Foundation // Object representation of a Standard Development Kit for RingCentral class SDK { // Set constants for SANDBOX and PRODUCTION servers. static var RC_SERVER_PRODUCTION: String = "https://platform.ringcentral.com" static var RC_SERVER_SANDBOX: String = "https://platform.devtest.ringcentral.com" // Platform variable, version, and current Subscriptions var platform: Platform var subscription: Subscription? let server: String var serverVersion: String! var versionString: String! var logger: Bool = false /// Constructor for making the SDK object. /// /// Example: /// /// init(appKey, appSecret, SDK.RC_SERVER_PRODUCTION) /// or /// /// init(appKey, appSecret, SDK.RC_SERVER_SANDBOX) /// /// :param: appKey The appKey of your app /// :param: appSecet The appSecret of your app /// :param: server Choice of PRODUCTION or SANDBOX init(appKey: String, appSecret: String, server: String) { platform = Platform(appKey: appKey, appSecret: appSecret, server: server) self.server = server setVersion() } /// Sets version to the version of the current SDK private func setVersion() { let url = NSURL(string: server + "/restapi/") // Sets up the request let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Accept") var response: NSURLResponse? var error: NSError? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) let readdata = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary let dict = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary self.serverVersion = dict["serverVersion"] as! String self.versionString = (dict["apiVersions"] as! NSArray)[0]["versionString"] as! String } /// Returns the server version. /// /// :returns: String of current version func getServerVersion() -> String { return serverVersion } /// Returns the Platform with the specified appKey and appSecret. /// /// :returns: A Platform to access the methods of the SDK func getPlatform() -> Platform { return self.platform } /// Returns the current Subscription. /// /// :returns: A Subscription that the user is currently following func getSubscription() -> Subscription? { return self.subscription } }
mit
053e665e4a693a857fc4aea8576bfad5
32.390244
111
0.634636
4.931532
false
false
false
false
radoslavyordanov/QuizGames-iOS
QuizGames/LoginViewController.swift
1
5174
/* * Copyright 2016 Radoslav Yordanov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import Alamofire class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var rememberMe: UISwitch! @IBOutlet weak var login: UIButton! @IBOutlet weak var register: UIButton! override func viewDidLoad() { super.viewDidLoad() login.layer.cornerRadius = 5 login.layer.borderWidth = 1 login.layer.borderColor = UIColor.whiteColor().CGColor register.layer.cornerRadius = 5 register.layer.borderWidth = 1 register.layer.borderColor = UIColor.whiteColor().CGColor username.delegate = self username.tag = 1 password.delegate = self password.tag = 2 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let preferences = NSUserDefaults.standardUserDefaults() let userId = preferences.integerForKey(Util.USER_ID_PREF) if userId != 0 { Util.userId = userId Util.userRoleId = preferences.integerForKey(Util.USER_ROLE_ID) self.performSegueWithIdentifier("showMainView", sender: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLoginTap(sender: AnyObject) { let params = [ "username": username.text!, "password": password.text! ] Alamofire.request(.POST, "\(Util.quizGamesAPI)/login", parameters: params, headers: nil, encoding: .JSON) .responseJSON { response in // print(response.request) // original URL request // print(response.response) // URL response // print(response.data) // server data // print(response.result) // result of response serialization if let results = response.result.value { // print("JSON: \(results)") if results["status"] as! String == "failure" { // invalid credentials let invalidCredentials = NSLocalizedString("invalidCredentials", comment: "") let alert = UIAlertController(title: nil, message: invalidCredentials, preferredStyle: .Alert) let okAction: UIAlertAction = UIAlertAction(title: "Okay", style: .Default) { action -> Void in } alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } else { if self.rememberMe.on { let preferences = NSUserDefaults.standardUserDefaults() preferences.setInteger(results["id"] as! Int, forKey: Util.USER_ID_PREF) preferences.setInteger(results["user_roleId"] as! Int, forKey: Util.USER_ROLE_ID) } Util.userId = results["id"] as! Int Util.userRoleId = results["user_roleId"] as! Int self.performSegueWithIdentifier("showMainView", sender: sender) } } else { // failed to connect let connectionMsg = NSLocalizedString("connectionMsg", comment: "") let alert = UIAlertController(title: nil, message: connectionMsg, preferredStyle: .Alert) let okAction: UIAlertAction = UIAlertAction(title: "Okay", style: .Default) { action -> Void in } alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } } } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField.tag == 1 { textField.resignFirstResponder() password.becomeFirstResponder() } else if textField.tag == 2 { onLoginTap(textField) } return true } override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } }
apache-2.0
1794c1fd8a546dd417842fe31ca85034
39.421875
119
0.579242
5.446316
false
false
false
false
fousa/gpxkit
Sources/Models/Point.swift
1
4550
// // GKPoint.swift // Pods // // Created by Jelle Vandebeeck on 15/03/16. // // import Foundation import CoreLocation import AEXML /// Type of GPS fix. none means GPS had no fix. To signify "the fix info is unknown, leave out fixType entirely. pps = military signal used. public enum FixType: String { /// GPS had no fix. case none = "none" /// 2 dimentional fix. case twoD = "2d" /// 3 dimentional fix. case threeD = "3d" /// Differential Global Positioning System. case dgps = "dgps" /// Military signal used case pps = "pps" } /** Represents a waypoint, point of interest, or named feature on a map. */ public final class Point { /// The coordinate of the point. public var coordinate: CLLocationCoordinate2D? /// Elevation (in meters) of the point. public var elevation: Float? /// Creation/modification timestamp for element. Date and time in are in Univeral Coordinated Time (UTC), not local time. public var time: NSDate? /// Magnetic variation. public var magneticVariation: Float? /// Height (in meters) of geoid (mean sea level) above WGS84 earth ellipsoid. As defined in NMEA GGA message. public var meanSeaLevelHeight: Float? /// The GPS name of the waypoint. This field will be transferred to and from the GPS. GPX does not place restrictions on the length of this field or the characters contained in it. It is up to the receiving application to validate the field before sending it to the GPS. public var name: String? /// GPS waypoint comment. Sent to GPS as comment. public var comment: String? /// A text description of the element. Holds additional information about the element intended for the user, not the GPS. public var description: String? /// Source of data. Included to give user some idea of reliability and accuracy of data. "Garmin eTrex", "USGS quad Boston North", e.g. public var source: String? /// Link to additional information about the waypoint. public var link: Link? /// Text of GPS symbol name. For interchange with other programs, use the exact spelling of the symbol as displayed on the GPS. If the GPS abbreviates words, spell them out. public var symbol: String? /// Type (classification) of the waypoint. public var type: String? /// Type of GPS fix. public var fix: FixType? /// Number of satellites used to calculate the GPX fix. public var satelites: Int? /// Horizontal dilution of precision. public var horizontalDilutionOfPrecision: Float? /// Vertical dilution of precision. public var verticalDilutionOfPrecision: Float? /// Position dilution of precision. public var positionDilutionOfPrecision: Float? /// Number of seconds since last DGPS update. public var ageOfTheGpxData: Float? /// Represents a differential GPS station. public var dgpsStationType: Int? } extension Point: Mappable { convenience init?(fromElement element: AEXMLElement) { // When the element is an error, don't create the instance. if let _ = element.error { return nil } // Check if coordinate is avaiable. guard let latitude = element.attributes["lat"], let longitude = element.attributes["lon"] else { return nil } self.init() coordinate <~ (Double(latitude)!, Double(longitude)!) elevation <~ element["ele"] magneticVariation <~ element["magvar"] meanSeaLevelHeight <~ element["geoidheight"] name <~ element["name"] comment <~ element["cmt"] description <~ element["desc"] source <~ element["src"] symbol <~ element["sym"] type <~ element["type"] fix <~ element["fix"] satelites <~ element["sat"] horizontalDilutionOfPrecision <~ element["hdop"] verticalDilutionOfPrecision <~ element["vdop"] positionDilutionOfPrecision <~ element["pdop"] ageOfTheGpxData <~ element["ageofdgpsdata"] dgpsStationType <~ element["dgpsid"] time <~ element["time"] link <~ element["link"] } }
mit
1c8d934d62e36faa57687f21ad5525ac
34.554688
274
0.610549
4.759414
false
false
false
false
takamashiro/XDYZB
XDYZB/XDYZB/Classes/Home/Controller/RecommendViewController.swift
1
4245
// // RecommendViewController.swift // XDYZB // // Created by takamashiro on 2016/9/27. // Copyright © 2016年 com.takamashiro. All rights reserved. // import UIKit import MJRefresh private let kCycleViewH = kScreenW * 3 / 8 private let kGameViewH : CGFloat = 90 class RecommendViewController: BaseAnchorViewController { //MARK: -懒加载属性 fileprivate lazy var recommandViewModel : RecommandViewModel = RecommandViewModel() fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() } extension RecommendViewController { override func setupUI() { // 1.先调用super.setupUI() super.setupUI() //2.将cycleView添加到CollectionView中 collectionView.addSubview(cycleView) // 3.将gameView添加collectionView中 collectionView.addSubview(gameView) collectionView.mj_header = header collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) header.ignoredScrollViewContentInsetTop = kCycleViewH + kGameViewH collectionView.mj_header = header let x = UIScreen.main.bounds.size.width - 44 let y = collectionView.bounds.size.height - 44 - kCycleViewH - kGameViewH let livingBtn = UIButton(frame: CGRect(x: x, y: y, width: 44, height: 44)) livingBtn.setImage(UIImage(named:"home_play_btn_44x44_"), for: UIControlState.normal) livingBtn.addTarget(self, action: #selector(presentLiveVC), for: UIControlEvents.touchUpInside) view.insertSubview(livingBtn, aboveSubview: gameView) } func presentLiveVC() { present(LiveMySelfViewController(), animated: true, completion: nil) } } //MARK:- 请求数据 extension RecommendViewController { override func loadData() { // 0.给父类中的ViewModel进行赋值 baseVM = recommandViewModel recommandViewModel.requestData() { // 1.展示推荐数据 self.collectionView.reloadData() // 2.将数据传递给GameView var tempGroups = self.recommandViewModel.anchorGroups tempGroups.removeFirst() tempGroups.removeFirst() let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" tempGroups.append(moreGroup) self.gameView.groups = tempGroups //3.数据请求完成 self.loadDataFinished() } // 2.请求轮播数据 recommandViewModel.requestCycleData { self.cycleView.cycleModels = self.recommandViewModel.cycleModels } } } extension RecommendViewController : UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { // 1.取出PrettyCell let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell // 2.设置数据 prettyCell.anchor = recommandViewModel.anchorGroups[indexPath.section].anchors[indexPath.item] return prettyCell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } }
mit
30c0e989c92e364f6b982d47c5a74e6e
33.033058
160
0.65153
5.355007
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModelTests/Days/DayAssertion.swift
1
954
import EurofurenceModel import TestUtilities class DayAssertion: Assertion { func assertDays(_ days: [Day], characterisedBy characteristics: [ConferenceDayCharacteristics]) { guard days.count == characteristics.count else { fail(message: "Differing amount of expected/actual days") return } let orderedCharacteristics = characteristics.sorted { (first, second) -> Bool in return first.date < second.date } for (idx, day) in days.enumerated() { let characteristic = orderedCharacteristics[idx] assertDay(day, characterisedBy: characteristic) } } func assertDay(_ day: Day?, characterisedBy characteristic: ConferenceDayCharacteristics) { guard let day = day else { fail(message: "Expected day: \(characteristic)") return } assert(day.date, isEqualTo: characteristic.date) } }
mit
5207f0c2b101f987349931c8d308680b
29.774194
101
0.637317
5.184783
false
false
false
false
KittenYang/A-GUIDE-TO-iOS-ANIMATION
Swift Version/AnimatedCircleDemo-Swift/AnimatedCircleDemo-Swift/ViewController.swift
1
1007
// // ViewController.swift // AnimatedCircleDemo-Swift // // Created by Kitten Yang on 1/18/16. // Copyright © 2016 Kitten Yang. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var slider: UISlider! private var circleView: CircleView! override func viewDidLoad() { super.viewDidLoad() circleView = CircleView(frame: CGRectMake(view.frame.size.width/2 - 320/2, view.frame.size.height/2 - 320/2, 320, 320)) view.addSubview(circleView) circleView.circleLayer.progress = CGFloat(slider.value) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func didValueChanged(sender: AnyObject) { if let slider = sender as? UISlider { progressLabel.text = "Current: \(slider.value)" circleView.circleLayer.progress = CGFloat(slider.value) } } }
gpl-2.0
b3484ffa4953b92b3ae2d4a61a3ab7a2
24.794872
127
0.656064
4.471111
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/SQLite.swift/Sources/SQLite/Typed/Schema.swift
9
22733
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension SchemaType { // MARK: - DROP TABLE / VIEW / VIRTUAL TABLE public func drop(ifExists: Bool = false) -> String { return drop("TABLE", tableName(), ifExists) } } extension Table { // MARK: - CREATE TABLE public func create(temporary: Bool = false, ifNotExists: Bool = false, withoutRowid: Bool = false, block: (TableBuilder) -> Void) -> String { let builder = TableBuilder() block(builder) let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .Temporary : nil, ifNotExists), "".wrap(builder.definitions) as Expression<Void>, withoutRowid ? Expression<Void>(literal: "WITHOUT ROWID") : nil ] return " ".join(clauses.flatMap { $0 }).asSQL() } public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .Temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - ALTER TABLE … ADD COLUMN public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V) -> String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V) -> String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil) -> String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil) -> String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } fileprivate func addColumn(_ expression: Expressible) -> String { return " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "ADD COLUMN"), expression ]).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: Table) -> String { return rename(to: to) } // MARK: - CREATE INDEX public func createIndex(_ columns: Expressible...) -> String { return createIndex(columns) } public func createIndex(_ columns: [Expressible], unique: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create("INDEX", indexName(columns), unique ? .Unique : nil, ifNotExists), Expression<Void>(literal: "ON"), tableName(qualified: false), "".wrap(columns) as Expression<Void> ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - DROP INDEX public func dropIndex(_ columns: Expressible...) -> String { return dropIndex(columns) } public func dropIndex(_ columns: [Expressible], ifExists: Bool = false) -> String { return drop("INDEX", indexName(columns), ifExists) } fileprivate func indexName(_ columns: [Expressible]) -> Expressible { let string = (["index", clauses.from.name, "on"] + columns.map { $0.expression.template }).joined(separator: " ").lowercased() let index = string.characters.reduce("") { underscored, character in guard character != "\"" else { return underscored } guard "a"..."z" ~= character || "0"..."9" ~= character else { return underscored + "_" } return underscored + String(character) } return database(namespace: index) } } extension View { // MARK: - CREATE VIEW public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(View.identifier, tableName(), temporary ? .Temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - DROP VIEW public func drop(ifExists: Bool = false) -> String { return drop("VIEW", tableName(), ifExists) } } extension VirtualTable { // MARK: - CREATE VIRTUAL TABLE public func create(_ using: Module, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(VirtualTable.identifier, tableName(), nil, ifNotExists), Expression<Void>(literal: "USING"), using ] return " ".join(clauses.flatMap { $0 }).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: VirtualTable) -> String { return rename(to: to) } } public final class TableBuilder { fileprivate var definitions = [Expressible]() public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool>? = nil) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool?>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } fileprivate func column(_ name: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) { definitions.append(definition(name, datatype, primaryKey, null, unique, check, defaultValue, references, collate)) } // MARK: - public func primaryKey<T : Value>(_ column: Expression<T>) { primaryKey([column]) } public func primaryKey<T : Value, U : Value>(_ compositeA: Expression<T>, _ b: Expression<U>) { primaryKey([compositeA, b]) } public func primaryKey<T : Value, U : Value, V : Value>(_ compositeA: Expression<T>, _ b: Expression<U>, _ c: Expression<V>) { primaryKey([compositeA, b, c]) } fileprivate func primaryKey(_ composite: [Expressible]) { definitions.append("PRIMARY KEY".prefix(composite)) } public func unique(_ columns: Expressible...) { unique(columns) } public func unique(_ columns: [Expressible]) { definitions.append("UNIQUE".prefix(columns)) } public func check(_ condition: Expression<Bool>) { check(Expression<Bool?>(condition)) } public func check(_ condition: Expression<Bool?>) { definitions.append("CHECK".prefix(condition)) } public enum Dependency: String { case noAction = "NO ACTION" case restrict = "RESTRICT" case setNull = "SET NULL" case setDefault = "SET DEFAULT" case cascade = "CASCADE" } public func foreignKey<T : Value>(_ column: Expression<T>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T : Value>(_ column: Expression<T?>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T : Value, U : Value>(_ composite: (Expression<T>, Expression<U>), references table: QueryType, _ other: (Expression<T>, Expression<U>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1]) let references = (table, ", ".join([other.0, other.1])) foreignKey(composite, references, update, delete) } public func foreignKey<T : Value, U : Value, V : Value>(_ composite: (Expression<T>, Expression<U>, Expression<V>), references table: QueryType, _ other: (Expression<T>, Expression<U>, Expression<V>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1, composite.2]) let references = (table, ", ".join([other.0, other.1, other.2])) foreignKey(composite, references, update, delete) } fileprivate func foreignKey(_ column: Expressible, _ references: (QueryType, Expressible), _ update: Dependency?, _ delete: Dependency?) { let clauses: [Expressible?] = [ "FOREIGN KEY".prefix(column), reference(references), update.map { Expression<Void>(literal: "ON UPDATE \($0.rawValue)") }, delete.map { Expression<Void>(literal: "ON DELETE \($0.rawValue)") } ] definitions.append(" ".join(clauses.flatMap { $0 })) } } public enum PrimaryKey { case `default` case autoincrement } public struct Module { fileprivate let name: String fileprivate let arguments: [Expressible] public init(_ name: String, _ arguments: [Expressible]) { self.init(name: name.quote(), arguments: arguments) } init(name: String, arguments: [Expressible]) { self.name = name self.arguments = arguments } } extension Module : Expressible { public var expression: Expression<Void> { return name.wrap(arguments) } } // MARK: - Private private extension QueryType { func create(_ identifier: String, _ name: Expressible, _ modifier: Modifier?, _ ifNotExists: Bool) -> Expressible { let clauses: [Expressible?] = [ Expression<Void>(literal: "CREATE"), modifier.map { Expression<Void>(literal: $0.rawValue) }, Expression<Void>(literal: identifier), ifNotExists ? Expression<Void>(literal: "IF NOT EXISTS") : nil, name ] return " ".join(clauses.flatMap { $0 }) } func rename(to: Self) -> String { return " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "RENAME TO"), Expression<Void>(to.clauses.from.name) ]).asSQL() } func drop(_ identifier: String, _ name: Expressible, _ ifExists: Bool) -> String { let clauses: [Expressible?] = [ Expression<Void>(literal: "DROP \(identifier)"), ifExists ? Expression<Void>(literal: "IF EXISTS") : nil, name ] return " ".join(clauses.flatMap { $0 }).asSQL() } } private func definition(_ column: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) -> Expressible { let clauses: [Expressible?] = [ column, Expression<Void>(literal: datatype), primaryKey.map { Expression<Void>(literal: $0 == .autoincrement ? "PRIMARY KEY AUTOINCREMENT" : "PRIMARY KEY") }, null ? nil : Expression<Void>(literal: "NOT NULL"), unique ? Expression<Void>(literal: "UNIQUE") : nil, check.map { " ".join([Expression<Void>(literal: "CHECK"), $0]) }, defaultValue.map { "DEFAULT".prefix($0) }, references.map(reference), collate.map { " ".join([Expression<Void>(literal: "COLLATE"), $0]) } ] return " ".join(clauses.flatMap { $0 }) } private func reference(_ primary: (QueryType, Expressible)) -> Expressible { return " ".join([ Expression<Void>(literal: "REFERENCES"), primary.0.tableName(qualified: false), "".wrap(primary.1) as Expression<Void> ]) } private enum Modifier : String { case Unique = "UNIQUE" case Temporary = "TEMPORARY" }
mit
f39d4badecab45b218ff9bcaaa250700
42.703846
260
0.643624
4.183726
false
false
false
false
doo/das-quadrat
Source/Shared/Endpoints/Users.swift
1
5309
// // Users.swift // Quadrat // // Created by Constantine Fry on 26/10/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public let UserSelf = "self" public class Users: Endpoint { override var endpoint: String { return "users" } /** https://developer.foursquare.com/docs/users/users */ public func get(userId: String = UserSelf, completionHandler: ResponseClosure? = nil) -> Task { return self.getWithPath(userId, parameters: nil, completionHandler) } // MARK: - General /** https://developer.foursquare.com/docs/users/requests */ public func requests(completionHandler: ResponseClosure? = nil) -> Task { let path = "requests" return self.getWithPath(path, parameters: nil, completionHandler) } /** https://developer.foursquare.com/docs/users/search */ public func search(parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "search" return self.getWithPath(path, parameters: parameters, completionHandler) } // MARK: - Aspects /** https://developer.foursquare.com/docs/users/checkins */ public func checkins(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/checkins" return self.getWithPath(path, parameters: parameters, completionHandler) } /** https://developer.foursquare.com/docs/users/friends */ public func friends(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/friends" return self.getWithPath(path, parameters: parameters, completionHandler) } /** https://developer.foursquare.com/docs/users/lists */ public func lists(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/lists" return self.getWithPath(path, parameters: parameters, completionHandler) } /** https://developer.foursquare.com/docs/users/mayorships */ public func mayorships(userId: String = UserSelf, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/mayorships" return self.getWithPath(path, parameters: nil, completionHandler) } /** https://developer.foursquare.com/docs/users/photos */ public func photos(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/photos" return self.getWithPath(path, parameters: parameters, completionHandler) } /** https://developer.foursquare.com/docs/users/tastes */ public func tastes(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/tastes" return self.getWithPath(path, parameters: parameters, completionHandler) } /** https://developer.foursquare.com/docs/users/venuehistory */ public func venuehistory(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/venuehistory" return self.getWithPath(path, parameters: parameters, completionHandler) } /** https://developer.foursquare.com/docs/users/venuelikes */ public func venuelikes(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/venuelikes" return self.getWithPath(path, parameters: parameters, completionHandler) } // MARK: - Actions /** https://developer.foursquare.com/docs/users/approve */ public func approve(userId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/approve" return self.postWithPath(path, parameters: nil, completionHandler) } /** https://developer.foursquare.com/docs/users/deny */ public func deny(userId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/deny" return self.postWithPath(path, parameters: nil, completionHandler) } /** https://developer.foursquare.com/docs/users/setpings */ public func setpings(userId: String, value: Bool, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/setpings" let parameters = [Parameter.value: (value) ? "true":"false"] return self.postWithPath(path, parameters: parameters, completionHandler) } /** https://developer.foursquare.com/docs/users/unfriend */ public func unfriend(userId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/unfriend" return self.postWithPath(path, parameters: nil, completionHandler) } /** https://developer.foursquare.com/docs/users/update */ public func update(photoURL: NSURL, completionHandler: ResponseClosure? = nil) -> Task { let path = UserSelf + "/update" let task = self.uploadTaskFromURL(photoURL, path: path, parameters: nil, completionHandler: completionHandler) return task } }
bsd-2-clause
2ded0ac84438e32df625f55d9726b922
43.241667
134
0.669618
4.568847
false
false
false
false
fancymax/12306ForMac
12306ForMac/Utilities/QueryDefaultManager.swift
1
2902
// // UserDefaultManager.swift // Train12306 // // Created by fancymax on 15/11/26. // Copyright © 2015年 fancy. All rights reserved. // import Foundation class QueryDefaultManager { static let sharedInstance = QueryDefaultManager() private let userNameKey = "userName" private let userPasswordKey = "userPassword" private let fromStationKey = "fromStation" private let toStationKey = "toStation" private let queryDateKey = "queryDate" private let selectedPassenger = "selectedPassenger" private let allSelectedDate = "allSelectedDate" private let ticketTaskManager = "ticketTaskManager" private let userDefaults = UserDefaults.standard private init() { registerUserDefault() } private func registerUserDefault() { let firstDefault = [fromStationKey: "深圳", toStationKey:"上海",queryDateKey:Date()] as [String : Any] userDefaults.register(defaults: firstDefault) } var lastUserName:String?{ get{ return userDefaults.object(forKey: userNameKey) as? String } set(newValue){ userDefaults.set(newValue, forKey: userNameKey) } } var lastUserPassword:String?{ get{ return userDefaults.object(forKey: userPasswordKey) as? String } set(newValue){ userDefaults.set(newValue, forKey: userPasswordKey) } } var lastFromStation:String{ get{ return userDefaults.object(forKey: fromStationKey) as! String } set(newValue){ userDefaults.set(newValue, forKey: fromStationKey) } } var lastToStation:String{ get{ return userDefaults.object(forKey: toStationKey) as! String } set(newValue){ userDefaults.set(newValue, forKey: toStationKey) } } var lastQueryDate:Date{ get{ return userDefaults.object(forKey: queryDateKey) as! Date } set(newValue){ userDefaults.set(newValue, forKey: queryDateKey) } } var lastSelectedPassenger:String? { get { return userDefaults.object(forKey: selectedPassenger) as? String } set(newValue) { userDefaults.set(newValue,forKey: selectedPassenger) } } var lastAllSelectedDates:[Date]? { get { return userDefaults.array(forKey: allSelectedDate) as? [Date] } set(newValue) { userDefaults.set(newValue,forKey: allSelectedDate) } } var lastTicketTaskManager:String? { get { return userDefaults.object(forKey: ticketTaskManager) as? String } set(newValue) { userDefaults.set(newValue,forKey: ticketTaskManager) } } }
mit
57040757c70f3078817eb3e5eb764305
26.018692
76
0.604981
4.778512
false
false
false
false
DerrickQin2853/SinaWeibo-Swift
SinaWeibo/SinaWeibo/Classes/View/EmoticonKeyboard/View/DQEmoticonPopView.swift
1
1072
// // DQEmoticonPopView.swift // SinaWeibo // // Created by admin on 2016/10/10. // Copyright © 2016年 Derrick_Qin. All rights reserved. // import UIKit import pop class DQEmoticonPopView: UIView { @IBOutlet weak var emoticonButton: DQEmoticonButton! var lastEmoticon: DQEmoticon? class func loadPopoView() -> DQEmoticonPopView { let nib = UINib(nibName: "DQEmoticonPopView", bundle: nil) return nib.instantiate(withOwner: nil, options: nil).last as! DQEmoticonPopView } func showEmoticon() { if let em = lastEmoticon { if em.chs == emoticonButton.emoticon?.chs { return } if em.code == emoticonButton.emoticon?.code { return } } let anim = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)! anim.fromValue = 40 anim.toValue = 25 anim.springBounciness = 20 anim.springSpeed = 20 emoticonButton.pop_add(anim, forKey: nil) } }
mit
a8a911b99b9e53ab33668653f93c7375
22.23913
87
0.589336
4.587983
false
false
false
false
arslanbilal/Swift-Stack
Stack.swift
1
1344
// // Stack.swift // Stack // // Created by Bilal ARSLAN on 11/10/14. // Copyright (c) 2014 Bilal ARSLAN. All rights reserved. // import Foundation class Stack<T> { private var top: Int private var items: [T] var size:Int init() { top = -1 items = [T]() size = 7 } init(size:Int) { top = -1 items = [T]() self.size = size } func push(item: T) -> Bool { if !isFull() { items.append(item) top++ return true } print("Stack is full! Could not pushed.") return false } func pop() -> T? { if !isEmpty() { top-- return items.removeLast() } print("Stack is empty! Could not popped.") return nil } func peek() -> T? { if !isEmpty() { return items.last } return nil } func isEmpty() -> Bool { return top == -1 } func isFull() -> Bool { return top == (size - 1) } func count() -> Int { return (top + 1) } func printStack() { for var i = items.count-1; i>=0; i-- { print("| \(items[i]) |") } print(" ------ ") print("\n\n") } }
mit
5c6bfce697fc1df1d0ca0ce51863a2af
16.684211
57
0.41369
3.884393
false
false
false
false
YesVideo/swix
swix_ios_app/swix_ios_app/swix/tests/speed.swift
1
1807
// // speed.swift // swix // // Created by Scott Sievert on 8/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation // should be run while optimized! class swixSpeedTests { init(){ time(pe1, name:"Project Euler 1") time(pe10, name:"Project Euler 10") time(pe73, name:"Project Euler 73") time(pi_approx, name:"Pi approximation") time(soft_thresholding, name:"Soft thresholding") } } func time(f:()->(), name:String="function"){ let start = NSDate() f() print(NSString(format:"\(name) time (s): %.4f", -1 * start.timeIntervalSinceNow)) } func pe1(){ let N = 1e6 let x = arange(N) // seeing where that modulo is 0 var i = argwhere((abs(x%3) < 1e-9) || (abs(x%5) < 1e-9)) // println(sum(x[i])) // prints 233168.0, the correct answer } func pe10(){ // find all primes let N = 2e6.int var primes = arange(Double(N)) let top = (sqrt(N.double)).int for i in 2 ..< top{ let max:Int = (N/i) let j = arange(2, max: max.double) * i.double primes[j] *= 0.0 } // sum(primes) is the correct answer } func pe73(){ let N = 1e3 let i = arange(N)+1 var (n, d) = meshgrid(i, y: i) var f = (n / d).flat f = unique(f) var j = (f > 1/3) && (f < 1/2) // println(f[argwhere(j)].n) } func soft_thresholding(){ let N = 1e2.int let j = linspace(-1, max: 1, num:N) var (x, y) = meshgrid(j, y: j) var z = pow(x, power: 2) + pow(y, power: 2) let i = abs(z) < 0.5 z[argwhere(i)] *= 0 z[argwhere(1-i)] -= 0.5 } func pi_approx(){ let N = 1e6 var k = arange(N) var pi_approx = 1 / (2*k + 1) pi_approx[2*k[0..<(N/2).int]+1] *= -1 // println(4 * pi_approx) // prints 3.14059265383979 }
mit
4b6e3d53e5c2eb9a021a8a6bcfc37d27
22.480519
85
0.542889
2.797214
false
false
false
false
mlilback/MJLCommon
Sources/MJLCommon/ExpiringCache.swift
1
2154
// // ExpiringCache.swift // // Copyright ©2017 Mark Lilback. This file is licensed under the ISC license. // import Foundation /// a psuedo dicionary that can remove items after a certain time interval has passed /// the owner must call expire() to remove expired entries public struct ExpiringCache<Key: Hashable, Value>: Collection { public typealias Element = (key: Key, value: Value) public typealias Iterator = DictionaryIterator<Key, Value> public typealias Index = DictionaryIndex<Key, Value> private var contents = [Key: Value]() private var times = [Key: TimeInterval]() public var startIndex: Index { return contents.startIndex } public var endIndex: Dictionary<Key, Value>.Index { return contents.endIndex } public let entryDuration: TimeInterval /// create an expiring cache /// /// - Parameter duration: the lifetime of an entry in the cache public init(duration: TimeInterval) { entryDuration = duration } public subscript (position: Index) -> Iterator.Element { return contents[position] } public subscript (key: Key) -> Value? { get { return contents[key] } set { contents[key] = newValue guard newValue != nil else { times.removeValue(forKey: key); return } times[key] = Date.timeIntervalSinceReferenceDate } } /// Removes all items from the cache public mutating func removeAll() { contents.removeAll() times.removeAll() } /// removes all expired items from the cache public mutating func expire() { let targetTime = Date.timeIntervalSinceReferenceDate - entryDuration times.keys.forEach { guard let keyTime = times[$0] else { return } if keyTime > targetTime { contents.removeValue(forKey: $0) times.removeValue(forKey: $0) } } } /// remove the value stored for key from the cache public mutating func removeValue(forKey key: Key) { contents.removeValue(forKey: key) times.removeValue(forKey: key) } public func index(after i: Dictionary<Key, Value>.Index) -> Dictionary<Key, Value>.Index { return contents.index(after: i) } public func makeIterator() -> DictionaryIterator<Key, Value> { return contents.makeIterator() } }
isc
d07fc7526c4a0eff05a85480785ab77d
27.706667
91
0.718997
3.858423
false
false
false
false
frootloops/swift
test/SILGen/call_chain_reabstraction.swift
1
1012
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s struct A { func g<U>(_ recur: (A, U) -> U) -> (A, U) -> U { return { _, x in return x } } // CHECK-LABEL: sil hidden @_T024call_chain_reabstraction1AV1f{{[_0-9a-zA-Z]*}}F // CHECK: [[G:%.*]] = function_ref @_T024call_chain_reabstraction1AV1g{{[_0-9a-zA-Z]*}}F // CHECK: [[G2:%.*]] = apply [[G]]<A> // CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @_T024call_chain_reabstraction1AVA2CIegyir_A3CIegyyd_TR // CHECK: [[REABSTRACT:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[G2]]) // CHECK: [[BORROW:%.*]] = begin_borrow [[REABSTRACT]] // CHECK: apply [[BORROW]]([[SELF:%.*]], [[SELF]]) // CHECK: destroy_value [[REABSTRACT]] func f() { let recur: (A, A) -> A = { c, x in x } let b = g(recur)(self, self) } }
apache-2.0
a81251cd23edd11a84d4b6f79fd4038f
52.263158
121
0.483202
3.477663
false
false
false
false
tdjackey/TicTacToe
TicTacToe/TicTacToe/ViewController.swift
1
10315
// // ViewController.swift // TicTacToe // // Created by 龚杰 on 7/29/15. // Copyright (c) 2015 tdjackey. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. clear() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var click = 0 var result = [0, 0, 0, 0, 0, 0, 0, 0, 0] var keyMove = -1 var whowins = 0 @IBOutlet weak var result1: UILabel! @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! @IBOutlet weak var button4: UIButton! @IBOutlet weak var button5: UIButton! @IBOutlet weak var button6: UIButton! @IBOutlet weak var button7: UIButton! @IBOutlet weak var button8: UIButton! @IBOutlet weak var button9: UIButton! @IBAction func touch1(sender: UIButton) { sender.setTitle("o", forState: UIControlState.Normal) result[0] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch2(sender: UIButton) { sender.setTitle("o", forState: UIControlState.Normal) result[1] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch3(sender: UIButton) { sender.setTitle("o", forState: UIControlState.Normal) result[2] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch4(sender: AnyObject) { sender.setTitle("o", forState: UIControlState.Normal) result[3] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch5(sender: AnyObject) { sender.setTitle("o", forState: UIControlState.Normal) result[4] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch6(sender: AnyObject) { sender.setTitle("o", forState: UIControlState.Normal) result[5] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch7(sender: AnyObject) { sender.setTitle("o", forState: UIControlState.Normal) result[6] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch8(sender: AnyObject) { sender.setTitle("o", forState: UIControlState.Normal) result[7] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } @IBAction func touch9(sender: AnyObject) { sender.setTitle("o", forState: UIControlState.Normal) result[8] = 1 click++ AIsolve() if click > 2 { var temp = checkboard() result1.text = temp } } func AImove(input: Int) { if input == 0{ button1.setTitle("x", forState: UIControlState.Normal) result[0] = 2 } if input == 1{ button2.setTitle("x", forState: UIControlState.Normal) result[1] = 2 } if input == 2{ button3.setTitle("x", forState: UIControlState.Normal) result[2] = 2 } if input == 3{ button4.setTitle("x", forState: UIControlState.Normal) result[3] = 2 } if input == 4{ button5.setTitle("x", forState: UIControlState.Normal) result[4] = 2 } if input == 5{ button6.setTitle("x", forState: UIControlState.Normal) result[5] = 2 } if input == 6{ button7.setTitle("x", forState: UIControlState.Normal) result[6] = 2 } if input == 7{ button8.setTitle("x", forState: UIControlState.Normal) result[7] = 2 } if input == 8{ button9.setTitle("x", forState: UIControlState.Normal) result[8] = 2 } } func AIsolve() { if nextToWin2() == true{ AImove(keyMove) keyMove = -1 var temp = checkboard() result1.text = temp } if nextToWin1() == true{ AImove(keyMove) keyMove = -1 var temp = checkboard() result1.text = temp } if(result[4] == 0){ button5.setTitle("x", forState: UIControlState.Normal) result[4] = 2 var temp = checkboard() result1.text = temp return } //var temp = Int(arc4random() % 2) if result[0] == 0{ button1.setTitle("x", forState: UIControlState.Normal) result[0] = 2 var temp = checkboard() result1.text = temp return }else if result[2] == 0{ button3.setTitle("x", forState: UIControlState.Normal) result[2] = 2 var temp = checkboard() result1.text = temp return } if result[6] == 0{ button7.setTitle("x", forState: UIControlState.Normal) result[6] = 2 var temp = checkboard() result1.text = temp return }else if result[8] == 0{ button9.setTitle("x", forState: UIControlState.Normal) result[8] = 2 var temp = checkboard() result1.text = temp return } //button2.setTitle("x", forState: UIControlState.Normal) } func clear(){ button1.setTitle("", forState:UIControlState.Normal) button2.setTitle("", forState:UIControlState.Normal) button3.setTitle("", forState:UIControlState.Normal) button4.setTitle("", forState:UIControlState.Normal) button5.setTitle("", forState:UIControlState.Normal) button6.setTitle("", forState:UIControlState.Normal) button7.setTitle("", forState:UIControlState.Normal) button8.setTitle("", forState:UIControlState.Normal) button9.setTitle("", forState:UIControlState.Normal) click = 0 result = [0,0,0,0,0,0,0,0,0] whowins = 0 keyMove = -1 //button5.setTitle("x", forState: UIControlState.Normal) //result[4] = 2 //var temp = checkboard() //result1.text = temp return } func nextToWin1() -> Bool { var i = 0 keyMove = -1 for i = 0; i < 9; i++ { if result[i] == 0 { result[i] = 1 if checkboard() == "Player 1 wins" { keyMove = i result[i] = 0 return true } result[i] = 0 } } return false } func nextToWin2() -> Bool { var i = 0 keyMove = -1 for i = 0; i < 9; i++ { if result[i] == 0 { result[i] = 2 if checkboard() == "AI wins" { keyMove = i result[i] = 0 return true } result[i] = 0 } } return false } func checkboard() -> String { //println("haha") if result[0] == result[1] && result[1] == result[2] && result[0] != 0{ if result[0] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else if result[3] == result[4] && result[4] == result[5] && result[3] != 0{ if result[3] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else if result[6] == result[7] && result[7] == result[8] && result[6] != 0{ if result[6] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else if result[0] == result[3] && result[3] == result[6] && result[6] != 0{ if result[0] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else if result[1] == result[4] && result[4] == result[7] && result[4] != 0{ if result[1] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else if result[2] == result[5] && result[5] == result[8] && result[5] != 0{ if result[2] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else if result[0] == result[4] && result[4] == result[8] && result[4] != 0{ if result[0] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else if result[2] == result[4] && result[4] == result[6] && result[2] != 0{ if result[2] == 2{ clear() return "AI wins" }else{ clear() return "Player 1 wins" } }else{ if click > 5{ clear() return "tie" }else { return "" } } } }
cc0-1.0
bd373bffded487cc47d8c99c604236bb
27.641667
84
0.462904
4.372774
false
false
false
false
efremidze/Magnetic
Sources/SKMultilineLabelNode.swift
1
2866
// // SKMultilineLabelNode.swift // Magnetic // // Created by Lasha Efremidze on 5/11/17. // Copyright © 2017 efremidze. All rights reserved. // import SpriteKit @objcMembers open class SKMultilineLabelNode: SKNode { open var text: String? { didSet { update() } } open var fontName: String? { didSet { update() } } open var fontSize: CGFloat = 32 { didSet { update() } } open var fontColor: UIColor? { didSet { update() } } open var separator: String? { didSet { update() } } open var verticalAlignmentMode: SKLabelVerticalAlignmentMode = .baseline { didSet { update() } } open var horizontalAlignmentMode: SKLabelHorizontalAlignmentMode = .center { didSet { update() } } open var lineHeight: CGFloat? { didSet { update() } } open var width: CGFloat! { didSet { update() } } func update() { self.removeAllChildren() guard let text = text else { return } var stack = Stack<String>() var sizingLabel = makeSizingLabel() let words = separator.map { text.components(separatedBy: $0) } ?? text.map { String($0) } for (index, word) in words.enumerated() { sizingLabel.text += word if sizingLabel.frame.width > width, index > 0 { stack.add(toStack: word) sizingLabel = makeSizingLabel() } else { stack.add(toCurrent: word) } } let lines = stack.values.map { $0.joined(separator: separator ?? "") } for (index, line) in lines.enumerated() { let label = SKLabelNode(fontNamed: fontName) label.text = line label.fontSize = fontSize label.fontColor = fontColor label.verticalAlignmentMode = verticalAlignmentMode label.horizontalAlignmentMode = horizontalAlignmentMode let y = (CGFloat(index) - (CGFloat(lines.count) / 2) + 0.5) * -(lineHeight ?? fontSize) label.position = CGPoint(x: 0, y: y) self.addChild(label) } } private func makeSizingLabel() -> SKLabelNode { let label = SKLabelNode(fontNamed: fontName) label.fontSize = fontSize return label } } private struct Stack<U> { typealias T = (stack: [[U]], current: [U]) private var value: T var values: [[U]] { return value.stack + [value.current] } init() { self.value = (stack: [], current: []) } mutating func add(toStack element: U) { self.value = (stack: value.stack + [value.current], current: [element]) } mutating func add(toCurrent element: U) { self.value = (stack: value.stack, current: value.current + [element]) } } private func +=(lhs: inout String?, rhs: String) { lhs = (lhs ?? "") + rhs }
mit
a86db3db906d1de13c80ce6d451c73df
31.931034
102
0.580105
4.276119
false
false
false
false
swift-gtk/SwiftGTK
Sources/UIKit/HeaderBar.swift
1
5077
public class HeaderBar: Container { /* internal var n_HeaderBar: UnsafeMutablePointer<GtkHeaderBar> internal init(n_HeaderBar: UnsafeMutablePointer<GtkHeaderBar>) { self.n_HeaderBar = n_HeaderBar super.init(n_Container: UnsafeMutablePointer<GtkContainer>(n_HeaderBar)) } /// Creates a new `HeaderBar` widget. public convenience init() { self.init(n_HeaderBar: UnsafeMutablePointer<GtkHeaderBar>(gtk_header_bar_new())) } /// The title should help a user identify the current view. A good title /// should not include the application name. public var title: String { set { gtk_header_bar_set_title(n_HeaderBar, newValue) } get { return String(cString: gtk_header_bar_get_title(n_HeaderBar)) } } /// The title should give a user an additional detail to help him identify the /// current view. /// /// - Note: `HeaderBar` by default reserves room for the subtitle, even if /// none is currently set. If this is not desired, set the `hasSubtitle` /// property to `false`. public var subtitle: String { set { gtk_header_bar_set_subtitle(n_HeaderBar, subtitle) } get { return String(cString: gtk_header_bar_get_subtitle(n_HeaderBar)) } } /// Whether the header bar should reserve space for a subtitle, even if none /// is currently set. public var hasSubtitle: Bool { set { gtk_header_bar_set_has_subtitle(n_HeaderBar, newValue ? 1 : 0) } get { return gtk_header_bar_get_has_subtitle(n_HeaderBar) != 0 } } internal weak var _customTitle: Widget? /// Center widget; that is a child widget that will be centered with respect /// to the full width of the box, even if the children at either side take up /// different amounts of space. public var customTitle: Widget? { set { gtk_header_bar_set_custom_title(n_HeaderBar, newValue?.n_Widget) _customTitle = newValue } get { let n_Widget = gtk_header_bar_get_custom_title(n_HeaderBar) if n_Widget == _customTitle?.n_Widget { return _customTitle } if let n_Widget = n_Widget { print("WARNING: [HeaderBar.customTitle] generate widget from pointer") let widget = Container.correctWidgetForWidget(Widget(n_Widget: n_Widget)) _customTitle = widget return widget } return nil } } /// Adds `child` to bar, packed with reference to the start of the bar. /// /// - Parameter child: the `Widget` to be added to bar public func packStart(child: Widget) { guard child.parent == nil else { return } gtk_header_bar_pack_start(n_HeaderBar, child.n_Widget) if !_children.contains(child) { _children.append(child) } } /// Adds `child` to bar, packed with reference to the end of the bar. /// /// Parameter child: the `Widget` to be added to bar public func packEnd(child: Widget) { guard child.parent == nil else { return } gtk_header_bar_pack_end(n_HeaderBar, child.n_Widget) if !_children.contains(child) { _children.append(child) } } /// Whether this header bar shows the standard window decorations, including /// close, maximize, and minimize. public var showCloseButton: Bool { set { gtk_header_bar_set_show_close_button(n_HeaderBar, newValue ? 1 : 0) } get { return gtk_header_bar_get_show_close_button(n_HeaderBar) != 0 } } /// The decoration layout for this header bar, overriding the /// `DecorationLayout` setting. /// /// There can be valid reasons for overriding the setting, such as a header /// bar design that does not allow for buttons to take room on the right, or /// only offers room for a single close button. Split header bars are another /// example for overriding the setting. /// /// The format of the string is button names, separated by commas. A colon /// separates the buttons that should appear on the left from those on the /// right. Recognized button names are minimize, maximize, close, icon (the /// window icon) and menu (a menu button for the fallback app menu). /// /// For example, `“menu:minimize,maximize,close”` specifies a menu on the /// left, and minimize, maximize and close buttons on the right. public var decorationLayout: String { set { gtk_header_bar_set_decoration_layout(n_HeaderBar, newValue) } get { return String(cString: gtk_header_bar_get_decoration_layout(n_HeaderBar)) } } */ }
gpl-2.0
6236ee13523482471aac9d8363b87fe5
33.746575
86
0.591169
4.43832
false
false
false
false
reactive-swift/Event
Sources/Event/EventEmitter.swift
1
4644
//===--- EventEmitter.swift ----------------------------------------------===// //Copyright (c) 2016 Crossroad Labs s.r.o. // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import Boilerplate import ExecutionContext internal struct Listener { internal let _id:NSUUID internal let listener:(Signal<Any>)->Void internal let event:HashableContainer internal init<Payload>(event:HashableContainer, listener:@escaping (Signal<Payload>)->Void) { self._id = NSUUID() self.event = event self.listener = { signature, payload in guard let payload = payload as? Payload else { return } listener((signature, payload)) } } } extension Listener : Hashable { internal var hashValue: Int { get { return self._id.hashValue } } } internal func ==(lhs:Listener, rhs:Listener) -> Bool { return lhs._id == rhs._id } public protocol EventEmitter : AnyObject, ExecutionContextTenantProtocol, SignatureProvider { var dispatcher:EventDispatcher {get} } public extension EventEmitter { public var signature: Int { get { return dispatcher.signature } } } public typealias Off = ()->Void public extension EventEmitter { internal func on<E : Event>(_ event: E, handler:@escaping (Signal<E.Payload>)->Void) -> Off { let listener = dispatcher.addListener(event: event, context: context, handler: handler) return { [weak self]()->Void in self?.dispatcher.removeListener(listener: listener, context: self!.context) } } public func emit<E : Event>(_ event: E, payload:E.Payload, signature:Set<Int> = []) { dispatcher.dispatch(event, context: context, payload: payload, signature: signature) } } public struct HashableContainer : Hashable { private let _hash:Int internal let _equator:(Any)->Bool public let value:Any public init<T: Hashable>(hashable:T) { self._hash = hashable.hashValue self._equator = { other in guard let other = other as? T else { return false } return hashable == other } self.value = hashable } public var hashValue: Int { get { return self._hash } } } public func ==(lhs:HashableContainer, rhs:HashableContainer) -> Bool { return lhs._equator(rhs.value) } public class EventDispatcher : SignatureProvider { private var registry:Dictionary<HashableContainer,Set<Listener>> = [:] public init() { } internal func addListener<E : Event>(event: E, context:ExecutionContextProtocol, handler:@escaping (Signal<E.Payload>)->Void) -> Listener { return context.sync { let container = HashableContainer(hashable: event) let listener = Listener(event: container, listener: handler) if self.registry[container] == nil { self.registry[container] = Set() } self.registry[container]?.insert(listener) return listener } } internal func removeListener(listener:Listener, context:ExecutionContextProtocol) { context.immediateIfCurrent { let _ = self.registry[listener.event]?.remove(listener) } } internal func dispatch<E : Event>(_ event:E, context:ExecutionContextProtocol, payload:E.Payload, signature:Set<Int>) { let sig = self.signature if signature.contains(sig) { return } var sigset = signature sigset.insert(sig) context.immediateIfCurrent { let container = HashableContainer(hashable: event) if let listeners = self.registry[container] { for listener in listeners { listener.listener((sigset, payload)) } } } } }
apache-2.0
4c4e0f663439949c421e604405e95716
29.352941
143
0.595392
4.862827
false
false
false
false
cfilipov/TextTable
Sources/TextTable/SimpleFormat.swift
1
1185
// // SimpleFormat.swift // TextTable // // Created by Cristian Filipov on 8/13/16. // // import Foundation public enum Simple: TextTableStyle { public static func prepare(_ s: String, for column: Column) -> String { var string = s if let width = column.width { string = string.truncated(column.truncate, length: width) string = string.pad(column.align, length: width) } return escape(string) } public static func escape(_ s: String) -> String { return s } public static func begin(_ table: inout String, index: Int, columns: [Column]) { } public static func end(_ table: inout String, index: Int, columns: [Column]) { } public static func header(_ table: inout String, index: Int, columns: [Column]) { table += columns.map{$0.headerString(for: self)}.joined(separator: " ") table += "\n" table += columns.map{$0.repeated("-")}.joined(separator: " ") table += "\n" } public static func row(_ table: inout String, index: Int, columns: [Column]) { table += columns.map{$0.string(for: self)}.joined(separator: " ") table += "\n" } }
mit
1316eca53f72a6836940a15e7b744fb7
29.384615
86
0.597468
3.847403
false
false
false
false
thomaskamps/SlideFeedback
SlideFeedback/SlideFeedback/FirebaseManager.swift
1
5106
// // FirebaseManager.swift // SlideFeedback // // Created by Thomas Kamps on 08-06-17. // Copyright © 2017 Thomas Kamps. All rights reserved. // import Foundation import Firebase class FirebaseManager { // make singleton static let sharedInstance = FirebaseManager() private init() { // listen for changes in authstate Auth.auth().addStateDidChangeListener() { auth, user in // if a user is logged in if user != nil { self.userID = Auth.auth().currentUser?.uid // get users role self.ref.child("users").child(self.userID!).observeSingleEvent(of: .value, with: { (snapshot) in let value = snapshot.value as? NSDictionary self.role = value?["role"] as? Int NotificationCenter.default.post(name: Notification.Name("userStatusChanged"), object: nil) }) { (error) in print(error.localizedDescription) } } else { NotificationCenter.default.post(name: Notification.Name("userLoggedOut"), object: nil) } } userID = Auth.auth().currentUser?.uid } // init vars var ref = Database.database().reference() var userID: String? var role: Int? var history: [String: [String: Any]]? // Log in and automatically set userID func login(email: String, password: String) throws { var saveError: Any? Auth.auth().signIn(withEmail: email, password: password) {(user, error) in saveError = error } if saveError == nil { self.userID = Auth.auth().currentUser?.uid } else { throw saveError as! Error! } } func logOut() throws { do { try Auth.auth().signOut() } catch let signOutError as NSError { throw signOutError } } func createUser(name: String, password: String, email: String) throws { var registerError: Any? Auth.auth().createUser(withEmail: email, password: password) {(user, error) in registerError = error if error == nil { self.ref.child("users").child((user?.uid)!).setValue(["name": name, "role": 10]) } } // when user is created without errors, log him in if registerError == nil { do { try self.login(email: email, password: password) } catch let loginError as NSError { throw loginError } } else { throw registerError as! NSError } } func startSlides(dirName: String, uniqueID: String, timeStamp: String, name: String, numPages: Int) { // save data for slides let data = ["dirName": dirName, "timeStamp": timeStamp, "name": name, "numPages": numPages] as [String : Any] self.ref.child("users").child(self.userID!).child(self.getRefName()).child(uniqueID).setValue(data) } func saveFeedback(uniqueID: String, currentPage: Int, feedback: String, studentCount: Int?) { // save data for feedback let feedbackRef = self.ref.child("users").child(self.userID!).child(self.getRefName()).child(uniqueID).child("feedback") let key = feedbackRef.childByAutoId().key feedbackRef.child(key).setValue(["page": currentPage, "feedback": feedback, "studentCount": studentCount]) } func getHistory() { // retrieve historical data from db self.ref.child("users").child(self.userID!).child(self.getRefName()).observeSingleEvent(of: .value, with: { (snapshot) in // if history data is valid if let histDict = snapshot.value as? [String : [String : Any]] { // set data and notify self.history = histDict NotificationCenter.default.post(name: Notification.Name("newHistory"), object: nil) } }) } func deletePresentation(uniqueID: String) { // delete a presentation from history self.ref.child("users").child(self.userID!).child(self.getRefName()).child(uniqueID).removeValue() } func getRefName() -> String { // history is for lecturers and students stored under a different name // this is to prevent interference if a user is to switch roles if self.role == 20 { return "presentations" } else { return "saved_slides" } } }
unlicense
0b58c9aef509ec25ac4ee15bd6090b9a
29.568862
129
0.515965
5.151362
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Services/Service.TapManagement.swift
1
1364
import Foundation extension Service { open class TapManagement: Service { public init(characteristics: [AnyCharacteristic] = []) { var unwrapped = characteristics.map { $0.wrapped } active = getOrCreateAppend( type: .active, characteristics: &unwrapped, generator: { PredefinedCharacteristic.active() }) cryptoHash = getOrCreateAppend( type: .cryptoHash, characteristics: &unwrapped, generator: { PredefinedCharacteristic.cryptoHash() }) tapType = getOrCreateAppend( type: .tapType, characteristics: &unwrapped, generator: { PredefinedCharacteristic.tapType() }) token = getOrCreateAppend( type: .token, characteristics: &unwrapped, generator: { PredefinedCharacteristic.token() }) super.init(type: .tapManagement, characteristics: unwrapped) } // MARK: - Required Characteristics public let active: GenericCharacteristic<Enums.Active> public let cryptoHash: GenericCharacteristic<Data?> public let tapType: GenericCharacteristic<UInt16> public let token: GenericCharacteristic<Data?> // MARK: - Optional Characteristics } }
mit
c22fc9831f230717d6562321bbbf4df2
39.117647
72
0.596774
5.982456
false
false
false
false
sschiau/swift-package-manager
Sources/Basic/misc.swift
1
4422
/* 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 SPMLibc import POSIX /// Replace the current process image with a new process image. /// /// - Parameters: /// - path: Absolute path to the executable. /// - args: The executable arguments. public func exec(path: String, args: [String]) throws { let cArgs = CStringArray(args) guard execv(path, cArgs.cArray) != -1 else { throw POSIX.SystemError.exec(errno, path: path, args: args) } } // MARK: Utility function for searching for executables /// Create a list of AbsolutePath search paths from a string, such as the PATH environment variable. /// /// - Parameters: /// - pathString: The path string to parse. /// - currentWorkingDirectory: The current working directory, the relative paths will be converted to absolute paths /// based on this path. /// - Returns: List of search paths. public func getEnvSearchPaths( pathString: String?, currentWorkingDirectory: AbsolutePath? ) -> [AbsolutePath] { // Compute search paths from PATH variable. return (pathString ?? "").split(separator: ":").map(String.init).compactMap({ pathString in // If this is an absolute path, we're done. if pathString.first == "/" { return AbsolutePath(pathString) } // Otherwise convert it into absolute path relative to the working directory. guard let cwd = currentWorkingDirectory else { return nil } return AbsolutePath(pathString, relativeTo: cwd) }) } /// Lookup an executable path from an environment variable value, current working /// directory or search paths. Only return a value that is both found and executable. /// /// This method searches in the following order: /// * If env value is a valid absolute path, return it. /// * If env value is relative path, first try to locate it in current working directory. /// * Otherwise, in provided search paths. /// /// - Parameters: /// - filename: The name of the file to find. /// - currentWorkingDirectory: The current working directory to look in. /// - searchPaths: The additional search paths to look in if not found in cwd. /// - Returns: Valid path to executable if present, otherwise nil. public func lookupExecutablePath( filename value: String?, currentWorkingDirectory: AbsolutePath? = localFileSystem.currentWorkingDirectory, searchPaths: [AbsolutePath] = [] ) -> AbsolutePath? { // We should have a value to continue. guard let value = value, !value.isEmpty else { return nil } let path: AbsolutePath if let cwd = currentWorkingDirectory { // We have a value, but it could be an absolute or a relative path. path = AbsolutePath(value, relativeTo: cwd) } else if let absPath = try? AbsolutePath(validating: value) { // Current directory not being available is not a problem // for the absolute-specified paths. path = absPath } else { return nil } if localFileSystem.isExecutableFile(path) { return path } // Ensure the value is not a path. guard !value.contains("/") else { return nil } // Try to locate in search paths. for path in searchPaths { let exec = path.appending(component: value) if localFileSystem.isExecutableFile(exec) { return exec } } return nil } extension Range: Codable where Bound: Codable { private enum CodingKeys: String, CodingKey { case lowerBound, upperBound } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(lowerBound, forKey: .lowerBound) try container.encode(upperBound, forKey: .upperBound) } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let lowerBound = try container.decode(Bound.self, forKey: .lowerBound) let upperBound = try container.decode(Bound.self, forKey: .upperBound) self.init(uncheckedBounds: (lowerBound, upperBound)) } }
apache-2.0
7a59cb9b8ff89dd46229d71377949dee
34.95122
118
0.680914
4.563467
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Jetpack/Classes/ViewRelated/WordPress-to-Jetpack Migration/Success card/MigrationSuccessCardView.swift
1
3104
import UIKit @objc class MigrationSuccessCardView: UIView { private var onTap: (() -> Void)? private lazy var iconImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: Appearance.iconImageName)) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.layer.cornerRadius = 8 imageView.layer.cornerCurve = .continuous imageView.clipsToBounds = true return imageView }() private lazy var iconView: UIView = { let view = UIView() view.addSubview(iconImageView) return view }() private lazy var descriptionLabel: UILabel = { let label = UILabel() label.text = Appearance.descriptionText label.font = Appearance.descriptionFont label.numberOfLines = 0 label.adjustsFontForContentSizeCategory = true return label }() private lazy var mainStackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [iconView, descriptionLabel]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .horizontal stackView.spacing = 16 return stackView }() @objc private func viewTapped() { onTap?() } init(onTap: (() -> Void)? = nil) { self.onTap = onTap super.init(frame: .zero) addSubview(mainStackView) pinSubviewToAllEdges(mainStackView, insets: UIEdgeInsets(allEdges: 16)) NSLayoutConstraint.activate([ iconImageView.heightAnchor.constraint(equalToConstant: 32), iconImageView.widthAnchor.constraint(equalToConstant: 32), iconImageView.centerXAnchor.constraint(equalTo: iconView.centerXAnchor), iconImageView.centerYAnchor.constraint(equalTo: iconView.centerYAnchor), iconView.widthAnchor.constraint(equalTo: iconImageView.widthAnchor) ]) backgroundColor = .listForeground layer.cornerRadius = 10 clipsToBounds = true addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewTapped))) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private enum Appearance { static let iconImageName = "wp-migration-success-card-icon" static let descriptionText = NSLocalizedString("wp.migration.successcard.description", value: "Please delete the WordPress app", comment: "Description of the jetpack migration success card, used in My site.") static let descriptionFont = WPStyleGuide.fontForTextStyle(.subheadline, fontWeight: .regular) } } // TODO: This extension is temporary, and should be replaced by the actual condition to check, and placed in the proper location extension MigrationSuccessCardView { @objc static var shouldShowMigrationSuccessCard: Bool { AppConfiguration.isJetpack && showCard } private static let showCard = false }
gpl-2.0
256faf3d97bb07f7a89d13efcef39d3d
35.517647
134
0.662049
5.695413
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationsViewController.swift
1
79349
import Foundation import Combine import CoreData import CocoaLumberjack import WordPressShared import WordPressAuthenticator import Gridicons import UIKit /// The purpose of this class is to render the collection of Notifications, associated to the main /// WordPress.com account. /// /// Plus, we provide a simple mechanism to render the details for a specific Notification, /// given its remote identifier. /// class NotificationsViewController: UIViewController, UIViewControllerRestoration, UITableViewDataSource, UITableViewDelegate { @objc static let selectedNotificationRestorationIdentifier = "NotificationsSelectedNotificationKey" @objc static let selectedSegmentIndexRestorationIdentifier = "NotificationsSelectedSegmentIndexKey" // MARK: - Properties let formatter = FormattableContentFormatter() /// Table View /// @IBOutlet weak var tableView: UITableView! /// TableHeader /// @IBOutlet var tableHeaderView: UIView! /// Filtering Tab Bar /// @IBOutlet weak var filterTabBar: FilterTabBar! /// Jetpack Banner View /// Only visible in WordPress /// @IBOutlet weak var jetpackBannerView: JetpackBannerView! /// Inline Prompt Header View /// @IBOutlet var inlinePromptView: AppFeedbackPromptView! /// TableView Handler: Our commander in chief! /// fileprivate var tableViewHandler: WPTableViewHandler! /// NoResults View /// private let noResultsViewController = NoResultsViewController.controller() /// All of the data will be fetched during the FetchedResultsController init. Prevent overfetching /// fileprivate var lastReloadDate = Date() /// Indicates whether the view is required to reload results on viewWillAppear, or not /// var needsReloadResults = false /// Cached values used for returning the estimated row heights of autosizing cells. /// fileprivate let estimatedRowHeightsCache = NSCache<AnyObject, AnyObject>() /// Notifications that must be deleted display an "Undo" button, which simply cancels the deletion task. /// fileprivate var notificationDeletionRequests: [NSManagedObjectID: NotificationDeletionRequest] = [:] /// Notifications being deleted are proactively filtered from the list. /// fileprivate var notificationIdsBeingDeleted = Set<NSManagedObjectID>() /// Notifications that were unread when the list was loaded. /// fileprivate var unreadNotificationIds = Set<NSManagedObjectID>() /// Used to store (and restore) the currently selected filter segment. /// fileprivate var restorableSelectedSegmentIndex: Int = 0 /// Used to keep track of the currently selected notification, /// to restore it between table view reloads and state restoration. /// fileprivate var selectedNotification: Notification? = nil /// JetpackLoginVC being presented. /// internal var jetpackLoginViewController: JetpackLoginViewController? = nil /// Timestamp of the most recent note before updates /// Used to count notifications to show the second notifications prompt /// private var timestampBeforeUpdatesForSecondAlert: String? private lazy var notificationCommentDetailCoordinator: NotificationCommentDetailCoordinator = { return NotificationCommentDetailCoordinator(notificationsNavigationDataSource: self) }() /// Activity Indicator to be shown when refreshing a Jetpack site status. /// let activityIndicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView(style: .medium) indicator.hidesWhenStopped = true return indicator }() /// Notification Settings button private lazy var settingsBarButtonItem: UIBarButtonItem = { let settingsButton = UIBarButtonItem( image: .gridicon(.cog), style: .plain, target: self, action: #selector(showNotificationSettings) ) settingsButton.accessibilityLabel = NSLocalizedString( "Notification Settings", comment: "Link to Notification Settings section" ) return settingsButton }() /// Mark All As Read button private lazy var markAllAsReadBarButtonItem: UIBarButtonItem = { let markButton = UIBarButtonItem( image: .gridicon(.checkmark), style: .plain, target: self, action: #selector(showMarkAllAsReadConfirmation) ) markButton.accessibilityLabel = NSLocalizedString( "Mark All As Read", comment: "Marks all notifications under the filter as read" ) return markButton }() /// Used by JPScrollViewDelegate to send scroll position internal let scrollViewTranslationPublisher = PassthroughSubject<Bool, Never>() /// The last time when user seen notifications var lastSeenTime: String? { get { return userDefaults.string(forKey: Settings.lastSeenTime) } set { userDefaults.set(newValue, forKey: Settings.lastSeenTime) } } // MARK: - View Lifecycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) restorationClass = NotificationsViewController.self startListeningToAccountNotifications() startListeningToTimeChangeNotifications() } override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupTableHandler() setupTableView() setupTableFooterView() setupRefreshControl() setupNoResultsView() setupFilterBar() tableView.tableHeaderView = tableHeaderView setupConstraints() configureJetpackBanner() reloadTableViewPreservingSelection() startListeningToCommentDeletedNotifications() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) JetpackFeaturesRemovalCoordinator.presentOverlayIfNeeded(from: .notifications, in: self) syncNotificationsWithModeratedComments() setupInlinePrompt() // Manually deselect the selected row. if splitViewControllerIsHorizontallyCompact { // This is required due to a bug in iOS7 / iOS8 tableView.deselectSelectedRowWithAnimation(true) selectedNotification = nil } // While we're onscreen, please, update rows with animations tableViewHandler.updateRowAnimation = .fade // Tracking WPAnalytics.track(WPAnalyticsStat.openedNotificationsList) // Notifications startListeningToNotifications() resetApplicationBadge() updateLastSeenTime() // Refresh the UI reloadResultsControllerIfNeeded() updateMarkAllAsReadButton() if !splitViewControllerIsHorizontallyCompact { reloadTableViewPreservingSelection() } if shouldDisplayJetpackPrompt { promptForJetpackCredentials() } else { jetpackLoginViewController?.remove() } showNoResultsViewIfNeeded() selectFirstNotificationIfAppropriate() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) defer { if AppConfiguration.showsWhatIsNew { WPTabBarController.sharedInstance()?.presentWhatIsNew(on: self) } } syncNewNotifications() markSelectedNotificationAsRead() registerUserActivity() markWelcomeNotificationAsSeenIfNeeded() if userDefaults.notificationsTabAccessCount < Constants.inlineTabAccessCount { userDefaults.notificationsTabAccessCount += 1 } // Don't show the notification primers if we already asked during onboarding if userDefaults.onboardingNotificationsPromptDisplayed, userDefaults.notificationsTabAccessCount == 1 { return } if shouldShowPrimeForPush { setupNotificationPrompt() } else if AppRatingUtility.shared.shouldPromptForAppReview(section: InlinePrompt.section) { setupAppRatings() self.showInlinePrompt() } showNotificationPrimerAlertIfNeeded() showSecondNotificationsAlertIfNeeded() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopListeningToNotifications() dismissNoNetworkAlert() // If we're not onscreen, don't use row animations. Otherwise the fade animation might get animated incrementally tableViewHandler.updateRowAnimation = .none } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.layoutHeaderView() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) DispatchQueue.main.async { self.showNoResultsViewIfNeeded() } if splitViewControllerIsHorizontallyCompact { tableView.deselectSelectedRowWithAnimation(true) } else { if let selectedNotification = selectedNotification { selectRow(for: selectedNotification, animated: true, scrollPosition: .middle) } else { selectFirstNotificationIfAppropriate() } } tableView.tableHeaderView = tableHeaderView } // MARK: - State Restoration static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { return WPTabBarController.sharedInstance().notificationsViewController } override func encodeRestorableState(with coder: NSCoder) { if let uriRepresentation = selectedNotification?.objectID.uriRepresentation() { coder.encode(uriRepresentation, forKey: type(of: self).selectedNotificationRestorationIdentifier) } // If the filter's 'Unread', we won't save it because the notification // that's selected won't be unread any more once we come back to it. let index: Filter = (filter != .unread) ? filter : .none coder.encode(index.rawValue, forKey: type(of: self).selectedSegmentIndexRestorationIdentifier) super.encodeRestorableState(with: coder) } override func decodeRestorableState(with coder: NSCoder) { decodeSelectedSegmentIndex(with: coder) decodeSelectedNotification(with: coder) reloadResultsController() super.decodeRestorableState(with: coder) } fileprivate func decodeSelectedNotification(with coder: NSCoder) { if let uriRepresentation = coder.decodeObject(forKey: type(of: self).selectedNotificationRestorationIdentifier) as? URL { let context = ContextManager.sharedInstance().mainContext if let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: uriRepresentation), let object = try? context.existingObject(with: objectID), let notification = object as? Notification { selectedNotification = notification } } } fileprivate func decodeSelectedSegmentIndex(with coder: NSCoder) { restorableSelectedSegmentIndex = coder.decodeInteger(forKey: type(of: self).selectedSegmentIndexRestorationIdentifier) if let filterTabBar = filterTabBar, filterTabBar.selectedIndex != restorableSelectedSegmentIndex { filterTabBar.setSelectedIndex(restorableSelectedSegmentIndex, animated: false) } } override func applicationFinishedRestoringState() { super.applicationFinishedRestoringState() guard let navigationControllers = navigationController?.children else { return } // TODO: add check for CommentDetailViewController for case let detailVC as NotificationDetailsViewController in navigationControllers { if detailVC.onDeletionRequestCallback == nil, let note = detailVC.note { configureDetailsViewController(detailVC, withNote: note) } } } // MARK: - UITableViewDataSource Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableViewHandler.tableView(tableView, numberOfRowsInSection: section) } func numberOfSections(in tableView: UITableView) -> Int { tableViewHandler.numberOfSections(in: tableView) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ListTableViewCell.defaultReuseID, for: indexPath) configureCell(cell, at: indexPath) return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .none } // MARK: - UITableViewDelegate Methods func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sectionInfo = tableViewHandler.resultsController.sections?[section], let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ListTableHeaderView.defaultReuseID) as? ListTableHeaderView else { return nil } headerView.title = Notification.descriptionForSectionIdentifier(sectionInfo.name) return headerView } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Make sure no SectionFooter is rendered return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { // Make sure no SectionFooter is rendered return nil } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { estimatedRowHeightsCache.setObject(cell.frame.height as AnyObject, forKey: indexPath as AnyObject) } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { if let height = estimatedRowHeightsCache.object(forKey: indexPath as AnyObject) as? CGFloat { return height } return Settings.estimatedRowHeight } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Failsafe: Make sure that the Notification (still) exists guard let note = tableViewHandler.resultsController.managedObject(atUnsafe: indexPath) as? Notification else { tableView.deselectSelectedRowWithAnimation(true) return } // Push the Details: Unless the note has a pending deletion! guard deletionRequestForNoteWithID(note.objectID) == nil else { return } selectedNotification = note showDetails(for: note) if !splitViewControllerIsHorizontallyCompact { syncNotificationsWithModeratedComments() } } func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // skip when the notification is marked for deletion. guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification, deletionRequestForNoteWithID(note.objectID) == nil else { return nil } let isRead = note.read let title = isRead ? NSLocalizedString("Mark Unread", comment: "Marks a notification as unread") : NSLocalizedString("Mark Read", comment: "Marks a notification as unread") let action = UIContextualAction(style: .normal, title: title, handler: { (action, view, completionHandler) in if isRead { WPAnalytics.track(.notificationMarkAsUnreadTapped) self.markAsUnread(note: note) } else { WPAnalytics.track(.notificationMarkAsReadTapped) self.markAsRead(note: note) } completionHandler(true) }) action.backgroundColor = .neutral(.shade50) return UISwipeActionsConfiguration(actions: [action]) } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // skip when the notification is marked for deletion. guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification, let block: FormattableCommentContent = note.contentGroup(ofKind: .comment)?.blockOfKind(.comment), deletionRequestForNoteWithID(note.objectID) == nil else { return nil } // Approve comment guard let approveEnabled = block.action(id: ApproveCommentAction.actionIdentifier())?.enabled, approveEnabled == true, let approveAction = block.action(id: ApproveCommentAction.actionIdentifier()), let actionTitle = approveAction.command?.actionTitle else { return nil } let action = UIContextualAction(style: .normal, title: actionTitle, handler: { (_, _, completionHandler) in WPAppAnalytics.track(approveAction.on ? .notificationsCommentUnapproved : .notificationsCommentApproved, withProperties: [Stats.sourceKey: Stats.sourceValue], withBlogID: block.metaSiteID) let actionContext = ActionContext(block: block) approveAction.execute(context: actionContext) completionHandler(true) }) action.backgroundColor = approveAction.command?.actionColor let configuration = UISwipeActionsConfiguration(actions: [action]) configuration.performsFirstActionWithFullSwipe = false return configuration } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let note = sender as? Notification else { return } guard let detailsViewController = segue.destination as? NotificationDetailsViewController else { return } configureDetailsViewController(detailsViewController, withNote: note) } fileprivate func configureDetailsViewController(_ detailsViewController: NotificationDetailsViewController, withNote note: Notification) { detailsViewController.navigationItem.largeTitleDisplayMode = .never detailsViewController.dataSource = self detailsViewController.notificationCommentDetailCoordinator = notificationCommentDetailCoordinator detailsViewController.note = note detailsViewController.onDeletionRequestCallback = { request in self.showUndeleteForNoteWithID(note.objectID, request: request) } detailsViewController.onSelectedNoteChange = { note in self.selectRow(for: note) } } } // MARK: - User Interface Initialization // private extension NotificationsViewController { func setupNavigationBar() { navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .always // Don't show 'Notifications' in the next-view back button // we are using a space character because we need a non-empty string to ensure a smooth // transition back, with large titles enabled. navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) navigationItem.title = NSLocalizedString("Notifications", comment: "Notifications View Controller title") } func updateNavigationItems() { var barItems: [UIBarButtonItem] = [] if shouldDisplaySettingsButton { barItems.append(settingsBarButtonItem) } barItems.append(markAllAsReadBarButtonItem) navigationItem.setRightBarButtonItems(barItems, animated: false) } @objc func closeNotificationSettings() { dismiss(animated: true, completion: nil) } func setupConstraints() { // Inline prompt is initially hidden! inlinePromptView.translatesAutoresizingMaskIntoConstraints = false filterTabBar.tabBarHeightConstraintPriority = 999 let leading = tableHeaderView.safeLeadingAnchor.constraint(equalTo: tableView.safeLeadingAnchor) let trailing = tableHeaderView.safeTrailingAnchor.constraint(equalTo: tableView.safeTrailingAnchor) leading.priority = UILayoutPriority(999) trailing.priority = UILayoutPriority(999) NSLayoutConstraint.activate([ tableHeaderView.topAnchor.constraint(equalTo: tableView.topAnchor), leading, trailing ]) } func setupTableView() { // Register the cells tableView.register(ListTableHeaderView.defaultNib, forHeaderFooterViewReuseIdentifier: ListTableHeaderView.defaultReuseID) tableView.register(ListTableViewCell.defaultNib, forCellReuseIdentifier: ListTableViewCell.defaultReuseID) // UITableView tableView.accessibilityIdentifier = "Notifications Table" tableView.cellLayoutMarginsFollowReadableWidth = false tableView.estimatedSectionHeaderHeight = UITableView.automaticDimension WPStyleGuide.configureAutomaticHeightRows(for: tableView) WPStyleGuide.configureColors(view: view, tableView: tableView) } func setupTableFooterView() { // Fix: Hide the cellSeparators, when the table is empty tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 1)) } func setupTableHandler() { let handler = WPTableViewHandler(tableView: tableView) handler.cacheRowHeights = false handler.delegate = self tableViewHandler = handler } func setupInlinePrompt() { precondition(inlinePromptView != nil) inlinePromptView.alpha = WPAlphaZero inlinePromptView.isHidden = true } func setupRefreshControl() { let control = UIRefreshControl() control.addTarget(self, action: #selector(refresh), for: .valueChanged) tableView.refreshControl = control } func setupNoResultsView() { noResultsViewController.delegate = self } func setupFilterBar() { WPStyleGuide.configureFilterTabBar(filterTabBar) filterTabBar.superview?.backgroundColor = .filterBarBackground filterTabBar.items = Filter.allCases filterTabBar.addTarget(self, action: #selector(selectedFilterDidChange(_:)), for: .valueChanged) } } // MARK: - Jetpack banner UI Initialization // extension NotificationsViewController { /// Called on view load to determine whether the Jetpack banner should be shown on the view /// Also called in the completion block of the JetpackLoginViewController to show the banner once the user connects to a .com account func configureJetpackBanner() { guard JetpackBrandingVisibility.all.enabled else { return } jetpackBannerView.buttonAction = { [unowned self] in JetpackBrandingCoordinator.presentOverlay(from: self) JetpackBrandingAnalyticsHelper.trackJetpackPoweredBannerTapped(screen: .notifications) } jetpackBannerView.isHidden = false addTranslationObserver(jetpackBannerView) } } // MARK: - Notifications // private extension NotificationsViewController { func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) nc.addObserver(self, selector: #selector(notificationsWereUpdated), name: NSNotification.Name(rawValue: NotificationSyncMediatorDidUpdateNotifications), object: nil) nc.addObserver(self, selector: #selector(dynamicTypeDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil) } func startListeningToAccountNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(defaultAccountDidChange), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil) } func startListeningToTimeChangeNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(significantTimeChange), name: UIApplication.significantTimeChangeNotification, object: nil) } func startListeningToCommentDeletedNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(removeDeletedNotification), name: .NotificationCommentDeletedNotification, object: nil) } func stopListeningToNotifications() { let nc = NotificationCenter.default nc.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) nc.removeObserver(self, name: NSNotification.Name(rawValue: NotificationSyncMediatorDidUpdateNotifications), object: nil) } @objc func applicationDidBecomeActive(_ note: Foundation.Notification) { // Let's reset the badge, whenever the app comes back to FG, and this view was upfront! guard isViewLoaded == true && view.window != nil else { return } resetApplicationBadge() updateLastSeenTime() reloadResultsControllerIfNeeded() } @objc func defaultAccountDidChange(_ note: Foundation.Notification) { resetNotifications() resetLastSeenTime() resetApplicationBadge() guard isViewLoaded == true && view.window != nil else { needsReloadResults = true return } reloadResultsController() syncNewNotifications() } @objc func notificationsWereUpdated(_ note: Foundation.Notification) { // If we're onscreen, don't leave the badge updated behind guard UIApplication.shared.applicationState == .active else { return } resetApplicationBadge() updateLastSeenTime() } @objc func significantTimeChange(_ note: Foundation.Notification) { needsReloadResults = true if UIApplication.shared.applicationState == .active && isViewLoaded == true && view.window != nil { reloadResultsControllerIfNeeded() } } @objc func dynamicTypeDidChange() { tableViewHandler.resultsController.fetchedObjects?.forEach { ($0 as? Notification)?.resetCachedAttributes() } } } // MARK: - Public Methods // extension NotificationsViewController { /// Pushes the Details for a given notificationID, immediately, if the notification is already available. /// Otherwise, will attempt to Sync the Notification. If this cannot be achieved before the timeout defined /// by `Syncing.pushMaxWait` kicks in, we'll just do nothing (in order not to disrupt the UX!). /// /// - Parameter notificationID: The ID of the Notification that should be rendered onscreen. /// @objc func showDetailsForNotificationWithID(_ noteId: String) { if let note = loadNotification(with: noteId) { showDetails(for: note) return } syncNotification(with: noteId, timeout: Syncing.pushMaxWait) { note in self.showDetails(for: note) } } /// Pushes the details for a given Notification Instance. /// private func showDetails(for note: Notification) { DDLogInfo("Pushing Notification Details for: [\(note.notificationId)]") // Before trying to show the details of a notification, we need to make sure the view is loaded. // // Ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/12669#issuecomment-561579415 // Ref: https://sentry.io/organizations/a8c/issues/1329631657/ // loadViewIfNeeded() /// Note: markAsRead should be the *first* thing we do. This triggers a context save, and may have many side effects that /// could affect the OP's that go below!!!. /// /// YES figuring that out took me +90 minutes of debugger time!!! /// markAsRead(note: note) trackWillPushDetails(for: note) ensureNotificationsListIsOnscreen() ensureNoteIsNotBeingFiltered(note) selectRow(for: note, animated: false, scrollPosition: .top) // Display Details // if let postID = note.metaPostID, let siteID = note.metaSiteID, note.kind == .matcher || note.kind == .newPost { let readerViewController = ReaderDetailViewController.controllerWithPostID(postID, siteID: siteID) readerViewController.navigationItem.largeTitleDisplayMode = .never showDetailViewController(readerViewController, sender: nil) return } presentDetails(for: note) } private func presentDetails(for note: Notification) { // This dispatch avoids a bug that was occurring occasionally where navigation (nav bar and tab bar) // would be missing entirely when launching the app from the background and presenting a notification. // The issue seems tied to performing a `pop` in `prepareToShowDetails` and presenting // the new detail view controller at the same time. More info: https://github.com/wordpress-mobile/WordPress-iOS/issues/6976 // // Plus: Avoid pushing multiple DetailsViewController's, upon quick & repeated touch events. view.isUserInteractionEnabled = false DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.view.isUserInteractionEnabled = true if FeatureFlag.notificationCommentDetails.enabled, note.kind == .comment { guard let commentDetailViewController = self.notificationCommentDetailCoordinator.createViewController(with: note) else { DDLogError("Notifications: failed creating Comment Detail view.") return } self.notificationCommentDetailCoordinator.onSelectedNoteChange = { [weak self] note in self?.selectRow(for: note) } commentDetailViewController.navigationItem.largeTitleDisplayMode = .never self.showDetailViewController(commentDetailViewController, sender: nil) return } self.performSegue(withIdentifier: NotificationDetailsViewController.classNameWithoutNamespaces(), sender: note) } } /// Tracks: Details Event! /// private func trackWillPushDetails(for note: Notification) { // Ensure we don't track if the app has been launched by a push notification in the background if UIApplication.shared.applicationState != .background { let properties = [Stats.noteTypeKey: note.type ?? Stats.noteTypeUnknown] WPAnalytics.track(.openedNotificationDetails, withProperties: properties) } } /// Failsafe: Make sure the Notifications List is onscreen! /// private func ensureNotificationsListIsOnscreen() { guard navigationController?.visibleViewController != self else { return } _ = navigationController?.popViewController(animated: false) } /// This method will make sure the Notification that's about to be displayed is not currently being filtered. /// private func ensureNoteIsNotBeingFiltered(_ note: Notification) { guard filter != .none else { return } let noteIndexPath = tableView.indexPathsForVisibleRows?.first { indexPath in return note == tableViewHandler.resultsController.object(at: indexPath) as? Notification } guard noteIndexPath == nil else { return } filter = .none } /// Will display an Undelete button on top of a given notification. /// On timeout, the destructive action (received via parameter) will be executed, and the notification /// will (supposedly) get deleted. /// /// - Parameters: /// - noteObjectID: The Core Data ObjectID associated to a given notification. /// - request: A DeletionRequest Struct /// private func showUndeleteForNoteWithID(_ noteObjectID: NSManagedObjectID, request: NotificationDeletionRequest) { // Mark this note as Pending Deletion and Reload notificationDeletionRequests[noteObjectID] = request reloadRowForNotificationWithID(noteObjectID) // Dispatch the Action block perform(#selector(deleteNoteWithID), with: noteObjectID, afterDelay: Syncing.undoTimeout) } /// Presents the Notifications Settings screen. /// @objc func showNotificationSettings() { let controller = NotificationSettingsViewController() controller.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(closeNotificationSettings)) let navigationController = UINavigationController(rootViewController: controller) navigationController.modalPresentationStyle = .formSheet navigationController.modalTransitionStyle = .coverVertical present(navigationController, animated: true, completion: nil) } } // MARK: - Notifications Deletion Mechanism // private extension NotificationsViewController { @objc func deleteNoteWithID(_ noteObjectID: NSManagedObjectID) { // Was the Deletion Canceled? guard let request = deletionRequestForNoteWithID(noteObjectID) else { return } // Hide the Notification notificationIdsBeingDeleted.insert(noteObjectID) reloadResultsController() // Hit the Deletion Action request.action { success in self.notificationDeletionRequests.removeValue(forKey: noteObjectID) self.notificationIdsBeingDeleted.remove(noteObjectID) // Error: let's unhide the row if success == false { self.reloadResultsController() } } } func cancelDeletionRequestForNoteWithID(_ noteObjectID: NSManagedObjectID) { notificationDeletionRequests.removeValue(forKey: noteObjectID) reloadRowForNotificationWithID(noteObjectID) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(deleteNoteWithID), object: noteObjectID) } func deletionRequestForNoteWithID(_ noteObjectID: NSManagedObjectID) -> NotificationDeletionRequest? { return notificationDeletionRequests[noteObjectID] } // MARK: - Notifications Deletion from CommentDetailViewController // With the `notificationCommentDetails` feature, Comment moderation is handled by the view. // To avoid updating the Notifications here prematurely, affecting the previous/next buttons, // the Notifications are tracked in NotificationCommentDetailCoordinator when their comments are moderated. // Those Notifications are updated here when the view is shown to update the list accordingly. func syncNotificationsWithModeratedComments() { selectNextAvailableNotification(ignoring: notificationCommentDetailCoordinator.notificationsCommentModerated) notificationCommentDetailCoordinator.notificationsCommentModerated.forEach { syncNotification(with: $0.notificationId, timeout: Syncing.pushMaxWait, success: {_ in }) } notificationCommentDetailCoordinator.notificationsCommentModerated = [] } @objc func removeDeletedNotification(notification: NSNotification) { guard let userInfo = notification.userInfo, let deletedCommentID = userInfo[userInfoCommentIdKey] as? Int32, let notifications = tableViewHandler.resultsController.fetchedObjects as? [Notification] else { return } let notification = notifications.first(where: { notification -> Bool in guard let commentID = notification.metaCommentID else { return false } return commentID.intValue == deletedCommentID }) syncDeletedNotification(notification) } func syncDeletedNotification(_ notification: Notification?) { guard let notification = notification else { return } selectNextAvailableNotification(ignoring: [notification]) syncNotification(with: notification.notificationId, timeout: Syncing.pushMaxWait, success: { [weak self] notification in self?.notificationCommentDetailCoordinator.notificationsCommentModerated.removeAll(where: { $0.notificationId == notification.notificationId }) }) } func selectNextAvailableNotification(ignoring: [Notification]) { // If the currently selected notification is about to be removed, find the next available and select it. // This is only necessary for split view to prevent the details from showing for removed notifications. if !splitViewControllerIsHorizontallyCompact, let selectedNotification = selectedNotification, ignoring.contains(selectedNotification) { guard let notifications = tableViewHandler.resultsController.fetchedObjects as? [Notification], let nextAvailable = notifications.first(where: { !ignoring.contains($0) }), let indexPath = tableViewHandler.resultsController.indexPath(forObject: nextAvailable) else { self.selectedNotification = nil return } self.selectedNotification = nextAvailable tableView(tableView, didSelectRowAt: indexPath) } } } // MARK: - Marking as Read // private extension NotificationsViewController { private enum Localization { static let markAllAsReadNoticeSuccess = NSLocalizedString( "Notifications marked as read", comment: "Title for mark all as read success notice" ) static let markAllAsReadNoticeFailure = NSLocalizedString( "Failed marking Notifications as read", comment: "Message for mark all as read success notice" ) } func markSelectedNotificationAsRead() { guard let note = selectedNotification else { return } markAsRead(note: note) } func markAsRead(note: Notification) { guard !note.read else { return } NotificationSyncMediator()?.markAsRead(note) } /// Marks all messages as read under the selected filter. /// @objc func markAllAsRead() { guard let notes = tableViewHandler.resultsController.fetchedObjects as? [Notification] else { return } WPAnalytics.track(.notificationsMarkAllReadTapped) let unreadNotifications = notes.filter { !$0.read } NotificationSyncMediator()?.markAsRead(unreadNotifications, completion: { [weak self] error in let notice = Notice( title: error != nil ? Localization.markAllAsReadNoticeFailure : Localization.markAllAsReadNoticeSuccess ) ActionDispatcherFacade().dispatch(NoticeAction.post(notice)) self?.updateMarkAllAsReadButton() }) } /// Presents a confirmation action sheet for mark all as read action. @objc func showMarkAllAsReadConfirmation() { let title: String switch filter { case .none: title = NSLocalizedString( "Mark all notifications as read?", comment: "Confirmation title for marking all notifications as read." ) default: title = NSLocalizedString( "Mark all %1$@ notifications as read?", comment: "Confirmation title for marking all notifications under a filter as read. %1$@ is replaced by the filter name." ) } let cancelTitle = NSLocalizedString( "Cancel", comment: "Cancels the mark all as read action." ) let markAllTitle = NSLocalizedString( "OK", comment: "Marks all notifications as read." ) let alertController = UIAlertController( title: String.localizedStringWithFormat(title, filter.confirmationMessageTitle), message: nil, preferredStyle: .alert ) alertController.view.accessibilityIdentifier = "mark-all-as-read-alert" alertController.addCancelActionWithTitle(cancelTitle) alertController.addActionWithTitle(markAllTitle, style: .default) { [weak self] _ in self?.markAllAsRead() } present(alertController, animated: true, completion: nil) } func markAsUnread(note: Notification) { guard note.read else { return } NotificationSyncMediator()?.markAsUnread(note) updateMarkAllAsReadButton() } func markWelcomeNotificationAsSeenIfNeeded() { let welcomeNotificationSeenKey = userDefaults.welcomeNotificationSeenKey if !userDefaults.bool(forKey: welcomeNotificationSeenKey) { userDefaults.set(true, forKey: welcomeNotificationSeenKey) resetApplicationBadge() } } func updateMarkAllAsReadButton() { guard let notes = tableViewHandler.resultsController.fetchedObjects as? [Notification] else { return } let isEnabled = notes.first { !$0.read } != nil markAllAsReadBarButtonItem.tintColor = isEnabled ? .primary : .textTertiary markAllAsReadBarButtonItem.isEnabled = isEnabled } } // MARK: - Unread notifications caching // private extension NotificationsViewController { /// Updates the cached list of unread notifications, and optionally reloads the results controller. /// func refreshUnreadNotifications(reloadingResultsController: Bool = true) { guard let notes = tableViewHandler.resultsController.fetchedObjects as? [Notification] else { return } let previous = unreadNotificationIds // This is additive because we don't want to remove anything // from the list unless we explicitly call // clearUnreadNotifications() notes.lazy.filter({ !$0.read }).forEach { note in unreadNotificationIds.insert(note.objectID) } if previous != unreadNotificationIds && reloadingResultsController { reloadResultsController() } } /// Empties the cached list of unread notifications. /// func clearUnreadNotifications() { let shouldReload = !unreadNotificationIds.isEmpty unreadNotificationIds.removeAll() if shouldReload { reloadResultsController() } } } // MARK: - WPTableViewHandler Helpers // private extension NotificationsViewController { func reloadResultsControllerIfNeeded() { // NSFetchedResultsController groups notifications based on a transient property ("sectionIdentifier"). // Simply calling reloadData doesn't make the FRC recalculate the sections. // For that reason, let's force a reload, only when 1 day has elapsed, and sections would have changed. // let daysElapsed = Calendar.current.daysElapsedSinceDate(lastReloadDate) guard daysElapsed != 0 || needsReloadResults else { return } reloadResultsController() } func reloadResultsController() { // Update the Predicate: We can't replace the previous fetchRequest, since it's readonly! let fetchRequest = tableViewHandler.resultsController.fetchRequest fetchRequest.predicate = predicateForFetchRequest() /// Refetch + Reload _ = try? tableViewHandler.resultsController.performFetch() reloadTableViewPreservingSelection() // Empty State? showNoResultsViewIfNeeded() // Don't overwork! lastReloadDate = Date() needsReloadResults = false updateMarkAllAsReadButton() } func reloadRowForNotificationWithID(_ noteObjectID: NSManagedObjectID) { do { let note = try mainContext.existingObject(with: noteObjectID) if let indexPath = tableViewHandler.resultsController.indexPath(forObject: note) { tableView.reloadRows(at: [indexPath], with: .fade) } } catch { DDLogError("Error refreshing Notification Row \(error)") } } func selectRow(for notification: Notification, animated: Bool = true, scrollPosition: UITableView.ScrollPosition = .none) { selectedNotification = notification // also ensure that the index path returned from results controller does not have negative row index. // ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/15370 guard let indexPath = tableViewHandler.resultsController.indexPath(forObject: notification), indexPath != tableView.indexPathForSelectedRow, 0..<tableView.numberOfRows(inSection: indexPath.section) ~= indexPath.row else { return } DDLogInfo("\(self) \(#function) Selecting row at \(indexPath) for Notification: \(notification.notificationId) (\(notification.type ?? "Unknown type")) - \(notification.title ?? "No title")") tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition) } func reloadTableViewPreservingSelection() { tableView.reloadData() // Show the current selection if our split view isn't collapsed if !splitViewControllerIsHorizontallyCompact, let notification = selectedNotification { selectRow(for: notification, animated: false, scrollPosition: .none) } } } // MARK: - UIRefreshControl Methods // extension NotificationsViewController { @objc func refresh() { guard let mediator = NotificationSyncMediator() else { tableView.refreshControl?.endRefreshing() return } let start = Date() mediator.sync { [weak self] (error, _) in let delta = max(Syncing.minimumPullToRefreshDelay + start.timeIntervalSinceNow, 0) let delay = DispatchTime.now() + Double(Int64(delta * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delay) { self?.tableView.refreshControl?.endRefreshing() self?.clearUnreadNotifications() if let _ = error { self?.handleConnectionError() } } } } } extension NotificationsViewController: NetworkAwareUI { func contentIsEmpty() -> Bool { return tableViewHandler.resultsController.isEmpty() } func noConnectionMessage() -> String { return NSLocalizedString("No internet connection. Some content may be unavailable while offline.", comment: "Error message shown when the user is browsing Notifications without an internet connection.") } } extension NotificationsViewController: NetworkStatusDelegate { func networkStatusDidChange(active: Bool) { reloadResultsControllerIfNeeded() } } // MARK: - FilterTabBar Methods // extension NotificationsViewController { @objc func selectedFilterDidChange(_ filterBar: FilterTabBar) { selectedNotification = nil let properties = [Stats.selectedFilter: filter.analyticsTitle] WPAnalytics.track(.notificationsTappedSegmentedControl, withProperties: properties) updateUnreadNotificationsForFilterTabChange() reloadResultsController() selectFirstNotificationIfAppropriate() } @objc func selectFirstNotificationIfAppropriate() { guard !splitViewControllerIsHorizontallyCompact && selectedNotification == nil else { return } // If we don't currently have a selected notification and there is a notification in the list, then select it. if let firstNotification = tableViewHandler.resultsController.fetchedObjects?.first as? Notification, let indexPath = tableViewHandler.resultsController.indexPath(forObject: firstNotification) { selectRow(for: firstNotification, animated: false, scrollPosition: .none) self.tableView(tableView, didSelectRowAt: indexPath) return } // If we're not showing the Jetpack prompt or the fullscreen No Results View, // then clear any detail view controller that may be present. // (i.e. don't add an empty detail VC if the primary is full width) if let splitViewController = splitViewController as? WPSplitViewController, splitViewController.wpPrimaryColumnWidth != WPSplitViewControllerPrimaryColumnWidth.full { let controller = UIViewController() controller.navigationItem.largeTitleDisplayMode = .never showDetailViewController(controller, sender: nil) } } @objc func updateUnreadNotificationsForFilterTabChange() { if filter == .unread { refreshUnreadNotifications(reloadingResultsController: false) } else { clearUnreadNotifications() } } } // MARK: - WPTableViewHandlerDelegate Methods // extension NotificationsViewController: WPTableViewHandlerDelegate { func managedObjectContext() -> NSManagedObjectContext { return ContextManager.sharedInstance().mainContext } func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> { let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName()) request.sortDescriptors = [NSSortDescriptor(key: Filter.sortKey, ascending: false)] request.predicate = predicateForFetchRequest() return request } @objc func predicateForFetchRequest() -> NSPredicate { let deletedIdsPredicate = NSPredicate(format: "NOT (SELF IN %@)", Array(notificationIdsBeingDeleted)) let selectedFilterPredicate = predicateForSelectedFilters() return NSCompoundPredicate(andPredicateWithSubpredicates: [deletedIdsPredicate, selectedFilterPredicate]) } @objc func predicateForSelectedFilters() -> NSPredicate { guard let condition = filter.condition else { return NSPredicate(value: true) } var subpredicates: [NSPredicate] = [NSPredicate(format: condition)] if filter == .unread { subpredicates.append(NSPredicate(format: "SELF IN %@", Array(unreadNotificationIds))) } return NSCompoundPredicate(orPredicateWithSubpredicates: subpredicates) } func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) { guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification, let cell = cell as? ListTableViewCell else { return } cell.configureWithNotification(note) // handle undo overlays let deletionRequest = deletionRequestForNoteWithID(note.objectID) cell.configureUndeleteOverlay(with: deletionRequest?.kind.legendText) { [weak self] in self?.cancelDeletionRequestForNoteWithID(note.objectID) } // additional configurations cell.accessibilityHint = Self.accessibilityHint(for: note) } func sectionNameKeyPath() -> String { return "sectionIdentifier" } @objc func entityName() -> String { return Notification.classNameWithoutNamespaces() } private var shouldCountNotificationsForSecondAlert: Bool { userDefaults.notificationPrimerInlineWasAcknowledged && userDefaults.secondNotificationsAlertCount != Constants.secondNotificationsAlertDisabled } func tableViewWillChangeContent(_ tableView: UITableView) { guard shouldCountNotificationsForSecondAlert, let notification = tableViewHandler.resultsController.fetchedObjects?.first as? Notification, let timestamp = notification.timestamp else { timestampBeforeUpdatesForSecondAlert = nil return } timestampBeforeUpdatesForSecondAlert = timestamp } func tableViewDidChangeContent(_ tableView: UITableView) { refreshUnreadNotifications() // Update NoResults View showNoResultsViewIfNeeded() if let selectedNotification = selectedNotification { selectRow(for: selectedNotification, animated: false, scrollPosition: .none) } else { selectFirstNotificationIfAppropriate() } // count new notifications for second alert guard shouldCountNotificationsForSecondAlert else { return } userDefaults.secondNotificationsAlertCount += newNotificationsForSecondAlert if isViewOnScreen() { showSecondNotificationsAlertIfNeeded() } } // counts the new notifications for the second alert private var newNotificationsForSecondAlert: Int { guard let previousTimestamp = timestampBeforeUpdatesForSecondAlert, let notifications = tableViewHandler.resultsController.fetchedObjects as? [Notification] else { return 0 } for notification in notifications.enumerated() { if let timestamp = notification.element.timestamp, timestamp <= previousTimestamp { return notification.offset } } return 0 } private static func accessibilityHint(for note: Notification) -> String? { switch note.kind { case .comment: return NSLocalizedString("Shows details and moderation actions.", comment: "Accessibility hint for a comment notification.") case .commentLike, .like: return NSLocalizedString("Shows all likes.", comment: "Accessibility hint for a post or comment “like” notification.") case .follow: return NSLocalizedString("Shows all followers", comment: "Accessibility hint for a follow notification.") case .matcher, .newPost: return NSLocalizedString("Shows the post", comment: "Accessibility hint for a match/mention on a post notification.") default: return nil } } } // MARK: - Filter Helpers // private extension NotificationsViewController { func showFiltersSegmentedControlIfApplicable() { guard filterTabBar.isHidden == true && shouldDisplayFilters == true else { return } UIView.animate(withDuration: WPAnimationDurationDefault, animations: { self.filterTabBar.isHidden = false }) } func hideFiltersSegmentedControlIfApplicable() { if filterTabBar.isHidden == false && shouldDisplayFilters == false { self.filterTabBar.isHidden = true } } var shouldDisplayFilters: Bool { // Filters should only be hidden whenever there are no Notifications in the bucket (contrary to the FRC's // results, which are filtered by the active predicate!). // return mainContext.countObjects(ofType: Notification.self) > 0 && !shouldDisplayJetpackPrompt } } // MARK: - NoResults Helpers // private extension NotificationsViewController { func showNoResultsViewIfNeeded() { noResultsViewController.removeFromView() updateSplitViewAppearanceForNoResultsView() updateNavigationItems() // Hide the filter header if we're showing the Jetpack prompt hideFiltersSegmentedControlIfApplicable() // Show Filters if needed guard shouldDisplayNoResultsView == true else { showFiltersSegmentedControlIfApplicable() return } guard connectionAvailable() else { showNoConnectionView() return } // Refresh its properties: The user may have signed into WordPress.com noResultsViewController.configure(title: noResultsTitleText, buttonTitle: noResultsButtonText, subtitle: noResultsMessageText, image: "wp-illustration-notifications") addNoResultsToView() } func showNoConnectionView() { noResultsViewController.configure(title: noConnectionTitleText, subtitle: noConnectionMessage()) addNoResultsToView() } func addNoResultsToView() { addChild(noResultsViewController) tableView.insertSubview(noResultsViewController.view, belowSubview: tableHeaderView) noResultsViewController.view.frame = tableView.frame setupNoResultsViewConstraints() noResultsViewController.didMove(toParent: self) } func setupNoResultsViewConstraints() { guard let nrv = noResultsViewController.view else { return } tableHeaderView.translatesAutoresizingMaskIntoConstraints = false nrv.translatesAutoresizingMaskIntoConstraints = false nrv.setContentHuggingPriority(.defaultLow, for: .horizontal) NSLayoutConstraint.activate([ nrv.widthAnchor.constraint(equalTo: view.widthAnchor), nrv.centerXAnchor.constraint(equalTo: view.centerXAnchor), nrv.topAnchor.constraint(equalTo: tableHeaderView.bottomAnchor), nrv.bottomAnchor.constraint(equalTo: view.safeBottomAnchor) ]) } func updateSplitViewAppearanceForNoResultsView() { guard let splitViewController = splitViewController as? WPSplitViewController else { return } // Ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/14547 // Don't attempt to resize the columns for full width. let columnWidth: WPSplitViewControllerPrimaryColumnWidth = .default // The above line should be replace with the following line when the full width issue is resolved. // let columnWidth: WPSplitViewControllerPrimaryColumnWidth = (shouldDisplayFullscreenNoResultsView || shouldDisplayJetpackPrompt) ? .full : .default if splitViewController.wpPrimaryColumnWidth != columnWidth { splitViewController.wpPrimaryColumnWidth = columnWidth } if columnWidth == .default { splitViewController.dimDetailViewController(shouldDimDetailViewController, withAlpha: WPAlphaZero) } } var noConnectionTitleText: String { return NSLocalizedString("Unable to Sync", comment: "Title of error prompt shown when a sync the user initiated fails.") } var noResultsTitleText: String { return filter.noResultsTitle } var noResultsMessageText: String? { guard AppConfiguration.showsReader else { return nil } return filter.noResultsMessage } var noResultsButtonText: String? { guard AppConfiguration.showsReader else { return nil } return filter.noResultsButtonTitle } var shouldDisplayJetpackPrompt: Bool { return AccountHelper.isDotcomAvailable() == false && blogForJetpackPrompt != nil } var shouldDisplaySettingsButton: Bool { return AccountHelper.isDotcomAvailable() } var shouldDisplayNoResultsView: Bool { return tableViewHandler.resultsController.fetchedObjects?.count == 0 && !shouldDisplayJetpackPrompt } var shouldDisplayFullscreenNoResultsView: Bool { return shouldDisplayNoResultsView && filter == .none } var shouldDimDetailViewController: Bool { return shouldDisplayNoResultsView && filter != .none } } // MARK: - NoResultsViewControllerDelegate extension NotificationsViewController: NoResultsViewControllerDelegate { func actionButtonPressed() { let properties = [Stats.sourceKey: Stats.sourceValue] switch filter { case .none, .comment, .follow, .like: WPAnalytics.track(.notificationsTappedViewReader, withProperties: properties) WPTabBarController.sharedInstance().showReaderTab() case .unread: WPAnalytics.track(.notificationsTappedNewPost, withProperties: properties) WPTabBarController.sharedInstance().showPostTab() } } } // MARK: - Inline Prompt Helpers // internal extension NotificationsViewController { func showInlinePrompt() { guard inlinePromptView.alpha != WPAlphaFull, userDefaults.notificationPrimerAlertWasDisplayed, userDefaults.notificationsTabAccessCount >= Constants.inlineTabAccessCount else { return } UIView.animate(withDuration: WPAnimationDurationDefault, delay: 0, options: .curveEaseIn, animations: { self.inlinePromptView.isHidden = false }) UIView.animate(withDuration: WPAnimationDurationDefault * 0.5, delay: WPAnimationDurationDefault * 0.75, options: .curveEaseIn, animations: { self.inlinePromptView.alpha = WPAlphaFull }) WPAnalytics.track(.appReviewsSawPrompt) } func hideInlinePrompt(delay: TimeInterval) { UIView.animate(withDuration: WPAnimationDurationDefault * 0.75, delay: delay, animations: { self.inlinePromptView.alpha = WPAlphaZero }) UIView.animate(withDuration: WPAnimationDurationDefault, delay: delay + WPAnimationDurationDefault * 0.5, animations: { self.inlinePromptView.isHidden = true }) } } // MARK: - Sync'ing Helpers // private extension NotificationsViewController { func syncNewNotifications() { guard connectionAvailable() else { return } let mediator = NotificationSyncMediator() mediator?.sync() } func syncNotification(with noteId: String, timeout: TimeInterval, success: @escaping (_ note: Notification) -> Void) { let mediator = NotificationSyncMediator() let startDate = Date() DDLogInfo("Sync'ing Notification [\(noteId)]") mediator?.syncNote(with: noteId) { error, note in guard abs(startDate.timeIntervalSinceNow) <= timeout else { DDLogError("Error: Timeout while trying to load Notification [\(noteId)]") return } guard let note = note else { DDLogError("Error: Couldn't load Notification [\(noteId)]") return } DDLogInfo("Notification Sync'ed in \(startDate.timeIntervalSinceNow) seconds") success(note) } } func updateLastSeenTime() { guard let note = tableViewHandler.resultsController.fetchedObjects?.first as? Notification else { return } guard let timestamp = note.timestamp, timestamp != lastSeenTime else { return } let mediator = NotificationSyncMediator() mediator?.updateLastSeen(timestamp) { error in guard error == nil else { return } self.lastSeenTime = timestamp } } func loadNotification(with noteId: String) -> Notification? { let predicate = NSPredicate(format: "(notificationId == %@)", noteId) return mainContext.firstObject(ofType: Notification.self, matching: predicate) } func loadNotification(near note: Notification, withIndexDelta delta: Int) -> Notification? { guard let notifications = tableViewHandler?.resultsController.fetchedObjects as? [Notification] else { return nil } guard let noteIndex = notifications.firstIndex(of: note) else { return nil } let targetIndex = noteIndex + delta guard targetIndex >= 0 && targetIndex < notifications.count else { return nil } func notMatcher(_ note: Notification) -> Bool { return note.kind != .matcher } if delta > 0 { return notifications .suffix(from: targetIndex) .first(where: notMatcher) } else { return notifications .prefix(through: targetIndex) .reversed() .first(where: notMatcher) } } func resetNotifications() { do { selectedNotification = nil mainContext.deleteAllObjects(ofType: Notification.self) try mainContext.save() } catch { DDLogError("Error while trying to nuke Notifications Collection: [\(error)]") } } func resetLastSeenTime() { lastSeenTime = nil } func resetApplicationBadge() { // These notifications are cleared, so we just need to take Zendesk unread notifications // into account when setting the app icon count. UIApplication.shared.applicationIconBadgeNumber = ZendeskUtils.unreadNotificationsCount } } // MARK: - WPSplitViewControllerDetailProvider // extension NotificationsViewController: WPSplitViewControllerDetailProvider { func initialDetailViewControllerForSplitView(_ splitView: WPSplitViewController) -> UIViewController? { // The first notification view will be populated by `selectFirstNotificationIfAppropriate` // on viewWillAppear, so we'll just return an empty view here. let controller = UIViewController() controller.view.backgroundColor = .basicBackground return controller } private func fetchFirstNotification() -> Notification? { let context = managedObjectContext() let fetchRequest = self.fetchRequest() fetchRequest.fetchLimit = 1 if let results = try? context.fetch(fetchRequest) as? [Notification] { return results.first } return nil } } // MARK: - Details Navigation Datasource // extension NotificationsViewController: NotificationsNavigationDataSource { @objc func notification(succeeding note: Notification) -> Notification? { return loadNotification(near: note, withIndexDelta: -1) } @objc func notification(preceding note: Notification) -> Notification? { return loadNotification(near: note, withIndexDelta: +1) } } // MARK: - SearchableActivity Conformance // extension NotificationsViewController: SearchableActivityConvertable { var activityType: String { return WPActivityType.notifications.rawValue } var activityTitle: String { return NSLocalizedString("Notifications", comment: "Title of the 'Notifications' tab - used for spotlight indexing on iOS.") } var activityKeywords: Set<String>? { let keyWordString = NSLocalizedString("wordpress, notifications, alerts, updates", comment: "This is a comma separated list of keywords used for spotlight indexing of the 'Notifications' tab.") let keywordArray = keyWordString.arrayOfTags() guard !keywordArray.isEmpty else { return nil } return Set(keywordArray) } } // MARK: - Private Properties // private extension NotificationsViewController { var mainContext: NSManagedObjectContext { return ContextManager.sharedInstance().mainContext } var actionsService: NotificationActionsService { return NotificationActionsService(managedObjectContext: mainContext) } var userDefaults: UserPersistentRepository { return UserPersistentStoreFactory.instance() } var filter: Filter { get { let selectedIndex = filterTabBar?.selectedIndex ?? Filter.none.rawValue return Filter(rawValue: selectedIndex) ?? .none } set { filterTabBar?.setSelectedIndex(newValue.rawValue) reloadResultsController() } } enum Filter: Int, FilterTabBarItem, CaseIterable { case none = 0 case unread = 1 case comment = 2 case follow = 3 case like = 4 var condition: String? { switch self { case .none: return nil case .unread: return "read = NO" case .comment: return "type = '\(NotificationKind.comment.rawValue)'" case .follow: return "type = '\(NotificationKind.follow.rawValue)'" case .like: return "type = '\(NotificationKind.like.rawValue)' OR type = '\(NotificationKind.commentLike.rawValue)'" } } var title: String { switch self { case .none: return NSLocalizedString("All", comment: "Displays all of the Notifications, unfiltered") case .unread: return NSLocalizedString("Unread", comment: "Filters Unread Notifications") case .comment: return NSLocalizedString("Comments", comment: "Filters Comments Notifications") case .follow: return NSLocalizedString("Follows", comment: "Filters Follows Notifications") case .like: return NSLocalizedString("Likes", comment: "Filters Likes Notifications") } } var analyticsTitle: String { switch self { case .none: return "All" case .unread: return "Unread" case .comment: return "Comments" case .follow: return "Follows" case .like: return "Likes" } } var confirmationMessageTitle: String { switch self { case .none: return "" case .unread: return NSLocalizedString("unread", comment: "Displayed in the confirmation alert when marking unread notifications as read.") case .comment: return NSLocalizedString("comment", comment: "Displayed in the confirmation alert when marking comment notifications as read.") case .follow: return NSLocalizedString("follow", comment: "Displayed in the confirmation alert when marking follow notifications as read.") case .like: return NSLocalizedString("like", comment: "Displayed in the confirmation alert when marking like notifications as read.") } } var noResultsTitle: String { switch self { case .none: return NSLocalizedString("No notifications yet", comment: "Displayed in the Notifications Tab as a title, when there are no notifications") case .unread: return NSLocalizedString("You're all up to date!", comment: "Displayed in the Notifications Tab as a title, when the Unread Filter shows no unread notifications as a title") case .comment: return NSLocalizedString("No comments yet", comment: "Displayed in the Notifications Tab as a title, when the Comments Filter shows no notifications") case .follow: return NSLocalizedString("No followers yet", comment: "Displayed in the Notifications Tab as a title, when the Follow Filter shows no notifications") case .like: return NSLocalizedString("No likes yet", comment: "Displayed in the Notifications Tab as a title, when the Likes Filter shows no notifications") } } var noResultsMessage: String { switch self { case .none: return NSLocalizedString("Get active! Comment on posts from blogs you follow.", comment: "Displayed in the Notifications Tab as a message, when there are no notifications") case .unread: return NSLocalizedString("Reignite the conversation: write a new post.", comment: "Displayed in the Notifications Tab as a message, when the Unread Filter shows no notifications") case .comment: return NSLocalizedString("Join a conversation: comment on posts from blogs you follow.", comment: "Displayed in the Notifications Tab as a message, when the Comments Filter shows no notifications") case .follow, .like: return NSLocalizedString("Get noticed: comment on posts you've read.", comment: "Displayed in the Notifications Tab as a message, when the Follow Filter shows no notifications") } } var noResultsButtonTitle: String { switch self { case .none, .comment, .follow, .like: return NSLocalizedString("Go to Reader", comment: "Displayed in the Notifications Tab as a button title, when there are no notifications") case .unread: return NSLocalizedString("Create a Post", comment: "Displayed in the Notifications Tab as a button title, when the Unread Filter shows no notifications") } } static let sortKey = "timestamp" } enum Settings { static let estimatedRowHeight = CGFloat(70) static let lastSeenTime = "notifications_last_seen_time" } enum Stats { static let networkStatusKey = "network_status" static let noteTypeKey = "notification_type" static let noteTypeUnknown = "unknown" static let sourceKey = "source" static let sourceValue = "notifications" static let selectedFilter = "selected_filter" } enum Syncing { static let minimumPullToRefreshDelay = TimeInterval(1.5) static let pushMaxWait = TimeInterval(1.5) static let syncTimeout = TimeInterval(10) static let undoTimeout = TimeInterval(4) } enum InlinePrompt { static let section = "notifications" } } // MARK: - Push Notifications Permission Alert extension NotificationsViewController: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { guard let fancyAlertController = presented as? FancyAlertViewController else { return nil } return FancyAlertPresentationController(presentedViewController: fancyAlertController, presenting: presenting) } private func showNotificationPrimerAlertIfNeeded() { guard shouldShowPrimeForPush, !userDefaults.notificationPrimerAlertWasDisplayed else { return } DispatchQueue.main.asyncAfter(deadline: .now() + Constants.displayAlertDelay) { self.showNotificationPrimerAlert() } } private func notificationAlertApproveAction(_ controller: FancyAlertViewController) { InteractiveNotificationsManager.shared.requestAuthorization { _ in DispatchQueue.main.async { controller.dismiss(animated: true) } } } private func showNotificationPrimerAlert() { let alertController = FancyAlertViewController.makeNotificationPrimerAlertController(approveAction: notificationAlertApproveAction(_:)) showNotificationAlert(alertController) } private func showSecondNotificationAlert() { let alertController = FancyAlertViewController.makeNotificationSecondAlertController(approveAction: notificationAlertApproveAction(_:)) showNotificationAlert(alertController) } private func showNotificationAlert(_ alertController: FancyAlertViewController) { let mainContext = ContextManager.shared.mainContext guard (try? WPAccount.lookupDefaultWordPressComAccount(in: mainContext)) != nil else { return } PushNotificationsManager.shared.loadAuthorizationStatus { [weak self] (enabled) in guard enabled == .notDetermined else { return } UserPersistentStoreFactory.instance().notificationPrimerAlertWasDisplayed = true let alert = alertController alert.modalPresentationStyle = .custom alert.transitioningDelegate = self self?.tabBarController?.present(alert, animated: true) } } private func showSecondNotificationsAlertIfNeeded() { guard userDefaults.secondNotificationsAlertCount >= Constants.secondNotificationsAlertThreshold else { return } showSecondNotificationAlert() userDefaults.secondNotificationsAlertCount = Constants.secondNotificationsAlertDisabled } private enum Constants { static let inlineTabAccessCount = 6 static let displayAlertDelay = 0.2 // number of notifications after which the second alert will show up static let secondNotificationsAlertThreshold = 10 static let secondNotificationsAlertDisabled = -1 } } // MARK: - Scrolling // extension NotificationsViewController: WPScrollableViewController { // Used to scroll view to top when tapping on tab bar item when VC is already visible. func scrollViewToTop() { tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true) } } // MARK: - Jetpack banner delegate // extension NotificationsViewController: JPScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { processJetpackBannerVisibility(scrollView) } } // MARK: - StoryboardLoadable extension NotificationsViewController: StoryboardLoadable { static var defaultStoryboardName: String { return "Notifications" } }
gpl-2.0
6d69c74f02e225fb9d0b997ad4903114
36.891595
199
0.667251
5.998261
false
false
false
false
qiang437587687/Brother
Brother/Brother/StructTest.swift
1
1489
// // StructTest.swift // Brother // // Created by zhang on 15/11/26. // Copyright © 2015年 zhang. All rights reserved. // import UIKit struct zhang<T> { var name = "zhang" var age = 23 var gender:T? init(genderIn:T) { print("进来了") name = "zhangxianqiang" age = 25 gender = genderIn } } enum Marry <Male,Female> { typealias SerializedObjectMale = Male /// The type of error to be created by this `ResponseSerializer` if serialization fails. typealias ErrorObjectFemale = Female case zhang(SerializedObjectMale) case han(ErrorObjectFemale) //这个后面其实是类型 // let request:NSURLRequest? //枚举里面不能有 任何的存储类型.. internal var isSuccess: Bool { switch self { case .zhang: return true case .han: return false } } } class StructTest { var a = 1 var b : Int { return 2 } // class func test() { // print(b) //看来类方法里面确定了是这个 数值类型也不行... // } func test() { print("struct Strat") let zhangxianqiang = zhang<String>(genderIn: "男") print(zhangxianqiang.age) print(zhangxianqiang.name) print(zhangxianqiang.gender) print("struct End") } }
mit
46f3a26f39dd3a7db1cfed5feebb9bcf
16.620253
92
0.525144
4.046512
false
true
false
false
antonio081014/LeeCode-CodeBase
Swift/sort-colors.swift
2
1261
/** * https://leetcode.com/problems/sort-colors/ * * */ // Date: Thu Jun 11 09:14:08 PDT 2020 class Solution { func sortColors(_ nums: inout [Int]) { var r = 0 var w = 0 var b = 0 for c in nums { if c == 0 { r += 1 } else if c == 1 { w += 1 } else if c == 2 { b += 1 } } for index in 0 ..< nums.count { if r > 0 { nums[index] = 0 r -= 1 } else if w > 0 { nums[index] = 1 w -= 1 } else if b > 0 { nums[index] = 2 b -= 1 } } } } /** * https://leetcode.com/problems/sort-colors/ * * */ // Date: Thu Jun 11 10:01:38 PDT 2020 class Solution { func sortColors(_ nums: inout [Int]) { var start = 0 var end = nums.count - 1 var index = 0 while index <= end { if nums[index] == 0 { nums.swapAt(index, start) index += 1 start += 1 } else if nums[index] == 2 { nums.swapAt(index, end) end -= 1 } else { index += 1 } } } }
mit
52292e31c77cf8e8a22ab2a2d82ee5e7
21.927273
45
0.366376
3.88
false
false
false
false
pyngit/RealmSample
RealmSample/UserInputVC.swift
1
4745
// // ViewController.swift // RealmSample // // Created by pyngit on 2015/10/22. import UIKit class UserInputVC: UIViewController ,UIPickerViewDelegate { /* 画面内定数 */ let MONTH_LIST = ["1","2","3","4","5","6","7","8","9","10","11","12"]; let DAY_LIST = ["01","02","03","04","05","06","07","08","09","10" ,"11","12","13","14","15","16","17","18","19","20" ,"21","22","23","24","25","26","27","28","29","30","31"] /* 画面内UI */ //名前のフィールド @IBOutlet var nameTextField: UITextField! //誕生日のフィールド @IBOutlet var birthDayPicer: UIPickerView! /* クラス内メンバ変数 */ //選択した日付 var selectMonthIndex:Int = 0; var selectDayIndex:Int = 0; override func viewDidLoad() { super.viewDidLoad() print("UserInputVC viewDidLoad start."); //開始時に全件削除 do{ let service = UserService(); try service.deleteAll(); }catch let error as NSError { print("error :\(error)"); } print("UserInputVC viewDidLoad end."); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** 送信ボタン押下 */ @IBAction func onSubmit(sender: UIButton) { print("onSubmit \(sender)"); print("名前:\(nameTextField.text)"); selectMonthIndex = birthDayPicer.selectedRowInComponent(0); selectDayIndex = birthDayPicer.selectedRowInComponent(1); let birthDayStr:String = MONTH_LIST[selectMonthIndex] + DAY_LIST[selectDayIndex]; do{ //名前の必須チェック if(nameTextField.text != ""){ print("誕生日:\(Int.init(birthDayStr))"); let user = UserDomain(); user.name = nameTextField.text!; user.birthday = Int.init(birthDayStr)!; let service = UserService(); try service.add(user); let vo:UserInfoVO = UserInfoVO(); vo.userDomain = user; let storyboard: UIStoryboard = UIStoryboard(name: "Main" , bundle: NSBundle.mainBundle()) // 遷移するViewを定義する. let userResultVC: UserResultVC = storyboard.instantiateViewControllerWithIdentifier("userResult") as! UserResultVC; //次画面に情報を渡す。 userResultVC.userInfoVO = vo; // アニメーションを設定する. userResultVC.modalTransitionStyle = UIModalTransitionStyle.PartialCurl // Viewの移動する. self.presentViewController(userResultVC, animated: true, completion: nil) }else{ //必須エラー popUpAlert("名前は必須入力です。"); } }catch let error as NSError{ print("error:\(error)"); } } /** アラート表示 - parameter String: アラートメッセージ */ private func popUpAlert(alertMsg:String){ //アラート表示 let alertController = UIAlertController(title: "エラー", message: alertMsg, preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) presentViewController(alertController, animated: true, completion: nil) } //UI Picer用設定 //表示列 func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 2 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if(component == 0){ return MONTH_LIST.count; // 1列目の選択肢の数 }else{ return DAY_LIST.count; // 2列目の選択肢の数 } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if(component == 0){ return MONTH_LIST[row] // 1列目のrow番目に表示する値 }else{ return DAY_LIST[row] // 2列目のrow番目に表示する値 } } /* pickerが選択された際に呼ばれるデリゲートメソッド. */ func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if(component == 0){ }else{ } } }
mit
a520466f7f04b47a8a051f27d3e9ff17
28.813793
131
0.546611
4.327327
false
false
false
false
cybersamx/FotoBox
iOS/FotoBox/FolderViewController.swift
1
5999
// // FolderViewController.swift // FotoBox // // Created by Samuel Chow on 7/4/16. // Copyright © 2016 Cybersam. All rights reserved. // // Credit: Based off of BOXSampleFolderViewController (ObjC code) in the Box iOS sample code. import Foundation import Photos import UIKit import BoxContentSDK class FolderViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let client = BOXContentClient.defaultClient() var folderID: String! = BOXAPIFolderIDRoot var items: [AnyObject]? var request: BOXRequest? // MARK: - Private Helpers func fetchItems() { let request = client.folderItemsRequestWithID(folderID) request.performRequestWithCompletion { (items, error) in if error != nil { print("No items returned...") return } self.items = items self.tableView.reloadData() self.request = request } } func presentImagePicker() { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.sourceType = .PhotoLibrary self.presentViewController(imagePicker, animated: true) { print("Present picker") } } func presentActionSheet() { let alertController = UIAlertController(title: nil, message: "Please select an action", preferredStyle: .ActionSheet) if UIImagePickerController.isSourceTypeAvailable(.Camera) { // If camera isn't available on this device. let cameraAction = UIAlertAction(title: "Take Photo", style: .Default) { (action) in print("Camera UI not implemented") } alertController.addAction(cameraAction) } let libraryAction = UIAlertAction(title: "Import from Photo Library", style: .Default) { (action) in self.presentImagePicker() } alertController.addAction(libraryAction) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in print("Cancel") } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true) { } } // MARK: - UIImagePickerControllerDelegate internal func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) { self.dismissViewControllerAnimated(true, completion: nil) guard let url = info["UIImagePickerControllerReferenceURL"] as? NSURL else { return } let asset = PHAsset.fetchAssetsWithALAssetURLs([url], options: nil) guard let result = asset.firstObject where result is PHAsset else { return } let options = PHImageRequestOptions() options.networkAccessAllowed = true PHImageManager.defaultManager().requestImageDataForAsset(result as! PHAsset, options: options) { (imageData, dataUTI, orientation, imageInfo) in // Get file name. guard let fileURL = imageInfo?["PHImageFileURLKey"] as? NSURL else { return } let filePath = NSString(string: fileURL.path!) let fileName = filePath.lastPathComponent // Upload the photo. let request = self.client.fileUploadRequestToFolderWithID(self.folderID, fromData: imageData, fileName: fileName) request.enableCheckForCorruptionInTransit = true request.performRequestWithProgress(nil, completion: { (file, error) in if error != nil { print("Error...") return } self.items?.append(file) self.tableView.reloadData() }) } } internal func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true) { print("Cancel") } } // MARK: - Override UIViewController override func viewDidLoad() { super.viewDidLoad() fetchItems() let utilityButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(presentActionSheet)) navigationItem.rightBarButtonItem = utilityButton } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.request?.cancel() } // MARK: - Override UITableDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.items == nil { return 0 } return (self.items?.count)! } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! FileTableViewCell let item = self.items?[indexPath.row] as? BOXItem cell.client = client cell.item = item return cell } // MARK: - Override UITableDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as? FileTableViewCell let storyboard = UIStoryboard.init(name: "Main", bundle: nil) if cell?.item?.isFile == true || cell?.item?.isBookmark == true { let detailsViewController = storyboard.instantiateViewControllerWithIdentifier("DetailsViewController") as! DetailsViewController navigationController?.pushViewController(detailsViewController, animated: true) detailsViewController.itemID = cell?.item?.modelID } else if cell?.item?.isFolder == true { let folderViewController = storyboard.instantiateViewControllerWithIdentifier("FolderViewController") as! FolderViewController navigationController?.pushViewController(folderViewController, animated: true) folderViewController.folderID = cell?.item?.modelID } } }
mit
9408e1ac7f03e27eafe64e97b0e9474a
31.247312
148
0.685395
5.341051
false
false
false
false
klemenkosir/SwiftExtensions
SwiftExtensions/SwiftExtensions/UIFontExension.swift
1
1415
// // UIFontExension.swift // // // Created by Klemen Kosir on 21/04/16. // Copyright © 2016 Klemen Košir. All rights reserved. // import UIKit public enum SystemFontWeight : String { case UltraLight = "HelveticaNeue-UltraLight" case Thin = "HelveticaNeue-Thin" case Light = "HelveticaNeue-Light" case Regular = "HelveticaNeue" case Medium = "HelveticaNeue-Medium" case Semibold = "Helvetica-Bold" case Bold = "HelveticaNeue-Bold" case Heavy = "HelveticaNeue-CondensedBold" case Black = "HelveticaNeue-CondensedBlack" var weightValue:CGFloat? { if #available(iOS 8.2, *) { switch self { case .UltraLight: return UIFontWeightUltraLight case .Thin: return UIFontWeightThin case .Light: return UIFontWeightLight case .Regular: return UIFontWeightRegular case .Medium: return UIFontWeightMedium case .Semibold: return UIFontWeightSemibold case .Bold: return UIFontWeightBold case .Heavy: return UIFontWeightHeavy case .Black: return UIFontWeightBlack } } else { return nil } } } public extension UIFont { static func systemFontOfSize(_ fontSize:CGFloat, weight:SystemFontWeight) -> UIFont { if #available(iOS 8.2, *) { return UIFont.systemFont(ofSize: fontSize, weight: weight.weightValue!) } else { // Fallback on earlier versions return UIFont.init(name: weight.rawValue, size: fontSize)! } } }
mit
00ee522211d9e2e3ae3b5d2906c20df9
22.55
86
0.707714
3.698953
false
false
false
false
aleksandrshoshiashvili/AwesomeSpotlightView
AwesomeSpotlightViewDemoObjC/Pods/AwesomeSpotlightView/AwesomeSpotlightView/Classes/Localizator.swift
1
1223
// // Localizator.swift // AwesomeSpotlightView // // Created by David Cordero // Update by Alex Shoshiashvili // https://medium.com/@dcordero/a-different-way-to-deal-with-localized-strings-in-swift-3ea0da4cd143#.b863b9n1q import Foundation private class Localizator { static let sharedInstance = Localizator() lazy var localizableDictionary: NSDictionary! = { if let bundlePath = Bundle(for: AwesomeSpotlightView.self) .path(forResource: "AwesomeSpotlightViewBundle", ofType: "bundle") { if let path = Bundle(path: bundlePath)? .path(forResource: "Localizable", ofType: "plist") { return NSDictionary(contentsOfFile: path) } } fatalError("Localizable file NOT found") }() func localize(string: String) -> String { guard let localizedString = ((localizableDictionary.value(forKey: "Buttons") as AnyObject).value(forKey: string) as AnyObject).value(forKey: "value") as? String else { assertionFailure("Missing translation for: \(string)") return "" } return localizedString } } extension String { var localized: String { return Localizator.sharedInstance.localize(string: self) } }
mit
890d3e34b57948a93176cd565b9934dc
27.44186
171
0.679477
4.159864
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-07/ImageMetalling-07/AppDelegate.swift
1
4183
// // AppDelegate.swift // ImageMetalling-07 // // Created by denis svinarchuk on 14.12.15. // Copyright © 2015 IMetalling. All rights reserved. // import Cocoa import IMProcessing @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { private let openRecentKey = "imageMetalling-open-recent" private var openRecentMenuItems = Dictionary<String,NSMenuItem>() private func addOpenRecentMenuItemMenu(file:String){ let menuItem = openRecentMenu.insertItemWithTitle(file, action: #selector(AppDelegate.openRecentHandler(_:)), keyEquivalent: "", atIndex: 0) openRecentMenuItems[file]=menuItem } private var openRecentList:[String]?{ get { return NSUserDefaults.standardUserDefaults().objectForKey(openRecentKey) as? [String] } } private func addOpenRecentFileMenuItem(file:String){ var list = removeOpenRecentFileMenuItem(file) list.insert(file, atIndex: 0) NSUserDefaults.standardUserDefaults().setObject(list, forKey: openRecentKey) NSUserDefaults.standardUserDefaults().synchronize() addOpenRecentMenuItemMenu(file) } private func removeOpenRecentFileMenuItem(file:String) -> [String] { var list = openRecentList ?? [String]() if let index = list.indexOf(file){ list.removeAtIndex(index) if let menuItem = openRecentMenuItems[file] { openRecentMenu.removeItem(menuItem) } } NSUserDefaults.standardUserDefaults().setObject(list, forKey: openRecentKey) NSUserDefaults.standardUserDefaults().synchronize() return list } private var recentListMenuItems:[NSMenuItem] = [NSMenuItem]() @IBOutlet weak var openRecentMenu: NSMenu! func applicationDidFinishLaunching(aNotification: NSNotification) { for w in NSApp.windows{ w.backgroundColor = IMPColor(color: IMPPrefs.colors.background) } if let list = openRecentList { for file in list.reverse() { addOpenRecentMenuItemMenu(file) } IMPDocument.sharedInstance.currentFile = list[0] } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func menuAction(sender: NSMenuItem) { IMPMenuHandler.sharedInstance.currentMenuItem = sender } @IBAction func clearRecentOpened(sender: AnyObject) { if let list = openRecentList { for file in list { removeOpenRecentFileMenuItem(file) } } } @IBAction func openFile(sender: AnyObject) { let openPanel = NSOpenPanel() openPanel.canChooseFiles = true; openPanel.resolvesAliases = true; openPanel.extensionHidden = false; openPanel.allowedFileTypes = ["jpg", "tiff", "png"] let result = openPanel.runModal() if result == NSModalResponseOK { self.openRecentListAdd(openPanel.URLs) } } @IBAction func safeFile(sender: NSMenuItem) { let savePanel = NSSavePanel() savePanel.extensionHidden = false; savePanel.allowedFileTypes = ["jpg"] let result = savePanel.runModal() if result == NSModalResponseOK { IMPDocument.sharedInstance.saveCurrent((savePanel.URL?.path)!) } } func openRecentHandler(sender:NSMenuItem){ self.openFilePath(sender.title) } private func openFilePath(filePath: String){ IMPDocument.sharedInstance.currentFile = filePath addOpenRecentFileMenuItem(filePath) } private func openRecentListAdd(file:String){ self.openFilePath(file) } private func openRecentListAdd(urls:[NSURL]){ for url in urls{ if let file = url.path{ self.openRecentListAdd(file) } } } }
mit
4372f7ee1fd4a5c2f61d7130afd8f0d8
27.067114
148
0.617886
5.417098
false
false
false
false
minikin/Algorithmics
Pods/PSOperations/PSOperations/OperationCondition.swift
1
3908
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the fundamental logic relating to Operation conditions. */ import Foundation public let OperationConditionKey = "OperationCondition" /** A protocol for defining conditions that must be satisfied in order for an operation to begin execution. */ public protocol OperationCondition { /** The name of the condition. This is used in userInfo dictionaries of `.ConditionFailed` errors as the value of the `OperationConditionKey` key. */ static var name: String { get } /** Specifies whether multiple instances of the conditionalized operation may be executing simultaneously. */ static var isMutuallyExclusive: Bool { get } /** Some conditions may have the ability to satisfy the condition if another operation is executed first. Use this method to return an operation that (for example) asks for permission to perform the operation - parameter operation: The `Operation` to which the Condition has been added. - returns: An `NSOperation`, if a dependency should be automatically added. Otherwise, `nil`. - note: Only a single operation may be returned as a dependency. If you find that you need to return multiple operations, then you should be expressing that as multiple conditions. Alternatively, you could return a single `GroupOperation` that executes multiple operations internally. */ func dependencyForOperation(operation: Operation) -> NSOperation? /// Evaluate the condition, to see if it has been satisfied or not. func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) } /** An enum to indicate whether an `OperationCondition` was satisfied, or if it failed with an error. */ public enum OperationConditionResult { case Satisfied case Failed(NSError) var error: NSError? { switch self { case .Failed(let error): return error default: return nil } } } func ==(lhs: OperationConditionResult, rhs: OperationConditionResult) -> Bool { switch (lhs, rhs) { case (.Satisfied, .Satisfied): return true case (.Failed(let lError), .Failed(let rError)) where lError == rError: return true default: return false } } // MARK: Evaluate Conditions struct OperationConditionEvaluator { static func evaluate(conditions: [OperationCondition], operation: Operation, completion: [NSError] -> Void) { // Check conditions. let conditionGroup = dispatch_group_create() var results = [OperationConditionResult?](count: conditions.count, repeatedValue: nil) // Ask each condition to evaluate and store its result in the "results" array. for (index, condition) in conditions.enumerate() { dispatch_group_enter(conditionGroup) condition.evaluateForOperation(operation) { result in results[index] = result dispatch_group_leave(conditionGroup) } } // After all the conditions have evaluated, this block will execute. dispatch_group_notify(conditionGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { // Aggregate the errors that occurred, in order. var failures = results.flatMap { $0?.error } /* If any of the conditions caused this operation to be cancelled, check for that. */ if operation.cancelled { failures.append(NSError(code: .ConditionFailed)) } completion(failures) } } }
mit
6fc9d91698a3b4e6f6fc044c415638ff
33.875
113
0.650282
5.228916
false
false
false
false
ralcr/Localizabler
Localizabler/LocalizationsViewController.swift
1
4973
// // ViewController.swift // Localizabler // // Created by Cristian Baluta on 01/10/15. // Copyright © 2015 Cristian Baluta. All rights reserved. // import Cocoa class LocalizationsViewController: NSViewController { var presenter: LocalizationsPresenterInput? var windowPresenter: WindowPresenterInput? var wireframe: AppWireframe? @IBOutlet weak fileprivate var splitView: NSSplitView? @IBOutlet weak fileprivate var termsTableView: NSTableView? @IBOutlet weak fileprivate var translationsTableView: NSTableView? @IBOutlet weak fileprivate var butSave: NSButton? @IBOutlet weak fileprivate var butAdd: NSButton? @IBOutlet weak fileprivate var butRemove: NSButton? fileprivate var termsTableAlert: PlaceholderView? fileprivate var translationsTableAlert: PlaceholderView? class func instanceFromStoryboard() -> LocalizationsViewController { let storyBoard = NSStoryboard(name: "Main", bundle: nil) return storyBoard.instantiateController(withIdentifier: "LocalizationsViewController") as! LocalizationsViewController } override func viewDidLoad() { super.viewDidLoad() termsTableView!.backgroundColor = NSColor.clear butSave?.isEnabled = false presenter!.setupDataSourceFor(termsTableView: termsTableView!, translationsTableView: translationsTableView!) } } extension LocalizationsViewController { @IBAction func handleAddButtonClicked (_ sender: NSButton) { presenter!.insertNewTerm(afterIndex: termsTableView!.selectedRow) } @IBAction func handleRemoveButtonClicked (_ sender: NSButton) { let alert = NSAlert() alert.messageText = "Are you sure you want to remove this term?" alert.alertStyle = .warning alert.addButton(withTitle: "Delete") alert.addButton(withTitle: "Cancel") let result = alert.runModal() if result == NSAlertFirstButtonReturn { } else if ( result == NSAlertSecondButtonReturn ) { } if let index = termsTableView?.selectedRow { presenter!.removeTerm(atIndex: index) } } @IBAction func handleSaveButtonClicked (_ sender: NSButton) { presenter!.saveChanges() } } extension LocalizationsViewController { fileprivate func translationsAlert (_ message: String) -> PlaceholderView { if translationsTableAlert == nil { translationsTableAlert = PlaceholderView.instanceFromNib() translationsTableView?.addSubview(translationsTableAlert!) translationsTableAlert?.constrainToSuperview() } translationsTableAlert?.message = message return translationsTableAlert! } fileprivate func termsAlert (_ message: String) -> PlaceholderView { if termsTableAlert == nil { termsTableAlert = PlaceholderView.instanceFromNib() termsTableView?.addSubview(termsTableAlert!) termsTableAlert?.constrainToSuperview() } termsTableAlert?.message = message return termsTableAlert! } } extension LocalizationsViewController: LocalizationsPresenterOutput { func updatePlaceholders (message: String, hideTerms: Bool, hideTranslations: Bool) { translationsAlert(message).isHidden = hideTerms termsAlert(message).isHidden = hideTranslations } func enableSaving() { butSave?.isEnabled = true } func disableSaving() { butSave?.isEnabled = false } func insertNewTerm (atIndex index: Int) { termsTableView?.beginUpdates() termsTableView?.insertRows(at: IndexSet(integer: index), withAnimation: .effectFade) termsTableView?.endUpdates() } func removeTerm (atIndex index: Int) { termsTableView?.beginUpdates() termsTableView?.removeRows(at: IndexSet(integer: index), withAnimation: .effectFade) termsTableView?.endUpdates() } func reloadTerm (atIndex index: Int) { termsTableView?.reloadData(forRowIndexes: IndexSet(integer: index), columnIndexes: IndexSet(integer: 0)) } func selectedTermRow() -> Int? { return termsTableView?.selectedRow } func selectTerm (atRow row: Int) { let lastIndex = IndexSet([row]) self.termsTableView?.selectRowIndexes(lastIndex, byExtendingSelection: false) } func deselectActiveTerm() { termsTableView?.deselectRow(termsTableView!.selectedRow) } func showLanguagesPopup (_ languages: [String]) { windowPresenter!.setLanguagesPopup(languages) } func selectLanguage (_ language: String) { windowPresenter!.selectLanguageNamed(language) } func enableTermsEditingOptions (enabled: Bool) { butAdd?.isHidden = !enabled butRemove?.isHidden = !enabled } }
mit
360d82fe1333ca4d65f437b334ea19c9
29.691358
126
0.676388
5.375135
false
false
false
false
SEEK-Jobs/seek-stackable
Sources/Stack.swift
1
1910
// Copyright © 2016 SEEK. All rights reserved. // import UIKit public protocol Stack: class, Stackable { var thingsToStack: [Stackable] { get } var spacing: CGFloat { get } var layoutMargins: UIEdgeInsets { get } var width: CGFloat? { get } func framesForLayout(_ width: CGFloat, origin: CGPoint) -> [CGRect] } extension Stack { public var isHidden: Bool { return self.thingsToStack.allSatisfy { $0.isHidden } } func visibleThingsToStack() -> [Stackable] { return self.thingsToStack.filter({ !$0.isHidden }) } fileprivate func viewsToLayout() -> [UIView] { return visibleThingsToStack() .flatMap { stackable -> [UIView] in if let stack = stackable as? Stack { return stack.viewsToLayout() } else { if let view = stackable as? UIView { return [view] } else if let fixedSizeStackable = stackable as? FixedSizeStackable { return [fixedSizeStackable.view] } else { return [] } } } } public func layoutWithFrames(_ frames: [CGRect]) { let views = self.viewsToLayout() assert(frames.count == views.count, "layoutWithFrames could not be performed because of frame(\(frames.count)) / view(\(views.count)) count mismatch") if views.count == frames.count { for i in 0..<frames.count { views[i].frame = frames[i] } } } public func heightForFrames(_ frames: [CGRect]) -> CGFloat { return frames.maxY + self.layoutMargins.bottom } public func framesForLayout(_ width: CGFloat) -> [CGRect] { return self.framesForLayout(width, origin: CGPoint.zero) } }
mit
dc6c096a6d031e7135168c7c57d215b0
31.355932
158
0.550026
4.784461
false
false
false
false
atomkirk/TouchForms
TouchForms/Source/ImagePickerFormElement.swift
1
4694
// // TextFieldFormElement.swift // TouchForms // // Created by Adam Kirk on 7/25/15. // Copyright (c) 2015 Adam Kirk. All rights reserved. // import UIKit private enum SelectionOptions: String { case TakePhoto = "Take Photo" case ChooseFromLibrary = "Choose From Library" case Cancel = "Cancel" case RemovePhoto = "Remove Photo" } class ImagePickerDelegate: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate { var element: ImagePickerFormElement init(element: ImagePickerFormElement) { self.element = element } // MARK: - Image Picker Controller Delegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let image = info[UIImagePickerControllerEditedImage] as? UIImage ?? info[UIImagePickerControllerOriginalImage] as? UIImage { element.updateCell() element.delegate?.formElement(element, valueDidChange: image) picker.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } } // MARK: - Action Sheet Delegate func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { let buttonTitle = actionSheet.buttonTitleAtIndex(buttonIndex)! if let selection = SelectionOptions(rawValue: buttonTitle) { switch selection { case .TakePhoto: element.imagePickerController.sourceType = .Camera case .ChooseFromLibrary: element.imagePickerController.sourceType = .PhotoLibrary case .RemovePhoto: element.updateCell() element.delegate?.formElement(element, valueDidChange: nil) case .Cancel: return } element.delegate?.formElement(element, didRequestPresentationOfViewController: element.imagePickerController, animated: true, completion: nil) } } } public class ImagePickerFormElement: FormElement { public let label: String public var placeholderImage: UIImage? var imagePickerDelegate: ImagePickerDelegate? public lazy var imagePickerController: UIImagePickerController = { [unowned self] in let picker = UIImagePickerController() picker.modalPresentationStyle = .CurrentContext picker.delegate = self.imagePickerDelegate picker.allowsEditing = true return picker }() public init(label: String) { self.label = label super.init() self.imagePickerDelegate = ImagePickerDelegate(element: self) } // MARK: - Form Element public override func populateCell() { if let cell = cell as? ImagePickerFormCell { cell.formLabel?.text = label cell.formButton?.enabled = enabled cell.placeholderImage = placeholderImage } super.populateCell() } public override func canAddElement() -> Bool { return UIImagePickerController.isSourceTypeAvailable(.Camera) || UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) } public override func isEditable() -> Bool { return true } public override func beginEditing() { showActionSheet() } // MARK: - Cell Delegate public override func formCell(cell: FormCell, userDidPerformInteraction interaction: FormCellUserInteraction, view: UIView) { showActionSheet() } // MARK: - Private private func showActionSheet() { let actionSheet = UIActionSheet(title: nil, delegate: imagePickerDelegate!, cancelButtonTitle: nil, destructiveButtonTitle: nil) if UIImagePickerController.isSourceTypeAvailable(.Camera) { actionSheet.addButtonWithTitle(SelectionOptions.TakePhoto.rawValue) } if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) { actionSheet.addButtonWithTitle(SelectionOptions.ChooseFromLibrary.rawValue) } if let cell = cell as? ImagePickerFormCell where cell.formImageView?.image != nil { actionSheet.destructiveButtonIndex = actionSheet.addButtonWithTitle(SelectionOptions.RemovePhoto.rawValue) } actionSheet.cancelButtonIndex = actionSheet.addButtonWithTitle(SelectionOptions.Cancel.rawValue) delegate?.formElement(self, didRequestPresentationOfActionSheet: actionSheet) } }
mit
4ff692beddeb0e1d125cc93c126de444
33.77037
154
0.689604
5.882206
false
false
false
false
longjl/SwiftForms
SwiftForms/cells/FormTextViewCell.swift
4
3555
// // FormTextViewCell.swift // SwiftForms // // Created by Joey Padot on 12/6/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormTextViewCell : FormBaseCell, UITextViewDelegate { /// MARK: Cell views public let titleLabel = UILabel() public let textField = UITextView() /// MARK: Properties private var customConstraints: [AnyObject]! /// MARK: Class Funcs public override class func formRowCellHeight() -> CGFloat { return 110.0 } /// MARK: FormBaseCell public override func configure() { super.configure() selectionStyle = .None titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false) textField.setTranslatesAutoresizingMaskIntoConstraints(false) titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) contentView.addSubview(titleLabel) contentView.addSubview(textField) titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal) contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: contentView, attribute: .Height, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1.0, constant: 0.0)) contentView.addConstraint(NSLayoutConstraint(item: textField, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1.0, constant: 0.0)) textField.delegate = self } public override func update() { titleLabel.text = rowDescriptor.title textField.text = rowDescriptor.value as? String textField.secureTextEntry = false textField.autocorrectionType = .Default textField.autocapitalizationType = .Sentences textField.keyboardType = .Default } public override func constraintsViews() -> [String : UIView] { var views = ["titleLabel" : titleLabel, "textField" : textField] if self.imageView!.image != nil { views["imageView"] = imageView } return views } public override func defaultVisualConstraints() -> [String] { if self.imageView!.image != nil { if titleLabel.text != nil && count(titleLabel.text!) > 0 { return ["H:[imageView]-[titleLabel]-[textField]-16-|"] } else { return ["H:[imageView]-[textField]-16-|"] } } else { if titleLabel.text != nil && count(titleLabel.text!) > 0 { return ["H:|-16-[titleLabel]-[textField]-16-|"] } else { return ["H:|-16-[textField]-16-|"] } } } /// MARK: UITextViewDelegate public func textViewDidChange(textView: UITextView) { let trimmedText = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) rowDescriptor.value = count(trimmedText) > 0 ? trimmedText : nil } }
mit
dd92d954f40270568bdf7e78cdc000ea
34.89899
185
0.628869
5.304478
false
false
false
false
ruiying123/YRPageView
YRPageView/ViewController.swift
1
2576
// // ViewController.swift // YRPageView // // Created by kilrae on 2017/4/12. // Copyright © 2017年 yang. All rights reserved. // import UIKit class ViewController: UIViewController { fileprivate let imageNames: [String] = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg"] lazy var pageView: YRPageView = { let pageView = YRPageView(frame: .zero) pageView.itemSize = .zero pageView.register(YRPageViewCell.self, forCellWithReuseIdentifier: "cell") return pageView }() lazy var pageControl: YRPageControl = { let pageControl = YRPageControl(frame: .zero) pageControl.numberOfPages = self.imageNames.count pageControl.contentHorizontalAlignment = .center pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) return pageControl }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(pageView) pageView.dataSource = self pageView.delegate = self view.addSubview(pageControl) } override func viewWillLayoutSubviews() { pageView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 350) pageControl.frame = CGRect(x: 0, y: 350-50, width: view.bounds.width, height: 50) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: YRPageViewDataSource { func numberOfItems(pageView: YRPageView) -> Int { return imageNames.count } func pageView(_ pageView: YRPageView, cellForItemAt index: Int) -> YRPageViewCell { let cell = pageView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) cell.imageView?.image = UIImage(named: imageNames[index]) cell.imageView?.contentMode = .scaleAspectFill cell.imageView?.clipsToBounds = true // cell.textLabel?.text = index.description return cell } } extension ViewController: YRPageViewDelegate { func pageView(_ pageView: YRPageView, didSelectItemAtIndex index: Int) { pageView.deselectItem(at: index, animation: true) pageView.scrollToitem(at: index, animated: true) pageControl.currentPage = index } func pageViewDidScroll(_ pageView: YRPageView) { guard self.pageControl.currentPage != pageView.currentIndex else { return } pageControl.currentPage = pageView.currentIndex } }
mit
d1c1cd9e520b08014fff1c8dc97b5eed
30
106
0.654489
4.661232
false
false
false
false
stripysock/SwiftGen
Pods/Stencil/Stencil/Tokenizer.swift
1
1715
import Foundation public enum Token : Equatable { /// A token representing a piece of text. case Text(value:String) /// A token representing a variable. case Variable(value:String) /// A token representing a comment. case Comment(value:String) /// A token representing a template block. case Block(value:String) /// Returns the underlying value as an array seperated by spaces public func components() -> [String] { // TODO: Make this smarter and treat quoted strings as a single component let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() func strip(value: String) -> [String] { return value.stringByTrimmingCharactersInSet(characterSet).componentsSeparatedByCharactersInSet(characterSet) } switch self { case .Block(let value): return strip(value) case .Variable(let value): return strip(value) case .Text(let value): return strip(value) case .Comment(let value): return strip(value) } } public var contents:String { switch self { case .Block(let value): return value case .Variable(let value): return value case .Text(let value): return value case .Comment(let value): return value } } } public func ==(lhs:Token, rhs:Token) -> Bool { switch (lhs, rhs) { case (.Text(let lhsValue), .Text(let rhsValue)): return lhsValue == rhsValue case (.Variable(let lhsValue), .Variable(let rhsValue)): return lhsValue == rhsValue case (.Block(let lhsValue), .Block(let rhsValue)): return lhsValue == rhsValue case (.Comment(let lhsValue), .Comment(let rhsValue)): return lhsValue == rhsValue default: return false } }
mit
79112514cd5aab11ab4ed7243af1733d
25.384615
115
0.675219
4.443005
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPVisitedPopoverContent.swift
1
9063
// // KPVisitedPopoverContent.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/7/14. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit class KPVisitedPopoverContent: UIView, PopoverProtocol { var popoverView: KPPopoverView! var confirmAction: ((_ content: KPVisitedPopoverContent) -> Swift.Void)? var confirmButton: UIButton! static let KPShopPhotoInfoViewCellReuseIdentifier = "cell" var collectionView:UICollectionView! var collectionLayout:UICollectionViewFlowLayout! var shownCellIndex: [Int] = [Int]() var photos: [String] = [String]() { didSet { self.peopleLabel.text = "共有\(photos.count)人來過" self.invalidateIntrinsicContentSize() } } var animated: Bool = true lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 18.0) label.textAlignment = .center label.textColor = KPColorPalette.KPTextColor.mainColor label.text = "有誰來過這間咖啡?" return label }() lazy var peopleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 12.0) label.textAlignment = .center label.textColor = KPColorPalette.KPTextColor.grayColor_level4 return label }() lazy private var seperator: UIView = { let view = UIView() view.backgroundColor = KPColorPalette.KPBackgroundColor.grayColor_level6 return view }() private var buttonContainer: UIView! private var cancelButton: UIButton! override var intrinsicContentSize: CGSize { return CGSize(width: 280, height: (photos.count/5+1)*80+110) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white layer.cornerRadius = 4 addSubview(titleLabel) titleLabel.addConstraintForCenterAligningToSuperview(in: .horizontal) titleLabel.addConstraints(fromStringArray: ["V:|-16-[$self]", "H:|-16-[$self]-16-|"]) addSubview(peopleLabel) peopleLabel.addConstraintForCenterAligningToSuperview(in: .horizontal) peopleLabel.addConstraints(fromStringArray: ["V:[$view0]-6-[$self]", "H:|-16-[$self]-16-|"], views: [titleLabel]) buttonContainer = UIView() addSubview(buttonContainer) buttonContainer.addConstraintForCenterAligningToSuperview(in: .horizontal) buttonContainer.addConstraint(from: "V:[$self]|") //Collection view self.collectionLayout = UICollectionViewFlowLayout() self.collectionLayout.scrollDirection = .vertical self.collectionLayout.sectionInset = UIEdgeInsetsMake(8, 18, 8, 18) self.collectionLayout.minimumLineSpacing = 6.0 self.collectionLayout.minimumInteritemSpacing = 4.0 self.collectionLayout.itemSize = CGSize(width: 42, height: 42) self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.collectionLayout) self.collectionView.backgroundColor = UIColor.clear self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.showsHorizontalScrollIndicator = false self.collectionView.showsVerticalScrollIndicator = true self.collectionView.delaysContentTouches = true self.collectionView.register(KPShopPhotoCell.self, forCellWithReuseIdentifier: KPShopPhotoInfoView.KPShopPhotoInfoViewCellReuseIdentifier) self.addSubview(self.collectionView) self.collectionView.addConstraints(fromStringArray: ["H:|[$self]|", "V:[$view0]-8-[$self][$view1]"], views:[peopleLabel, buttonContainer]) addSubview(seperator) seperator.addConstraints(fromStringArray: ["V:[$self(1)]", "H:|[$self]|"]) seperator.addConstraintForAligning(to: .top, of: buttonContainer) cancelButton = UIButton(type: .custom) cancelButton.setTitle("取消", for: .normal) cancelButton.layer.cornerRadius = 2.0 cancelButton.layer.masksToBounds = true cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: UIDevice().isSuperCompact ? 13.0 : 15.0) cancelButton.setBackgroundImage(UIImage(color: KPColorPalette.KPBackgroundColor.grayColor_level4!), for: .normal) cancelButton.addTarget(self, action: #selector(KPVisitedPopoverContent.handleCancelButtonOnTapped), for: .touchUpInside) buttonContainer.addSubview(cancelButton) cancelButton.addConstraints(fromStringArray: ["V:|-8-[$self(36)]-8-|", "H:|-10-[$self($metric0)]"], metrics: [125]) confirmButton = UIButton(type: .custom) confirmButton.setTitle("打卡", for: .normal) confirmButton.layer.cornerRadius = 2.0 confirmButton.layer.masksToBounds = true confirmButton.titleLabel?.font = UIFont.systemFont(ofSize: 15.0) confirmButton.setBackgroundImage(UIImage(color: KPColorPalette.KPBackgroundColor.mainColor_light!), for: .normal) confirmButton.addTarget(self, action: #selector(KPVisitedPopoverContent.handleConfirmButtonOnTapped), for: .touchUpInside) buttonContainer.addSubview(confirmButton) confirmButton.addConstraints(fromStringArray: ["V:|-8-[$self(36)]-8-|", "H:[$view0]-10-[$self($metric0)]-10-|"], metrics: [125], views:[cancelButton]) } func handleCancelButtonOnTapped() { popoverView.dismiss() } func handleConfirmButtonOnTapped() { if confirmAction != nil { confirmAction!(self) } } } extension KPVisitedPopoverContent: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let displayCell = cell as! KPShopPhotoCell if !shownCellIndex.contains(indexPath.row) && animated { displayCell.shopPhoto.transform = CGAffineTransform(scaleX: 0.01, y: 0.01).rotated(by: -CGFloat.pi/3) UIView.animate(withDuration: 0.7, delay: 0.1+Double(indexPath.row)*0.02, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: { displayCell.shopPhoto.transform = CGAffineTransform.identity }) { (_) in self.shownCellIndex.append(indexPath.row) } } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KPShopPhotoInfoView.KPShopPhotoInfoViewCellReuseIdentifier, for: indexPath) as! KPShopPhotoCell cell.shopPhoto.af_setImage(withURL: URL(string: photos[indexPath.row])!, placeholderImage: UIImage(color: KPColorPalette.KPBackgroundColor.grayColor_level6!), filter: nil, progress: nil, progressQueue: DispatchQueue.global(), imageTransition: UIImageView.ImageTransition.crossDissolve(0.2), runImageTransitionIfCached: true, completion: { response in if let responseImage = response.result.value { cell.shopPhoto.image = responseImage } }) cell.shopPhoto.layer.cornerRadius = 21 return cell } }
mit
1f4328254da6f8eacecba5ec5ec09151
42.186603
134
0.589298
5.778489
false
false
false
false
Minecodecraft/EstateBand
EstateBand/SignupViewController.swift
1
6152
// // SignupViewController.swift // EstateBand // // Created by Minecode on 2017/6/11. // Copyright © 2017年 org.minecode. All rights reserved. // import UIKit import CoreData class SignupViewController: UIViewController { // Widget data @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var nameField: UITextField! @IBOutlet weak var accountField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var idField: UITextField! @IBOutlet weak var workNumberField: UITextField! @IBOutlet weak var maleButton: UIButton! @IBOutlet weak var femaleButton: UIButton! @IBOutlet weak var signupView: UIView! // Data var appDelegate: AppDelegate! override func viewDidLoad() { super.viewDidLoad() // 设置背景 self.view.backgroundColor = UIColor.init(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1.0) self.signupView.backgroundColor = UIColor.init(white: 1.0, alpha: 0.95) self.signupView.layer.cornerRadius = 15 // 初始化数据 self.appDelegate = UIApplication.shared.delegate as! AppDelegate // 注册收回键盘手势 view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapGesture))) // 设置控件 self.doneButton.layer.cornerRadius = 10 self.backButton.layer.cornerRadius = 8 } @IBAction func doneAction(_ sender: UIButton) { // 保存数据 saveContext() // 弹窗提醒 } @IBAction func sexSelectAction(_ sender: UIButton) { switch sender.tag { case 100: maleButton.isSelected = true femaleButton.isSelected = false case 101: maleButton.isSelected = false femaleButton.isSelected = true default: break } } @IBAction func backAction(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } func saveContext() { // 判断是否填写完毕 let done = (nameField.text != nil) && (accountField.text != nil) && (passwordField.text != nil) && (idField.text != nil) && (workNumberField.text != nil) if(done) { // 保存添加模型 let user = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user.name = nameField.text user.account = accountField.text user.password = passwordField.text user.id = Int32.init(idField.text!)! user.workNumber = Int32.init(workNumberField.text!)! user.sex = maleButton.state==UIControlState.selected ? true : false user.pic = "Default" // 弹窗提醒 do { try self.appDelegate.managedObjectContext.save() let alert = UIAlertController.init(title: "Success", message: "Registered successfully", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .cancel, handler: { (action) in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } catch { let alert = UIAlertController(title: "Failed", message: "Something error!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .cancel, handler: { (action) in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) } } else { let alert = UIAlertController(title: "Failed", message: "Please fill all the text field!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Confirm", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } func tapGesture(sender: UITapGestureRecognizer) { if sender.state == .ended { nameField.resignFirstResponder() accountField.resignFirstResponder() passwordField.resignFirstResponder() idField.resignFirstResponder() workNumberField.resignFirstResponder() } sender.cancelsTouchesInView = false } @IBAction func addDefaultData(_ sender: UIButton) { // 添加第一个人 let user_1 = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user_1.name = "Michael" user_1.account = "micheal123" user_1.password = "password" user_1.id = 10230003 user_1.workNumber = 210002 user_1.sex = true user_1.pic = "Michael" do { try self.appDelegate.managedObjectContext.save() } catch { NSLog("Save Failed") } // 添加第二个人 let user_2 = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user_2.name = "Mike" user_2.account = "[email protected]" user_2.password = "password" user_2.id = 20350012 user_2.workNumber = 210003 user_2.sex = true user_2.pic = "Mike" do { try self.appDelegate.managedObjectContext.save() } catch { NSLog("Save Failed") } // 添加第三个人 let user_3 = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.appDelegate.managedObjectContext) as! User user_3.name = "Steven" user_3.account = "[email protected]" user_3.password = "password" user_3.id = 43105128 user_3.workNumber = 210004 user_3.sex = true user_3.pic = "Steven" do { try self.appDelegate.managedObjectContext.save() } catch { NSLog("Save Failed") } } }
mit
7ccaf1a22ea61b5ad6e94eae22ab1dfb
36.154321
161
0.598771
4.570235
false
false
false
false
zmian/xcore.swift
Sources/Xcore/Cocoa/Blocks/MFMailComposeViewController+Blocks.swift
1
2014
// // Xcore // Copyright © 2015 Xcore // MIT license, see LICENSE file for details // import UIKit import MessageUI extension MFMailComposeViewController: MFMailComposeViewControllerDelegate { public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { var value: Result if let actionHandler = actionHandlerWrapper?.closure { if let error = error { value = .failure(error) } else { value = .success(result) } actionHandler(controller, value) } if shouldAutoDismiss { controller.dismiss(animated: true) } } } extension MFMailComposeViewController { public typealias Result = Swift.Result<MFMailComposeResult, Error> private class ClosureWrapper: NSObject { var closure: ((_ controller: MFMailComposeViewController, _ result: Result) -> Void)? init(_ closure: ((_ controller: MFMailComposeViewController, _ result: Result) -> Void)?) { self.closure = closure } } private enum AssociatedKey { static var actionHandler = "actionHandler" static var shouldAutoDismiss = "shouldAutoDismiss" } private var actionHandlerWrapper: ClosureWrapper? { get { associatedObject(&AssociatedKey.actionHandler) } set { setAssociatedObject(&AssociatedKey.actionHandler, value: newValue) } } public var shouldAutoDismiss: Bool { get { associatedObject(&AssociatedKey.shouldAutoDismiss, default: false) } set { mailComposeDelegate = self setAssociatedObject(&AssociatedKey.shouldAutoDismiss, value: newValue) } } public func didFinishWithResult( _ handler: @escaping (_ controller: MFMailComposeViewController, _ result: Result) -> Void ) { mailComposeDelegate = self actionHandlerWrapper = ClosureWrapper(handler) } }
mit
b6076c9f726426edc80b4c5b80d08a64
29.969231
140
0.656731
5.735043
false
false
false
false
Jnosh/swift
test/Interpreter/recursive_generics.swift
33
560
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // rdar://18067671 class List<T> { var value: T var next: List<T>? init(value: T) { self.value = value } init(value: T, next: List<T>) { self.value = value self.next = next } } let a = List(value: 0.0) let b = List(value: 1.0, next: a) let c = List(value: 2.0, next: b) b.value = 4.0 a.value = 8.0 print("begin") print(c.value) print(c.next!.value) print(c.next!.next!.value) // CHECK: begin // CHECK-NEXT: 2.0 // CHECK-NEXT: 4.0 // CHECK-NEXT: 8.0
apache-2.0
1b91a087bccf1f776493fee4d64045ba
17.064516
48
0.6
2.5
false
false
false
false
sergiosilvajr/ContactEmbedView
customswift/customswift/Utils.swift
1
803
// // Utils.swift // customswift // // Created by Luis Sergio da Silva Junior on 3/1/16. // Copyright © 2016 Luis Sergio. All rights reserved. // import UIKit class Utils{ static func getRandomColor() -> UIColor{ var color: UIColor let result = Int.random(0...5) switch result{ case 1: color = UIColor.greenColor() break case 2: color = UIColor.whiteColor() break case 3: color = UIColor.blueColor() break case 4: color = UIColor.magentaColor() break case 5: color = UIColor.yellowColor() break default: color = UIColor.redColor() break } return color } }
apache-2.0
7ac586e141319a39e1c6125c1a3b0db8
20.131579
54
0.502494
4.690058
false
false
false
false
CaueAlvesSilva/FeaturedGames
FeaturedGames/FeaturedGames/Extensions/UIViewController+Extensions.swift
1
1960
// // UIViewController+Extensions.swift // FeaturedGames // // Created by Cauê Silva on 04/08/17. // Copyright © 2017 Caue Alves. All rights reserved. // import Foundation import UIKit struct AlertDTO { var title: String var message: String var positiveActionTitle: String var negativeActionTitle: String? } extension UIViewController { func showConnectionErrorAlert(dto: AlertDTO, completion: ((UIAlertAction) -> Void)?) { let alertController = UIAlertController(title: dto.title, message: dto.message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: dto.positiveActionTitle, style: .default, handler: completion)) if let negativeActionTitle = dto.negativeActionTitle { alertController.addAction(UIAlertAction(title: negativeActionTitle, style: .default, handler: completion)) } present(alertController, animated: true, completion: nil) } func showLoader(with message: String = "carregando jogos...".localized) { let loader: LoaderView = UIView.fromNib() loader.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) let window = UIApplication.shared.keyWindow window?.addSubview(loader) window?.bringSubview(toFront: loader) loader.startAnimation(with: message) } func stopLoader() { let window = UIApplication.shared.keyWindow window?.subviews.forEach { if $0.isKind(of: LoaderView.self) { $0.removeFromSuperview() } } } func addSpecialNavigation(with title: String, and id: String = "") { let titleLabel = UILabel() self.title = "" titleLabel.fill(with: title, and: .navigation) titleLabel.sizeToFit() titleLabel.accessibilityIdentifier = "\(id).navigation.title" navigationItem.leftBarButtonItem = UIBarButtonItem(customView: titleLabel) } }
mit
97112368529554e5464010a85264b4e6
35.943396
118
0.684883
4.564103
false
false
false
false
vapor/vapor
Tests/VaporTests/RequestTests.swift
1
7670
import XCTVapor final class RequestTests: XCTestCase { func testCustomHostAddress() throws { let app = Application(.testing) defer { app.shutdown() } app.get("vapor", "is", "fun") { return $0.remoteAddress?.hostname ?? "n/a" } let ipV4Hostname = "127.0.0.1" try app.testable(method: .running(hostname: ipV4Hostname, port: 8080)).test(.GET, "vapor/is/fun") { res in XCTAssertEqual(res.body.string, ipV4Hostname) } } func testRequestPeerAddressForwarded() throws { let app = Application(.testing) defer { app.shutdown() } app.get("remote") { req -> String in req.headers.add(name: .forwarded, value: "for=192.0.2.60; proto=http; by=203.0.113.43") guard let peerAddress = req.peerAddress else { return "n/a" } return peerAddress.description } try app.testable(method: .running).test(.GET, "remote") { res in XCTAssertEqual(res.body.string, "[IPv4]192.0.2.60:80") } } func testRequestPeerAddressXForwardedFor() throws { let app = Application(.testing) defer { app.shutdown() } app.get("remote") { req -> String in req.headers.add(name: .xForwardedFor, value: "5.6.7.8") guard let peerAddress = req.peerAddress else { return "n/a" } return peerAddress.description } try app.testable(method: .running).test(.GET, "remote") { res in XCTAssertEqual(res.body.string, "[IPv4]5.6.7.8:80") } } func testRequestPeerAddressRemoteAddres() throws { let app = Application(.testing) defer { app.shutdown() } app.get("remote") { req -> String in guard let peerAddress = req.peerAddress else { return "n/a" } return peerAddress.description } let ipV4Hostname = "127.0.0.1" try app.testable(method: .running(hostname: ipV4Hostname, port: 8080)).test(.GET, "remote") { res in XCTAssertContains(res.body.string, "[IPv4]\(ipV4Hostname)") } } func testRequestPeerAddressMultipleHeadersOrder() throws { let app = Application(.testing) defer { app.shutdown() } app.get("remote") { req -> String in req.headers.add(name: .xForwardedFor, value: "5.6.7.8") req.headers.add(name: .forwarded, value: "for=192.0.2.60; proto=http; by=203.0.113.43") guard let peerAddress = req.peerAddress else { return "n/a" } return peerAddress.description } let ipV4Hostname = "127.0.0.1" try app.testable(method: .running(hostname: ipV4Hostname, port: 8080)).test(.GET, "remote") { res in XCTAssertEqual(res.body.string, "[IPv4]192.0.2.60:80") } } func testRequestRemoteAddress() throws { let app = Application(.testing) defer { app.shutdown() } app.get("remote") { $0.remoteAddress?.description ?? "n/a" } try app.testable(method: .running).test(.GET, "remote") { res in XCTAssertContains(res.body.string, "IP") } } func testURI() throws { do { var uri = URI(string: "http://vapor.codes/foo?bar=baz#qux") XCTAssertEqual(uri.scheme, "http") XCTAssertEqual(uri.host, "vapor.codes") XCTAssertEqual(uri.path, "/foo") XCTAssertEqual(uri.query, "bar=baz") XCTAssertEqual(uri.fragment, "qux") uri.query = "bar=baz&test=1" XCTAssertEqual(uri.string, "http://vapor.codes/foo?bar=baz&test=1#qux") uri.query = nil XCTAssertEqual(uri.string, "http://vapor.codes/foo#qux") } do { let uri = URI(string: "/foo/bar/baz") XCTAssertEqual(uri.path, "/foo/bar/baz") } do { let uri = URI(string: "ws://echo.websocket.org/") XCTAssertEqual(uri.scheme, "ws") XCTAssertEqual(uri.host, "echo.websocket.org") XCTAssertEqual(uri.path, "/") } do { let uri = URI(string: "http://foo") XCTAssertEqual(uri.scheme, "http") XCTAssertEqual(uri.host, "foo") XCTAssertEqual(uri.path, "") } do { let uri = URI(string: "foo") XCTAssertEqual(uri.scheme, "foo") XCTAssertEqual(uri.host, nil) XCTAssertEqual(uri.path, "") } do { let uri: URI = "/foo/bar/baz" XCTAssertEqual(uri.path, "/foo/bar/baz") } do { let foo = "foo" let uri: URI = "/\(foo)/bar/baz" XCTAssertEqual(uri.path, "/foo/bar/baz") } do { let uri = URI(scheme: "foo", host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment") } do { let bar = "bar" let uri = URI(scheme: "foo\(bar)", host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "foobar://host:1/test?query#fragment") } do { let uri = URI(scheme: "foo", host: "host", port: 1, path: "/test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment") } do { let scheme = "foo" let uri = URI(scheme: scheme, host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment") } do { let scheme: String? = "foo" let uri = URI(scheme: scheme, host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "foo://host:1/test?query#fragment") } do { let uri = URI(scheme: .http, host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "http://host:1/test?query#fragment") } do { let uri = URI(scheme: nil, host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "host:1/test?query#fragment") } do { let uri = URI(scheme: URI.Scheme(), host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "host:1/test?query#fragment") } do { let uri = URI(host: "host", port: 1, path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "host:1/test?query#fragment") } do { let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test", query: "query", fragment: "fragment") XCTAssertEqual(uri.string, "http+unix://%2Fpath/test?query#fragment") } do { let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test", fragment: "fragment") XCTAssertEqual(uri.string, "http+unix://%2Fpath/test#fragment") } do { let uri = URI(scheme: .httpUnixDomainSocket, host: "/path", path: "test") XCTAssertEqual(uri.string, "http+unix://%2Fpath/test") } do { let uri = URI() XCTAssertEqual(uri.string, "/") } } }
mit
b83ecd4ebf3364f14154c897d614e4a4
36.783251
123
0.535463
3.875695
false
true
false
false
michaello/Aloha
AlohaGIF/SwiftyOnboard/SwiftyOnboardOverlay.swift
1
2559
// // customOverlayView.swift // SwiftyOnboard // // Created by Jay on 3/26/17. // Copyright © 2017 Juan Pablo Fernandez. All rights reserved. // import UIKit open class SwiftyOnboardOverlay: UIView { open var pageControl: CHIPageControlChimayo = { let pageControl = CHIPageControlChimayo() pageControl.tintColor = .themeColor pageControl.padding = 6 pageControl.radius = 4 return pageControl }() open var continueButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Continue", for: .normal) button.contentHorizontalAlignment = .center return button }() open var skipButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Skip", for: .normal) button.contentHorizontalAlignment = .right return button }() override init(frame: CGRect) { super.init(frame: frame) setUp() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { for subview in subviews { if !subview.isHidden && subview.alpha > 0 && subview.isUserInteractionEnabled && subview.point(inside: convert(point, to: subview), with: event) { return true } } return false } open func set(style: SwiftyOnboardStyle) { switch style { case .light: continueButton.setTitleColor(.white, for: .normal) skipButton.setTitleColor(.white, for: .normal) case .dark: continueButton.setTitleColor(.black, for: .normal) skipButton.setTitleColor(.black, for: .normal) } } open func page(count: Int) { pageControl.numberOfPages = count } open func currentPage(index: Int) { pageControl.set(progress: index, animated: true) } func setUp() { self.addSubview(pageControl) pageControl.translatesAutoresizingMaskIntoConstraints = false pageControl.heightAnchor.constraint(equalToConstant: 15).isActive = true pageControl.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -170).isActive = true pageControl.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true pageControl.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true } }
mit
a2cf8a4f770dd98483e2eb940a731875
30.195122
158
0.626271
4.835539
false
false
false
false
kliu/ssziparchive
Example/SwiftExample_macOS/ViewController.swift
2
5679
// // ViewController.swift // SwiftExample_macOS // // Created by Antoine Cœur on 2019/4/26. // import Cocoa #if UseCarthage import ZipArchive #else import SSZipArchive #endif class ViewController: NSViewController { @IBOutlet weak var passwordField: NSTextField! @IBOutlet weak var zipButton: NSButton! @IBOutlet weak var unzipButton: NSButton! @IBOutlet weak var hasPasswordButton: NSButton! @IBOutlet weak var resetButton: NSButton! @IBOutlet weak var file1: NSTextField! @IBOutlet weak var file2: NSTextField! @IBOutlet weak var file3: NSTextField! @IBOutlet weak var info: NSTextField! var samplePath: String! var zipPath: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. samplePath = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/Sample Data").path print("Sample path:", samplePath!) resetPressed(resetButton) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } // MARK: IBAction @IBAction func zipPressed(_: NSButton) { zipPath = tempZipPath() print("Zip path:", zipPath!) let password = passwordField.stringValue let success = SSZipArchive.createZipFile(atPath: zipPath!, withContentsOfDirectory: samplePath, keepParentDirectory: false, compressionLevel: -1, password: !password.isEmpty ? password : nil, aes: true, progressHandler: nil) if success { print("Success zip") info.stringValue = "Success zip" unzipButton.isEnabled = true hasPasswordButton.isEnabled = true } else { print("No success zip") info.stringValue = "No success zip" } resetButton.isEnabled = true } @IBAction func unzipPressed(_: NSButton) { guard let zipPath = self.zipPath else { return } guard let unzipPath = tempUnzipPath() else { return } print("Unzip path:", unzipPath) let password = passwordField.stringValue let success: Bool = SSZipArchive.unzipFile(atPath: zipPath, toDestination: unzipPath, preserveAttributes: true, overwrite: true, nestedZipLevel: 1, password: !password.isEmpty ? password : nil, error: nil, delegate: nil, progressHandler: nil, completionHandler: nil) if success != false { print("Success unzip") info.stringValue = "Success unzip" } else { print("No success unzip") info.stringValue = "No success unzip" return } var items: [String] do { items = try FileManager.default.contentsOfDirectory(atPath: unzipPath) } catch { return } for (index, item) in items.enumerated() { switch index { case 0: file1.stringValue = item case 1: file2.stringValue = item case 2: file3.stringValue = item default: print("Went beyond index of assumed files") } } unzipButton.isEnabled = false } @IBAction func hasPasswordPressed(_: NSButton) { guard let zipPath = zipPath else { return } let success = SSZipArchive.isFilePasswordProtected(atPath: zipPath) if success { print("Yes, it's password protected.") info.stringValue = "Yes, it's password protected." } else { print("No, it's not password protected.") info.stringValue = "No, it's not password protected." } } @IBAction func resetPressed(_: NSButton) { file1.stringValue = "" file2.stringValue = "" file3.stringValue = "" info.stringValue = "" zipButton.isEnabled = true unzipButton.isEnabled = false hasPasswordButton.isEnabled = false resetButton.isEnabled = false } // MARK: Private func tempZipPath() -> String { var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] path += "/\(UUID().uuidString).zip" return path } func tempUnzipPath() -> String? { var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] path += "/\(UUID().uuidString)" let url = URL(fileURLWithPath: path) do { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } catch { return nil } return url.path } }
mit
541205896e1dee4194d27c9e9117fab9
32.011628
112
0.510391
5.787971
false
false
false
false
KagasiraBunJee/TryHard
TryHard/THFriendListVC.swift
1
3721
// // THFriendListVC.swift // TryHard // // Created by Sergei on 7/22/16. // Copyright © 2016 Sergey Polishchuk. All rights reserved. // import UIKit import FoldingCell class THFriendListVC: UIViewController, UITableViewDataSource, UITableViewDelegate, PJSIPBuddyDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchFriend: THTextField! var sipManager:THPJSipManager! var buddies:[PJSIPBuddy]! let kCloseCellHeight: CGFloat = 75 // equal or greater foregroundView height let kOpenCellHeight: CGFloat = 300 // equal or greater containerView height var cellHeights = [CGFloat]() override func viewDidLoad() { super.viewDidLoad() sipManager = THPJSipManager.sharedManager() sipManager.buddyDelegate = self buddies = sipManager.buddyList() tableView.tableFooterView = UIView() tableView.delegate = self tableView.dataSource = self searchFriend.onDone = { self.sipManager.addBuddy(self.searchFriend.text!) } refresh() } func refresh() { cellHeights.removeAll(keepCapacity: false) for _ in 0...4 { cellHeights.append(kCloseCellHeight) } } //MARK:- UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return buddies.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let buddy = buddies[indexPath.row]; let cell = tableView.dequeueReusableCellWithIdentifier("friendCell") as! THFriendCell cell.buddyName.text = buddy.buddyLogin cell.setBuddyStatus(buddy.buddyStatus) return cell } //MARK:- UITableViewDelegate func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return cellHeights[indexPath.row] } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! THFriendCell var duration = 0.0 if cellHeights[indexPath.row] == kCloseCellHeight { // open cell cellHeights[indexPath.row] = kOpenCellHeight cell.selectedAnimation(true, animated: true, completion: nil) duration = 0.5 } else {// close cell cellHeights[indexPath.row] = kCloseCellHeight cell.selectedAnimation(false, animated: true, completion: nil) duration = 1.1 } UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { () -> Void in tableView.beginUpdates() tableView.endUpdates() }, completion: nil) } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell is THFriendCell { let foldingCell = cell as! THFriendCell if cellHeights[indexPath.row] == kCloseCellHeight { foldingCell.selectedAnimation(false, animated: false, completion:nil) } else { foldingCell.selectedAnimation(true, animated: false, completion: nil) } } } //MARK:- PJSIPBuddyDelegate func pjsip_onBuddyStateChanged(buddyId: Int32, buddy: PJSIPBuddy!) { buddies = sipManager.buddyList() refresh() tableView.reloadData() } }
mit
ac6477db53f49cec49834b5ee9710c40
30.525424
125
0.626344
5.321888
false
false
false
false